Files
Phraseanet/Phraseanet-production-client/dist/production.js
2020-10-15 17:54:10 +03:00

63649 lines
2.8 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("jQuery"));
else if(typeof define === 'function' && define.amd)
define(["jQuery"], factory);
else if(typeof exports === 'object')
exports["app"] = factory(require("jQuery"));
else
root["app"] = factory(root["jQuery"]);
})(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_0__) {
return webpackJsonpapp([4],[
/* 0 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_0__;
/***/ }),
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */,
/* 5 */,
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */,
/* 10 */,
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.userModule = exports.utilsModule = exports.commonModule = exports.dialogModule = undefined;
var _common = __webpack_require__(90);
var _common2 = _interopRequireDefault(_common);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _user = __webpack_require__(45);
var _user2 = _interopRequireDefault(_user);
var _utils = __webpack_require__(56);
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.dialogModule = _dialog2.default;
exports.commonModule = _common2.default;
exports.utilsModule = _utils2.default;
exports.userModule = _user2.default;
/***/ }),
/* 12 */,
/* 13 */,
/* 14 */,
/* 15 */,
/* 16 */,
/* 17 */,
/* 18 */,
/* 19 */,
/* 20 */,
/* 21 */,
/* 22 */,
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Selectable = function Selectable(services, $container, options) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var defaults = {
allow_multiple: false,
selector: '',
callbackSelection: null,
selectStart: null,
selectStop: null,
limit: null,
localeService: localeService
};
options = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? options : {};
var $this = this;
if ($container.data('selectionnable')) {
/* this container is already selectionnable */
if (window.console) {
console.error('Trying to apply new selection to existing one');
}
return $container.data('selectionnable');
}
this.stream = new Rx.Subject();
this.$container = $container;
this.options = _jquery2.default.extend(defaults, options);
this.datas = [];
this.$container.data('selectionnable', this);
this.$container.addClass('selectionnable');
this.$container.on('click', this.options.selector, function (event) {
event.preventDefault();
if (typeof $this.options.selectStart === 'function') {
$this.options.selectStart(_jquery2.default.extend(_jquery2.default.Event('selectStart'), event), $this);
}
var $that = (0, _jquery2.default)(this);
var k = get_value($that, $this);
if (appCommons.utilsModule.is_shift_key(event) && (0, _jquery2.default)('.last_selected', this.$container).filter($this.options.selector).length !== 0) {
var lst = (0, _jquery2.default)($this.options.selector, this.$container);
var index1 = _jquery2.default.inArray((0, _jquery2.default)('.last_selected', this.$container).filter($this.options.selector)[0], lst);
var index2 = _jquery2.default.inArray($that[0], lst);
if (index2 < index1) {
var tmp = index1;
index1 = index2 - 1 < 0 ? index2 : index2 - 1;
index2 = tmp;
}
var stopped = false;
if (index2 !== -1 && index1 !== -1) {
var exp = $this.options.selector + ':gt(' + index1 + '):lt(' + (index2 - index1) + ')';
_jquery2.default.each((0, _jquery2.default)(exp, this.$container), function (i, n) {
if (!(0, _jquery2.default)(n).hasClass('selected') && stopped === false) {
if (!$this.hasReachLimit()) {
var contain = get_value((0, _jquery2.default)(n), $this);
$this.push(contain);
(0, _jquery2.default)(n).addClass('selected');
} else {
alert(localeService.t('max_record_selected'));
stopped = true;
}
}
});
}
if ($this.has(k) === false && stopped === false) {
if (!$this.hasReachLimit()) {
$this.push(k);
$that.addClass('selected');
} else {
alert(localeService.t('max_record_selected'));
}
}
} else {
if (!appCommons.utilsModule.is_ctrl_key(event)) {
$this.empty().push(k);
(0, _jquery2.default)('.selected', this.$container).filter($this.options.selector).removeClass('selected');
$that.addClass('selected');
} else {
if ($this.has(k) === true) {
$this.remove(k);
$that.removeClass('selected');
} else {
if (!$this.hasReachLimit()) {
$this.push(k);
$that.addClass('selected');
} else {
alert(localeService.t('max_record_selected'));
}
}
}
}
(0, _jquery2.default)('.last_selected', this.$container).removeClass('last_selected');
$that.addClass('last_selected');
$this.stream.onNext({
asArray: $this.datas,
serialized: $this.serialize()
});
if (typeof $this.options.selectStop === 'function') {
$this.options.selectStop(_jquery2.default.extend(_jquery2.default.Event('selectStop'), event), $this);
}
});
return this;
};
function get_value(element, Selectable) {
if (typeof Selectable.options.callbackSelection === 'function') {
return Selectable.options.callbackSelection((0, _jquery2.default)(element));
} else {
return (0, _jquery2.default)('input[name="id"]', (0, _jquery2.default)(element)).val();
}
}
Selectable.prototype = {
push: function push(element) {
if (this.options.allow_multiple === true || !this.has(element)) {
this.datas.push(element);
}
return this;
},
hasReachLimit: function hasReachLimit() {
if (this.options.limit !== null && this.options.limit <= this.datas.length) {
return true;
}
return false;
},
remove: function remove(element) {
this.datas = _jquery2.default.grep(this.datas, function (n) {
return n !== element;
});
return this;
},
has: function has(element) {
return _jquery2.default.inArray(element, this.datas) >= 0;
},
get: function get() {
return this.datas;
},
empty: function empty() {
var $this = this;
this.datas = [];
(0, _jquery2.default)(this.options.selector, this.$container).filter('.selected:visible').removeClass('selected');
if (typeof $this.options.selectStop === 'function') {
$this.options.selectStop(_jquery2.default.Event('selectStop'), $this);
}
return this;
},
length: function length() {
return this.datas.length;
},
size: function size() {
return this.datas.length;
},
serialize: function serialize(separator) {
separator = separator || ';';
return this.datas.join(separator);
},
selectAll: function selectAll() {
this.select('*');
return this;
},
select: function select(selector) {
var $this = this;
var stopped = false;
(0, _jquery2.default)(this.options.selector, this.$container).filter(selector).not('.selected').filter(':visible').each(function () {
if (!$this.hasReachLimit()) {
$this.push(get_value(this, $this));
(0, _jquery2.default)(this).addClass('selected');
} else {
if (stopped === false) {
alert($this.options.localeService.t('max_record_selected'));
}
stopped = true;
}
});
$this.stream.onNext({
asArray: $this.datas,
serialized: $this.serialize()
});
if (typeof $this.options.selectStop === 'function') {
$this.options.selectStop(_jquery2.default.Event('selectStop'), $this);
}
return this;
}
};
exports.default = Selectable;
/***/ }),
/* 24 */,
/* 25 */,
/* 26 */,
/* 27 */,
/* 28 */,
/* 29 */,
/* 30 */,
/* 31 */,
/* 32 */,
/* 33 */,
/* 34 */,
/* 35 */,
/* 36 */,
/* 37 */,
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/*** IMPORTS FROM imports-loader ***/
(function() {
(function(window, $) {
'use strict';
// Builds a 4 characters unique id
var uniqId = function(prefix) {
prefix = prefix || '';
return prefix + ("0000" + (Math.random() * Math.pow(36, 4) << 0).toString(36)).substr(-4);
};
// Builds query parameters from a geoname object
var RequestDataBuilder = function(geo, datas) {
this.datas = datas || {};
if (!geo instanceof GeotoCompleter) {
throw 'You must provide an instance of GeotoCompleter';
}
if (geo.getOption('sort')) {
this.datas.sort = geo.getOption('sort');
}
if (geo.getOption('client-ip')) {
this.datas.sortParams = geo.getOption('sortParams');
}
if (geo.getOption('country')) {
this.datas.country = geo.getOption('country');
}
if (geo.getOption('name')) {
this.datas.name = geo.getOption('name');
}
if (geo.getOption('limit')) {
this.datas.limit = geo.getOption('limit');
}
};
RequestDataBuilder.prototype.getRequestDatas = function() {
return this.datas;
};
// Handles request to the remote Geonames Server
var RequestManager = function(server) {
var _request = false;
var _endpoint = server;
this.search = function(resource, datas, errorCallback, parseresults) {
_request = $.ajax({
type: "GET",
dataType: "jsonp",
jsonpCallback: "parseresults",
url: _endpoint + resource,
beforeSend: function() {
if (_request && typeof _request.abort === 'function') {
_request.abort();
}
},
error: errorCallback,
data: datas
})
.done(parseresults)
.always(function() {
_request = false;
});
};
};
var GeotoCompleter = function(el, serverEndpoint, options) {
if (typeof $.ui === 'undefined') {
throw 'jQuery UI must be loaded';
}
if($(el).data('geocompleter')) {
return $(el).data('geocompleter');
}
var _serverEndpoint = serverEndpoint.substr(serverEndpoint.length - 1) === '/' ? serverEndpoint : serverEndpoint + '/';
this._requestManager = new RequestManager(_serverEndpoint);
this.$el = $(el);
this._opts = $.extend({
"name": null,
"sort": null,
"client-ip": null,
"country": null,
"limit": null,
"init-input": true
}, options);
this.$input = null;
this.$el.data('geocompleter', this);
};
GeotoCompleter.prototype.getOption = function(name) {
if (!(name in this._opts)) {
return null;
}
return this._opts[name];
};
GeotoCompleter.prototype.setOption = function(name, value) {
if (!(name in this._opts)) {
return this;
}
this._opts[name] = value;
return this;
};
GeotoCompleter.prototype.getAutocompleter = function() {
return this.$input;
};
GeotoCompleter.prototype.destroy = function() {
if (this.$input) {
this.$input.remove();
this.$el.show();
this.$el.val('');
this.$el.data('geocompleter', null);
}
};
GeotoCompleter.prototype.init = function() {
if (null !== this.$input) {
return;
}
var self = this;
var updateGeonameField = function(value) {
self.$el.val(value);
};
var updateCityField = function(value) {
self.$input.val(value);
};
var resetGeonameField = function() {
self.$el.val('');
};
var resetCityField = function() {
self.$input.val('');
};
var isGeonameFieldSetted = function() {
return self.$el.val() !== '';
};
var highlight = function (s, t) {
var matcher = new RegExp("("+$.ui.autocomplete.escapeRegex(t)+")", "ig" );
return s.replace(matcher, "<span class='ui-state-highlight'>$1</span>");
};
// Creates city input
this.$input = $('<input />')
.attr('name', uniqId(this.$el.attr('name')))
.attr('id', uniqId(this.$el.attr('id')))
.attr('type', 'text')
.attr('class', this.$el.attr('class'))
.addClass("geocompleter-input");
// Prevents form submission when pressing ENTER
this.$input.keypress(function(event) {
var code = (event.keyCode ? event.keyCode : event.which);
if(code === $.ui.keyCode.ENTER ) {
event.preventDefault();
return false;
}
});
// On any keyup except (esc, up, down, enter) fields are desynchronised, reset geonames field
this.$input.keyup(function(event) {
var code = (event.keyCode ? event.keyCode : event.which);
var unBindKeys = [
$.ui.keyCode.ESCAPE,
$.ui.keyCode.UP,
$.ui.keyCode.DOWN,
$.ui.keyCode.LEFT,
$.ui.keyCode.RIGHT,
$.ui.keyCode.ENTER
];
if (-1 === $.inArray(code, unBindKeys)){
resetGeonameField();
}
});
this.$el.hide();
this.$el.after(this.$input);
// Overrides prototype to render values without autoescape, useful to highlight values
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).html( item.label ) )
.appendTo( ul );
};
// Saves response content
var responseContent;
// Builds a jquery autocompleter
this.$input.autocomplete({
create: function(event) {
if(self.$el.val() !== "" && self.getOption("init-input")) {
self._requestManager.search(
"city/" + parseInt(self.$el.val(), 10),
{},
function(jqXhr, status, error) {
return;
}, function (data) {
var country = data.country.name || "";
self.$input.val(data.name + ("" !== country ? "," + country : ""));
}
);
}
},
source: function(request, response) {
var name, country, terms = '';
terms = request.term.split(',');
if (terms.length === 2) {
country = terms.pop();
}
name = terms.pop();
self.setOption('name', $.trim(name));
self.setOption('country', $.trim(country));
var requestDataBuilder = new RequestDataBuilder(self);
self._requestManager.search(
"city",
requestDataBuilder.getRequestDatas(),
function(jqXhr, status, error) {
if (jqXhr.status !== 0 && jqXhr.statusText !== 'abort') {
response([]);
self.$input.trigger('geotocompleter.request.error', [jqXhr, status, error]);
}
}, function(data) {
response($.map(data || [], function(item) {
var country = country ? country : name;
var labelName = highlight(item.name, name);
var labelCountry = highlight((item.country ? item.country.name || '' : ''), country);
var labelRegion = highlight((item.region ? item.region.name || '' : ''), name);
return {
label: labelName + ("" !== labelCountry ? ", " + labelCountry : "") + ("" !== labelRegion ? " <span class='region'>" + labelRegion + "</span>" : ""),
value: item.name + (item.country ? ", " + item.country.name : ''),
geonameid: item.geonameid
};
}));
}
);
},
messages: {
noResults: '',
results: function() {}
},
response: function (event, ui) {
responseContent = [];
if (ui.content) {
responseContent = ui.content;
// Sets geoname id if values are re synchronized
if (ui.content.length > 0) {
var items = $.grep(ui.content, function(item) {
return item.value === self.$input.val() ? item : null;
});
if (items.length > 0) {
updateGeonameField(items[0].geonameid);
}
}
}
},
select: function(event, ui) {
if (ui.item) {
updateGeonameField(ui.item.geonameid);
}
},
focus: function (event, ui) {
var code = (event.keyCode ? event.keyCode : event.which);
// Updates geoname ID only if key up and key down are pressed
if (ui.item && -1 !== $.inArray(code, [$.ui.keyCode.DOWN, $.ui.keyCode.UP])) {
updateGeonameField(ui.item.geonameid);
}
},
close : function (event, ui) {
var ev = event.originalEvent;
if ("undefined" === typeof ev) {
return false;
}
var code = (ev.keyCode ? ev.keyCode : ev.which);
// If esc key is pressed or user leaves the input
if ((ev.type === "keydown" && code === $.ui.keyCode.ESCAPE) || ev.type === "blur") {
if (isGeonameFieldSetted() && responseContent.length > 0) {
var geonameId = self.$el.val();
// Update city input according to the setted geonameId
var responseValues = $.grep(responseContent, function(item) {
return item.geonameid === geonameId ? item : null;
});
if (responseValues.length > 0) {
self.$input.val(responseValues[0].value);
}
return false;
}
// Resets both field as nothing is no more sychronized
resetGeonameField();
resetCityField();
}
}
}).autocomplete("widget").addClass("geocompleter-menu");
var onInit = self.getOption('onInit');
// On Initialization callback
if (onInit !== null && typeof onInit === 'function') {
onInit(this.$el, this.$input);
}
};
var methods = {
init: function(options) {
var settings = $.extend({
server: ''
}, options);
if ('' === settings.server) {
throw '"server" must be set';
}
return this.each(function() {
var geocompleter = new GeotoCompleter(this, settings.server, settings);
geocompleter.init();
});
},
destroy: function() {
return this.each(function() {
var geocompleter = $(this).data('geocompleter');
if (geocompleter) {
geocompleter.destroy();
}
});
},
autocompleter: function() {
var args = arguments;
return this.each(function() {
var geocompleter = $(this).data('geocompleter');
if (args[0] === "on" && typeof args[1] === "string" && typeof args[2] === "function") {
// Bind addition events
geocompleter.getAutocompleter().on(args[1], args[2]);
} else {
$.fn.autocomplete.apply(geocompleter.getAutocompleter(),args);
}
});
}
};
$.fn.geocompleter = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.geocompleter');
}
};
})(window, jQuery);
}.call(window));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.generateRandStr = exports.cleanTags = exports.escapeHtml = undefined;
var _phraseanetCommon = __webpack_require__(11);
var AppCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var entityMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#39;',
'/': '&#x2F;'
};
var escapeHtml = function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
};
// @TODO - check legacy code
var cleanTags = function cleanTags(string) {
var chars2replace = [{
f: '&',
t: '&amp;'
}, {
f: '<',
t: '&lt;'
}, {
f: '>',
t: '&gt;'
}];
for (var c in chars2replace) {
string = string.replace(RegExp(chars2replace[c].f, 'g'), chars2replace[c].t);
}
return string;
};
var generateRandStr = function generateRandStr() {
var sLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 5;
var s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
return Array(sLength).join().split(',').map(function () {
return s.charAt(Math.floor(Math.random() * s.length));
}).join('');
};
exports.escapeHtml = escapeHtml;
exports.cleanTags = cleanTags;
exports.generateRandStr = generateRandStr;
/***/ }),
/* 40 */
/***/ (function(module, exports) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function(useSourceMap) {
var list = [];
// return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if(item[2]) {
return "@media " + item[2] + "{" + content + "}";
} else {
return content;
}
}).join("");
};
// import a list of modules into the list
list.i = function(modules, mediaQuery) {
if(typeof modules === "string")
modules = [[null, modules, ""]];
var alreadyImportedModules = {};
for(var i = 0; i < this.length; i++) {
var id = this[i][0];
if(typeof id === "number")
alreadyImportedModules[id] = true;
}
for(i = 0; i < modules.length; i++) {
var item = modules[i];
// skip already imported module
// this implementation is not 100% perfect for weird media query combinations
// when a module is imported multiple times with different media queries.
// I hope this will never occur (Hey this way we have smaller bundles)
if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
if(mediaQuery && !item[2]) {
item[2] = mediaQuery;
} else if(mediaQuery) {
item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
}
list.push(item);
}
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || '';
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */'
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
}
// Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
return '/*# ' + data + ' */';
}
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var stylesInDom = {};
var memoize = function (fn) {
var memo;
return function () {
if (typeof memo === "undefined") memo = fn.apply(this, arguments);
return memo;
};
};
var isOldIE = memoize(function () {
// Test for IE <= 9 as proposed by Browserhacks
// @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
// Tests for existence of standard globals is to allow style-loader
// to operate correctly into non-standard environments
// @see https://github.com/webpack-contrib/style-loader/issues/177
return window && document && document.all && !window.atob;
});
var getElement = (function (fn) {
var memo = {};
return function(selector) {
if (typeof memo[selector] === "undefined") {
memo[selector] = fn.call(this, selector);
}
return memo[selector]
};
})(function (target) {
return document.querySelector(target)
});
var singleton = null;
var singletonCounter = 0;
var stylesInsertedAtTop = [];
var fixUrls = __webpack_require__(153);
module.exports = function(list, options) {
if (typeof DEBUG !== "undefined" && DEBUG) {
if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
}
options = options || {};
options.attrs = typeof options.attrs === "object" ? options.attrs : {};
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
if (!options.singleton) options.singleton = isOldIE();
// By default, add <style> tags to the <head> element
if (!options.insertInto) options.insertInto = "head";
// By default, add <style> tags to the bottom of the target
if (!options.insertAt) options.insertAt = "bottom";
var styles = listToStyles(list, options);
addStylesToDom(styles, options);
return function update (newList) {
var mayRemove = [];
for (var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
domStyle.refs--;
mayRemove.push(domStyle);
}
if(newList) {
var newStyles = listToStyles(newList, options);
addStylesToDom(newStyles, options);
}
for (var i = 0; i < mayRemove.length; i++) {
var domStyle = mayRemove[i];
if(domStyle.refs === 0) {
for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j]();
delete stylesInDom[domStyle.id];
}
}
};
};
function addStylesToDom (styles, options) {
for (var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
if(domStyle) {
domStyle.refs++;
for(var j = 0; j < domStyle.parts.length; j++) {
domStyle.parts[j](item.parts[j]);
}
for(; j < item.parts.length; j++) {
domStyle.parts.push(addStyle(item.parts[j], options));
}
} else {
var parts = [];
for(var j = 0; j < item.parts.length; j++) {
parts.push(addStyle(item.parts[j], options));
}
stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
}
}
}
function listToStyles (list, options) {
var styles = [];
var newStyles = {};
for (var i = 0; i < list.length; i++) {
var item = list[i];
var id = options.base ? item[0] + options.base : item[0];
var css = item[1];
var media = item[2];
var sourceMap = item[3];
var part = {css: css, media: media, sourceMap: sourceMap};
if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]});
else newStyles[id].parts.push(part);
}
return styles;
}
function insertStyleElement (options, style) {
var target = getElement(options.insertInto)
if (!target) {
throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");
}
var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1];
if (options.insertAt === "top") {
if (!lastStyleElementInsertedAtTop) {
target.insertBefore(style, target.firstChild);
} else if (lastStyleElementInsertedAtTop.nextSibling) {
target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling);
} else {
target.appendChild(style);
}
stylesInsertedAtTop.push(style);
} else if (options.insertAt === "bottom") {
target.appendChild(style);
} else {
throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
}
}
function removeStyleElement (style) {
if (style.parentNode === null) return false;
style.parentNode.removeChild(style);
var idx = stylesInsertedAtTop.indexOf(style);
if(idx >= 0) {
stylesInsertedAtTop.splice(idx, 1);
}
}
function createStyleElement (options) {
var style = document.createElement("style");
options.attrs.type = "text/css";
addAttrs(style, options.attrs);
insertStyleElement(options, style);
return style;
}
function createLinkElement (options) {
var link = document.createElement("link");
options.attrs.type = "text/css";
options.attrs.rel = "stylesheet";
addAttrs(link, options.attrs);
insertStyleElement(options, link);
return link;
}
function addAttrs (el, attrs) {
Object.keys(attrs).forEach(function (key) {
el.setAttribute(key, attrs[key]);
});
}
function addStyle (obj, options) {
var style, update, remove, result;
// If a transform function was defined, run it on the css
if (options.transform && obj.css) {
result = options.transform(obj.css);
if (result) {
// If transform returns a value, use that instead of the original css.
// This allows running runtime transformations on the css.
obj.css = result;
} else {
// If the transform function returns a falsy value, don't add this css.
// This allows conditional loading of css
return function() {
// noop
};
}
}
if (options.singleton) {
var styleIndex = singletonCounter++;
style = singleton || (singleton = createStyleElement(options));
update = applyToSingletonTag.bind(null, style, styleIndex, false);
remove = applyToSingletonTag.bind(null, style, styleIndex, true);
} else if (
obj.sourceMap &&
typeof URL === "function" &&
typeof URL.createObjectURL === "function" &&
typeof URL.revokeObjectURL === "function" &&
typeof Blob === "function" &&
typeof btoa === "function"
) {
style = createLinkElement(options);
update = updateLink.bind(null, style, options);
remove = function () {
removeStyleElement(style);
if(style.href) URL.revokeObjectURL(style.href);
};
} else {
style = createStyleElement(options);
update = applyToTag.bind(null, style);
remove = function () {
removeStyleElement(style);
};
}
update(obj);
return function updateStyle (newObj) {
if (newObj) {
if (
newObj.css === obj.css &&
newObj.media === obj.media &&
newObj.sourceMap === obj.sourceMap
) {
return;
}
update(obj = newObj);
} else {
remove();
}
};
}
var replaceText = (function () {
var textStore = [];
return function (index, replacement) {
textStore[index] = replacement;
return textStore.filter(Boolean).join('\n');
};
})();
function applyToSingletonTag (style, index, remove, obj) {
var css = remove ? "" : obj.css;
if (style.styleSheet) {
style.styleSheet.cssText = replaceText(index, css);
} else {
var cssNode = document.createTextNode(css);
var childNodes = style.childNodes;
if (childNodes[index]) style.removeChild(childNodes[index]);
if (childNodes.length) {
style.insertBefore(cssNode, childNodes[index]);
} else {
style.appendChild(cssNode);
}
}
}
function applyToTag (style, obj) {
var css = obj.css;
var media = obj.media;
if(media) {
style.setAttribute("media", media)
}
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
while(style.firstChild) {
style.removeChild(style.firstChild);
}
style.appendChild(document.createTextNode(css));
}
}
function updateLink (link, options, obj) {
var css = obj.css;
var sourceMap = obj.sourceMap;
/*
If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled
and there is no publicPath defined then lets turn convertToAbsoluteUrls
on by default. Otherwise default to the convertToAbsoluteUrls option
directly
*/
var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap;
if (options.convertToAbsoluteUrls || autoFixUrls) {
css = fixUrls(css);
}
if (sourceMap) {
// http://stackoverflow.com/a/26603875
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
}
var blob = new Blob([css], { type: "text/css" });
var oldSrc = link.href;
link.href = URL.createObjectURL(blob);
if(oldSrc) URL.revokeObjectURL(oldSrc);
}
/***/ }),
/* 42 */,
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof global !== "undefined") {
win = global;
} else if (typeof self !== "undefined"){
win = self;
} else {
win = {};
}
module.exports = win;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6)))
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function create_dialog() {
if ((0, _jquery2.default)('#p4_alerts').length === 0) {
(0, _jquery2.default)('body').append('<div id="p4_alerts"></div>');
}
return (0, _jquery2.default)('#p4_alerts');
}
function alert(title, message, callback) {
var $dialog = create_dialog();
var button = {};
button.Ok = function () {
if (typeof callback === 'function') {
callback();
} else {
$dialog.dialog('close');
}
};
if ($dialog.data('ui-dialog')) {
$dialog.dialog('destroy');
}
$dialog.attr('title', title).empty().append(message).dialog({
autoOpen: false,
closeOnEscape: true,
resizable: false,
draggable: false,
modal: true,
buttons: button,
overlay: {
backgroundColor: '#000',
opacity: 0.7
}
}).dialog('open');
if (typeof callback === 'function') {
$dialog.bind('dialogclose', function (event, ui) {
callback();
});
}
return;
}
var Alerts = alert;
exports.default = Alerts;
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8); // @TODO enable lints
/* eslint-disable no-undef*/
humane.info = humane.spawn({ addnCls: 'humane-libnotify-info', timeout: 1000 });
humane.error = humane.spawn({ addnCls: 'humane-libnotify-error', timeout: 1000 });
humane.forceNew = true;
function setPref(name, value) {
var prefName = 'pref_' + name;
if (_jquery2.default.data[prefName] && _jquery2.default.data[prefName].abort) {
_jquery2.default.data[prefName].abort();
_jquery2.default.data[prefName] = false;
}
_jquery2.default.data[prefName] = _jquery2.default.ajax({
type: 'POST',
url: '/user/preferences/',
data: {
prop: name,
value: value
},
dataType: 'json',
timeout: _jquery2.default.data[prefName] = false,
error: _jquery2.default.data[prefName] = false,
success: function success(data) {
if (data.success) {
humane.info(data.message);
} else {
humane.error(data.message);
}
_jquery2.default.data[prefName] = false;
return data;
}
});
return _jquery2.default.data[prefName];
}
exports.default = { setPref: setPref };
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _notifyLayout = __webpack_require__(108);
var _notifyLayout2 = _interopRequireDefault(_notifyLayout);
var _notifyService = __webpack_require__(109);
var _notifyService2 = _interopRequireDefault(_notifyService);
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// import user from '../user/index.js';
var notify = function notify(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var defaultPollingTime = 10000;
var defaultConfig = {
url: null,
moduleId: null,
userId: null,
_isValid: false
};
var initialize = function initialize() {
(0, _notifyLayout2.default)(services).initialize();
};
var createNotifier = function createNotifier(state) {
if (state === undefined) {
return defaultConfig;
}
if (state.url === undefined) {
return defaultConfig;
}
return (0, _lodash2.default)({}, defaultConfig, {
url: state.url,
moduleId: state.moduleId,
userId: state.userId,
_isValid: true
});
};
//const appendNotifications = (content) => notifyUiComponent().addNotifications(content);
var isValid = function isValid(notificationInstance) {
return notificationInstance._isValid || false;
};
var poll = function poll(notificationInstance) {
var notificationSource = Rx.Observable.fromPromise((0, _notifyService2.default)({
configService: configService
}).getNotification({
module: notificationInstance.moduleId,
usr: notificationInstance.userId
}));
notificationSource.subscribe(function (x) {
return onPollSuccess(x, notificationInstance);
}, function (e) {
return onPollError(e, notificationInstance);
}, function () {});
};
var onPollSuccess = function onPollSuccess(data, notificationInstance) {
// broadcast session refresh event
appEvents.emit('session.refresh', data);
// broadcast notification refresh event
if (data.changed.length > 0) {
appEvents.emit('notification.refresh', data);
}
// append notification content
(0, _notifyLayout2.default)(services).addNotifications(data.notifications);
var t = 120000;
if (data.apps && parseInt(data.apps, 10) > 1) {
t = Math.round(Math.sqrt(parseInt(data.apps, 10) - 1) * 1.3 * 60000);
}
window.setTimeout(poll, t, notificationInstance);
return true;
};
var onPollError = function onPollError(data, notificationInstance) {
if (data.status === 'disconnected' || data.status === 'session') {
appEvents.emit('user.disconnected', data);
return false;
}
window.setTimeout(poll, defaultPollingTime, notificationInstance);
};
return {
initialize: initialize,
/*appendNotifications: (content) => {
notifyLayout().addNotifications(content)
},*/
createNotifier: createNotifier,
isValid: isValid,
poll: poll
};
};
exports.default = notify;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
var _toolbar = __webpack_require__(110);
var _toolbar2 = _interopRequireDefault(_toolbar);
var _mainMenu = __webpack_require__(74);
var _mainMenu2 = _interopRequireDefault(_mainMenu);
var _keyboard = __webpack_require__(187);
var _keyboard2 = _interopRequireDefault(_keyboard);
var _cgu = __webpack_require__(188);
var _cgu2 = _interopRequireDefault(_cgu);
var _edit = __webpack_require__(61);
var _edit2 = _interopRequireDefault(_edit);
var _export = __webpack_require__(68);
var _export2 = _interopRequireDefault(_export);
var _share = __webpack_require__(189);
var _share2 = _interopRequireDefault(_share);
var _index = __webpack_require__(73);
var _index2 = _interopRequireDefault(_index);
var _addToBasket = __webpack_require__(190);
var _addToBasket2 = _interopRequireDefault(_addToBasket);
var _removeFromBasket = __webpack_require__(191);
var _removeFromBasket2 = _interopRequireDefault(_removeFromBasket);
var _print = __webpack_require__(72);
var _print2 = _interopRequireDefault(_print);
var _preferences = __webpack_require__(192);
var _preferences2 = _interopRequireDefault(_preferences);
var _order = __webpack_require__(75);
var _order2 = _interopRequireDefault(_order);
var _recordPreview = __webpack_require__(196);
var _recordPreview2 = _interopRequireDefault(_recordPreview);
var _alert = __webpack_require__(44);
var _alert2 = _interopRequireDefault(_alert);
var _uploader = __webpack_require__(200);
var _uploader2 = _interopRequireDefault(_uploader);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ui = function ui(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var activeZone = false;
var searchSelection = { asArray: [], serialized: '' };
var workzoneSelection = { asArray: [], serialized: '' };
var initialize = function initialize(options) {
var $container = options.$container;
// init state navigation
// records and baskets actions in global interface:
(0, _export2.default)(services).initialize();
(0, _addToBasket2.default)(services).initialize();
(0, _removeFromBasket2.default)(services).initialize();
(0, _print2.default)(services).initialize();
(0, _share2.default)(services).initialize(options);
(0, _cgu2.default)(services).initialize(options);
(0, _preferences2.default)(services).initialize(options);
(0, _order2.default)(services).initialize(options);
var editRecord = (0, _edit2.default)(services);
editRecord.initialize();
var previewRecord = (0, _recordPreview2.default)(services);
var previewIsOpen = false;
previewRecord.getPreviewStream().subscribe(function (previewOptions) {
previewIsOpen = previewOptions.open;
});
previewRecord.initialize();
// add interface components:
(0, _toolbar2.default)(services).initialize();
(0, _mainMenu2.default)(services).initialize();
(0, _keyboard2.default)(services).initialize();
(0, _uploader2.default)(services).initialize();
// main menu > help context menu
(0, _jquery2.default)('.shortcuts-trigger').bind('click', function () {
(0, _keyboard2.default)(services).openModal();
});
$container.on('keydown', function (event) {
var specialKeyState = {
isCancelKey: false,
isShortcutKey: false
};
if ((0, _jquery2.default)('#MODALDL').is(':visible')) {
switch (event.keyCode) {
case 27:
// hide download
hideOverlay(2);
(0, _jquery2.default)('#MODALDL').css({
display: 'none'
});
break;
default:
}
} else {
if ((0, _jquery2.default)('#EDITWINDOW').is(':visible')) {
// access to editor instead of edit modal
specialKeyState = editRecord.onGlobalKeydown(event, specialKeyState);
} else if (previewIsOpen) {
specialKeyState = previewRecord.onGlobalKeydown(event, specialKeyState);
} else if ((0, _jquery2.default)('#EDIT_query').hasClass('focused')) {
// if return true - nothing to do
} else if ((0, _jquery2.default)('.overlay').is(':visible')) {
// if return true - nothing to do
} else if ((0, _jquery2.default)('.ui-widget-overlay').is(':visible')) {
// if return true - nothing to do
} else {
switch (getActiveZone()) {
case 'rightFrame':
specialKeyState = _searchResultKeyDownEvent(event, specialKeyState);
break;
case 'idFrameC':
specialKeyState = _workzoneKeyDownEvent(event, specialKeyState);
break;
case 'mainMenu':
break;
case 'headBlock':
break;
default:
break;
}
}
}
if (!(0, _jquery2.default)('#EDIT_query').hasClass('focused') && event.keyCode !== 17) {
if ((0, _jquery2.default)('#keyboard-dialog.auto').length > 0 && specialKeyState.isShortcutKey) {
(0, _keyboard2.default)(services).openModal();
}
}
if (specialKeyState.isCancelKey) {
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
return true;
});
};
// @TODO to be moved
var _searchResultKeyDownEvent = function _searchResultKeyDownEvent(event, specialKeyState) {
switch (event.keyCode) {
case 65:
// a
if (appCommons.utilsModule.is_ctrl_key(event)) {
appEvents.emit('search.selection.selectAll');
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
}
break;
case 80:
// P
if (appCommons.utilsModule.is_ctrl_key(event)) {
appEvents.emit('record.doPrint', 'lst=' + searchSelection.serialized);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
case 69:
// e
if (appCommons.utilsModule.is_ctrl_key(event)) {
// eq to: editRecord.doEdit()
appEvents.emit('record.doEdit', {
type: 'IMGT',
value: searchSelection.serialized
});
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
case 40:
// down arrow
(0, _jquery2.default)('#answers').scrollTop((0, _jquery2.default)('#answers').scrollTop() + 30);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
case 38:
// down arrow
(0, _jquery2.default)('#answers').scrollTop((0, _jquery2.default)('#answers').scrollTop() - 30);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
case 37:
// previous page
(0, _jquery2.default)('#PREV_PAGE').trigger('click');
specialKeyState.isShortcutKey = true;
break;
case 39:
// previous page
(0, _jquery2.default)('#NEXT_PAGE').trigger('click');
specialKeyState.isShortcutKey = true;
break;
case 9:
// tab
if (!appCommons.utilsModule.is_ctrl_key(event) && !(0, _jquery2.default)('.ui-widget-overlay').is(':visible') && !(0, _jquery2.default)('.overlay_box').is(':visible')) {
document.getElementById('EDIT_query').focus();
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
default:
}
return specialKeyState;
};
// @TODO to be moved
var _workzoneKeyDownEvent = function _workzoneKeyDownEvent(event, specialKeyState) {
switch (event.keyCode) {
case 65:
// a
if (appCommons.utilsModule.is_ctrl_key(event)) {
appEvents.emit('workzone.selection.selectAll');
// p4.WorkZone.Selection.selectAll();
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
case 80:
// P
if (appCommons.utilsModule.is_ctrl_key(event)) {
appEvents.emit('record.doPrint', 'lst=' + workzoneSelection.serialized);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
case 69:
// e
if (appCommons.utilsModule.is_ctrl_key(event)) {
// eq to: editRecord.doEdit()
appEvents.emit('record.doEdit', {
type: 'IMGT',
value: workzoneSelection.serialized
});
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
// case 46:// del
// _deleteRecords(searchSelection.serialized);
// specialKeyState.isCancelKey = true;
// break;
case 40:
// down arrow
(0, _jquery2.default)('#baskets div.bloc').scrollTop((0, _jquery2.default)('#baskets div.bloc').scrollTop() + 30);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
case 38:
// down arrow
(0, _jquery2.default)('#baskets div.bloc').scrollTop((0, _jquery2.default)('#baskets div.bloc').scrollTop() - 30);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
case 37:
// previous page
(0, _jquery2.default)('#PREV_PAGE').trigger('click');
break;
case 39:
// previous page
(0, _jquery2.default)('#NEXT_PAGE').trigger('click');
break;
case 9:
// tab
if (!appCommons.utilsModule.is_ctrl_key(event) && !(0, _jquery2.default)('.ui-widget-overlay').is(':visible') && !(0, _jquery2.default)('.overlay_box').is(':visible')) {
document.getElementById('EDIT_query').focus();
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
default:
}
return specialKeyState;
};
var hideOverlay = function hideOverlay(n) {
var div = 'OVERLAY';
if (typeof n !== 'undefined') {
div += n;
}
(0, _jquery2.default)('#' + div).hide().remove();
};
var showModal = function showModal(cas, options) {
var content = '';
var callback = null;
var button = {
OK: function OK(e) {
hideOverlay(3);
(0, _jquery2.default)(this).dialog('close');
return;
}
};
var escape = true;
var onClose = function onClose() {};
switch (cas) {
case 'timeout':
content = localeService.t('serverTimeout');
break;
case 'error':
content = localeService.t('serverError');
break;
case 'disconnected':
content = localeService.t('serverDisconnected');
escape = false;
callback = function callback(e) {
self.location.replace(self.location.href);
};
break;
default:
break;
}
if (typeof _alert2.default === 'undefined') {
alert(localeService.t('serverDisconnected'));
self.location.replace(self.location.href);
} else {
(0, _alert2.default)(options.title, content, callback);
}
return;
};
var getActiveZone = function getActiveZone() {
return activeZone;
};
var setActiveZone = function setActiveZone(zoneId) {
activeZone = zoneId;
return activeZone;
};
var activeZoning = function activeZoning() {
(0, _jquery2.default)('#idFrameC, #rightFrame').bind('mousedown', function (event) {
var old_zone = getActiveZone();
setActiveZone((0, _jquery2.default)(this).attr('id'));
if (getActiveZone() !== old_zone && getActiveZone() !== 'headBlock') {
(0, _jquery2.default)('.effectiveZone.activeZone').removeClass('activeZone');
(0, _jquery2.default)('.effectiveZone', this).addClass('activeZone'); // .flash('#555555');
}
(0, _jquery2.default)('#EDIT_query').blur();
});
(0, _jquery2.default)('#rightFrame').trigger('mousedown');
};
var resizeAll = function resizeAll() {
var body = (0, _jquery2.default)('body');
window.bodySize.y = body.height();
window.bodySize.x = body.width();
var headBlockH = (0, _jquery2.default)('#headBlock').outerHeight();
var bodyY = window.bodySize.y - headBlockH - 2;
var bodyW = window.bodySize.x - 2;
// $('#desktop').height(bodyY).width(bodyW);
appEvents.emit('preview.doResize');
if ((0, _jquery2.default)('#idFrameC').data('ui-resizable')) {
(0, _jquery2.default)('#idFrameC').resizable('option', 'maxWidth', 600);
(0, _jquery2.default)('#idFrameC').resizable('option', 'minWidth', 360);
}
answerSizer();
linearizeUi();
};
var answerSizer = function answerSizer() {
var el = (0, _jquery2.default)('#idFrameC').outerWidth();
if (!_jquery2.default.support.cssFloat) {
// $('#idFrameC .insidebloc').width(el - 56);
}
var widthA = Math.round(window.bodySize.x - el - 10);
(0, _jquery2.default)('#rightFrame').width(widthA);
(0, _jquery2.default)('#rightFrame').css('left', (0, _jquery2.default)('#idFrameC').width());
};
var linearizeUi = function linearizeUi() {
var list = (0, _jquery2.default)('#answers .list');
var fllWidth = (0, _jquery2.default)('#answers').innerWidth();
var n = void 0;
if (list.length > 0) {
fllWidth -= 16;
var stdWidth = 567;
var diff = 28;
n = Math.round(fllWidth / stdWidth);
var w = Math.floor(fllWidth / n) - diff;
if (w < 567 && n > 1) {
w = Math.floor(fllWidth / (n - 1)) - diff;
}
(0, _jquery2.default)('#answers .list').width(w);
} else {
var minMargin = 5;
var el = (0, _jquery2.default)('#answers .diapo:first');
var diapoWidth = el.outerWidth() + minMargin * 2;
fllWidth -= 26;
n = Math.floor(fllWidth / diapoWidth);
var margin = Math.floor(fllWidth % diapoWidth / (2 * n));
margin = margin + minMargin;
(0, _jquery2.default)('#answers .diapo').css('margin', '5px ' + margin + 'px');
var answerIcons = (0, _jquery2.default)('#answers .bottom_actions_holder .fa-stack');
var answerIconsHolder = (0, _jquery2.default)('.bottom_actions_holder');
if (el.outerWidth() < 180) {
answerIcons.css('width', '20px');
answerIcons.css('font-size', '10px');
answerIconsHolder.addClass('twenty');
}
if (el.outerWidth() >= 180 && el.outerWidth() < 260) {
answerIcons.css('width', '24px');
answerIcons.css('font-size', '12px');
answerIconsHolder.addClass('twenty-four');
}
if (el.outerWidth() >= 260) {
answerIcons.css('width', '30px');
answerIcons.css('font-size', '15px');
answerIcons.closest('td').css('width', '110px');
answerIconsHolder.css('height', '36px');
answerIconsHolder.addClass('thirty');
}
}
};
var saveWindow = function saveWindow() {
var key = '';
var value = '';
if ((0, _jquery2.default)('#idFrameE').is(':visible') && (0, _jquery2.default)('#EDITWINDOW').is(':visible')) {
key = 'edit_window';
value = (0, _jquery2.default)('#idFrameE').outerWidth() / (0, _jquery2.default)('#EDITWINDOW').innerWidth();
} else {
key = 'search_window';
value = (0, _jquery2.default)('#idFrameC').outerWidth() / window.bodySize.x;
}
appCommons.userModule.setPref(key, value);
};
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelection = selection;
},
'broadcast.workzoneResultSelection': function broadcastWorkzoneResultSelection(selection) {
workzoneSelection = selection;
},
'ui.resizeAll': resizeAll,
'ui.answerSizer': answerSizer,
'ui.linearizeUi': linearizeUi,
'ui.saveWindow': saveWindow
});
return { initialize: initialize, showModal: showModal, activeZoning: activeZoning, getActiveZone: getActiveZone, resizeAll: resizeAll };
};
exports.default = ui;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(123);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var fnToStr = Function.prototype.toString;
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr.call(value);
return constructorRegex.test(fnStr);
} catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) { return false; }
fnToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
module.exports = function isCallable(value) {
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
if (typeof value === 'function' && !value.prototype) { return true; }
if (hasToStringTag) { return tryFunctionObject(value); }
if (isES6ClassFn(value)) { return false; }
var strClass = toStr.call(value);
return strClass === fnClass || strClass === genClass;
};
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /* eslint-disable quotes */
/* eslint-disable no-undef */
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
var _markerCollection = __webpack_require__(145);
var _markerCollection2 = _interopRequireDefault(_markerCollection);
var _markerGLCollection = __webpack_require__(146);
var _markerGLCollection2 = _interopRequireDefault(_markerGLCollection);
var _utils = __webpack_require__(39);
var _provider = __webpack_require__(147);
var _provider2 = _interopRequireDefault(_provider);
var _fr = __webpack_require__(148);
var _fr2 = _interopRequireDefault(_fr);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(149);
__webpack_require__(154);
__webpack_require__(156);
__webpack_require__(158);
__webpack_require__(162);
var leafletMap = function leafletMap(services) {
var configService = services.configService,
localeService = services.localeService,
eventEmitter = services.eventEmitter;
var $container = null;
var parentOptions = {};
var tabOptions = {};
var mapOptions = {};
var mapUID = void 0;
var mapbox = void 0;
var mapboxgl = void 0;
var leafletDraw = void 0;
var featureLayer = null;
var map = null;
var geocoder = null;
var mapboxClient = null;
var $tabContent = void 0;
var tabContainerName = 'leafletTabContainer';
var editable = void 0;
var drawable = void 0;
var searchable = void 0;
var drawnItems = void 0;
var activeProvider = {};
var recordConfig = {};
var currentZoomLevel = 0;
var shouldUpdateZoom = false;
var features = null;
var geojson = {};
var labelLayerId = void 0;
var mapboxGLDefaultPosition = void 0;
var shapesWebGl = {};
var MapboxCircle = void 0;
var mapboxCircleCollection = [];
var shouldDrawCircle = false;
var shouldRemoveCircle = false;
var turf = null;
var editableCircleOpts = {
editable: true,
minRadius: 10,
fillColor: '#000000',
fillOpacity: 0.05,
strokeColor: '#0000ff',
strokeOpacity: 0.25,
strokeWeight: 2,
debugEl: document.getElementById('debug')
};
//let markerMapboxGl = {};
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, parentOptions = _options.parentOptions, _options);
tabOptions = options.tabOptions || false;
mapOptions = options.mapOptions !== undefined ? _underscore2.default.extend(mapOptions, options.mapOptions) : mapOptions;
editable = options.editable || false;
drawable = options.drawable || false;
searchable = options.searchable || false;
drawnItems = options.drawnItems || false;
recordConfig = parentOptions.recordConfig || false;
mapUID = 'leafletMap' + (0, _utils.generateRandStr)(5);
var providerConfig = (0, _provider2.default)(services);
var isProviderInitalized = providerConfig.initialize();
if (isProviderInitalized === true) {
activeProvider = providerConfig.getConfiguration();
if (tabOptions !== false) {
// @TODO deepmerge
var tabPlist = _underscore2.default.extend({
tabProperties: {
id: tabContainerName,
title: localeService.t('Geolocalisation'),
classes: 'descBoxes'
},
position: 1
}, tabOptions);
eventEmitter.emit('appendTab', tabPlist);
}
}
onResizeEditor = _underscore2.default.debounce(onResizeEditor, 300);
return isProviderInitalized;
};
var onRecordSelectionChanged = function onRecordSelectionChanged(params) {
if (activeProvider.accessToken === undefined) {
return;
}
var selection = params.selection;
if (map != null) {
if (shouldUseMapboxGl() && !map.loaded()) {
//refresh marker after 2 sec
setTimeout(function () {
refreshMarkers(selection);
}, 2000);
} else {
refreshMarkers(selection);
}
}
};
var onTabAdded = function onTabAdded(params) {
if (activeProvider.accessToken === undefined) {
return;
}
var origParams = params.origParams,
selection = params.selection;
if (origParams.tabProperties.id === tabContainerName) {
$container = (0, _jquery2.default)('#' + tabContainerName, parentOptions.$container);
appendMapContent({ selection: selection });
}
};
var appendMapContent = function appendMapContent(params) {
var selection = params.selection;
initializeMap(selection);
};
var initializeMap = function initializeMap(pois) {
// if not access token provided - stop mapbox loading
if (activeProvider.accessToken === undefined) {
throw new Error('MapBox require an access token');
}
__webpack_require__.e/* require.ensure */(3).then((function () {
// select geocoding provider:
mapbox = __webpack_require__(259);
leafletDraw = __webpack_require__(260);
__webpack_require__(261);
mapboxgl = __webpack_require__(66);
var MapboxClient = __webpack_require__(262);
var MapboxLanguage = __webpack_require__(263);
MapboxCircle = __webpack_require__(264);
turf = __webpack_require__(265);
$container.empty().append('<div id="' + mapUID + '" class="phrasea-popup" style="width: 100%;height:100%; position: absolute;top:0;left:0"></div>');
if (editable) {
// init add marker context menu only if 1 record is available and has no coords
if (pois.length === 1) {
var poiIndex = 0;
var selectedPoi = pois[poiIndex];
var poiCoords = haveValidCoords(selectedPoi);
if (poiCoords === false) {
mapOptions = (0, _lodash2.default)({
contextmenu: true,
contextmenuWidth: 140,
contextmenuItems: [{
text: localeService.t('mapMarkerAdd'),
callback: function callback(e) {
addMarkerOnce(e, poiIndex, selectedPoi);
}
}]
}, mapOptions);
}
}
}
if (!shouldUseMapboxGl()) {
L.mapbox.accessToken = activeProvider.accessToken;
map = L.mapbox.map(mapUID, 'mapbox.streets', mapOptions);
shouldUpdateZoom = false;
map.setView(activeProvider.defaultPosition, activeProvider.defaultZoom);
if (searchable) {
map.addControl(L.mapbox.geocoderControl('mapbox.places'));
}
var layers = {
Streets: L.mapbox.tileLayer('mapbox.streets'),
Outdoors: L.mapbox.tileLayer('mapbox.outdoors'),
Satellite: L.mapbox.tileLayer('mapbox.satellite')
};
layers.Streets.addTo(map);
L.control.layers(layers).addTo(map);
geocoder = L.mapbox.geocoder('mapbox.places');
if (drawable) {
addDrawableLayers();
}
addMarkersLayers();
refreshMarkers(pois);
} else {
mapboxgl.accessToken = activeProvider.accessToken;
if (mapboxGLDefaultPosition == null) {
mapboxGLDefaultPosition = _jquery2.default.extend([], activeProvider.defaultPosition);
mapboxGLDefaultPosition.reverse();
}
map = new mapboxgl.Map({
container: mapUID,
style: activeProvider.mapLayers[0].value,
center: mapboxGLDefaultPosition, // format different lng/lat
zoom: activeProvider.defaultZoom
});
if (!isIE()) {
//use mapboxlanguage if not IE11. Waiting for PR to be merged here https://github.com/mapbox/mapbox-gl-language/pulls
var language = new MapboxLanguage({ defaultLanguage: (0, _jquery2.default)('html').attr('lang') || 'en' });
map.addControl(language);
}
//markerMapboxGl = new mapboxgl.Marker();
shouldUpdateZoom = false;
mapboxClient = new MapboxClient(mapboxgl.accessToken);
if (drawable) {
// disable map rotation using right click + drag
map.dragRotate.disable();
// disable map rotation using touch rotation gesture
map.touchZoomRotate.disableRotation();
map.addControl(new mapboxgl.NavigationControl({
showCompass: false
}));
(0, _jquery2.default)('.map_search_dialog .ui-dialog-titlebar-close').on('click', function (event) {
event.preventDefault();
(0, _jquery2.default)('#EDIT_query').val('');
//eventEmitter.emit('shapeRemoved', {shapes: {}, drawnItems: {}});
eventEmitter.emit('updateCircleGeo', { shapes: [], drawnItems: [] });
eventEmitter.emit('updateSearchValue');
removeCircleIfExist();
removeNoticeControl();
});
(0, _jquery2.default)('.submit-geo-search-action').on('click', function (event) {
removeCircleIfExist();
removeNoticeControl();
});
addCircleDrawControl();
addNoticeControl();
addCircleGeoDrawing(drawnItems);
} else {
map.addControl(new mapboxgl.NavigationControl());
}
map.on('style.load', function () {
// Triggered when `setStyle` is called.
if (map.getStyle().name == "Mapbox Streets" || map.getStyle().name == "Mapbox Light") {
add3DBuildingsLayersGL();
}
if (geojson.hasOwnProperty('features')) addMarkersLayersGL(geojson);
});
map.on('load', function () {
var layers = map.getStyle().layers;
for (var i = 0; i < layers.length; i++) {
if (layers[i].type === 'symbol' && layers[i].layout['text-field']) {
labelLayerId = layers[i].id;
break;
}
}
geojson = {
type: 'FeatureCollection',
features: []
};
if (activeProvider.mapLayers.length > 1) {
addMapLayerControl(activeProvider.mapLayers);
}
if (!drawable) {
addMarkersLayersGL(geojson);
refreshMarkers(pois);
} else {
map.flyTo(_extends({
center: mapboxGLDefaultPosition, zoom: activeProvider.defaultZoom
}, activeProvider.transitionOptions));
//if bounds exist, move to bounds
// if (!_.isEmpty(drawnItems)) {
// map.fitBounds(drawnItems[0].originalBounds);
// } else {
// map.flyTo({
// center: mapboxGLDefaultPosition, zoom: activeProvider.defaultZoom,
// ...activeProvider.transitionOptions
// });
// }
//map.on('moveend', calculateBounds).on('zoomend', calculateBounds);
}
});
}
currentZoomLevel = activeProvider.markerDefaultZoom;
map.on('zoomend', function () {
if (shouldUpdateZoom) {
currentZoomLevel = map.getZoom();
}
(0, _jquery2.default)('#map-zoom-to-setting').val(map.getZoom());
});
map.on('dragend', function () {
var LngLat = map.getCenter();
var arr = [];
arr.push(String(LngLat['lat']));
arr.push(String(LngLat['lng']));
(0, _jquery2.default)('#map-position-to-setting').val('["' + LngLat['lat'] + '","' + LngLat['lng'] + '"]');
});
map.on('remove', function () {
console.log('remove');
});
}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
};
var removeCircleIfExist = function removeCircleIfExist() {
if (mapboxCircleCollection.length > 0) {
_underscore2.default.each(mapboxCircleCollection, function (circleObj) {
circleObj.remove();
});
}
};
var boundsTo5percentRadius = function boundsTo5percentRadius(bounds) {
// noinspection JSUnresolvedVariable
// noinspection JSCheckFunctionSignatures
return Math.round(turf.distance(bounds.getSouthWest().toArray(), bounds.getNorthEast().toArray(), { units: 'meters' }) * .05);
};
var calculateBounds = function calculateBounds() {
//get visible bounds of map
var bounds = map.getBounds();
var refactoredBoundsCoordinates = refactoredBounds(bounds);
shapesWebGl['0'] = {
type: 'rectangle',
latlng: refactoredBoundsCoordinates,
bounds: getMappedFieldsCollection(refactoredBoundsCoordinates),
originalBounds: bounds
};
eventEmitter.emit('shapeCreated', { shapes: shapesWebGl, drawnItems: shapesWebGl });
};
var refactoredBounds = function refactoredBounds(bounds) {
if (bounds !== undefined) {
var LngLat = [];
var sw = bounds._sw;
var nw = { lng: bounds._sw.lng, lat: bounds._ne.lat };
var ne = bounds._ne;
var se = { lng: bounds._ne.lng, lat: bounds._sw.lat };
var LngLat = [sw, nw, ne, se];
return LngLat;
}
};
var addNoticeControl = function addNoticeControl() {
var controlContainerList = (0, _jquery2.default)('.mapboxgl-control-container');
var $noticeButton = (0, _jquery2.default)('<button id="map-notice-btn"><img src="/assets/common/images/icons/button-information-grey.png" width="34" height="34"/></button>');
controlContainerList.append($noticeButton);
var $noticeBox = (0, _jquery2.default)('<div id="notice-box"><span class="notice-header"><img src="/assets/common/images/icons/information-grey.png" width="18" height="18" /><span class="notice-title">' + localeService.t("title notice") + '</span></span><span class="notice-desc">' + localeService.t("description notice") + '</span><span class="notice-close-btn"><img src="/assets/common/images/icons/button-close-gray.png" /></span></div>');
controlContainerList.append($noticeBox);
$noticeButton.on('click', function (event) {
$noticeBox.show();
$noticeButton.hide();
});
(0, _jquery2.default)('.notice-close-btn').on('click', function (event) {
$noticeBox.hide();
$noticeButton.show();
});
};
var removeNoticeControl = function removeNoticeControl() {
var controlContainerList = (0, _jquery2.default)('.mapboxgl-control-container');
if (controlContainerList.find('#notice-box').length > 0) {
(0, _jquery2.default)('#notice-box').remove();
}
};
var addCircleDrawControl = function addCircleDrawControl() {
// let controlContainerList = $('.mapboxgl-control-container');
// let $circleControlContainer = $('<div class="circle-control-container"></div>');
// controlContainerList.append($circleControlContainer);
// let $toggleDrawCircleButton = $('<button class="draw-icon" id="map-circle-draw-btn"><i class="fa fa-plus-square" aria-hidden="true"></i></button>');
// let $toggleRemoveCircleButton = $('<button class="draw-icon" id="map-circle-remove-btn"><i class="fa fa-trash" aria-hidden="true"></i></button>');
// $circleControlContainer.empty().append($toggleDrawCircleButton).append($toggleRemoveCircleButton);
//
// $toggleDrawCircleButton.on('click', function (event) {
// $(this).toggleClass('selected');
// shouldDrawCircle = !shouldDrawCircle;
// if (shouldDrawCircle) {
// if ($('#map-circle-remove-btn').hasClass('selected')) {
// $('#map-circle-remove-btn').removeClass('selected');
// shouldRemoveCircle = !shouldRemoveCircle;
// }
// }
// });
//
// $toggleRemoveCircleButton.on('click', function (event) {
// $(this).toggleClass('selected');
// shouldRemoveCircle = !shouldRemoveCircle;
// if (shouldRemoveCircle) {
// if ($('#map-circle-draw-btn').hasClass('selected')) {
// $('#map-circle-draw-btn').removeClass('selected');
// shouldDrawCircle = !shouldDrawCircle;
// }
// }
// });
//
// map.on('click', function (e) {
// if (shouldDrawCircle) {
// addCircle(e.lonLat, boundsTo5percentRadius(map.getBounds()));
// }
// });
map.on('contextmenu', function (e) {
addCircle(e.lngLat, boundsTo5percentRadius(map.getBounds()));
});
};
var addCircleGeoDrawing = function addCircleGeoDrawing(drawnItems) {
_underscore2.default.map(drawnItems, function (items) {
var lngLat = {};
lngLat['lng'] = items.center.lng;
lngLat['lat'] = items.center.lat;
addCircle(lngLat, items.radius);
});
};
var addCircle = function addCircle(lngLat, radius) {
var myCircle = new MapboxCircle(lngLat, radius, editableCircleOpts).once('click', function (mapMouseEvent) {
var instanceId = myCircle.__instanceId;
myCircle.remove();
mapboxCircleCollection = _underscore2.default.reject(mapboxCircleCollection, function (circleObj) {
return circleObj.__instanceId === instanceId;
});
eventEmitter.emit('updateCircleGeo', {
shapes: mapboxCircleCollection,
drawnItems: mapboxCircleCollection
});
}).on('centerchanged', function (circleObj) {
eventEmitter.emit('updateCircleGeo', {
shapes: mapboxCircleCollection,
drawnItems: mapboxCircleCollection
});
}).on('radiuschanged', function (circleObj) {
eventEmitter.emit('updateCircleGeo', {
shapes: mapboxCircleCollection,
drawnItems: mapboxCircleCollection
});
}).addTo(map);
mapboxCircleCollection.push(myCircle);
eventEmitter.emit('updateCircleGeo', { shapes: mapboxCircleCollection, drawnItems: mapboxCircleCollection });
};
var addMapLayerControl = function addMapLayerControl(layerArray) {
var controlContainerList = (0, _jquery2.default)('.mapboxgl-control-container');
_underscore2.default.each(controlContainerList, function (controlContainer) {
if ((0, _jquery2.default)(controlContainer).find('.map-selection-container').length > 0) {
(0, _jquery2.default)(controlContainer).find('.map-selection-container').remove();
}
var mapSelectionContainer = (0, _jquery2.default)('<div class="dropdown map-selection-container"><button class="map-drop-btn"><i class="fa fa-map" aria-hidden="true"></i></button><div id="mapSelectionDropDown" class="map-dropdown-content"></div></div>');
var $mapSelectionDropDown = mapSelectionContainer.find('#mapSelectionDropDown');
(0, _jquery2.default)(controlContainer).append(mapSelectionContainer);
(0, _jquery2.default)(controlContainer).on('click', 'button', function (event) {
$mapSelectionDropDown.get(0).classList.toggle("show");
});
var map_list_div = document.createElement('div');
_underscore2.default.each(layerArray, function (layer, index) {
var div_layer = document.createElement('div');
//add checked attr for first element
var isChecked = index == 0 ? "checked=checked" : "";
(0, _jquery2.default)(div_layer).append('<label><input id=' + layer.name + ' name="mapradio" type=\'radio\' value=' + layer.value + ' ' + isChecked + '>\n <span for=' + layer.name + '>' + layer.name + '</span></label>');
(0, _jquery2.default)(map_list_div).append(div_layer);
});
$mapSelectionDropDown.empty().append(map_list_div);
(0, _jquery2.default)(controlContainer).on('click', 'input[name="mapradio"]', function (event) {
switchLayer((0, _jquery2.default)(event.target));
});
(0, _jquery2.default)('body').on('click', function (event) {
if ((0, _jquery2.default)(event.target).is('button.map-drop-btn') || (0, _jquery2.default)(event.target).is('button.map-drop-btn i')) {
return;
} else {
var dropdowns = $mapSelectionDropDown;
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
});
});
};
var switchLayer = function switchLayer($elem) {
map.setStyle($elem.val());
};
var addDrawableLayers = function addDrawableLayers() {
if (localeService.getLocale() === 'fr') {
L.drawLocal = _fr2.default;
}
// should restore drawn items?
// user.getPreferences
var drawingGroup = void 0;
drawingGroup = new L.FeatureGroup();
map.addLayer(drawingGroup);
// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw({
draw: {
circle: false,
polyline: false,
polygon: false,
marker: false,
position: 'topleft',
rectangle: {
//title: 'Draw a sexy polygon!',
allowIntersection: false,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#0c4554'
},
showArea: true
}
},
edit: {
featureGroup: drawingGroup
}
});
var shapesDrawned = {};
map.addControl(drawControl);
map.on('draw:created', function (event) {
var type = event.layerType;
var layer = event.layer;
var layerId = drawingGroup.getLayerId(layer);
shapesDrawned[layerId] = {
type: type,
options: layer.options,
latlng: layer.getLatLngs(),
bounds: getMappedFieldsCollection(layer.getLatLngs())
};
drawingGroup.addLayer(layer);
eventEmitter.emit('shapeCreated', { shapes: shapesDrawned, drawnItems: shapesDrawned });
});
map.on('draw:edited', function (event) {
var layers = event.layers;
layers.eachLayer(function (layer) {
var layerId = drawingGroup.getLayerId(layer);
// get type from drawed shape:
var currentType = shapesDrawned[layerId].type;
shapesDrawned[layerId] = (0, _lodash2.default)(shapesDrawned[layerId], {
options: layer.options,
latlng: layer.getLatLngs(),
bounds: getMappedFieldsCollection(layer.getLatLngs())
});
});
eventEmitter.emit('shapeEdited', { shapes: shapesDrawned, drawnItems: shapesDrawned });
});
map.on('draw:deleted', function (event) {
var layers = event.layers;
layers.eachLayer(function (layer) {
var layerId = drawingGroup.getLayerId(layer);
delete shapesDrawned[layerId];
});
eventEmitter.emit('shapeRemoved', { shapes: shapesDrawned, drawnItems: shapesDrawned });
});
// draw serialized items:
applyDrawings(drawnItems, drawingGroup);
};
/***
* Draw serialized shapes
* @param shapesDrawned
* @param drawingGroup
*/
var applyDrawings = function applyDrawings(shapesDrawned, drawingGroup) {
for (var shapeIndex in shapesDrawned) {
if (shapesDrawned.hasOwnProperty(shapeIndex)) {
var shape = shapesDrawned[shapeIndex];
var newShape = L.rectangle(shape.latlng, shape.options);
var newShapeType = '';
switch (shape.type) {
case 'rectangle':
newShape = L.rectangle(shape.latlng, shape.options);
newShapeType = L.Draw.Rectangle.TYPE;
break;
default:
newShape = L.rectangle(shape.latlng, shape.options);
newShapeType = L.Draw.Rectangle.TYPE;
}
// start editor for new shape:
newShape.editing.enable();
drawingGroup.addLayer(newShape);
// fire created event manually:
map.fire('draw:created', { layer: newShape, layerType: newShapeType });
newShape.editing.disable();
}
}
};
var addMarkerOnce = function addMarkerOnce(e, poiIndex, poi) {
// inject coords into poi's fields:
var mappedCoords = getMappedFields(e.latlng);
var pois = [(0, _lodash2.default)(poi, mappedCoords)];
refreshMarkers(pois).then(function () {
// broadcast event:
var wrappedMappedFields = {};
// values needs to be wrapped in a array:
for (var fieldIndex in mappedCoords) {
if (mappedCoords.hasOwnProperty(fieldIndex)) {
wrappedMappedFields[fieldIndex] = [mappedCoords[fieldIndex]];
}
}
var presets = {
fields: wrappedMappedFields //presetFields
};
map.contextmenu.disable();
eventEmitter.emit('recordEditor.addPresetValuesFromDataSource', { data: presets, recordIndex: poiIndex });
});
};
var add3DBuildingsLayersGL = function add3DBuildingsLayersGL() {
map.addLayer({
'id': '3d-buildings',
'source': 'composite',
'source-layer': 'building',
'filter': ['==', 'extrude', 'true'],
'type': 'fill-extrusion',
'minzoom': 15,
'paint': {
'fill-extrusion-color': '#aaa',
// use an 'interpolate' expression to add a smooth transition effect to the
// buildings as the user zooms in
'fill-extrusion-height': ["interpolate", ["linear"], ["zoom"], 15, 0, 15.05, ["get", "height"]],
'fill-extrusion-base': ["interpolate", ["linear"], ["zoom"], 15, 0, 15.05, ["get", "min_height"]],
'fill-extrusion-opacity': .6
}
}, labelLayerId);
};
var addMarkersLayersGL = function addMarkersLayersGL(geojson) {
map.addSource('data', {
type: 'geojson',
data: geojson
});
map.addLayer({
id: 'points',
source: 'data',
type: 'symbol',
layout: {
"icon-image": "star-15",
"icon-size": 1.5
}
});
};
var addMarkersLayers = function addMarkersLayers() {
if (featureLayer !== null) {
featureLayer.clearLayers();
} else {
featureLayer = L.mapbox.featureLayer([], {
pointToLayer: function pointToLayer(feature, latlng) {
if (feature.properties.radius !== undefined) {
// L.circleMarker() draws a circle with fixed radius in pixels.
// To draw a circle overlay with a radius in meters, use L.circle()
return L.circleMarker(latlng, { radius: feature.properties.radius || 10 });
} else {
var marker = __webpack_require__(80); //L.marker(feature);
return marker.style(feature, latlng, { accessToken: activeProvider.accessToken });
}
}
}).addTo(map);
}
};
var refreshMarkers = function refreshMarkers(pois) {
return buildGeoJson(pois).then(function (geoJsonPoiCollection) {
if (map != null) {
if (shouldUseMapboxGl()) {
geojson = {
type: 'FeatureCollection',
features: geoJsonPoiCollection
};
map.getSource('data').setData(geojson);
var markerGlColl = (0, _markerGLCollection2.default)(services);
markerGlColl.initialize({ map: map, geojson: geojson, editable: editable });
if (geojson.features.length > 0) {
shouldUpdateZoom = true;
// var popup = new mapboxgl.Popup()
// .setText(geojson.features[0].properties.title);
//markerMapboxGl.setLngLat(geojson.features[0].geometry.coordinates).setPopup(popup).addTo(map);
map.flyTo(_extends({
center: geojson.features[0].geometry.coordinates, zoom: currentZoomLevel
}, activeProvider.transitionOptions));
var position = {};
position.lng = geojson.features[0].geometry.coordinates[0];
position.lat = geojson.features[0].geometry.coordinates[1];
updateMarkerPosition(geojson.features[0].properties.recordIndex, position);
} else {
shouldUpdateZoom = false;
//markerMapboxGl.setLngLat(activeProvider.defaultPosition).addTo(map);
map.flyTo(_extends({
center: mapboxGLDefaultPosition, zoom: activeProvider.defaultZoom
}, activeProvider.transitionOptions));
}
} else {
addMarkersLayers();
var markerColl = (0, _markerCollection2.default)(services);
markerColl.initialize({ map: map, featureLayer: featureLayer, geoJsonPoiCollection: geoJsonPoiCollection, editable: editable });
if (featureLayer.getLayers().length > 0) {
shouldUpdateZoom = true;
map.fitBounds(featureLayer.getBounds(), { maxZoom: currentZoomLevel });
var position = {};
position.lng = featureLayer.getGeoJSON()[0].geometry.coordinates[0];
position.lat = featureLayer.getGeoJSON()[0].geometry.coordinates[1];
updateMarkerPosition(featureLayer.getGeoJSON()[0].properties.recordIndex, position);
console.log('ato');
} else {
// set default position
shouldUpdateZoom = false;
map.setView(activeProvider.defaultPosition, activeProvider.defaultZoom);
}
}
}
});
};
/**
* build geoJson features return as a promise
* @param pois
* @returns {*}
*/
var buildGeoJson = function buildGeoJson(pois) {
var geoJsonPoiCollection = [];
var asyncQueries = [];
var geoJsonPromise = _jquery2.default.Deferred();
for (var poiIndex in pois) {
var poi = pois[poiIndex];
var poiCoords = extractCoords(poi);
var poiTitle = poi.FileName || poi.Filename || poi.Title || poi.NomDeFichier;
if (poiCoords[0] !== false && poiCoords[1] !== false) {
geoJsonPoiCollection.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: poiCoords
},
properties: {
recordIndex: poiIndex,
'marker-color': '0c4554',
'marker-zoom': currentZoomLevel,
title: '' + poiTitle
}
});
} else {
// coords are not available, fallback on city/province/country if available
var query = '';
query += poi.City !== undefined && poi.City !== null ? poi.City : '';
query += poi.Country !== undefined && poi.Country !== null ? ', ' + poi.Country + ' ' : '';
if (query !== '') {
if (shouldUseMapboxGl()) {
getDataForMapboxGl(asyncQueries, query, poiIndex, poiTitle, geoJsonPoiCollection);
} else {
getDataForMapbox(asyncQueries, query, poiIndex, poiTitle, geoJsonPoiCollection);
}
}
}
}
if (asyncQueries.length > 0) {
_jquery2.default.when.apply(null, asyncQueries).done(function () {
geoJsonPromise.resolve(geoJsonPoiCollection);
});
} else {
geoJsonPromise.resolve(geoJsonPoiCollection);
}
return geoJsonPromise.promise();
};
var getDataForMapboxGl = function getDataForMapboxGl(asyncQueries, query, poiIndex, poiTitle, geoJsonPoiCollection) {
var geoPromise = _jquery2.default.Deferred();
mapboxClient.geocodeForward(query, function (err, data) {
// take the first feature if exists
if (data !== undefined) {
if (data.features.length > 0) {
var bestResult = data.features[0];
bestResult.properties.recordIndex = poiIndex;
bestResult.properties['marker-zoom'] = currentZoomLevel;
bestResult.properties['marker-color'] = "0c4554";
bestResult.properties.title = '' + poiTitle;
geoJsonPoiCollection.push(bestResult);
}
}
geoPromise.resolve(geoJsonPoiCollection);
});
asyncQueries.push(geoPromise);
};
var getDataForMapbox = function getDataForMapbox(asyncQueries, query, poiIndex, poiTitle, geoJsonPoiCollection) {
var geoPromise = _jquery2.default.Deferred();
geocoder.query(query, function (err, data) {
// take the first feature if exists
if (data.results !== undefined) {
if (data.results.features.length > 0) {
/*let circleArea = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: data.results.features[0].center //[[ data.bounds ]]
},
properties: {
title: `${poi.FileName}`
}
};
circleArea.properties['marker-zoom'] = 5;
circleArea.properties.radius = 50;
geoJsonPoiCollection.push(circleArea);*/
var bestResult = data.results.features[0];
bestResult.properties.recordIndex = poiIndex;
bestResult.properties['marker-zoom'] = currentZoomLevel;
bestResult.properties.title = '' + poiTitle;
geoJsonPoiCollection.push(bestResult);
}
}
geoPromise.resolve(geoJsonPoiCollection);
});
asyncQueries.push(geoPromise);
};
var extractCoords = function extractCoords(poi) {
if (poi !== undefined) {
return [activeProvider.fieldPosition.longitude(poi), activeProvider.fieldPosition.latitude(poi)];
}
return [false, false];
};
var haveValidCoords = function haveValidCoords(poi) {
if (poi !== undefined) {
return activeProvider.fieldPosition.longitude(poi) && activeProvider.fieldPosition.latitude(poi);
}
return false;
};
var onResizeEditor = function onResizeEditor() {
if (activeProvider.accessToken === undefined) {
return;
}
if (map !== null) {
if (shouldUseMapboxGl()) {
map.resize();
if (geojson.hasOwnProperty('features') && geojson.features.length > 0) {
shouldUpdateZoom = true;
//markerMapboxGl.setLngLat(geojson.features[0].geometry.coordinates).addTo(map);
map.flyTo(_extends({
center: geojson.features[0].geometry.coordinates, zoom: currentZoomLevel
}, activeProvider.transitionOptions));
} else {
shouldUpdateZoom = false;
//markerMapboxGl.setLngLat(activeProvider.defaultPosition).addTo(map);
map.flyTo(_extends({
center: mapboxGLDefaultPosition, zoom: activeProvider.defaultZoom
}, activeProvider.transitionOptions));
}
} else {
map.invalidateSize();
if (featureLayer.getLayers().length > 0) {
shouldUpdateZoom = true;
map.fitBounds(featureLayer.getBounds(), { maxZoom: currentZoomLevel });
} else {
// set default position
shouldUpdateZoom = false;
map.setView(activeProvider.defaultPosition, activeProvider.defaultZoom);
}
}
}
};
var onMarkerChange = function onMarkerChange(params) {
var marker = params.marker,
position = params.position;
if (editable) {
updateMarkerPosition(marker.feature.properties.recordIndex, position);
}
};
var updateMarkerPosition = function updateMarkerPosition(recordIndex, position) {
var mappedFields = getMappedFields(position);
var wrappedMappedFields = {};
// values needs to be wrapped in a array:
for (var mappedFieldIndex in mappedFields) {
if (mappedFields.hasOwnProperty(mappedFieldIndex)) {
wrappedMappedFields[mappedFieldIndex] = [mappedFields[mappedFieldIndex]];
}
}
var presets = {
fields: wrappedMappedFields //presetFields
};
eventEmitter.emit('recordEditor.addPresetValuesFromDataSource', { data: presets, recordIndex: recordIndex });
};
var getMappedFields = function getMappedFields(position) {
var fieldMapping = activeProvider.provider['position-fields'] !== undefined ? activeProvider.provider['position-fields'] : [];
var mappedFields = {};
if (fieldMapping.length > 0) {
_underscore2.default.each(fieldMapping, function (mapping) {
// latitude and longitude are combined in a composite field
if (mapping.type === 'latlng') {
mappedFields[mapping.name] = position.lat + ' ' + position.lng;
} else if (mapping.type === 'lat') {
mappedFields[mapping.name] = '' + position.lat;
} else if (mapping.type === 'lon') {
mappedFields[mapping.name] = '' + position.lng;
}
});
} else {
mappedFields["meta.Latitude"] = '' + position.lat;
mappedFields["meta.Longitude"] = '' + position.lng;
}
return mappedFields;
};
var getMappedFieldsCollection = function getMappedFieldsCollection(positions) {
var mappedPositions = [];
for (var positionIndex in positions) {
if (positions.hasOwnProperty(positionIndex)) {
mappedPositions.push(getMappedFields(positions[positionIndex]));
}
}
return mappedPositions;
};
var shouldUseMapboxGl = function shouldUseMapboxGl() {
if (activeProvider.defaultMapProvider === "mapboxWebGL" && mapboxgl !== undefined && mapboxgl.supported()) {
return true;
}
return false;
};
var isIE = function isIE() {
var ua = navigator.userAgent;
/* MSIE used to detect old browsers and Trident used to newer ones*/
var is_ie = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
return is_ie;
};
eventEmitter.listenAll({
'recordSelection.changed': onRecordSelectionChanged,
'appendTab.complete': onTabAdded,
/* eslint-disable quote-props */
'markerChange': onMarkerChange,
'tabChange': onResizeEditor
});
return { initialize: initialize, appendMapContent: appendMapContent };
};
exports.default = leafletMap;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FieldCollection = function () {
function FieldCollection(fieldsList) {
_classCallCheck(this, FieldCollection);
this.fields = fieldsList;
}
_createClass(FieldCollection, [{
key: 'getFields',
value: function getFields() {
return this.fields;
}
}, {
key: 'getFieldOptionsById',
value: function getFieldOptionsById(meta_struct_id) {
/*var name = this.fields[meta_struct_id].name;
var label = this.fields[meta_struct_id].label;
var multi = ;
var required = this.fields[meta_struct_id].required;
var readonly = this.fields[meta_struct_id].readonly;
var maxLength = this.fields[meta_struct_id].maxLength;
var minLength = this.fields[meta_struct_id].minLength;
var type = this.fields[meta_struct_id].type;
var separator = this.fields[meta_struct_id].separator;
var vocabularyControl = this.fields[meta_struct_id].vocabularyControl || null;
var vocabularyRestricted = this.fields[meta_struct_id].vocabularyRestricted || null;*/
return {
multi: this.fields[meta_struct_id].multi,
required: this.fields[meta_struct_id].required,
readonly: this.fields[meta_struct_id].readonly,
maxLength: this.fields[meta_struct_id].maxLength,
minLength: this.fields[meta_struct_id].minLength,
type: this.fields[meta_struct_id].type,
separator: this.fields[meta_struct_id].separator,
vocabularyControl: this.fields[meta_struct_id].vocabularyControl || null,
vocabularyRestricted: this.fields[meta_struct_id].vocabularyRestricted || null
};
}
}, {
key: 'setActiveField',
value: function setActiveField(metaStructId) {
this.metaStructId = metaStructId;
}
}, {
key: 'getActiveFieldIndex',
value: function getActiveFieldIndex() {
return this.metaStructId === undefined ? '?' : this.metaStructId;
}
}, {
key: 'getActiveField',
value: function getActiveField() {
return this.fields[this.getActiveFieldIndex()];
}
}, {
key: 'getFieldByIndex',
value: function getFieldByIndex() {
var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (this.fields[id] !== undefined) {
return this.fields[id];
}
return false;
}
}, {
key: 'getFieldByName',
value: function getFieldByName(fieldName) {
var foundField = false;
for (var field in this.fields) {
if (this.fields[field].name === fieldName) {
foundField = this.fields[field];
}
}
return foundField;
}
}, {
key: 'getFieldStatus',
value: function getFieldStatus() {
var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
}
}, {
key: 'updateField',
value: function updateField(id, data) {
if (this.fields[id] !== undefined) {
this.fields[id] = (0, _lodash2.default)(this.fields[id], data);
return this.fields[id];
}
}
}]);
return FieldCollection;
}();
exports.default = FieldCollection;
/***/ }),
/* 52 */,
/* 53 */,
/* 54 */,
/* 55 */,
/* 56 */,
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var lazyload = __webpack_require__(58);
var publication = function publication(services) {
var ajaxState = {
query: null,
isRunning: false
};
var $answers = void 0;
var curPage = void 0;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize() {
$answers = (0, _jquery2.default)('#answers');
// refresh current view
$answers.on('click', '.feed_reload', function (event) {
event.preventDefault();
fetchPublications(curPage);
});
// navigate to a specific feed
$answers.on('click', '.ajax_answers', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
var append = $this.hasClass('append');
var noScroll = $this.hasClass('no_scroll');
_fetchRemote((0, _jquery2.default)(event.currentTarget).attr('href'), {}).then(function (data) {
if (!append) {
$answers.empty();
if (!noScroll) {
$answers.scrollTop(0);
}
$answers.append(data);
$answers.find('img.lazyload').lazyload({
container: $answers
});
} else {
(0, _jquery2.default)('.see_more.loading', $answers).remove();
$answers.append(data);
$answers.find('img.lazyload').lazyload({
container: $answers
});
if (!noScroll) {
$answers.animate({
scrollTop: $answers.scrollTop() + $answers.innerHeight() - 80
});
}
}
appEvents.emit('search.doAfterSearch');
});
});
// subscribe_rss
$answers.on('click', '.subscribe_rss', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
var renew = false;
/*if (typeof (renew) === 'undefined') {
renew = 'false';
} else {
renew = renew ? 'true' : 'false';
}*/
var buttons = {};
buttons[localeService.t('renewRss')] = function () {
$this.trigger({
type: 'click',
renew: true
});
};
buttons[localeService.t('fermer')] = function () {
(0, _jquery2.default)('#DIALOG').empty().dialog('destroy');
};
event.stopPropagation();
_jquery2.default.ajax({
type: 'GET',
url: $this.attr('href') + (event.renew === true ? '?renew=true' : ''),
dataType: 'json',
success: function success(data) {
if (data.texte !== false && data.titre !== false) {
if ((0, _jquery2.default)('#DIALOG').data('ui-dialog')) {
(0, _jquery2.default)('#DIALOG').dialog('destroy');
}
(0, _jquery2.default)('#DIALOG').attr('title', data.titre).empty().append(data.texte).dialog({
autoOpen: false,
closeOnEscape: true,
resizable: false,
draggable: false,
modal: true,
buttons: buttons,
width: 650,
height: 250,
overlay: {
backgroundColor: '#000',
opacity: 0.7
},
open: function open() {
(0, _jquery2.default)('#copy-feed').on('click', function (event) {
event.preventDefault();
var copyText = document.getElementById('input-select-copy');
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
document.execCommand('copy');
});
}
}).dialog('open');
}
}
});
});
// edit a feed
$answers.on('click', '.feed .entry a.feed_edit', function () {
var $this = (0, _jquery2.default)(this);
_jquery2.default.ajax({
type: 'GET',
url: $this.attr('href'),
dataType: 'html',
success: function success(data) {
return openModal(data);
}
});
return false;
});
// remove a feed
$answers.on('click', '.feed .entry a.feed_delete', function () {
if (!confirm('etes vous sur de vouloir supprimer cette entree ?')) {
return false;
}
var $this = (0, _jquery2.default)(this);
_jquery2.default.ajax({
type: 'POST',
url: $this.attr('href'),
dataType: 'json',
success: function success(data) {
if (data.error === false) {
var $entry = $this.closest('.entry');
$entry.animate({
height: 0,
opacity: 0
}, function () {
$entry.remove();
});
} else {
alert(data.message);
}
}
});
return false;
});
$answers.on('mouseover', '.feed .entry', function () {
(0, _jquery2.default)(this).addClass('hover');
});
$answers.on('mouseout', '.feed .entry', function () {
(0, _jquery2.default)(this).removeClass('hover');
});
$answers.on('click', '.see_more a', function (event) {
var $see_more = (0, _jquery2.default)(this).closest('.see_more');
$see_more.addClass('loading');
});
};
var _fetchRemote = function _fetchRemote(url, data) {
var page = 0;
if (data.page === undefined) {
page = data.page;
}
ajaxState.query = _jquery2.default.ajax({
type: 'GET',
url: url,
dataType: 'html',
data: data,
beforeSend: function beforeSend() {
if (ajaxState.isRunning && ajaxState.query.abort) {
ajaxState.query.abort();
}
if (page === 0) {
appEvents.emit('search.doClearSearch');
}
ajaxState.isRunning = true;
$answers.addClass('loading');
},
error: function error() {
ajaxState.isRunning = false;
$answers.removeClass('loading');
},
timeout: function timeout() {
ajaxState.isRunning = false;
$answers.removeClass('loading');
},
success: function success(data) {
ajaxState.isRunning = false;
}
});
return ajaxState.query;
};
function checkFeedVFieldError() {
if ((0, _jquery2.default)('.feed_warning').hasClass('alert-error')) {
(0, _jquery2.default)('.ui-dialog-buttons').find('button').eq(1).prop('disabled', true);
} else {
(0, _jquery2.default)('.ui-dialog-buttons').find('button').eq(1).prop('disabled', false);
}
}
function feedFieldValidator(field, feedWarning, length) {
field.on('change keyup', function () {
if ((0, _jquery2.default)(this).val().length > length) {
feedWarning.addClass('alert alert-error');
} else {
feedWarning.removeClass('alert alert-error');
}
checkFeedVFieldError();
});
}
var openModal = function openModal(data) {
var buttons = {};
var modal = _dialog2.default.create(services, {
size: 'Full',
closeOnEscape: true,
closeButton: true,
title: localeService.t('Publication')
});
//Add custom class to dialog wrapper
(0, _jquery2.default)('.dialog-Full').closest('.ui-dialog').addClass('black-dialog-wrap publish-dialog');
modal.setContent(data);
buttons[localeService.t('valider')] = onSubmitPublication;
modal.setOption('buttons', buttons);
var $feeds_item = (0, _jquery2.default)('.feeds .feed', modal.getDomElement());
var $form = (0, _jquery2.default)('form.main_form', modal.getDomElement());
var $feed_title_field = (0, _jquery2.default)('#feed_add_title', modal.getDomElement());
var $feed_title_warning = (0, _jquery2.default)('.feed_title_warning', modal.getDomElement());
var $feed_subtitle_field = (0, _jquery2.default)('#feed_add_subtitle', modal.getDomElement());
var $feed_subtitle_warning = (0, _jquery2.default)('.feed_subtitle_warning', modal.getDomElement());
feedFieldValidator($feed_title_field, $feed_title_warning, 128);
feedFieldValidator($feed_subtitle_field, $feed_subtitle_warning, 1024);
$feeds_item.bind('click', function () {
$feeds_item.removeClass('selected');
(0, _jquery2.default)(this).addClass('selected');
(0, _jquery2.default)('input[name="feed_id"]', $form).val((0, _jquery2.default)('input', this).val());
}).hover(function () {
(0, _jquery2.default)(this).addClass('hover');
}, function () {
(0, _jquery2.default)(this).removeClass('hover');
});
$form.bind('submit', function () {
return false;
});
var formMode = 'create';
// is edit mode?
if ((0, _jquery2.default)('input[name="item_id"]').length > 0) {
formMode = 'edit';
}
(0, _jquery2.default)('#modal_feed .record_list').sortable({
placeholder: 'ui-state-highlight',
stop: function stop(event, ui) {
var lst = [];
(0, _jquery2.default)('#modal_feed .record_list .sortable form').each(function (i, el) {
if (formMode === 'create') {
lst.push((0, _jquery2.default)('input[name="sbas_id"]', el).val() + '_' + (0, _jquery2.default)('input[name="record_id"]', el).val());
} else {
lst.push((0, _jquery2.default)('input[name="item_id"]', el).val());
}
});
(0, _jquery2.default)('#modal_feed form.main_form input[name="lst"]').val(lst.join(';'));
}
});
return;
};
var onSubmitPublication = function onSubmitPublication() {
var $dialog = _dialog2.default.get(1);
var error = false;
var $form = (0, _jquery2.default)('form.main_form', $dialog.getDomElement());
(0, _jquery2.default)('.required_text', $form).each(function (i, el) {
if (_jquery2.default.trim((0, _jquery2.default)(el).val()) === '') {
(0, _jquery2.default)(el).addClass('error');
error = true;
}
});
if (error) {
alert(localeService.t('feed_require_fields'));
}
if ((0, _jquery2.default)('input[name="feed_id"]', $form).val() === '') {
alert(localeService.t('feed_require_feed'));
error = true;
}
if (error) {
return false;
}
_jquery2.default.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {
(0, _jquery2.default)('button', $dialog.getDomElement()).prop('disabled', true);
},
error: function error() {
(0, _jquery2.default)('button', $dialog.getDomElement()).prop('disabled', false);
},
timeout: function timeout() {
(0, _jquery2.default)('button', $dialog.getDomElement()).prop('disabled', false);
},
success: function success(data) {
(0, _jquery2.default)('.state-navigation').trigger('click');
(0, _jquery2.default)('button', $dialog.getDomElement()).prop('disabled', false);
if (data.error === true) {
alert(data.message);
return;
}
if ((0, _jquery2.default)('form.main_form', $dialog.getDomElement()).hasClass('entry_update')) {
var id = (0, _jquery2.default)('form input[name="entry_id"]', $dialog.getDomElement()).val();
var container = (0, _jquery2.default)('#entry_' + id);
container.replaceWith(data.datas);
container.hide().fadeIn();
// @TODO: something was happening here
$answers.find('img.lazyload').lazyload({
container: $answers
});
}
$dialog.close(1);
}
});
};
var fetchPublications = function fetchPublications(page) {
if (page === undefined && $answers !== undefined) {
// @TODO $answers can be undefined
$answers.empty();
}
if ($answers !== undefined) {
curPage = page;
return _fetchRemote(url + 'prod/feeds/', {
page: page
}).then(function (data) {
(0, _jquery2.default)('.next_publi_link', $answers).remove();
$answers.append(data);
$answers.find('img.lazyload').lazyload({
container: $answers
});
appEvents.emit('search.doAfterSearch');
if (page > 0) {
$answers.stop().animate({
scrollTop: $answers.scrollTop() + $answers.height()
}, 700);
}
return;
});
}
};
var publishRecords = function publishRecords(type, value) {
var options = {
lst: '',
ssel: '',
act: ''
};
switch (type) {
case 'IMGT':
case 'CHIM':
options.lst = value;
break;
case 'STORY':
options.story = value;
break;
case 'SSTT':
options.ssel = value;
break;
default:
}
_jquery2.default.post(url + 'prod/feeds/requestavailable/', options, function (data) {
return openModal(data);
});
return;
};
var activatePublicationState = function activatePublicationState() {
appEvents.emit('publication.fetch');
};
appEvents.listenAll({
'publication.activeState': activatePublicationState,
'publication.fetch': fetchPublications
});
return {
initialize: initialize,
fetchPublications: fetchPublications,
publishRecords: publishRecords,
openModal: openModal
};
};
exports.default = publication;
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/*** IMPORTS FROM imports-loader ***/
(function() {
/*!
* Lazy Load - jQuery plugin for lazy loading images
*
* Copyright (c) 2007-2015 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://www.appelsiini.net/projects/lazyload
*
* Version: 1.9.7
*
*/
(function($, window, document, undefined) {
var $window = $(window);
$.fn.lazyload = function(options) {
var elements = this;
var $container;
var settings = {
threshold : 0,
failure_limit : 0,
event : "scroll",
effect : "show",
container : window,
data_attribute : "original",
skip_invisible : false,
appear : null,
load : null,
placeholder : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC"
};
function update() {
var counter = 0;
elements.each(function() {
var $this = $(this);
if (settings.skip_invisible && !$this.is(":visible")) {
return;
}
if ($.abovethetop(this, settings) ||
$.leftofbegin(this, settings)) {
/* Nothing. */
} else if (!$.belowthefold(this, settings) &&
!$.rightoffold(this, settings)) {
$this.trigger("appear");
/* if we found an image we'll load, reset the counter */
counter = 0;
} else {
if (++counter > settings.failure_limit) {
return false;
}
}
});
}
if(options) {
/* Maintain BC for a couple of versions. */
if (undefined !== options.failurelimit) {
options.failure_limit = options.failurelimit;
delete options.failurelimit;
}
if (undefined !== options.effectspeed) {
options.effect_speed = options.effectspeed;
delete options.effectspeed;
}
$.extend(settings, options);
}
/* Cache container as jQuery as object. */
$container = (settings.container === undefined ||
settings.container === window) ? $window : $(settings.container);
/* Fire one scroll event per scroll. Not one scroll event per image. */
if (0 === settings.event.indexOf("scroll")) {
$container.bind(settings.event, function() {
return update();
});
}
this.each(function() {
var self = this;
var $self = $(self);
self.loaded = false;
/* If no src attribute given use data:uri. */
if ($self.attr("src") === undefined || $self.attr("src") === false) {
if ($self.is("img")) {
$self.attr("src", settings.placeholder);
}
}
/* When appear is triggered load original image. */
$self.one("appear", function() {
if (!this.loaded) {
if (settings.appear) {
var elements_left = elements.length;
settings.appear.call(self, elements_left, settings);
}
$("<img />")
.bind("load", function() {
var original = $self.attr("data-" + settings.data_attribute);
$self.hide();
if ($self.is("img")) {
$self.attr("src", original);
} else {
$self.css("background-image", "url('" + original + "')");
}
$self[settings.effect](settings.effect_speed);
self.loaded = true;
/* Remove image from array so it is not looped next time. */
var temp = $.grep(elements, function(element) {
return !element.loaded;
});
elements = $(temp);
if (settings.load) {
var elements_left = elements.length;
settings.load.call(self, elements_left, settings);
}
})
.attr("src", $self.attr("data-" + settings.data_attribute));
}
});
/* When wanted event is triggered load original image */
/* by triggering appear. */
if (0 !== settings.event.indexOf("scroll")) {
$self.bind(settings.event, function() {
if (!self.loaded) {
$self.trigger("appear");
}
});
}
});
/* Check if something appears when window is resized. */
$window.bind("resize", function() {
update();
});
/* With IOS5 force loading images when navigating with back button. */
/* Non optimal workaround. */
if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) {
$window.bind("pageshow", function(event) {
if (event.originalEvent && event.originalEvent.persisted) {
elements.each(function() {
$(this).trigger("appear");
});
}
});
}
/* Force initial check if images should appear. */
$(document).ready(function() {
update();
});
return this;
};
/* Convenience methods in jQuery namespace. */
/* Use as $.belowthefold(element, {threshold : 100, container : window}) */
$.belowthefold = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop();
} else {
fold = $(settings.container).offset().top + $(settings.container).height();
}
return fold <= $(element).offset().top - settings.threshold;
};
$.rightoffold = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.width() + $window.scrollLeft();
} else {
fold = $(settings.container).offset().left + $(settings.container).width();
}
return fold <= $(element).offset().left - settings.threshold;
};
$.abovethetop = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.scrollTop();
} else {
fold = $(settings.container).offset().top;
}
return fold >= $(element).offset().top + settings.threshold + $(element).height();
};
$.leftofbegin = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.scrollLeft();
} else {
fold = $(settings.container).offset().left;
}
return fold >= $(element).offset().left + settings.threshold + $(element).width();
};
$.inviewport = function(element, settings) {
return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) &&
!$.belowthefold(element, settings) && !$.abovethetop(element, settings);
};
/* Custom selectors for your convenience. */
/* Use as $("img:below-the-fold").something() or */
/* $("img").filter(":below-the-fold").something() which is faster */
$.extend($.expr[":"], {
"below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
"above-the-top" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
"in-viewport" : function(a) { return $.inviewport(a, {threshold : 0}); },
/* Maintain BC for couple of versions. */
"above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-fold" : function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-fold" : function(a) { return !$.rightoffold(a, {threshold : 0}); }
});
})(jQuery, window, document);
}.call(window));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */
!function() {
'use strict'
var re = {
not_string: /[^s]/,
not_bool: /[^t]/,
not_type: /[^T]/,
not_primitive: /[^v]/,
number: /[diefg]/,
numeric_arg: /[bcdiefguxX]/,
json: /[j]/,
not_json: /[^j]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
sign: /^[\+\-]/
}
function sprintf(key) {
// `arguments` is not an array, but should be fine for this call
return sprintf_format(sprintf_parse(key), arguments)
}
function vsprintf(fmt, argv) {
return sprintf.apply(null, [fmt].concat(argv || []))
}
function sprintf_format(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, match, pad, pad_character, pad_length, is_positive, sign
for (i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === 'string') {
output += parse_tree[i]
}
else if (Array.isArray(parse_tree[i])) {
match = parse_tree[i] // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor]
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k]))
}
arg = arg[match[2][k]]
}
}
else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]]
}
else { // positional argument (implicit)
arg = argv[cursor++]
}
if (re.not_type.test(match[8]) && re.not_primitive.test(match[8]) && arg instanceof Function) {
arg = arg()
}
if (re.numeric_arg.test(match[8]) && (typeof arg !== 'number' && isNaN(arg))) {
throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
}
if (re.number.test(match[8])) {
is_positive = arg >= 0
}
switch (match[8]) {
case 'b':
arg = parseInt(arg, 10).toString(2)
break
case 'c':
arg = String.fromCharCode(parseInt(arg, 10))
break
case 'd':
case 'i':
arg = parseInt(arg, 10)
break
case 'j':
arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0)
break
case 'e':
arg = match[7] ? parseFloat(arg).toExponential(match[7]) : parseFloat(arg).toExponential()
break
case 'f':
arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg)
break
case 'g':
arg = match[7] ? String(Number(arg.toPrecision(match[7]))) : parseFloat(arg)
break
case 'o':
arg = (parseInt(arg, 10) >>> 0).toString(8)
break
case 's':
arg = String(arg)
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
case 't':
arg = String(!!arg)
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
case 'T':
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
case 'u':
arg = parseInt(arg, 10) >>> 0
break
case 'v':
arg = arg.valueOf()
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
case 'x':
arg = (parseInt(arg, 10) >>> 0).toString(16)
break
case 'X':
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
break
}
if (re.json.test(match[8])) {
output += arg
}
else {
if (re.number.test(match[8]) && (!is_positive || match[3])) {
sign = is_positive ? '+' : '-'
arg = arg.toString().replace(re.sign, '')
}
else {
sign = ''
}
pad_character = match[4] ? match[4] === '0' ? '0' : match[4].charAt(1) : ' '
pad_length = match[6] - (sign + arg).length
pad = match[6] ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
output += match[5] ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
}
}
}
return output
}
var sprintf_cache = Object.create(null)
function sprintf_parse(fmt) {
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt]
}
var _fmt = fmt, match, parse_tree = [], arg_names = 0
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0])
}
else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push('%')
}
else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1
var field_list = [], replacement_field = match[2], field_match = []
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = re.key_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
}
else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
}
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
match[2] = field_list
}
else {
arg_names |= 2
}
if (arg_names === 3) {
throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
}
parse_tree.push(match)
}
else {
throw new SyntaxError('[sprintf] unexpected placeholder')
}
_fmt = _fmt.substring(match[0].length)
}
return sprintf_cache[fmt] = parse_tree
}
/**
* export to either browser or node.js
*/
/* eslint-disable quote-props */
if (true) {
exports['sprintf'] = sprintf
exports['vsprintf'] = vsprintf
}
if (typeof window !== 'undefined') {
window['sprintf'] = sprintf
window['vsprintf'] = vsprintf
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return {
'sprintf': sprintf,
'vsprintf': vsprintf
}
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
}
}
/* eslint-enable quote-props */
}()
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(97);
__webpack_require__(37);
__webpack_require__(98);
var workzoneFacets = function workzoneFacets(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var selectedFacets = {};
var facets = null;
var ORDER_BY_BCT = 'ORDER_BY_BCT';
var ORDER_ALPHA_ASC = 'ORDER_ALPHA_ASC';
var ORDER_ALPHA_DESC = 'ORDER_ALPHA_DESC';
var ORDER_BY_HITS = 'ORDER_BY_HITS';
var ORDER_BY_HITS_ASC = 'ORDER_BY_HITS_ASC';
var facetStatus = _jquery2.default.parseJSON(sessionStorage.getItem('facetStatus')) || [];
var hiddenFacetsList = [];
var resetSelectedFacets = function resetSelectedFacets() {
selectedFacets = {};
return selectedFacets;
};
/**
* add missing selected facets fields into "facets", from "selectedFacets"
* why : because if we negates all values for a facet field (all red), the facet will disapear from next query->answers
* (not in "facets" anymore, not in ux). So we lose the posibility to delete or invert a facet value.
* nb : negating all facets values does not mean there will be 0 results, because the field can be empty for some records.
*/
function facetsAddMissingSelected(_selectedFacets, _facets) {
_.each(_selectedFacets, function (v, k) {
var found = _.find(_facets, function (facet) {
return facet.field == k;
});
if (!found) {
var i = _facets.push(_.clone(v)); // add a "fake" facet to facets
_facets[i - 1].values = []; // with no values
}
});
};
var loadFacets = function loadFacets(data) {
hiddenFacetsList = data.hiddenFacetsList;
function sortIteration(i) {
switch (data.facetValueOrder) {
case ORDER_ALPHA_ASC:
return i.value.toString().toLowerCase();
break;
case ORDER_BY_HITS_ASC:
return i.count;
break;;
case ORDER_BY_HITS:
return i.count * -1;
break;
}
}
facetsAddMissingSelected(selectedFacets, data.facets);
// Convert facets data to fancytree source format
var treeSource = _.map(data.facets, function (facet) {
// Values
var values = _.map(_.sortBy(facet.values, sortIteration), function (value) {
var type = facet.type; // todo : define a new phraseanet "color" type for fields. for now we push a "type" for every value, copied from field type
// patch "color" type values
var textLimit = 15; // cut long values (set to 0 to not cut)
var text = value.value.toString();
var label = text;
var title = text;
var tooltip = text;
var match = text.match(/^(.*)\[#([0-9a-fA-F]{6})].*$/);
if (match && match[2] != null) {
// text looks like a color !
var colorCode = '#' + match[2];
// add color circle and remove color code from text;
var textWithoutColorCode = text.replace('[' + colorCode + ']', '');
if (textLimit > 0 && textWithoutColorCode.length > textLimit) {
textWithoutColorCode = textWithoutColorCode.substring(0, textLimit) + '…';
}
// patch
type = "COLOR-AGGREGATE";
label = textWithoutColorCode;
tooltip = _.escape(textWithoutColorCode);
title = '<span class="color-dot" style="background-color: ' + colorCode + ';"></span> ' + tooltip;
} else {
// keep text as it is, just cut if too long
if (textLimit > 0 && text.length > textLimit) {
text = text.substring(0, textLimit) + '…';
}
label = text;
/*title = tooltip = _.escape(text);*/
}
return {
// custom data
query: value.query,
field: facet.field,
raw_value: value.raw_value,
value: value.value,
label: label, // displayed when selected (blue/red), escape is done later (render)
type: type, // todo ? define a new phraseanet "color" type for fields. for now we push a "type" for every value
count: value.count,
// jquerytree data
title: title + ' (' + formatNumber(value.count) + ')',
tooltip: tooltip + ' (' + formatNumber(value.count) + ')'
};
});
// Facet
return {
// custom data
name: facet.name,
field: facet.field,
label: facet.label,
type: facet.type,
// jquerytree data
title: facet.label,
folder: true,
children: values,
expanded: !_.some(facetStatus, function (o) {
return _.has(o, facet.name);
})
};
});
if (data.facetOrder == ORDER_ALPHA_ASC) {
treeSource.sort(_sortFacets('title', true, function (a) {
return a.toUpperCase();
}));
}
if (data.facetOrder == ORDER_ALPHA_DESC) {
treeSource.sort(_sortFacets('title', false, function (a) {
return a.toUpperCase();
}));
}
if (data.filterFacet == true) {
treeSource = _hideSingleValueFacet(treeSource);
}
if (hiddenFacetsList.length > 0) {
treeSource = _shouldMaskNodes(treeSource, hiddenFacetsList);
}
treeSource = _parseColors(treeSource);
return _getFacetsTree().reload(treeSource).done(function () {
_.each((0, _jquery2.default)('#proposals').find('.fancytree-expanded'), function (element, i) {
(0, _jquery2.default)(element).find('.fancytree-title, .fancytree-expander').css('line-height', '50px');
(0, _jquery2.default)(element).find('.mask-facets-btn, .fancytree-expander').css('height', '50px');
var li_s = (0, _jquery2.default)(element).next().children('li');
var ul = (0, _jquery2.default)(element).next();
if (li_s.length > 5) {
_.each(li_s, function (el, i) {
if (i > 4) {
(0, _jquery2.default)(el).hide();
}
});
ul.append('<button class="see_more_btn">See more</button>');
}
});
(0, _jquery2.default)('.see_more_btn').on('click', function () {
(0, _jquery2.default)(this).closest('ul').children().show();
(0, _jquery2.default)(this).hide();
return false;
});
});
};
function _parseColors(source) {
_.forEach(source, function (facet) {
if (!_.isUndefined(facet.children) && facet.children.length > 0) {
_.forEach(facet.children, function (child) {
var title = child.title;
child.title = _formatColorText(title.toString());
});
}
});
return source;
}
function _formatColorText(string) {
var textLimit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
//get color code from text if exist
var regexp = /^(.*)\[#([0-9a-fA-F]{6})].*$/;
var match = string.match(regexp);
if (match && match[2] != null) {
var colorCode = '#' + match[2];
// //add color circle and re move color code from text;
var textWithoutColorCode = string.replace('[' + colorCode + ']', '');
if (textLimit > 0 && textWithoutColorCode.length > textLimit) {
textWithoutColorCode = textWithoutColorCode.substring(0, textLimit) + '…';
}
return '<span class="color-dot" style="background-color: ' + colorCode + '"></span>' + ' ' + textWithoutColorCode;
} else {
if (textLimit > 0 && string.length > textLimit) {
string = string.substring(0, textLimit) + '…';
}
return string;
}
}
// from stackoverflow
// http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects/979325#979325
function _sortFacets(field, reverse, primer) {
var key = function key(x) {
return primer ? primer(x[field]) : x[field];
};
return function (a, b) {
var A = key(a);
var B = key(b);
return (A < B ? -1 : A > B ? 1 : 0) * [-1, 1][+!!reverse];
};
}
function _shouldMaskNodes(source, facetsList) {
var filteredSource = source.slice();
_.each(facetsList, function (facetsValue, index) {
for (var i = filteredSource.length - 1; i > -1; --i) {
var facet = filteredSource[i];
if (facet['name'] !== undefined) {
if (facet['name'] === facetsValue.name) {
filteredSource.splice(i, 1);
}
}
}
});
return filteredSource;
}
/**
* hide facets with only one value (experimental)
*
* @param source treesource
* @returns {*}
*/
function _hideSingleValueFacet(source) {
var filteredSource = [];
_.forEach(source, function (facet) {
if (!_.isUndefined(facet.children) && (facet.children.length > 1 || !_.isUndefined(selectedFacets[facet.field]))) {
filteredSource.push(facet);
}
});
source = filteredSource;
return source;
}
function _sortByPredefinedFacets(source, field, predefinedFieldOrder) {
var filteredSource = source.slice();
var ordered = [];
_.each(predefinedFieldOrder, function (fieldValue, index) {
for (var i = filteredSource.length - 1; i > -1; --i) {
var facet = filteredSource[i];
if (facet[field] !== undefined) {
if (facet[field] === fieldValue) {
ordered.push(facet);
// remove from filtered
filteredSource.splice(i, 1);
}
}
}
});
var olen = filteredSource.length;
// fill predefined facets with non predefined facets
for (var i = 0; i < olen; i++) {
ordered.push(filteredSource[i]);
}
return ordered;
}
/*Format number to local fr */
function formatNumber(number) {
var locale = 'fr';
var formatter = new Intl.NumberFormat(locale);
return formatter.format(number);
}
function _getFacetsTree() {
var $facetsTree = (0, _jquery2.default)('#proposals');
if (!$facetsTree.data('ui-fancytree')) {
$facetsTree.fancytree({
clickFolderMode: 2, // expand
icons: false,
source: [],
activate: function activate(event, data) {
var eventType = event.originalEvent;
//if user did not click, then no need to perform any query
if (eventType == null) {
return;
}
var facet = data.node.parent;
var facetData = {
value: data.node.data,
enabled: true,
negated: event.altKey // ,
// mode: event.altKey ? "EXCEPT" : "AND"
};
if (selectedFacets[facet.data.field] == null) {
selectedFacets[facet.data.field] = facet.data;
selectedFacets[facet.data.field].values = [];
}
selectedFacets[facet.data.field].values.push(facetData);
appEvents.emit('search.doRefreshState');
},
collapse: function collapse(event, data) {
var dict = {};
dict[data.node.data.name] = "collapse";
if (_.findWhere(facetStatus, dict) !== undefined) {
facetStatus = _.without(facetStatus, _.findWhere(facetStatus, dict));
}
facetStatus.push(dict);
sessionStorage.setItem('facetStatus', JSON.stringify(facetStatus));
},
expand: function expand(event, data) {
var dict = {};
dict[data.node.data.name] = "collapse";
if (_.findWhere(facetStatus, dict) !== undefined) {
facetStatus = _.without(facetStatus, _.findWhere(facetStatus, dict));
}
sessionStorage.setItem('facetStatus', JSON.stringify(facetStatus));
},
renderNode: function renderNode(event, data) {
var facetFilter = "";
var node = data.node;
var $nodeSpan = (0, _jquery2.default)(node.span);
// check if span of node already rendered
if (!$nodeSpan.data('rendered')) {
var deleteButton = (0, _jquery2.default)('<div class="mask-facets-btn"><a></a></div>');
$nodeSpan.append(deleteButton);
deleteButton.hide();
$nodeSpan.hover(function () {
/*Dont show deleteButton if there is selected facet*/
if ((0, _jquery2.default)('.fancytree-folder', data.node.li).find('[class^="facetFilter_"]').length === 0) {
deleteButton.show();
}
}, function () {
deleteButton.hide();
});
deleteButton.click(function () {
var nodeObj = { name: node.data.name, title: node.title };
hiddenFacetsList.push(nodeObj);
node.remove();
appEvents.emit('searchAdvancedForm.saveHiddenFacetsList', hiddenFacetsList);
appEvents.emit('search.reloadHiddenFacetList', hiddenFacetsList);
});
// span rendered
$nodeSpan.data('rendered', true);
if (data.node.folder) {
// here we render a "fieldname" level
if (!_.isUndefined(selectedFacets[data.node.data.field])) {
// here the field already contains selected facetvalues (to be rendered blue or red)
if ((0, _jquery2.default)('.fancytree-folder', data.node.li).find('.dataNode').length == 0) {
var dataNode = document.createElement('div');
dataNode.setAttribute('class', 'dataNode');
(0, _jquery2.default)('.fancytree-folder', data.node.li).append(dataNode);
} else {
//remove existing facets
(0, _jquery2.default)('.dataNode', data.node.li).empty();
}
_.each(selectedFacets[data.node.data.field].values, function (facetValue) {
var label = facetValue.value.label;
var facetFilter = facetValue.value.label;
var facetTitle = facetValue.value.value + ' (' + formatNumber(facetValue.value.count) + ')';
var s_label = document.createElement('SPAN');
s_label.setAttribute('class', 'facetFilter-label');
s_label.setAttribute('title', facetTitle);
var f_except = (0, _jquery2.default)('#facet_except').val();
var f_and = (0, _jquery2.default)('#facet_and').val();
var f_close = (0, _jquery2.default)('#facet_remove').val();
var selected_facet_tooltip = (facetValue.negated ? f_and : f_except) + ' : ' + facetTitle;
var remove_facet_tooltip = f_close + ' : ' + facetTitle;
var length = 15;
var facetFilterString = _formatColorText(facetFilter.toString(), length);
_.each(_jquery2.default.parseHTML(facetFilterString), function (elem) {
s_label.appendChild(elem);
});
var buttonsSpan = document.createElement('SPAN');
buttonsSpan.setAttribute('class', 'buttons-span');
var s_inverse = document.createElement('A');
s_inverse.setAttribute('class', 'facetFilter-inverse');
s_inverse.setAttribute('title', selected_facet_tooltip);
var s_closer = document.createElement('A');
s_closer.setAttribute('class', 'facetFilter-closer');
s_closer.setAttribute('title', remove_facet_tooltip);
var s_gradient = document.createElement('SPAN');
s_gradient.setAttribute('class', 'facetFilter-gradient');
s_gradient.appendChild(document.createTextNode('\xA0'));
s_label.appendChild(s_gradient);
var s_facet = document.createElement('SPAN');
var s_class = 'facetFilter' + '_' + (facetValue.negated ? 'EXCEPT' : 'AND');
s_facet.setAttribute('class', s_class);
s_facet.removeAttribute('title');
s_facet.appendChild(s_label);
s_facet.appendChild(buttonsSpan);
buttonsSpan.appendChild(s_inverse);
buttonsSpan.appendChild(s_closer);
(0, _jquery2.default)(s_closer).on('click', function (event) {
event.stopPropagation();
var $facet = (0, _jquery2.default)(this).parent().parent();
var facetField = $facet.data('facetField');
var facetLabel = $facet.data('facetLabel');
var facetNegated = $facet.data('facetNegated');
selectedFacets[facetField].values = _.reject(selectedFacets[facetField].values, function (facetValue) {
return facetValue.value.label == facetLabel && facetValue.negated == facetNegated;
});
appEvents.emit('search.doRefreshState');
return false;
});
(0, _jquery2.default)(s_inverse).on('click', function (event) {
event.stopPropagation();
var $facet = (0, _jquery2.default)(this).parent().parent();
var facetField = $facet.data('facetField');
var facetLabel = $facet.data('facetLabel');
var facetNegated = $facet.data('facetNegated');
var found = _.find(selectedFacets[facetField].values, function (facetValue) {
return facetValue.value.label == facetLabel && facetValue.negated == facetNegated;
});
if (found) {
var s_class = "facetFilter" + '_' + (found.negated ? "EXCEPT" : "AND");
$facet.removeClass(s_class);
found.negated = !found.negated;
s_class = "facetFilter" + '_' + (found.negated ? "EXCEPT" : "AND");
$facet.addClass(s_class);
appEvents.emit('search.doRefreshState');
}
return false;
});
var newNode = document.createElement('div');
newNode.setAttribute('class', 'newNode');
s_facet = (0, _jquery2.default)(newNode.appendChild(s_facet));
s_facet.data('facetField', data.node.data.field);
s_facet.data('facetLabel', label);
s_facet.data('facetNegated', facetValue.negated);
/*add selected facet tooltip*/
// s_facet.attr('title', facetValue.value.value);
s_facet.hover(function () {
(0, _jquery2.default)(buttonsSpan).show();
}, function () {
(0, _jquery2.default)(buttonsSpan).hide();
});
(0, _jquery2.default)('.fancytree-folder .dataNode', data.node.li).append(newNode);
});
}
} else {
// here we render a facet value
}
}
}
});
}
return $facetsTree.fancytree('getTree');
}
var setSelectedFacets = function setSelectedFacets(facets) {
if (!_.isObject(facets) || facets.length === 0) {
facets = {};
}
selectedFacets = facets;
};
var getSelectedFacets = function getSelectedFacets(cb) {
cb(selectedFacets);
};
appEvents.listenAll({
'facets.doLoadFacets': loadFacets,
'facets.doResetSelectedFacets': resetSelectedFacets,
'facets.doAddMissingSelectedFacets': facetsAddMissingSelected,
'facets.setSelectedFacets': setSelectedFacets,
'facets.getSelectedFacets': getSelectedFacets
});
return {
loadFacets: loadFacets,
getSelectedFacets: getSelectedFacets,
resetSelectedFacets: resetSelectedFacets,
setSelectedFacets: setSelectedFacets
};
};
exports.default = workzoneFacets;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _index = __webpack_require__(112);
var _index2 = _interopRequireDefault(_index);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var editRecord = function editRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
var recordEditor = (0, _index2.default)(services);
appEvents.listenAll({
'record.doEdit': _doEdit
});
var initialize = function initialize() {
$container = (0, _jquery2.default)('body');
$container.on('click', '.edit-record-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var type = '';
var kind = $el.data('kind');
var idContent = $el.data('id');
switch (kind) {
case 'basket':
type = 'SSTT';
break;
case 'record':
type = 'IMGT';
break;
default:
}
_doEdit({ type: type, value: idContent });
});
};
var openModal = function openModal(datas) {
(0, _jquery2.default)('#EDITWINDOW').empty().addClass('loading');
//commonModule.showOverlay(2);
(0, _jquery2.default)('#EDITWINDOW').show();
_jquery2.default.ajax({
url: url + 'prod/records/edit/',
type: 'POST',
dataType: 'html',
data: datas,
success: function success(data) {
(0, _jquery2.default)('#EDITWINDOW').removeClass('loading').empty().html(data);
// let recordEditor = recordEditorService(services);
recordEditor.initialize({
$container: (0, _jquery2.default)('#EDITWINDOW'),
recordConfig: window.recordEditorConfig
});
(0, _jquery2.default)('#tooltip').hide();
return;
},
error: function error(XHR, textStatus, errorThrown) {
if (XHR.status === 0) {
return false;
}
}
});
return true;
};
// open Modal
function _doEdit(options) {
var type = options.type,
value = options.value;
var datas = {
lst: '',
ssel: '',
act: ''
};
switch (type) {
case 'IMGT':
datas.lst = value;
break;
case 'SSTT':
datas.ssel = value;
break;
case 'STORY':
datas.story = value;
break;
default:
}
return openModal(datas);
}
var onGlobalKeydown = function onGlobalKeydown(event, specialKeyState) {
if (specialKeyState === undefined) {
var _specialKeyState = {
isCancelKey: false,
isShortcutKey: false
};
}
switch (event.keyCode) {
case 9:
// tab ou shift-tab
fieldNavigate(event, appCommons.utilsModule.is_shift_key(event) ? -1 : 1);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
case 27:
cancelChanges({ event: event });
specialKeyState.isShortcutKey = true;
break;
case 33:
// pg up
if (!options.textareaIsDirty || validateFieldChanges(event, 'ask_ok')) {
skipImage(event, 1);
}
specialKeyState.isCancelKey = true;
break;
case 34:
// pg dn
if (!options.textareaIsDirty || validateFieldChanges(event, 'ask_ok')) {
skipImage(event, -1);
}
specialKeyState.isCancelKey = true;
break;
default:
}
return specialKeyState;
};
function fieldNavigate(evt, dir) {
var current_field = (0, _jquery2.default)('#divS .edit_field.active');
if (current_field.length === 0) {
current_field = (0, _jquery2.default)('#divS .edit_field:first');
current_field.trigger('click');
} else {
if (dir >= 0) {
current_field.next().trigger('click');
} else {
current_field.prev().trigger('click');
}
}
}
return { initialize: initialize, openModal: openModal, onGlobalKeydown: onGlobalKeydown };
};
exports.default = editRecord;
/***/ }),
/* 62 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_video_js__ = __webpack_require__(118);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_video_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_video_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_videojs_swf_package_json__ = __webpack_require__(142);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_videojs_swf_package_json___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_videojs_swf_package_json__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_global_window__ = __webpack_require__(43);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_global_window___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_global_window__);
var version$1 = "2.1.0";
/**
* @file flash-rtmp.js
* @module flash-rtmp
*/
/**
* Add RTMP properties to the {@link Flash} Tech.
*
* @param {Flash} Flash
* The flash tech class.
*
* @mixin FlashRtmpDecorator
*
* @return {Flash}
* The flash tech with RTMP properties added.
*/
function FlashRtmpDecorator(Flash) {
Flash.streamingFormats = {
'rtmp/mp4': 'MP4',
'rtmp/flv': 'FLV'
};
/**
* Join connection and stream with an ampersand.
*
* @param {string} connection
* The connection string.
*
* @param {string} stream
* The stream string.
*
* @return {string}
* The connection and stream joined with an `&` character
*/
Flash.streamFromParts = function (connection, stream) {
return connection + '&' + stream;
};
/**
* The flash parts object that contains connection and stream info.
*
* @typedef {Object} Flash~PartsObject
*
* @property {string} connection
* The connection string of a source, defaults to an empty string.
*
* @property {string} stream
* The stream string of the source, defaults to an empty string.
*/
/**
* Convert a source url into a stream and connection parts.
*
* @param {string} src
* the source url
*
* @return {Flash~PartsObject}
* The parts object that contains a connection and a stream
*/
Flash.streamToParts = function (src) {
var parts = {
connection: '',
stream: ''
};
if (!src) {
return parts;
}
// Look for the normal URL separator we expect, '&'.
// If found, we split the URL into two pieces around the
// first '&'.
var connEnd = src.search(/&(?!\w+=)/);
var streamBegin = void 0;
if (connEnd !== -1) {
streamBegin = connEnd + 1;
} else {
// If there's not a '&', we use the last '/' as the delimiter.
connEnd = streamBegin = src.lastIndexOf('/') + 1;
if (connEnd === 0) {
// really, there's not a '/'?
connEnd = streamBegin = src.length;
}
}
parts.connection = src.substring(0, connEnd);
parts.stream = src.substring(streamBegin, src.length);
return parts;
};
/**
* Check if the source type is a streaming type.
*
* @param {string} srcType
* The mime type to check.
*
* @return {boolean}
* - True if the source type is a streaming type.
* - False if the source type is not a streaming type.
*/
Flash.isStreamingType = function (srcType) {
return srcType in Flash.streamingFormats;
};
// RTMP has four variations, any string starting
// with one of these protocols should be valid
/**
* Regular expression used to check if the source is an rtmp source.
*
* @property {RegExp} Flash.RTMP_RE
*/
Flash.RTMP_RE = /^rtmp[set]?:\/\//i;
/**
* Check if the source itself is a streaming type.
*
* @param {string} src
* The url to the source.
*
* @return {boolean}
* - True if the source url indicates that the source is streaming.
* - False if the shource url indicates that the source url is not streaming.
*/
Flash.isStreamingSrc = function (src) {
return Flash.RTMP_RE.test(src);
};
/**
* A source handler for RTMP urls
* @type {Object}
*/
Flash.rtmpSourceHandler = {};
/**
* Check if Flash can play the given mime type.
*
* @param {string} type
* The mime type to check
*
* @return {string}
* 'maybe', or '' (empty string)
*/
Flash.rtmpSourceHandler.canPlayType = function (type) {
if (Flash.isStreamingType(type)) {
return 'maybe';
}
return '';
};
/**
* Check if Flash can handle the source natively
*
* @param {Object} source
* The source object
*
* @param {Object} [options]
* The options passed to the tech
*
* @return {string}
* 'maybe', or '' (empty string)
*/
Flash.rtmpSourceHandler.canHandleSource = function (source, options) {
var can = Flash.rtmpSourceHandler.canPlayType(source.type);
if (can) {
return can;
}
if (Flash.isStreamingSrc(source.src)) {
return 'maybe';
}
return '';
};
/**
* Pass the source to the flash object.
*
* @param {Object} source
* The source object
*
* @param {Flash} tech
* The instance of the Flash tech
*
* @param {Object} [options]
* The options to pass to the source
*/
Flash.rtmpSourceHandler.handleSource = function (source, tech, options) {
var srcParts = Flash.streamToParts(source.src);
tech.setRtmpConnection(srcParts.connection);
tech.setRtmpStream(srcParts.stream);
};
// Register the native source handler
Flash.registerSourceHandler(Flash.rtmpSourceHandler);
return Flash;
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var inherits = function (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 possibleConstructorReturn = function (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;
};
/**
* @file flash.js
* VideoJS-SWF - Custom Flash Player with HTML5-ish API
* https://github.com/zencoder/video-js-swf
* Not using setupTriggers. Using global onEvent func to distribute events
*/
var Tech = __WEBPACK_IMPORTED_MODULE_0_video_js___default.a.getComponent('Tech');
var Dom = __WEBPACK_IMPORTED_MODULE_0_video_js___default.a.dom;
var Url = __WEBPACK_IMPORTED_MODULE_0_video_js___default.a.url;
var createTimeRange = __WEBPACK_IMPORTED_MODULE_0_video_js___default.a.createTimeRange;
var mergeOptions = __WEBPACK_IMPORTED_MODULE_0_video_js___default.a.mergeOptions;
var navigator = __WEBPACK_IMPORTED_MODULE_2_global_window___default.a && __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.navigator || {};
/**
* Flash Media Controller - Wrapper for Flash Media API
*
* @mixes FlashRtmpDecorator
* @mixes Tech~SouceHandlerAdditions
* @extends Tech
*/
var Flash = function (_Tech) {
inherits(Flash, _Tech);
/**
* Create an instance of this Tech.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} ready
* Callback function to call when the `Flash` Tech is ready.
*/
function Flash(options, ready) {
classCallCheck(this, Flash);
// Set the source when ready
var _this = possibleConstructorReturn(this, _Tech.call(this, options, ready));
if (options.source) {
_this.ready(function () {
this.setSource(options.source);
}, true);
}
// Having issues with Flash reloading on certain page actions
// (hide/resize/fullscreen) in certain browsers
// This allows resetting the playhead when we catch the reload
if (options.startTime) {
_this.ready(function () {
this.load();
this.play();
this.currentTime(options.startTime);
}, true);
}
// Add global window functions that the swf expects
// A 4.x workflow we weren't able to solve for in 5.0
// because of the need to hard code these functions
// into the swf for security reasons
__WEBPACK_IMPORTED_MODULE_2_global_window___default.a.videojs = __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.videojs || {};
__WEBPACK_IMPORTED_MODULE_2_global_window___default.a.videojs.Flash = __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.videojs.Flash || {};
__WEBPACK_IMPORTED_MODULE_2_global_window___default.a.videojs.Flash.onReady = Flash.onReady;
__WEBPACK_IMPORTED_MODULE_2_global_window___default.a.videojs.Flash.onEvent = Flash.onEvent;
__WEBPACK_IMPORTED_MODULE_2_global_window___default.a.videojs.Flash.onError = Flash.onError;
_this.on('seeked', function () {
this.lastSeekTarget_ = undefined;
});
return _this;
}
/**
* Create the `Flash` Tech's DOM element.
*
* @return {Element}
* The element that gets created.
*/
Flash.prototype.createEl = function createEl() {
var options = this.options_;
// If video.js is hosted locally you should also set the location
// for the hosted swf, which should be relative to the page (not video.js)
// Otherwise this adds a CDN url.
// The CDN also auto-adds a swf URL for that specific version.
if (!options.swf) {
options.swf = 'https://vjs.zencdn.net/swf/' + __WEBPACK_IMPORTED_MODULE_1_videojs_swf_package_json__["version"] + '/video-js.swf';
}
// Generate ID for swf object
var objId = options.techId;
// Merge default flashvars with ones passed in to init
var flashVars = mergeOptions({
// SWF Callback Functions
readyFunction: 'videojs.Flash.onReady',
eventProxyFunction: 'videojs.Flash.onEvent',
errorEventProxyFunction: 'videojs.Flash.onError',
// Player Settings
autoplay: options.autoplay,
preload: options.preload,
loop: options.loop,
muted: options.muted
}, options.flashVars);
// Merge default parames with ones passed in
var params = mergeOptions({
// Opaque is needed to overlay controls, but can affect playback performance
wmode: 'opaque',
// Using bgcolor prevents a white flash when the object is loading
bgcolor: '#000000'
}, options.params);
// Merge default attributes with ones passed in
var attributes = mergeOptions({
// Both ID and Name needed or swf to identify itself
id: objId,
name: objId,
'class': 'vjs-tech'
}, options.attributes);
this.el_ = Flash.embed(options.swf, flashVars, params, attributes);
this.el_.tech = this;
return this.el_;
};
/**
* Called by {@link Player#play} to play using the `Flash` `Tech`.
*/
Flash.prototype.play = function play() {
if (this.ended()) {
this.setCurrentTime(0);
}
this.el_.vjs_play();
};
/**
* Called by {@link Player#pause} to pause using the `Flash` `Tech`.
*/
Flash.prototype.pause = function pause() {
this.el_.vjs_pause();
};
/**
* A getter/setter for the `Flash` Tech's source object.
* > Note: Please use {@link Flash#setSource}
*
* @param {Tech~SourceObject} [src]
* The source object you want to set on the `Flash` techs.
*
* @return {Tech~SourceObject|undefined}
* - The current source object when a source is not passed in.
* - undefined when setting
*
* @deprecated Since version 5.
*/
Flash.prototype.src = function src(_src) {
if (_src === undefined) {
return this.currentSrc();
}
// Setting src through `src` not `setSrc` will be deprecated
return this.setSrc(_src);
};
/**
* A getter/setter for the `Flash` Tech's source object.
*
* @param {Tech~SourceObject} [src]
* The source object you want to set on the `Flash` techs.
*/
Flash.prototype.setSrc = function setSrc(src) {
var _this2 = this;
// Make sure source URL is absolute.
src = Url.getAbsoluteURL(src);
this.el_.vjs_src(src);
// Currently the SWF doesn't autoplay if you load a source later.
// e.g. Load player w/ no source, wait 2s, set src.
if (this.autoplay()) {
this.setTimeout(function () {
return _this2.play();
}, 0);
}
};
/**
* Indicates whether the media is currently seeking to a new position or not.
*
* @return {boolean}
* - True if seeking to a new position
* - False otherwise
*/
Flash.prototype.seeking = function seeking() {
return this.lastSeekTarget_ !== undefined;
};
/**
* Returns the current time in seconds that the media is at in playback.
*
* @param {number} time
* Current playtime of the media in seconds.
*/
Flash.prototype.setCurrentTime = function setCurrentTime(time) {
var seekable = this.seekable();
if (seekable.length) {
// clamp to the current seekable range
time = time > seekable.start(0) ? time : seekable.start(0);
time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1);
this.lastSeekTarget_ = time;
this.trigger('seeking');
this.el_.vjs_setProperty('currentTime', time);
_Tech.prototype.setCurrentTime.call(this);
}
};
/**
* Get the current playback time in seconds
*
* @return {number}
* The current time of playback in seconds.
*/
Flash.prototype.currentTime = function currentTime() {
// when seeking make the reported time keep up with the requested time
// by reading the time we're seeking to
if (this.seeking()) {
return this.lastSeekTarget_ || 0;
}
return this.el_.vjs_getProperty('currentTime');
};
/**
* Get the current source
*
* @method currentSrc
* @return {Tech~SourceObject}
* The current source
*/
Flash.prototype.currentSrc = function currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
}
return this.el_.vjs_getProperty('currentSrc');
};
/**
* Get the total duration of the current media.
*
* @return {number}
8 The total duration of the current media.
*/
Flash.prototype.duration = function duration() {
if (this.readyState() === 0) {
return NaN;
}
var duration = this.el_.vjs_getProperty('duration');
return duration >= 0 ? duration : Infinity;
};
/**
* Load media into Tech.
*/
Flash.prototype.load = function load() {
this.el_.vjs_load();
};
/**
* Get the poster image that was set on the tech.
*/
Flash.prototype.poster = function poster() {
this.el_.vjs_getProperty('poster');
};
/**
* Poster images are not handled by the Flash tech so make this is a no-op.
*/
Flash.prototype.setPoster = function setPoster() {};
/**
* Determine the time ranges that can be seeked to in the media.
*
* @return {TimeRange}
* Returns the time ranges that can be seeked to.
*/
Flash.prototype.seekable = function seekable() {
var duration = this.duration();
if (duration === 0) {
return createTimeRange();
}
return createTimeRange(0, duration);
};
/**
* Get and create a `TimeRange` object for buffering.
*
* @return {TimeRange}
* The time range object that was created.
*/
Flash.prototype.buffered = function buffered() {
var ranges = this.el_.vjs_getProperty('buffered');
if (ranges.length === 0) {
return createTimeRange();
}
return createTimeRange(ranges[0][0], ranges[0][1]);
};
/**
* Get fullscreen support -
*
* Flash does not allow fullscreen through javascript
* so this always returns false.
*
* @return {boolean}
* The Flash tech does not support fullscreen, so it will always return false.
*/
Flash.prototype.supportsFullScreen = function supportsFullScreen() {
// Flash does not allow fullscreen through javascript
return false;
};
/**
* Flash does not allow fullscreen through javascript
* so this always returns false.
*
* @return {boolean}
* The Flash tech does not support fullscreen, so it will always return false.
*/
Flash.prototype.enterFullScreen = function enterFullScreen() {
return false;
};
/**
* Gets available media playback quality metrics as specified by the W3C's Media
* Playback Quality API.
*
* @see [Spec]{@link https://wicg.github.io/media-playback-quality}
*
* @return {Object}
* An object with supported media playback quality metrics
*/
Flash.prototype.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
var videoPlaybackQuality = this.el_.vjs_getProperty('getVideoPlaybackQuality');
if (__WEBPACK_IMPORTED_MODULE_2_global_window___default.a.performance && typeof __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.performance.now === 'function') {
videoPlaybackQuality.creationTime = __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.performance.now();
} else if (__WEBPACK_IMPORTED_MODULE_2_global_window___default.a.performance && __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.performance.timing && typeof __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.performance.timing.navigationStart === 'number') {
videoPlaybackQuality.creationTime = __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.Date.now() - __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.performance.timing.navigationStart;
}
return videoPlaybackQuality;
};
return Flash;
}(Tech);
// Create setters and getters for attributes
var _readWrite = ['rtmpConnection', 'rtmpStream', 'preload', 'defaultPlaybackRate', 'playbackRate', 'autoplay', 'loop', 'controls', 'volume', 'muted', 'defaultMuted'];
var _readOnly = ['networkState', 'readyState', 'initialTime', 'startOffsetTime', 'paused', 'ended', 'videoWidth', 'videoHeight'];
var _api = Flash.prototype;
/**
* Create setters for the swf on the element
*
* @param {string} attr
* The name of the parameter
*
* @private
*/
function _createSetter(attr) {
var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1);
_api['set' + attrUpper] = function (val) {
return this.el_.vjs_setProperty(attr, val);
};
}
/**
* Create petters for the swf on the element
*
* @param {string} attr
* The name of the parameter
*
* @private
*/
function _createGetter(attr) {
_api[attr] = function () {
return this.el_.vjs_getProperty(attr);
};
}
// Create getter and setters for all read/write attributes
for (var i = 0; i < _readWrite.length; i++) {
_createGetter(_readWrite[i]);
_createSetter(_readWrite[i]);
}
// Create getters for read-only attributes
for (var _i = 0; _i < _readOnly.length; _i++) {
_createGetter(_readOnly[_i]);
}
/** ------------------------------ Getters ------------------------------ **/
/**
* Get the value of `rtmpConnection` from the swf.
*
* @method Flash#rtmpConnection
* @return {string}
* The current value of `rtmpConnection` on the swf.
*/
/**
* Get the value of `rtmpStream` from the swf.
*
* @method Flash#rtmpStream
* @return {string}
* The current value of `rtmpStream` on the swf.
*/
/**
* Get the value of `preload` from the swf. `preload` indicates
* what should download before the media is interacted with. It can have the following
* values:
* - none: nothing should be downloaded
* - metadata: poster and the first few frames of the media may be downloaded to get
* media dimensions and other metadata
* - auto: allow the media and metadata for the media to be downloaded before
* interaction
*
* @method Flash#preload
* @return {string}
* The value of `preload` from the swf. Will be 'none', 'metadata',
* or 'auto'.
*/
/**
* Get the value of `defaultPlaybackRate` from the swf.
*
* @method Flash#defaultPlaybackRate
* @return {number}
* The current value of `defaultPlaybackRate` on the swf.
*/
/**
* Get the value of `playbackRate` from the swf. `playbackRate` indicates
* the rate at which the media is currently playing back. Examples:
* - if playbackRate is set to 2, media will play twice as fast.
* - if playbackRate is set to 0.5, media will play half as fast.
*
* @method Flash#playbackRate
* @return {number}
* The value of `playbackRate` from the swf. A number indicating
* the current playback speed of the media, where 1 is normal speed.
*/
/**
* Get the value of `autoplay` from the swf. `autoplay` indicates
* that the media should start to play as soon as the page is ready.
*
* @method Flash#autoplay
* @return {boolean}
* - The value of `autoplay` from the swf.
* - True indicates that the media ashould start as soon as the page loads.
* - False indicates that the media should not start as soon as the page loads.
*/
/**
* Get the value of `loop` from the swf. `loop` indicates
* that the media should return to the start of the media and continue playing once
* it reaches the end.
*
* @method Flash#loop
* @return {boolean}
* - The value of `loop` from the swf.
* - True indicates that playback should seek back to start once
* the end of a media is reached.
* - False indicates that playback should not loop back to the start when the
* end of the media is reached.
*/
/**
* Get the value of `mediaGroup` from the swf.
*
* @method Flash#mediaGroup
* @return {string}
* The current value of `mediaGroup` on the swf.
*/
/**
* Get the value of `controller` from the swf.
*
* @method Flash#controller
* @return {string}
* The current value of `controller` on the swf.
*/
/**
* Get the value of `controls` from the swf. `controls` indicates
* whether the native flash controls should be shown or hidden.
*
* @method Flash#controls
* @return {boolean}
* - The value of `controls` from the swf.
* - True indicates that native controls should be showing.
* - False indicates that native controls should be hidden.
*/
/**
* Get the value of the `volume` from the swf. `volume` indicates the current
* audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
* so on.
*
* @method Flash#volume
* @return {number}
* The volume percent as a decimal. Value will be between 0-1.
*/
/**
* Get the value of the `muted` from the swf. `muted` indicates the current
* audio level should be silent.
*
* @method Flash#muted
* @return {boolean}
* - True if the audio should be set to silent
* - False otherwise
*/
/**
* Get the value of `defaultMuted` from the swf. `defaultMuted` indicates
* whether the media should start muted or not. Only changes the default state of the
* media. `muted` and `defaultMuted` can have different values. `muted` indicates the
* current state.
*
* @method Flash#defaultMuted
* @return {boolean}
* - The value of `defaultMuted` from the swf.
* - True indicates that the media should start muted.
* - False indicates that the media should not start muted.
*/
/**
* Get the value of `networkState` from the swf. `networkState` indicates
* the current network state. It returns an enumeration from the following list:
* - 0: NETWORK_EMPTY
* - 1: NEWORK_IDLE
* - 2: NETWORK_LOADING
* - 3: NETWORK_NO_SOURCE
*
* @method Flash#networkState
* @return {number}
* The value of `networkState` from the swf. This will be a number
* from the list in the description.
*/
/**
* Get the value of `readyState` from the swf. `readyState` indicates
* the current state of the media element. It returns an enumeration from the
* following list:
* - 0: HAVE_NOTHING
* - 1: HAVE_METADATA
* - 2: HAVE_CURRENT_DATA
* - 3: HAVE_FUTURE_DATA
* - 4: HAVE_ENOUGH_DATA
*
* @method Flash#readyState
* @return {number}
* The value of `readyState` from the swf. This will be a number
* from the list in the description.
*/
/**
* Get the value of `readyState` from the swf. `readyState` indicates
* the current state of the media element. It returns an enumeration from the
* following list:
* - 0: HAVE_NOTHING
* - 1: HAVE_METADATA
* - 2: HAVE_CURRENT_DATA
* - 3: HAVE_FUTURE_DATA
* - 4: HAVE_ENOUGH_DATA
*
* @method Flash#readyState
* @return {number}
* The value of `readyState` from the swf. This will be a number
* from the list in the description.
*/
/**
* Get the value of `initialTime` from the swf.
*
* @method Flash#initialTime
* @return {number}
* The `initialTime` proprety on the swf.
*/
/**
* Get the value of `startOffsetTime` from the swf.
*
* @method Flash#startOffsetTime
* @return {number}
* The `startOffsetTime` proprety on the swf.
*/
/**
* Get the value of `paused` from the swf. `paused` indicates whether the swf
* is current paused or not.
*
* @method Flash#paused
* @return {boolean}
* The value of `paused` from the swf.
*/
/**
* Get the value of `ended` from the swf. `ended` indicates whether
* the media has reached the end or not.
*
* @method Flash#ended
* @return {boolean}
* - True indicates that the media has ended.
* - False indicates that the media has not ended.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
*/
/**
* Get the value of `videoWidth` from the swf. `videoWidth` indicates
* the current width of the media in css pixels.
*
* @method Flash#videoWidth
* @return {number}
* The value of `videoWidth` from the swf. This will be a number
* in css pixels.
*/
/**
* Get the value of `videoHeight` from the swf. `videoHeigth` indicates
* the current height of the media in css pixels.
*
* @method Flassh.prototype.videoHeight
* @return {number}
* The value of `videoHeight` from the swf. This will be a number
* in css pixels.
*/
/** ------------------------------ Setters ------------------------------ **/
/**
* Set the value of `rtmpConnection` on the swf.
*
* @method Flash#setRtmpConnection
* @param {string} rtmpConnection
* New value to set the `rtmpConnection` property to.
*/
/**
* Set the value of `rtmpStream` on the swf.
*
* @method Flash#setRtmpStream
* @param {string} rtmpStream
* New value to set the `rtmpStream` property to.
*/
/**
* Set the value of `preload` on the swf. `preload` indicates
* what should download before the media is interacted with. It can have the following
* values:
* - none: nothing should be downloaded
* - metadata: poster and the first few frames of the media may be downloaded to get
* media dimensions and other metadata
* - auto: allow the media and metadata for the media to be downloaded before
* interaction
*
* @method Flash#setPreload
* @param {string} preload
* The value of `preload` to set on the swf. Should be 'none', 'metadata',
* or 'auto'.
*/
/**
* Set the value of `defaultPlaybackRate` on the swf.
*
* @method Flash#setDefaultPlaybackRate
* @param {number} defaultPlaybackRate
* New value to set the `defaultPlaybackRate` property to.
*/
/**
* Set the value of `playbackRate` on the swf. `playbackRate` indicates
* the rate at which the media is currently playing back. Examples:
* - if playbackRate is set to 2, media will play twice as fast.
* - if playbackRate is set to 0.5, media will play half as fast.
*
* @method Flash#setPlaybackRate
* @param {number} playbackRate
* New value of `playbackRate` on the swf. A number indicating
* the current playback speed of the media, where 1 is normal speed.
*/
/**
* Set the value of `autoplay` on the swf. `autoplay` indicates
* that the media should start to play as soon as the page is ready.
*
* @method Flash#setAutoplay
* @param {boolean} autoplay
* - The value of `autoplay` from the swf.
* - True indicates that the media ashould start as soon as the page loads.
* - False indicates that the media should not start as soon as the page loads.
*/
/**
* Set the value of `loop` on the swf. `loop` indicates
* that the media should return to the start of the media and continue playing once
* it reaches the end.
*
* @method Flash#setLoop
* @param {boolean} loop
* - True indicates that playback should seek back to start once
* the end of a media is reached.
* - False indicates that playback should not loop back to the start when the
* end of the media is reached.
*/
/**
* Set the value of `mediaGroup` on the swf.
*
* @method Flash#setMediaGroup
* @param {string} mediaGroup
* New value of `mediaGroup` to set on the swf.
*/
/**
* Set the value of `controller` on the swf.
*
* @method Flash#setController
* @param {string} controller
* New value the current value of `controller` on the swf.
*/
/**
* Get the value of `controls` from the swf. `controls` indicates
* whether the native flash controls should be shown or hidden.
*
* @method Flash#controls
* @return {boolean}
* - The value of `controls` from the swf.
* - True indicates that native controls should be showing.
* - False indicates that native controls should be hidden.
*/
/**
* Set the value of the `volume` on the swf. `volume` indicates the current
* audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
* so on.
*
* @method Flash#setVolume
* @param {number} percentAsDecimal
* The volume percent as a decimal. Value will be between 0-1.
*/
/**
* Set the value of the `muted` on the swf. `muted` indicates that the current
* audio level should be silent.
*
* @method Flash#setMuted
* @param {boolean} muted
* - True if the audio should be set to silent
* - False otherwise
*/
/**
* Set the value of `defaultMuted` on the swf. `defaultMuted` indicates
* whether the media should start muted or not. Only changes the default state of the
* media. `muted` and `defaultMuted` can have different values. `muted` indicates the
* current state.
*
* @method Flash#setDefaultMuted
* @param {boolean} defaultMuted
* - True indicates that the media should start muted.
* - False indicates that the media should not start muted.
*/
/* Flash Support Testing -------------------------------------------------------- */
/**
* Check if the Flash tech is currently supported.
*
* @return {boolean}
* - True for Chrome and Safari Desktop and if flash tech is supported
* - False otherwise
*/
Flash.isSupported = function () {
// for Chrome Desktop and Safari Desktop
if (__WEBPACK_IMPORTED_MODULE_0_video_js___default.a.browser.IS_CHROME && !__WEBPACK_IMPORTED_MODULE_0_video_js___default.a.browser.IS_ANDROID || __WEBPACK_IMPORTED_MODULE_0_video_js___default.a.browser.IS_SAFARI && !__WEBPACK_IMPORTED_MODULE_0_video_js___default.a.browser.IS_IOS) {
return true;
}
// for other browsers
return Flash.version()[0] >= 10;
};
// Add Source Handler pattern functions to this tech
Tech.withSourceHandlers(Flash);
/*
* Native source handler for flash, simply passes the source to the swf element.
*
* @property {Tech~SourceObject} source
* The source object
*
* @property {Flash} tech
* The instance of the Flash tech
*/
Flash.nativeSourceHandler = {};
/**
* Check if the Flash can play the given mime type.
*
* @param {string} type
* The mimetype to check
*
* @return {string}
* 'maybe', or '' (empty string)
*/
Flash.nativeSourceHandler.canPlayType = function (type) {
if (type in Flash.formats) {
return 'maybe';
}
return '';
};
/**
* Check if the media element can handle a source natively.
*
* @param {Tech~SourceObject} source
* The source object
*
* @param {Object} [options]
* Options to be passed to the tech.
*
* @return {string}
* 'maybe', or '' (empty string).
*/
Flash.nativeSourceHandler.canHandleSource = function (source, options) {
var type = void 0;
/**
* Guess the mime type of a file if it does not have one
*
* @param {Tech~SourceObject} src
* The source object to guess the mime type for
*
* @return {string}
* The mime type that was guessed
*/
function guessMimeType(src) {
var ext = Url.getFileExtension(src);
if (ext) {
return 'video/' + ext;
}
return '';
}
if (!source.type) {
type = guessMimeType(source.src);
} else {
// Strip code information from the type because we don't get that specific
type = source.type.replace(/;.*/, '').toLowerCase();
}
return Flash.nativeSourceHandler.canPlayType(type);
};
/**
* Pass the source to the swf.
*
* @param {Tech~SourceObject} source
* The source object
*
* @param {Flash} tech
* The instance of the Flash tech
*
* @param {Object} [options]
* The options to pass to the source
*/
Flash.nativeSourceHandler.handleSource = function (source, tech, options) {
tech.setSrc(source.src);
};
/**
* noop for native source handler dispose, as cleanup will happen automatically.
*/
Flash.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Flash.registerSourceHandler(Flash.nativeSourceHandler);
/**
* Flash supported mime types.
*
* @constant {Object}
*/
Flash.formats = {
'video/flv': 'FLV',
'video/x-flv': 'FLV',
'video/mp4': 'MP4',
'video/m4v': 'MP4'
};
/**
* Called when the the swf is "ready", and makes sure that the swf is really
* ready using {@link Flash#checkReady}
*
* @param {Object} currSwf
* The current swf object
*/
Flash.onReady = function (currSwf) {
var el = Dom.$('#' + currSwf);
var tech = el && el.tech;
// if there is no el then the tech has been disposed
// and the tech element was removed from the player div
if (tech && tech.el()) {
// check that the flash object is really ready
Flash.checkReady(tech);
}
};
/**
* The SWF isn't always ready when it says it is. Sometimes the API functions still
* need to be added to the object. If it's not ready, we set a timeout to check again
* shortly.
*
* @param {Flash} tech
* The instance of the flash tech to check.
*/
Flash.checkReady = function (tech) {
// stop worrying if the tech has been disposed
if (!tech.el()) {
return;
}
// check if API property exists
if (tech.el().vjs_getProperty) {
// tell tech it's ready
tech.triggerReady();
} else {
// wait longer
this.setTimeout(function () {
Flash.checkReady(tech);
}, 50);
}
};
/**
* Trigger events from the swf on the Flash Tech.
*
* @param {number} swfID
* The id of the swf that had the event
*
* @param {string} eventName
* The name of the event to trigger
*/
Flash.onEvent = function (swfID, eventName) {
var tech = Dom.$('#' + swfID).tech;
var args = Array.prototype.slice.call(arguments, 2);
// dispatch Flash events asynchronously for two reasons:
// - Flash swallows any exceptions generated by javascript it
// invokes
// - Flash is suspended until the javascript returns which may cause
// playback performance issues
tech.setTimeout(function () {
tech.trigger(eventName, args);
}, 1);
};
/**
* Log errors from the swf on the Flash tech.
*
* @param {number} swfID
* The id of the swf that had an error.
*
* @param {string} err
* The error to set on the Flash Tech.
*
* @return {MediaError|undefined}
* - Returns a MediaError when err is 'srcnotfound'
* - Returns undefined otherwise.
*/
Flash.onError = function (swfID, err) {
var tech = Dom.$('#' + swfID).tech;
// trigger MEDIA_ERR_SRC_NOT_SUPPORTED
if (err === 'srcnotfound') {
return tech.error(4);
}
// trigger a custom error
if (typeof err === 'string') {
tech.error('FLASH: ' + err);
} else {
err.origin = 'flash';
tech.error(err);
}
};
/**
* Get the current version of Flash that is in use on the page.
*
* @return {Array}
* an array of versions that are available.
*/
Flash.version = function () {
var version$$1 = '0,0,0';
// IE
try {
version$$1 = new __WEBPACK_IMPORTED_MODULE_2_global_window___default.a.ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
// other browsers
} catch (e) {
try {
if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
version$$1 = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
}
} catch (err) {
// satisfy linter
}
}
return version$$1.split(',');
};
/**
* Only use for non-iframe embeds.
*
* @param {Object} swf
* The videojs-swf object.
*
* @param {Object} flashVars
* Names and values to use as flash option variables.
*
* @param {Object} params
* Style parameters to set on the object.
*
* @param {Object} attributes
* Attributes to set on the element.
*
* @return {Element}
* The embeded Flash DOM element.
*/
Flash.embed = function (swf, flashVars, params, attributes) {
var code = Flash.getEmbedCode(swf, flashVars, params, attributes);
// Get element by embedding code and retrieving created element
var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0];
return obj;
};
/**
* Only use for non-iframe embeds.
*
* @param {Object} swf
* The videojs-swf object.
*
* @param {Object} flashVars
* Names and values to use as flash option variables.
*
* @param {Object} params
* Style parameters to set on the object.
*
* @param {Object} attributes
* Attributes to set on the element.
*
* @return {Element}
* The embeded Flash DOM element.
*/
Flash.getEmbedCode = function (swf, flashVars, params, attributes) {
var objTag = '<object type="application/x-shockwave-flash" ';
var flashVarsString = '';
var paramsString = '';
var attrsString = '';
// Convert flash vars to string
if (flashVars) {
Object.getOwnPropertyNames(flashVars).forEach(function (key) {
flashVarsString += key + '=' + flashVars[key] + '&amp;';
});
}
// Add swf, flashVars, and other default params
params = mergeOptions({
movie: swf,
flashvars: flashVarsString,
// Required to talk to swf
allowScriptAccess: 'always',
// All should be default, but having security issues.
allowNetworking: 'all'
}, params);
// Create param tags string
Object.getOwnPropertyNames(params).forEach(function (key) {
paramsString += '<param name="' + key + '" value="' + params[key] + '" />';
});
attributes = mergeOptions({
// Add swf to attributes (need both for IE and Others to work)
data: swf,
// Default to 100% width/height
width: '100%',
height: '100%'
}, attributes);
// Create Attributes string
Object.getOwnPropertyNames(attributes).forEach(function (key) {
attrsString += key + '="' + attributes[key] + '" ';
});
return '' + objTag + attrsString + '>' + paramsString + '</object>';
};
// Run Flash through the RTMP decorator
FlashRtmpDecorator(Flash);
if (Tech.getTech('Flash')) {
__WEBPACK_IMPORTED_MODULE_0_video_js___default.a.log.warn('Not using videojs-flash as it appears to already be registered');
__WEBPACK_IMPORTED_MODULE_0_video_js___default.a.log.warn('videojs-flash should only be used with video.js@6 and above');
} else {
__WEBPACK_IMPORTED_MODULE_0_video_js___default.a.registerTech('Flash', Flash);
}
Flash.VERSION = version$1;
/* harmony default export */ __webpack_exports__["default"] = (Flash);
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(124);
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.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 = function (object, name, value, predicate) {
if (name in object && (!isFunction(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 = keys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(48);
var ES = __webpack_require__(126);
var replace = bind.call(Function.call, String.prototype.replace);
var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/;
var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/;
module.exports = function trim() {
var S = ES.ToString(ES.CheckObjectCoercible(this));
return replace(replace(S, leftWhitespace, ''), rightWhitespace, '');
};
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(64);
var zeroWidthSpace = '\u200b';
module.exports = function getPolyfill() {
if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) {
return String.prototype.trim;
}
return implementation;
};
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
/* Mapbox GL JS is licensed under the 3-Clause BSD License. Full text of license: https://github.com/mapbox/mapbox-gl-js/blob/v1.11.0/LICENSE.txt */
(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.mapboxgl = factory());
}(this, (function () { 'use strict';
/* eslint-disable */
var shared, worker, mapboxgl;
// define gets called three times: one for each chunk. we rely on the order
// they're imported to know which is which
function define(_, chunk) {
if (!shared) {
shared = chunk;
} else if (!worker) {
worker = chunk;
} else {
var workerBundleString = 'var sharedChunk = {}; (' + shared + ')(sharedChunk); (' + worker + ')(sharedChunk);'
var sharedChunk = {};
shared(sharedChunk);
mapboxgl = chunk(sharedChunk);
if (typeof window !== 'undefined') {
mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));
}
}
}
define(["exports"],(function(t){"use strict";function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r=n;function n(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=n,this.p2x=r,this.p2y=n;}n.prototype.sampleCurveX=function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},n.prototype.sampleCurveY=function(t){return ((this.ay*t+this.by)*t+this.cy)*t},n.prototype.sampleCurveDerivativeX=function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},n.prototype.solveCurveX=function(t,e){var r,n,i,a,o;for(void 0===e&&(e=1e-6),i=t,o=0;o<8;o++){if(a=this.sampleCurveX(i)-t,Math.abs(a)<e)return i;var s=this.sampleCurveDerivativeX(i);if(Math.abs(s)<1e-6)break;i-=a/s;}if((i=t)<(r=0))return r;if(i>(n=1))return n;for(;r<n;){if(a=this.sampleCurveX(i),Math.abs(a-t)<e)return i;t>a?r=i:n=i,i=.5*(n-r)+r;}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var i=a;function a(t,e){this.x=t,this.y=e;}a.prototype={clone:function(){return new a(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},a.convert=function(t){return t instanceof a?t:Array.isArray(t)?new a(t[0],t[1]):t};var o="undefined"!=typeof self?self:{};function s(t,e,n,i){var a=new r(t,e,n,i);return function(t){return a.solve(t)}}var u=s(.25,.1,.25,1);function l(t,e,r){return Math.min(r,Math.max(e,t))}function p(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function c(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o];}return t}var h=1;function f(){return h++}function y(){return function t(e){return e?(e^16*Math.random()>>e/4).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,t)}()}function d(t){return !!t&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)}function m(t,e){t.forEach((function(t){e[t]&&(e[t]=e[t].bind(e));}));}function v(t,e){return -1!==t.indexOf(e,t.length-e.length)}function g(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function x(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function b(t){return Array.isArray(t)?t.map(b):"object"==typeof t&&t?g(t,b):t}var w={};function _(t){w[t]||("undefined"!=typeof console&&console.warn(t),w[t]=!0);}function A(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function S(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r<n;i=r++)e+=((o=t[i]).x-(a=t[r]).x)*(a.y+o.y);return e}function k(){return "undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function I(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""})),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r;}return e}var z=null;function C(t){if(null==z){var e=t.navigator?t.navigator.userAgent:null;z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return z}function M(t){try{var e=o[t];return e.setItem("_mapbox_test_",1),e.removeItem("_mapbox_test_"),!0}catch(t){return !1}}var E,T,P,B,V=o.performance&&o.performance.now?o.performance.now.bind(o.performance):Date.now.bind(Date),F=o.requestAnimationFrame||o.mozRequestAnimationFrame||o.webkitRequestAnimationFrame||o.msRequestAnimationFrame,D=o.cancelAnimationFrame||o.mozCancelAnimationFrame||o.webkitCancelAnimationFrame||o.msCancelAnimationFrame,L={now:V,frame:function(t){var e=F(t);return {cancel:function(){return D(e)}}},getImageData:function(t,e){void 0===e&&(e=0);var r=o.document.createElement("canvas"),n=r.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return r.width=t.width,r.height=t.height,n.drawImage(t,0,0,t.width,t.height),n.getImageData(-e,-e,t.width+2*e,t.height+2*e)},resolveURL:function(t){return E||(E=o.document.createElement("a")),E.href=t,E.href},hardwareConcurrency:o.navigator&&o.navigator.hardwareConcurrency||4,get devicePixelRatio(){return o.devicePixelRatio},get prefersReducedMotion(){return !!o.matchMedia&&(null==T&&(T=o.matchMedia("(prefers-reduced-motion: reduce)")),T.matches)}},R={API_URL:"https://api.mapbox.com",get EVENTS_URL(){return this.API_URL?0===this.API_URL.indexOf("https://api.mapbox.cn")?"https://events.mapbox.cn/events/v2":0===this.API_URL.indexOf("https://api.mapbox.com")?"https://events.mapbox.com/events/v2":null:null},FEEDBACK_URL:"https://apps.mapbox.com/feedback",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,MAX_PARALLEL_IMAGE_REQUESTS:16},O={supported:!1,testSupport:function(t){!U&&B&&(j?q(t):P=t);}},U=!1,j=!1;function q(t){var e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,B),t.isContextLost())return;O.supported=!0;}catch(t){}t.deleteTexture(e),U=!0;}o.document&&((B=o.document.createElement("img")).onload=function(){P&&q(P),P=null,j=!0;},B.onerror=function(){U=!0,P=null;},B.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");var N="01",K=function(t,e){this._transformRequestFn=t,this._customAccessToken=e,this._createSkuToken();};function G(t){return 0===t.indexOf("mapbox:")}K.prototype._createSkuToken=function(){var t=function(){for(var t="",e=0;e<10;e++)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return {token:["1",N,t].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=t.token,this._skuTokenExpiresAt=t.tokenExpiresAt;},K.prototype._isSkuTokenExpired=function(){return Date.now()>this._skuTokenExpiresAt},K.prototype.transformRequest=function(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}},K.prototype.normalizeStyleURL=function(t,e){if(!G(t))return t;var r=H(t);return r.path="/styles/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},K.prototype.normalizeGlyphsURL=function(t,e){if(!G(t))return t;var r=H(t);return r.path="/fonts/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},K.prototype.normalizeSourceURL=function(t,e){if(!G(t))return t;var r=H(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),this._makeAPIURL(r,this._customAccessToken||e)},K.prototype.normalizeSpriteURL=function(t,e,r,n){var i=H(t);return G(t)?(i.path="/styles/v1"+i.path+"/sprite"+e+r,this._makeAPIURL(i,this._customAccessToken||n)):(i.path+=""+e+r,Y(i))},K.prototype.normalizeTileURL=function(t,e){if(this._isSkuTokenExpired()&&this._createSkuToken(),t&&!G(t))return t;var r=H(t);r.path=r.path.replace(/(\.(png|jpg)\d*)(?=$)/,(L.devicePixelRatio>=2||512===e?"@2x":"")+(O.supported?".webp":"$1")),r.path=r.path.replace(/^.+\/v4\//,"/"),r.path="/v4"+r.path;var n=this._customAccessToken||function(t){for(var e=0,r=t;e<r.length;e+=1){var n=r[e].match(/^access_token=(.*)$/);if(n)return n[1]}return null}(r.params)||R.ACCESS_TOKEN;return R.REQUIRE_ACCESS_TOKEN&&n&&this._skuToken&&r.params.push("sku="+this._skuToken),this._makeAPIURL(r,n)},K.prototype.canonicalizeTileURL=function(t,e){var r=H(t);if(!r.path.match(/(^\/v4\/)/)||!r.path.match(/\.[\w]+$/))return t;var n="mapbox://tiles/";n+=r.path.replace("/v4/","");var i=r.params;return e&&(i=i.filter((function(t){return !t.match(/^access_token=/)}))),i.length&&(n+="?"+i.join("&")),n},K.prototype.canonicalizeTileset=function(t,e){for(var r=!!e&&G(e),n=[],i=0,a=t.tiles||[];i<a.length;i+=1){var o=a[i];X(o)?n.push(this.canonicalizeTileURL(o,r)):n.push(o);}return n},K.prototype._makeAPIURL=function(t,e){var r="See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes",n=H(R.API_URL);if(t.protocol=n.protocol,t.authority=n.authority,"/"!==n.path&&(t.path=""+n.path+t.path),!R.REQUIRE_ACCESS_TOKEN)return Y(t);if(!(e=e||R.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+r);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+r);return t.params=t.params.filter((function(t){return -1===t.indexOf("access_token")})),t.params.push("access_token="+e),Y(t)};var Z=/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i;function X(t){return Z.test(t)}var J=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function H(t){var e=t.match(J);if(!e)throw new Error("Unable to parse URL object");return {protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function Y(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}function $(t){if(!t)return null;var e=t.split(".");if(!e||3!==e.length)return null;try{return JSON.parse(decodeURIComponent(o.atob(e[1]).split("").map((function(t){return "%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})).join("")))}catch(t){return null}}var W=function(t){this.type=t,this.anonId=null,this.eventData={},this.queue=[],this.pendingRequest=null;};W.prototype.getStorageKey=function(t){var e,r=$(R.ACCESS_TOKEN);return e=r&&r.u?o.btoa(encodeURIComponent(r.u).replace(/%([0-9A-F]{2})/g,(function(t,e){return String.fromCharCode(Number("0x"+e))}))):R.ACCESS_TOKEN||"",t?"mapbox.eventData."+t+":"+e:"mapbox.eventData:"+e},W.prototype.fetchEventData=function(){var t=M("localStorage"),e=this.getStorageKey(),r=this.getStorageKey("uuid");if(t)try{var n=o.localStorage.getItem(e);n&&(this.eventData=JSON.parse(n));var i=o.localStorage.getItem(r);i&&(this.anonId=i);}catch(t){_("Unable to read from LocalStorage");}},W.prototype.saveEventData=function(){var t=M("localStorage"),e=this.getStorageKey(),r=this.getStorageKey("uuid");if(t)try{o.localStorage.setItem(r,this.anonId),Object.keys(this.eventData).length>=1&&o.localStorage.setItem(e,JSON.stringify(this.eventData));}catch(t){_("Unable to write to LocalStorage");}},W.prototype.processRequests=function(t){},W.prototype.postEvent=function(t,e,r,n){var i=this;if(R.EVENTS_URL){var a=H(R.EVENTS_URL);a.params.push("access_token="+(n||R.ACCESS_TOKEN||""));var o={event:this.type,created:new Date(t).toISOString(),sdkIdentifier:"mapbox-gl-js",sdkVersion:"1.11.0",skuId:N,userId:this.anonId},s=e?c(o,e):o,u={url:Y(a),headers:{"Content-Type":"text/plain"},body:JSON.stringify([s])};this.pendingRequest=bt(u,(function(t){i.pendingRequest=null,r(t),i.saveEventData(),i.processRequests(n);}));}},W.prototype.queueRequest=function(t,e){this.queue.push(t),this.processRequests(e);};var Q,tt,et=function(t){function e(){t.call(this,"map.load"),this.success={},this.skuToken="";}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postMapLoadEvent=function(t,e,r,n){this.skuToken=r,(R.EVENTS_URL&&n||R.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return G(t)||X(t)})))&&this.queueRequest({id:e,timestamp:Date.now()},n);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){var r=this.queue.shift(),n=r.id,i=r.timestamp;n&&this.success[n]||(this.anonId||this.fetchEventData(),d(this.anonId)||(this.anonId=y()),this.postEvent(i,{skuToken:this.skuToken},(function(t){t||n&&(e.success[n]=!0);}),t));}},e}(W),rt=new(function(t){function e(e){t.call(this,"appUserTurnstile"),this._customAccessToken=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postTurnstileEvent=function(t,e){R.EVENTS_URL&&R.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return G(t)||X(t)}))&&this.queueRequest(Date.now(),e);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){this.anonId&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();var r=$(R.ACCESS_TOKEN),n=r?r.u:R.ACCESS_TOKEN,i=n!==this.eventData.tokenU;d(this.anonId)||(this.anonId=y(),i=!0);var a=this.queue.shift();if(this.eventData.lastSuccess){var o=new Date(this.eventData.lastSuccess),s=new Date(a),u=(a-this.eventData.lastSuccess)/864e5;i=i||u>=1||u<-1||o.getDate()!==s.getDate();}else i=!0;if(!i)return this.processRequests();this.postEvent(a,{"enabled.telemetry":!1},(function(t){t||(e.eventData.lastSuccess=a,e.eventData.tokenU=n);}),t);}},e}(W)),nt=rt.postTurnstileEvent.bind(rt),it=new et,at=it.postMapLoadEvent.bind(it),ot=500,st=50;function ut(){o.caches&&!Q&&(Q=o.caches.open("mapbox-tiles"));}function lt(t){var e=t.indexOf("?");return e<0?t:t.slice(0,e)}var pt,ct=1/0;function ht(){return null==pt&&(pt=o.OffscreenCanvas&&new o.OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof o.createImageBitmap),pt}var ft={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(ft);var yt=function(t){function e(e,r,n){401===r&&X(n)&&(e+=": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes"),t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error),dt=k()?function(){return self.worker&&self.worker.referrer}:function(){return ("blob:"===o.location.protocol?o.parent:o).location.href};var mt,vt,gt=function(t,e){if(!(/^file:/.test(r=t.url)||/^file:/.test(dt())&&!/^\w+:/.test(r))){if(o.fetch&&o.Request&&o.AbortController&&o.Request.prototype.hasOwnProperty("signal"))return function(t,e){var r,n=new o.AbortController,i=new o.Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,referrer:dt(),signal:n.signal}),a=!1,s=!1,u=(r=i.url).indexOf("sku=")>0&&X(r);"json"===t.type&&i.headers.set("Accept","application/json");var l=function(r,n,a){if(!s){if(r&&"SecurityError"!==r.message&&_(r),n&&a)return p(n);var l=Date.now();o.fetch(i).then((function(r){if(r.ok){var n=u?r.clone():null;return p(r,n,l)}return e(new yt(r.statusText,r.status,t.url))})).catch((function(t){20!==t.code&&e(new Error(t.message));}));}},p=function(r,n,u){("arrayBuffer"===t.type?r.arrayBuffer():"json"===t.type?r.json():r.text()).then((function(t){s||(n&&u&&function(t,e,r){if(ut(),Q){var n={status:e.status,statusText:e.statusText,headers:new o.Headers};e.headers.forEach((function(t,e){return n.headers.set(e,t)}));var i=I(e.headers.get("Cache-Control")||"");i["no-store"]||(i["max-age"]&&n.headers.set("Expires",new Date(r+1e3*i["max-age"]).toUTCString()),new Date(n.headers.get("Expires")).getTime()-r<42e4||function(t,e){if(void 0===tt)try{new Response(new ReadableStream),tt=!0;}catch(t){tt=!1;}tt?e(t.body):t.blob().then(e);}(e,(function(e){var r=new o.Response(e,n);ut(),Q&&Q.then((function(e){return e.put(lt(t.url),r)})).catch((function(t){return _(t.message)}));})));}}(i,n,u),a=!0,e(null,t,r.headers.get("Cache-Control"),r.headers.get("Expires")));})).catch((function(t){s||e(new Error(t.message));}));};return u?function(t,e){if(ut(),!Q)return e(null);var r=lt(t.url);Q.then((function(t){t.match(r).then((function(n){var i=function(t){if(!t)return !1;var e=new Date(t.headers.get("Expires")||0),r=I(t.headers.get("Cache-Control")||"");return e>Date.now()&&!r["no-cache"]}(n);t.delete(r),i&&t.put(r,n.clone()),e(null,n,i);})).catch(e);})).catch(e);}(i,l):l(null,null),{cancel:function(){s=!0,a||n.abort();}}}(t,e);if(k()&&self.worker&&self.worker.actor)return self.worker.actor.send("getResource",t,e,void 0,!0)}var r;return function(t,e){var r=new o.XMLHttpRequest;for(var n in r.open(t.method||"GET",t.url,!0),"arrayBuffer"===t.type&&(r.responseType="arraybuffer"),t.headers)r.setRequestHeader(n,t.headers[n]);return "json"===t.type&&(r.responseType="text",r.setRequestHeader("Accept","application/json")),r.withCredentials="include"===t.credentials,r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){if((r.status>=200&&r.status<300||0===r.status)&&null!==r.response){var n=r.response;if("json"===t.type)try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n,r.getResponseHeader("Cache-Control"),r.getResponseHeader("Expires"));}else e(new yt(r.statusText,r.status,t.url));},r.send(t.body),{cancel:function(){return r.abort()}}}(t,e)},xt=function(t,e){return gt(c(t,{type:"arrayBuffer"}),e)},bt=function(t,e){return gt(c(t,{method:"POST"}),e)};mt=[],vt=0;var wt=function(t,e){if(O.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),vt>=R.MAX_PARALLEL_IMAGE_REQUESTS){var r={requestParameters:t,callback:e,cancelled:!1,cancel:function(){this.cancelled=!0;}};return mt.push(r),r}vt++;var n=!1,i=function(){if(!n)for(n=!0,vt--;mt.length&&vt<R.MAX_PARALLEL_IMAGE_REQUESTS;){var t=mt.shift();t.cancelled||(t.cancel=wt(t.requestParameters,t.callback).cancel);}},a=xt(t,(function(t,r,n,a){i(),t?e(t):r&&(ht()?function(t,e){var r=new o.Blob([new Uint8Array(t)],{type:"image/png"});o.createImageBitmap(r).then((function(t){e(null,t);})).catch((function(t){e(new Error("Could not load image because of "+t.message+". Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));}));}(r,e):function(t,e,r,n){var i=new o.Image,a=o.URL;i.onload=function(){e(null,i),a.revokeObjectURL(i.src);},i.onerror=function(){return e(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."))};var s=new o.Blob([new Uint8Array(t)],{type:"image/png"});i.cacheControl=r,i.expires=n,i.src=t.byteLength?a.createObjectURL(s):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";}(r,e,n,a));}));return {cancel:function(){a.cancel(),i();}}};function _t(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function At(t,e,r){if(r&&r[t]){var n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}var St=function(t,e){void 0===e&&(e={}),c(this,e),this.type=t;},kt=function(t){function e(e,r){void 0===r&&(r={}),t.call(this,"error",c({error:e},r));}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(St),It=function(){};It.prototype.on=function(t,e){return this._listeners=this._listeners||{},_t(t,e,this._listeners),this},It.prototype.off=function(t,e){return At(t,e,this._listeners),At(t,e,this._oneTimeListeners),this},It.prototype.once=function(t,e){return this._oneTimeListeners=this._oneTimeListeners||{},_t(t,e,this._oneTimeListeners),this},It.prototype.fire=function(t,e){"string"==typeof t&&(t=new St(t,e||{}));var r=t.type;if(this.listens(r)){t.target=this;for(var n=0,i=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];n<i.length;n+=1)i[n].call(this,t);for(var a=0,o=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];a<o.length;a+=1){var s=o[a];At(r,s,this._oneTimeListeners),s.call(this,t);}var u=this._eventedParent;u&&(c(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),u.fire(t));}else t instanceof kt&&console.error(t.error);return this},It.prototype.listens=function(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},It.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var zt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{},within:{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},in:{group:"Lookup"},"index-of":{group:"Lookup"},slice:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},"interpolate-hcl":{group:"Ramps, scales, curves"},"interpolate-lab":{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},format:{group:"Types"},image:{group:"Types"},"number-format":{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"feature-state":{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Feature data"},accumulated:{group:"Feature data"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},distance:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},within:{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}},Ct=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);};function Mt(t){var e=t.value;return e?[new Ct(t.key,e,"constants have been deprecated as of v8")]:[]}function Et(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o];}return t}function Tt(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function Pt(t){if(Array.isArray(t))return t.map(Pt);if(t instanceof Object&&!(t instanceof Number||t instanceof String||t instanceof Boolean)){var e={};for(var r in t)e[r]=Pt(t[r]);return e}return Tt(t)}var Bt=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(Error),Vt=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;r<n.length;r+=1){var i=n[r];this.bindings[i[0]]=i[1];}};Vt.prototype.concat=function(t){return new Vt(this,t)},Vt.prototype.get=function(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(t+" not found in scope.")},Vt.prototype.has=function(t){return !!this.bindings[t]||!!this.parent&&this.parent.has(t)};var Ft={kind:"null"},Dt={kind:"number"},Lt={kind:"string"},Rt={kind:"boolean"},Ot={kind:"color"},Ut={kind:"object"},jt={kind:"value"},qt={kind:"collator"},Nt={kind:"formatted"},Kt={kind:"resolvedImage"};function Gt(t,e){return {kind:"array",itemType:t,N:e}}function Zt(t){if("array"===t.kind){var e=Zt(t.itemType);return "number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var Xt=[Ft,Dt,Lt,Rt,Ot,Nt,Ut,Gt(jt),Kt];function Jt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Jt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=Xt;r<n.length;r+=1)if(!Jt(n[r],e))return null}return "Expected "+Zt(t)+" but found "+Zt(e)+" instead."}function Ht(t,e){return e.some((function(e){return e.kind===t.kind}))}function Yt(t,e){return e.some((function(e){return "null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t}))}var $t=e((function(t,e){var r={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function n(t){return (t=Math.round(t))<0?0:t>255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function a(t){return (e="%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))<0?0:e>1?1:e;var e;}function o(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,s=t.replace(/ /g,"").toLowerCase();if(s in r)return r[s].slice();if("#"===s[0])return 4===s.length?(e=parseInt(s.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===s.length&&(e=parseInt(s.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var u=s.indexOf("("),l=s.indexOf(")");if(-1!==u&&l+1===s.length){var p=s.substr(0,u),c=s.substr(u+1,l-(u+1)).split(","),h=1;switch(p){case"rgba":if(4!==c.length)return null;h=a(c.pop());case"rgb":return 3!==c.length?null:[i(c[0]),i(c[1]),i(c[2]),h];case"hsla":if(4!==c.length)return null;h=a(c.pop());case"hsl":if(3!==c.length)return null;var f=(parseFloat(c[0])%360+360)%360/360,y=a(c[1]),d=a(c[2]),m=d<=.5?d*(y+1):d+y-d*y,v=2*d-m;return [n(255*o(v,m,f+1/3)),n(255*o(v,m,f)),n(255*o(v,m,f-1/3)),h];default:return null}}return null};}catch(t){}})).parseCSSColor,Wt=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n;};Wt.parse=function(t){if(t){if(t instanceof Wt)return t;if("string"==typeof t){var e=$t(t);if(e)return new Wt(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},Wt.prototype.toString=function(){var t=this.toArray(),e=t[1],r=t[2],n=t[3];return "rgba("+Math.round(t[0])+","+Math.round(e)+","+Math.round(r)+","+n+")"},Wt.prototype.toArray=function(){var t=this.a;return 0===t?[0,0,0,0]:[255*this.r/t,255*this.g/t,255*this.b/t,t]},Wt.black=new Wt(0,0,0,1),Wt.white=new Wt(1,1,1,1),Wt.transparent=new Wt(0,0,0,0),Wt.red=new Wt(1,0,0,1);var Qt=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});};Qt.prototype.compare=function(t,e){return this.collator.compare(t,e)},Qt.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var te=function(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;},ee=function(t){this.sections=t;};ee.fromString=function(t){return new ee([new te(t,null,null,null,null)])},ee.prototype.isEmpty=function(){return 0===this.sections.length||!this.sections.some((function(t){return 0!==t.text.length||t.image&&0!==t.image.name.length}))},ee.factory=function(t){return t instanceof ee?t:ee.fromString(t)},ee.prototype.toString=function(){return 0===this.sections.length?"":this.sections.map((function(t){return t.text})).join("")},ee.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e<r.length;e+=1){var n=r[e];if(n.image)t.push(["image",n.image.name]);else {t.push(n.text);var i={};n.fontStack&&(i["text-font"]=["literal",n.fontStack.split(",")]),n.scale&&(i["font-scale"]=n.scale),n.textColor&&(i["text-color"]=["rgba"].concat(n.textColor.toArray())),t.push(i);}}return t};var re=function(t){this.name=t.name,this.available=t.available;};function ne(t,e,r,n){return "number"==typeof t&&t>=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function ie(t){if(null===t)return !0;if("string"==typeof t)return !0;if("boolean"==typeof t)return !0;if("number"==typeof t)return !0;if(t instanceof Wt)return !0;if(t instanceof Qt)return !0;if(t instanceof ee)return !0;if(t instanceof re)return !0;if(Array.isArray(t)){for(var e=0,r=t;e<r.length;e+=1)if(!ie(r[e]))return !1;return !0}if("object"==typeof t){for(var n in t)if(!ie(t[n]))return !1;return !0}return !1}function ae(t){if(null===t)return Ft;if("string"==typeof t)return Lt;if("boolean"==typeof t)return Rt;if("number"==typeof t)return Dt;if(t instanceof Wt)return Ot;if(t instanceof Qt)return qt;if(t instanceof ee)return Nt;if(t instanceof re)return Kt;if(Array.isArray(t)){for(var e,r=t.length,n=0,i=t;n<i.length;n+=1){var a=ae(i[n]);if(e){if(e===a)continue;e=jt;break}e=a;}return Gt(e||jt,r)}return Ut}function oe(t){var e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Wt||t instanceof ee||t instanceof re?t.toString():JSON.stringify(t)}re.prototype.toString=function(){return this.name},re.fromString=function(t){return t?new re({name:t,available:!1}):null},re.prototype.serialize=function(){return ["image",this.name]};var se=function(t,e){this.type=t,this.value=e;};se.parse=function(t,e){if(2!==t.length)return e.error("'literal' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(!ie(t[1]))return e.error("invalid value");var r=t[1],n=ae(r),i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new se(n,r)},se.prototype.evaluate=function(){return this.value},se.prototype.eachChild=function(){},se.prototype.outputDefined=function(){return !0},se.prototype.serialize=function(){return "array"===this.type.kind||"object"===this.type.kind?["literal",this.value]:this.value instanceof Wt?["rgba"].concat(this.value.toArray()):this.value instanceof ee?this.value.serialize():this.value};var ue=function(t){this.name="ExpressionEvaluationError",this.message=t;};ue.prototype.toJSON=function(){return this.message};var le={string:Lt,number:Dt,boolean:Rt,object:Ut},pe=function(t,e){this.type=t,this.args=e;};pe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r,n=1,i=t[0];if("array"===i){var a,o;if(t.length>2){var s=t[1];if("string"!=typeof s||!(s in le)||"object"===s)return e.error('The item type argument of "array" must be one of string, number, boolean',1);a=le[s],n++;}else a=jt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);o=t[2],n++;}r=Gt(a,o);}else r=le[i];for(var u=[];n<t.length;n++){var l=e.parse(t[n],n,jt);if(!l)return null;u.push(l);}return new pe(r,u)},pe.prototype.evaluate=function(t){for(var e=0;e<this.args.length;e++){var r=this.args[e].evaluate(t);if(!Jt(this.type,ae(r)))return r;if(e===this.args.length-1)throw new ue("Expected value to be of type "+Zt(this.type)+", but found "+Zt(ae(r))+" instead.")}return null},pe.prototype.eachChild=function(t){this.args.forEach(t);},pe.prototype.outputDefined=function(){return this.args.every((function(t){return t.outputDefined()}))},pe.prototype.serialize=function(){var t=this.type,e=[t.kind];if("array"===t.kind){var r=t.itemType;if("string"===r.kind||"number"===r.kind||"boolean"===r.kind){e.push(r.kind);var n=t.N;("number"==typeof n||this.args.length>1)&&e.push(n);}}return e.concat(this.args.map((function(t){return t.serialize()})))};var ce=function(t){this.type=Nt,this.sections=t;};ce.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");for(var n=[],i=!1,a=1;a<=t.length-1;++a){var o=t[a];if(i&&"object"==typeof o&&!Array.isArray(o)){i=!1;var s=null;if(o["font-scale"]&&!(s=e.parse(o["font-scale"],1,Dt)))return null;var u=null;if(o["text-font"]&&!(u=e.parse(o["text-font"],1,Gt(Lt))))return null;var l=null;if(o["text-color"]&&!(l=e.parse(o["text-color"],1,Ot)))return null;var p=n[n.length-1];p.scale=s,p.font=u,p.textColor=l;}else {var c=e.parse(t[a],1,jt);if(!c)return null;var h=c.type.kind;if("string"!==h&&"value"!==h&&"null"!==h&&"resolvedImage"!==h)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:c,scale:null,font:null,textColor:null});}}return new ce(n)},ce.prototype.evaluate=function(t){return new ee(this.sections.map((function(e){var r=e.content.evaluate(t);return ae(r)===Kt?new te("",r,null,null,null):new te(oe(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))},ce.prototype.eachChild=function(t){for(var e=0,r=this.sections;e<r.length;e+=1){var n=r[e];t(n.content),n.scale&&t(n.scale),n.font&&t(n.font),n.textColor&&t(n.textColor);}},ce.prototype.outputDefined=function(){return !1},ce.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e<r.length;e+=1){var n=r[e];t.push(n.content.serialize());var i={};n.scale&&(i["font-scale"]=n.scale.serialize()),n.font&&(i["text-font"]=n.font.serialize()),n.textColor&&(i["text-color"]=n.textColor.serialize()),t.push(i);}return t};var he=function(t){this.type=Kt,this.input=t;};he.parse=function(t,e){if(2!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,Lt);return r?new he(r):e.error("No image name provided.")},he.prototype.evaluate=function(t){var e=this.input.evaluate(t),r=re.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r},he.prototype.eachChild=function(t){t(this.input);},he.prototype.outputDefined=function(){return !1},he.prototype.serialize=function(){return ["image",this.input.serialize()]};var fe={"to-boolean":Rt,"to-color":Ot,"to-number":Dt,"to-string":Lt},ye=function(t,e){this.type=t,this.args=e;};ye.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[0];if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");for(var n=fe[r],i=[],a=1;a<t.length;a++){var o=e.parse(t[a],a,jt);if(!o)return null;i.push(o);}return new ye(n,i)},ye.prototype.evaluate=function(t){if("boolean"===this.type.kind)return Boolean(this.args[0].evaluate(t));if("color"===this.type.kind){for(var e,r,n=0,i=this.args;n<i.length;n+=1){if(r=null,(e=i[n].evaluate(t))instanceof Wt)return e;if("string"==typeof e){var a=t.parseColor(e);if(a)return a}else if(Array.isArray(e)&&!(r=e.length<3||e.length>4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":ne(e[0],e[1],e[2],e[3])))return new Wt(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new ue(r||"Could not parse color from value '"+("string"==typeof e?e:String(JSON.stringify(e)))+"'")}if("number"===this.type.kind){for(var o=null,s=0,u=this.args;s<u.length;s+=1){if(null===(o=u[s].evaluate(t)))return 0;var l=Number(o);if(!isNaN(l))return l}throw new ue("Could not convert "+JSON.stringify(o)+" to number.")}return "formatted"===this.type.kind?ee.fromString(oe(this.args[0].evaluate(t))):"resolvedImage"===this.type.kind?re.fromString(oe(this.args[0].evaluate(t))):oe(this.args[0].evaluate(t))},ye.prototype.eachChild=function(t){this.args.forEach(t);},ye.prototype.outputDefined=function(){return this.args.every((function(t){return t.outputDefined()}))},ye.prototype.serialize=function(){if("formatted"===this.type.kind)return new ce([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if("resolvedImage"===this.type.kind)return new he(this.args[0]).serialize();var t=["to-"+this.type.kind];return this.eachChild((function(e){t.push(e.serialize());})),t};var de=["Unknown","Point","LineString","Polygon"],me=function(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null;};me.prototype.id=function(){return this.feature&&"id"in this.feature?this.feature.id:null},me.prototype.geometryType=function(){return this.feature?"number"==typeof this.feature.type?de[this.feature.type]:this.feature.type:null},me.prototype.geometry=function(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null},me.prototype.canonicalID=function(){return this.canonical},me.prototype.properties=function(){return this.feature&&this.feature.properties||{}},me.prototype.parseColor=function(t){var e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=Wt.parse(t)),e};var ve=function(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;};ve.prototype.evaluate=function(t){return this._evaluate(t,this.args)},ve.prototype.eachChild=function(t){this.args.forEach(t);},ve.prototype.outputDefined=function(){return !1},ve.prototype.serialize=function(){return [this.name].concat(this.args.map((function(t){return t.serialize()})))},ve.parse=function(t,e){var r,n=t[0],i=ve.definitions[n];if(!i)return e.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0);for(var a=Array.isArray(i)?i[0]:i.type,o=Array.isArray(i)?[[i[1],i[2]]]:i.overloads,s=o.filter((function(e){var r=e[0];return !Array.isArray(r)||r.length===t.length-1})),u=null,l=0,p=s;l<p.length;l+=1){var c=p[l],h=c[0],f=c[1];u=new Oe(e.registry,e.path,null,e.scope);for(var y=[],d=!1,m=1;m<t.length;m++){var v=t[m],g=Array.isArray(h)?h[m-1]:h.type,x=u.parse(v,1+y.length,g);if(!x){d=!0;break}y.push(x);}if(!d)if(Array.isArray(h)&&h.length!==y.length)u.error("Expected "+h.length+" arguments, but found "+y.length+" instead.");else {for(var b=0;b<y.length;b++){var w=Array.isArray(h)?h[b]:h.type,_=y[b];u.concat(b+1).checkSubtype(w,_.type);}if(0===u.errors.length)return new ve(n,a,f,y)}}if(1===s.length)(r=e.errors).push.apply(r,u.errors);else {for(var A=(s.length?s:o).map((function(t){var e;return e=t[0],Array.isArray(e)?"("+e.map(Zt).join(", ")+")":"("+Zt(e.type)+"...)"})).join(" | "),S=[],k=1;k<t.length;k++){var I=e.parse(t[k],1+S.length);if(!I)return null;S.push(Zt(I.type));}e.error("Expected arguments of type "+A+", but found ("+S.join(", ")+") instead.");}return null},ve.register=function(t,e){for(var r in ve.definitions=e,e)t[r]=ve;};var ge=function(t,e,r){this.type=qt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;};function xe(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function be(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function we(t,e){var r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*8192),Math.round(n*i*8192)]}function _e(t,e,r){return e[1]>t[1]!=r[1]>t[1]&&t[0]<(r[0]-e[0])*(t[1]-e[1])/(r[1]-e[1])+e[0]}function Ae(t,e){for(var r,n,i,a,o,s,u,l=!1,p=0,c=e.length;p<c;p++)for(var h=e[p],f=0,y=h.length;f<y-1;f++){if((a=(r=t)[0]-(n=h[f])[0])*(u=r[1]-(i=h[f+1])[1])-(s=r[0]-i[0])*(o=r[1]-n[1])==0&&a*s<=0&&o*u<=0)return !1;_e(t,h[f],h[f+1])&&(l=!l);}return l}function Se(t,e){for(var r=0;r<e.length;r++)if(Ae(t,e[r]))return !0;return !1}function ke(t,e,r,n){var i=n[0]-r[0],a=n[1]-r[1],o=(t[0]-r[0])*a-i*(t[1]-r[1]),s=(e[0]-r[0])*a-i*(e[1]-r[1]);return o>0&&s<0||o<0&&s>0}function Ie(t,e,r){for(var n=0,i=r;n<i.length;n+=1)for(var a=i[n],o=0;o<a.length-1;++o)if(0!=(c=[(p=a[o+1])[0]-(l=a[o])[0],p[1]-l[1]])[0]*(h=[(u=e)[0]-(s=t)[0],u[1]-s[1]])[1]-c[1]*h[0]&&ke(s,u,l,p)&&ke(l,p,s,u))return !0;var s,u,l,p,c,h;return !1}function ze(t,e){for(var r=0;r<t.length;++r)if(!Ae(t[r],e))return !1;for(var n=0;n<t.length-1;++n)if(Ie(t[n],t[n+1],e))return !1;return !0}function Ce(t,e){for(var r=0;r<e.length;r++)if(ze(t,e[r]))return !0;return !1}function Me(t,e,r){for(var n=[],i=0;i<t.length;i++){for(var a=[],o=0;o<t[i].length;o++){var s=we(t[i][o],r);xe(e,s),a.push(s);}n.push(a);}return n}function Ee(t,e,r){for(var n=[],i=0;i<t.length;i++){var a=Me(t[i],e,r);n.push(a);}return n}function Te(t,e,r,n){if(t[0]<r[0]||t[0]>r[2]){var i=.5*n,a=t[0]-r[0]>i?-n:r[0]-t[0]>i?n:0;0===a&&(a=t[0]-r[2]>i?-n:r[2]-t[0]>i?n:0),t[0]+=a;}xe(e,t);}function Pe(t,e,r,n){for(var i=8192*Math.pow(2,n.z),a=[8192*n.x,8192*n.y],o=[],s=0,u=t;s<u.length;s+=1)for(var l=0,p=u[s];l<p.length;l+=1){var c=p[l],h=[c.x+a[0],c.y+a[1]];Te(h,e,r,i),o.push(h);}return o}function Be(t,e,r,n){for(var i,a=8192*Math.pow(2,n.z),o=[8192*n.x,8192*n.y],s=[],u=0,l=t;u<l.length;u+=1){for(var p=[],c=0,h=l[u];c<h.length;c+=1){var f=h[c],y=[f.x+o[0],f.y+o[1]];xe(e,y),p.push(y);}s.push(p);}if(e[2]-e[0]<=a/2){(i=e)[0]=i[1]=1/0,i[2]=i[3]=-1/0;for(var d=0,m=s;d<m.length;d+=1)for(var v=0,g=m[d];v<g.length;v+=1)Te(g[v],e,r,a);}return s}ge.parse=function(t,e){if(2!==t.length)return e.error("Expected one argument.");var r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");var n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Rt);if(!n)return null;var i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Rt);if(!i)return null;var a=null;return r.locale&&!(a=e.parse(r.locale,1,Lt))?null:new ge(n,i,a)},ge.prototype.evaluate=function(t){return new Qt(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)},ge.prototype.eachChild=function(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);},ge.prototype.outputDefined=function(){return !1},ge.prototype.serialize=function(){var t={};return t["case-sensitive"]=this.caseSensitive.serialize(),t["diacritic-sensitive"]=this.diacriticSensitive.serialize(),this.locale&&(t.locale=this.locale.serialize()),["collator",t]};var Ve=function(t,e){this.type=Rt,this.geojson=t,this.geometries=e;};function Fe(t){if(t instanceof ve){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Ve)return !1;var e=!0;return t.eachChild((function(t){e&&!Fe(t)&&(e=!1);})),e}function De(t){if(t instanceof ve&&"feature-state"===t.name)return !1;var e=!0;return t.eachChild((function(t){e&&!De(t)&&(e=!1);})),e}function Le(t,e){if(t instanceof ve&&e.indexOf(t.name)>=0)return !1;var r=!0;return t.eachChild((function(t){r&&!Le(t,e)&&(r=!1);})),r}Ve.parse=function(t,e){if(2!==t.length)return e.error("'within' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(ie(t[1])){var r=t[1];if("FeatureCollection"===r.type)for(var n=0;n<r.features.length;++n){var i=r.features[n].geometry.type;if("Polygon"===i||"MultiPolygon"===i)return new Ve(r,r.features[n].geometry)}else if("Feature"===r.type){var a=r.geometry.type;if("Polygon"===a||"MultiPolygon"===a)return new Ve(r,r.geometry)}else if("Polygon"===r.type||"MultiPolygon"===r.type)return new Ve(r,r)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")},Ve.prototype.evaluate=function(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){var r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){var a=Me(e.coordinates,n,i),o=Pe(t.geometry(),r,n,i);if(!be(r,n))return !1;for(var s=0,u=o;s<u.length;s+=1)if(!Ae(u[s],a))return !1}if("MultiPolygon"===e.type){var l=Ee(e.coordinates,n,i),p=Pe(t.geometry(),r,n,i);if(!be(r,n))return !1;for(var c=0,h=p;c<h.length;c+=1)if(!Se(h[c],l))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){var r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){var a=Me(e.coordinates,n,i),o=Be(t.geometry(),r,n,i);if(!be(r,n))return !1;for(var s=0,u=o;s<u.length;s+=1)if(!ze(u[s],a))return !1}if("MultiPolygon"===e.type){var l=Ee(e.coordinates,n,i),p=Be(t.geometry(),r,n,i);if(!be(r,n))return !1;for(var c=0,h=p;c<h.length;c+=1)if(!Ce(h[c],l))return !1}return !0}(t,this.geometries)}return !1},Ve.prototype.eachChild=function(){},Ve.prototype.outputDefined=function(){return !0},Ve.prototype.serialize=function(){return ["within",this.geojson]};var Re=function(t,e){this.type=e.type,this.name=t,this.boundExpression=e;};Re.parse=function(t,e){if(2!==t.length||"string"!=typeof t[1])return e.error("'var' expression requires exactly one string literal argument.");var r=t[1];return e.scope.has(r)?new Re(r,e.scope.get(r)):e.error('Unknown variable "'+r+'". Make sure "'+r+'" has been bound in an enclosing "let" expression before using it.',1)},Re.prototype.evaluate=function(t){return this.boundExpression.evaluate(t)},Re.prototype.eachChild=function(){},Re.prototype.outputDefined=function(){return !1},Re.prototype.serialize=function(){return ["var",this.name]};var Oe=function(t,e,r,n,i){void 0===e&&(e=[]),void 0===n&&(n=new Vt),void 0===i&&(i=[]),this.registry=t,this.path=e,this.key=e.map((function(t){return "["+t+"]"})).join(""),this.scope=n,this.errors=i,this.expectedType=r;};function Ue(t,e){for(var r,n=t.length-1,i=0,a=n,o=0;i<=a;)if((r=t[o=Math.floor((i+a)/2)])<=e){if(o===n||e<t[o+1])return o;i=o+1;}else {if(!(r>e))throw new ue("Input is not a number.");a=o-1;}return 0}Oe.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},Oe.prototype._parse=function(t,e){function r(t,e,r){return "assert"===r?new pe(e,[t]):"coerce"===r?new ye(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var n=t[0];if("string"!=typeof n)return this.error("Expression name must be a string, but found "+typeof n+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var i=this.registry[n];if(i){var a=i.parse(t,this);if(!a)return null;if(this.expectedType){var o=this.expectedType,s=a.type;if("string"!==o.kind&&"number"!==o.kind&&"boolean"!==o.kind&&"object"!==o.kind&&"array"!==o.kind||"value"!==s.kind)if("color"!==o.kind&&"formatted"!==o.kind&&"resolvedImage"!==o.kind||"value"!==s.kind&&"string"!==s.kind){if(this.checkSubtype(o,s))return null}else a=r(a,o,e.typeAnnotation||"coerce");else a=r(a,o,e.typeAnnotation||"assert");}if(!(a instanceof se)&&"resolvedImage"!==a.type.kind&&function t(e){if(e instanceof Re)return t(e.boundExpression);if(e instanceof ve&&"error"===e.name)return !1;if(e instanceof ge)return !1;if(e instanceof Ve)return !1;var r=e instanceof ye||e instanceof pe,n=!0;return e.eachChild((function(e){n=r?n&&t(e):n&&e instanceof se;})),!!n&&Fe(e)&&Le(e,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}(a)){var u=new me;try{a=new se(a.type,a.evaluate(u));}catch(t){return this.error(t.message),null}}return a}return this.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':"Expected an array, but found "+typeof t+" instead.")},Oe.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Oe(this.registry,n,e||null,i,this.errors)},Oe.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map((function(t){return "["+t+"]"})).join("");this.errors.push(new Bt(n,t));},Oe.prototype.checkSubtype=function(t,e){var r=Jt(t,e);return r&&this.error(r),r};var je=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n<i.length;n+=1){var a=i[n],o=a[1];this.labels.push(a[0]),this.outputs.push(o);}};function qe(t,e,r){return t*(1-r)+e*r}je.parse=function(t,e){if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");var r=e.parse(t[1],1,Dt);if(!r)return null;var n=[],i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(var a=1;a<t.length;a+=2){var o=1===a?-1/0:t[a],s=t[a+1],u=a,l=a+1;if("number"!=typeof o)return e.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.',u);if(n.length&&n[n.length-1][0]>=o)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',u);var p=e.parse(s,l,i);if(!p)return null;i=i||p.type,n.push([o,p]);}return new je(i,r,n)},je.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[Ue(e,n)].evaluate(t)},je.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1)t(r[e]);},je.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))},je.prototype.serialize=function(){for(var t=["step",this.input.serialize()],e=0;e<this.labels.length;e++)e>0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var Ne=Object.freeze({__proto__:null,number:qe,color:function(t,e,r){return new Wt(qe(t.r,e.r,r),qe(t.g,e.g,r),qe(t.b,e.b,r),qe(t.a,e.a,r))},array:function(t,e,r){return t.map((function(t,n){return qe(t,e[n],r)}))}}),Ke=6/29*3*(6/29),Ge=Math.PI/180,Ze=180/Math.PI;function Xe(t){return t>.008856451679035631?Math.pow(t,1/3):t/Ke+4/29}function Je(t){return t>6/29?t*t*t:Ke*(t-4/29)}function He(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Ye(t){return (t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function $e(t){var e=Ye(t.r),r=Ye(t.g),n=Ye(t.b),i=Xe((.4124564*e+.3575761*r+.1804375*n)/.95047),a=Xe((.2126729*e+.7151522*r+.072175*n)/1);return {l:116*a-16,a:500*(i-a),b:200*(a-Xe((.0193339*e+.119192*r+.9503041*n)/1.08883)),alpha:t.a}}function We(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=1*Je(e),r=.95047*Je(r),n=1.08883*Je(n),new Wt(He(3.2404542*r-1.5371385*e-.4985314*n),He(-.969266*r+1.8760108*e+.041556*n),He(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}function Qe(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}var tr={forward:$e,reverse:We,interpolate:function(t,e,r){return {l:qe(t.l,e.l,r),a:qe(t.a,e.a,r),b:qe(t.b,e.b,r),alpha:qe(t.alpha,e.alpha,r)}}},er={forward:function(t){var e=$e(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*Ze;return {h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*Ge,r=t.c;return We({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return {h:Qe(t.h,e.h,r),c:qe(t.c,e.c,r),l:qe(t.l,e.l,r),alpha:qe(t.alpha,e.alpha,r)}}},rr=Object.freeze({__proto__:null,lab:tr,hcl:er}),nr=function(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(var a=0,o=i;a<o.length;a+=1){var s=o[a],u=s[1];this.labels.push(s[0]),this.outputs.push(u);}};function ir(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}nr.interpolationFactor=function(t,e,n,i){var a=0;if("exponential"===t.name)a=ir(e,t.base,n,i);else if("linear"===t.name)a=ir(e,1,n,i);else if("cubic-bezier"===t.name){var o=t.controlPoints;a=new r(o[0],o[1],o[2],o[3]).solve(ir(e,1,n,i));}return a},nr.parse=function(t,e){var r=t[0],n=t[1],i=t[2],a=t.slice(3);if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){var o=n[1];if("number"!=typeof o)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:o};}else {if("cubic-bezier"!==n[0])return e.error("Unknown interpolation type "+String(n[0]),1,0);var s=n.slice(1);if(4!==s.length||s.some((function(t){return "number"!=typeof t||t<0||t>1})))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:s};}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(i=e.parse(i,2,Dt)))return null;var u=[],l=null;"interpolate-hcl"===r||"interpolate-lab"===r?l=Ot:e.expectedType&&"value"!==e.expectedType.kind&&(l=e.expectedType);for(var p=0;p<a.length;p+=2){var c=a[p],h=a[p+1],f=p+3,y=p+4;if("number"!=typeof c)return e.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',f);if(u.length&&u[u.length-1][0]>=c)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',f);var d=e.parse(h,y,l);if(!d)return null;l=l||d.type,u.push([c,d]);}return "number"===l.kind||"color"===l.kind||"array"===l.kind&&"number"===l.itemType.kind&&"number"==typeof l.N?new nr(l,r,n,i,u):e.error("Type "+Zt(l)+" is not interpolatable.")},nr.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var a=Ue(e,n),o=nr.interpolationFactor(this.interpolation,n,e[a],e[a+1]),s=r[a].evaluate(t),u=r[a+1].evaluate(t);return "interpolate"===this.operator?Ne[this.type.kind.toLowerCase()](s,u,o):"interpolate-hcl"===this.operator?er.reverse(er.interpolate(er.forward(s),er.forward(u),o)):tr.reverse(tr.interpolate(tr.forward(s),tr.forward(u),o))},nr.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1)t(r[e]);},nr.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))},nr.prototype.serialize=function(){var t;t="linear"===this.interpolation.name?["linear"]:"exponential"===this.interpolation.name?1===this.interpolation.base?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier"].concat(this.interpolation.controlPoints);for(var e=[this.operator,t,this.input.serialize()],r=0;r<this.labels.length;r++)e.push(this.labels[r],this.outputs[r].serialize());return e};var ar=function(t,e){this.type=t,this.args=e;};ar.parse=function(t,e){if(t.length<2)return e.error("Expectected at least one argument.");var r=null,n=e.expectedType;n&&"value"!==n.kind&&(r=n);for(var i=[],a=0,o=t.slice(1);a<o.length;a+=1){var s=e.parse(o[a],1+i.length,r,void 0,{typeAnnotation:"omit"});if(!s)return null;r=r||s.type,i.push(s);}var u=n&&i.some((function(t){return Jt(n,t.type)}));return new ar(u?jt:r,i)},ar.prototype.evaluate=function(t){for(var e,r=null,n=0,i=0,a=this.args;i<a.length&&(n++,(r=a[i].evaluate(t))&&r instanceof re&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null===r);i+=1);return r},ar.prototype.eachChild=function(t){this.args.forEach(t);},ar.prototype.outputDefined=function(){return this.args.every((function(t){return t.outputDefined()}))},ar.prototype.serialize=function(){var t=["coalesce"];return this.eachChild((function(e){t.push(e.serialize());})),t};var or=function(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;};or.prototype.evaluate=function(t){return this.result.evaluate(t)},or.prototype.eachChild=function(t){for(var e=0,r=this.bindings;e<r.length;e+=1)t(r[e][1]);t(this.result);},or.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found "+(t.length-1)+" instead.");for(var r=[],n=1;n<t.length-1;n+=2){var i=t[n];if("string"!=typeof i)return e.error("Expected string, but found "+typeof i+" instead.",n);if(/[^a-zA-Z0-9_]/.test(i))return e.error("Variable names must contain only alphanumeric characters or '_'.",n);var a=e.parse(t[n+1],n+1);if(!a)return null;r.push([i,a]);}var o=e.parse(t[t.length-1],t.length-1,e.expectedType,r);return o?new or(r,o):null},or.prototype.outputDefined=function(){return this.result.outputDefined()},or.prototype.serialize=function(){for(var t=["let"],e=0,r=this.bindings;e<r.length;e+=1){var n=r[e];t.push(n[0],n[1].serialize());}return t.push(this.result.serialize()),t};var sr=function(t,e,r){this.type=t,this.index=e,this.input=r;};sr.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Dt),n=e.parse(t[2],2,Gt(e.expectedType||jt));return r&&n?new sr(n.type.itemType,r,n):null},sr.prototype.evaluate=function(t){var e=this.index.evaluate(t),r=this.input.evaluate(t);if(e<0)throw new ue("Array index out of bounds: "+e+" < 0.");if(e>=r.length)throw new ue("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new ue("Array index must be an integer, but found "+e+" instead.");return r[e]},sr.prototype.eachChild=function(t){t(this.index),t(this.input);},sr.prototype.outputDefined=function(){return !1},sr.prototype.serialize=function(){return ["at",this.index.serialize(),this.input.serialize()]};var ur=function(t,e){this.type=Rt,this.needle=t,this.haystack=e;};ur.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,jt),n=e.parse(t[2],2,jt);return r&&n?Ht(r.type,[Rt,Lt,Dt,Ft,jt])?new ur(r,n):e.error("Expected first argument to be of type boolean, string, number or null, but found "+Zt(r.type)+" instead"):null},ur.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!Yt(e,["boolean","string","number","null"]))throw new ue("Expected first argument to be of type boolean, string, number or null, but found "+Zt(ae(e))+" instead.");if(!Yt(r,["string","array"]))throw new ue("Expected second argument to be of type array or string, but found "+Zt(ae(r))+" instead.");return r.indexOf(e)>=0},ur.prototype.eachChild=function(t){t(this.needle),t(this.haystack);},ur.prototype.outputDefined=function(){return !0},ur.prototype.serialize=function(){return ["in",this.needle.serialize(),this.haystack.serialize()]};var lr=function(t,e,r){this.type=Dt,this.needle=t,this.haystack=e,this.fromIndex=r;};lr.parse=function(t,e){if(t.length<=2||t.length>=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,jt),n=e.parse(t[2],2,jt);if(!r||!n)return null;if(!Ht(r.type,[Rt,Lt,Dt,Ft,jt]))return e.error("Expected first argument to be of type boolean, string, number or null, but found "+Zt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Dt);return i?new lr(r,n,i):null}return new lr(r,n)},lr.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!Yt(e,["boolean","string","number","null"]))throw new ue("Expected first argument to be of type boolean, string, number or null, but found "+Zt(ae(e))+" instead.");if(!Yt(r,["string","array"]))throw new ue("Expected second argument to be of type array or string, but found "+Zt(ae(r))+" instead.");if(this.fromIndex){var n=this.fromIndex.evaluate(t);return r.indexOf(e,n)}return r.indexOf(e)},lr.prototype.eachChild=function(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);},lr.prototype.outputDefined=function(){return !1},lr.prototype.serialize=function(){if(null!=this.fromIndex&&void 0!==this.fromIndex){var t=this.fromIndex.serialize();return ["index-of",this.needle.serialize(),this.haystack.serialize(),t]}return ["index-of",this.needle.serialize(),this.haystack.serialize()]};var pr=function(t,e,r,n,i,a){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=a;};pr.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},a=[],o=2;o<t.length-1;o+=2){var s=t[o],u=t[o+1];Array.isArray(s)||(s=[s]);var l=e.concat(o);if(0===s.length)return l.error("Expected at least one branch label.");for(var p=0,c=s;p<c.length;p+=1){var h=c[p];if("number"!=typeof h&&"string"!=typeof h)return l.error("Branch labels must be numbers or strings.");if("number"==typeof h&&Math.abs(h)>Number.MAX_SAFE_INTEGER)return l.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof h&&Math.floor(h)!==h)return l.error("Numeric branch labels must be integer values.");if(r){if(l.checkSubtype(r,ae(h)))return null}else r=ae(h);if(void 0!==i[String(h)])return l.error("Branch labels must be unique.");i[String(h)]=a.length;}var f=e.parse(u,o,n);if(!f)return null;n=n||f.type,a.push(f);}var y=e.parse(t[1],1,jt);if(!y)return null;var d=e.parse(t[t.length-1],t.length-1,n);return d?"value"!==y.type.kind&&e.concat(1).checkSubtype(r,y.type)?null:new pr(r,n,y,i,a,d):null},pr.prototype.evaluate=function(t){var e=this.input.evaluate(t);return (ae(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},pr.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);},pr.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))&&this.otherwise.outputDefined()},pr.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,a=Object.keys(this.cases).sort();i<a.length;i+=1){var o=a[i];void 0===(c=n[this.cases[o]])?(n[this.cases[o]]=r.length,r.push([this.cases[o],[o]])):r[c][1].push(o);}for(var s=function(e){return "number"===t.inputType.kind?Number(e):e},u=0,l=r;u<l.length;u+=1){var p=l[u],c=p[0],h=p[1];e.push(1===h.length?s(h[0]):h.map(s)),e.push(this.outputs[outputIndex$1].serialize());}return e.push(this.otherwise.serialize()),e};var cr=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r;};cr.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var n=[],i=1;i<t.length-1;i+=2){var a=e.parse(t[i],i,Rt);if(!a)return null;var o=e.parse(t[i+1],i+1,r);if(!o)return null;n.push([a,o]),r=r||o.type;}var s=e.parse(t[t.length-1],t.length-1,r);return s?new cr(r,n,s):null},cr.prototype.evaluate=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[1];if(n[0].evaluate(t))return i.evaluate(t)}return this.otherwise.evaluate(t)},cr.prototype.eachChild=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[1];t(n[0]),t(i);}t(this.otherwise);},cr.prototype.outputDefined=function(){return this.branches.every((function(t){return t[1].outputDefined()}))&&this.otherwise.outputDefined()},cr.prototype.serialize=function(){var t=["case"];return this.eachChild((function(e){t.push(e.serialize());})),t};var hr=function(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;};function fr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function yr(t,e,r,n){return 0===n.compare(e,r)}function dr(t,e,r){var n="=="!==t&&"!="!==t;return function(){function i(t,e,r){this.type=Rt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}return i.parse=function(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");var r=t[0],a=e.parse(t[1],1,jt);if(!a)return null;if(!fr(r,a.type))return e.concat(1).error('"'+r+"\" comparisons are not supported for type '"+Zt(a.type)+"'.");var o=e.parse(t[2],2,jt);if(!o)return null;if(!fr(r,o.type))return e.concat(2).error('"'+r+"\" comparisons are not supported for type '"+Zt(o.type)+"'.");if(a.type.kind!==o.type.kind&&"value"!==a.type.kind&&"value"!==o.type.kind)return e.error("Cannot compare types '"+Zt(a.type)+"' and '"+Zt(o.type)+"'.");n&&("value"===a.type.kind&&"value"!==o.type.kind?a=new pe(o.type,[a]):"value"!==a.type.kind&&"value"===o.type.kind&&(o=new pe(a.type,[o])));var s=null;if(4===t.length){if("string"!==a.type.kind&&"string"!==o.type.kind&&"value"!==a.type.kind&&"value"!==o.type.kind)return e.error("Cannot use collator to compare non-string types.");if(!(s=e.parse(t[3],3,qt)))return null}return new i(a,o,s)},i.prototype.evaluate=function(i){var a=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){var s=ae(a),u=ae(o);if(s.kind!==u.kind||"string"!==s.kind&&"number"!==s.kind)throw new ue('Expected arguments for "'+t+'" to be (string, string) or (number, number), but found ('+s.kind+", "+u.kind+") instead.")}if(this.collator&&!n&&this.hasUntypedArgument){var l=ae(a),p=ae(o);if("string"!==l.kind||"string"!==p.kind)return e(i,a,o)}return this.collator?r(i,a,o,this.collator.evaluate(i)):e(i,a,o)},i.prototype.eachChild=function(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);},i.prototype.outputDefined=function(){return !0},i.prototype.serialize=function(){var e=[t];return this.eachChild((function(t){e.push(t.serialize());})),e},i}()}hr.parse=function(t,e){if(t.length<=2||t.length>=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,jt),n=e.parse(t[2],2,Dt);if(!r||!n)return null;if(!Ht(r.type,[Gt(jt),Lt,jt]))return e.error("Expected first argument to be of type array or string, but found "+Zt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Dt);return i?new hr(r.type,r,n,i):null}return new hr(r.type,r,n)},hr.prototype.evaluate=function(t){var e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);if(!Yt(e,["string","array"]))throw new ue("Expected first argument to be of type array or string, but found "+Zt(ae(e))+" instead.");if(this.endIndex){var n=this.endIndex.evaluate(t);return e.slice(r,n)}return e.slice(r)},hr.prototype.eachChild=function(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);},hr.prototype.outputDefined=function(){return !1},hr.prototype.serialize=function(){if(null!=this.endIndex&&void 0!==this.endIndex){var t=this.endIndex.serialize();return ["slice",this.input.serialize(),this.beginIndex.serialize(),t]}return ["slice",this.input.serialize(),this.beginIndex.serialize()]};var mr=dr("==",(function(t,e,r){return e===r}),yr),vr=dr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !yr(0,e,r,n)})),gr=dr("<",(function(t,e,r){return e<r}),(function(t,e,r,n){return n.compare(e,r)<0})),xr=dr(">",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),br=dr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),wr=dr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0})),_r=function(t,e,r,n,i){this.type=Lt,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;};_r.parse=function(t,e){if(3!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,Dt);if(!r)return null;var n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");var i=null;if(n.locale&&!(i=e.parse(n.locale,1,Lt)))return null;var a=null;if(n.currency&&!(a=e.parse(n.currency,1,Lt)))return null;var o=null;if(n["min-fraction-digits"]&&!(o=e.parse(n["min-fraction-digits"],1,Dt)))return null;var s=null;return n["max-fraction-digits"]&&!(s=e.parse(n["max-fraction-digits"],1,Dt))?null:new _r(r,i,a,o,s)},_r.prototype.evaluate=function(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))},_r.prototype.eachChild=function(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);},_r.prototype.outputDefined=function(){return !1},_r.prototype.serialize=function(){var t={};return this.locale&&(t.locale=this.locale.serialize()),this.currency&&(t.currency=this.currency.serialize()),this.minFractionDigits&&(t["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(t["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),t]};var Ar=function(t){this.type=Dt,this.input=t;};Ar.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+Zt(r.type)+" instead."):new Ar(r):null},Ar.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new ue("Expected value to be of type string or array, but found "+Zt(ae(e))+" instead.")},Ar.prototype.eachChild=function(t){t(this.input);},Ar.prototype.outputDefined=function(){return !1},Ar.prototype.serialize=function(){var t=["length"];return this.eachChild((function(e){t.push(e.serialize());})),t};var Sr={"==":mr,"!=":vr,">":xr,"<":gr,">=":wr,"<=":br,array:pe,at:sr,boolean:pe,case:cr,coalesce:ar,collator:ge,format:ce,image:he,in:ur,"index-of":lr,interpolate:nr,"interpolate-hcl":nr,"interpolate-lab":nr,length:Ar,let:or,literal:se,match:pr,number:pe,"number-format":_r,object:pe,slice:hr,step:je,string:pe,"to-boolean":ye,"to-color":ye,"to-number":ye,"to-string":ye,var:Re,within:Ve};function kr(t,e){var r=e[0],n=e[1],i=e[2],a=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var o=a?a.evaluate(t):1,s=ne(r,n,i,o);if(s)throw new ue(s);return new Wt(r/255*o,n/255*o,i/255*o,o)}function Ir(t,e){return t in e}function zr(t,e){var r=e[t];return void 0===r?null:r}function Cr(t){return {type:t}}function Mr(t){return {result:"success",value:t}}function Er(t){return {result:"error",value:t}}function Tr(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Pr(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Br(t){return !!t.expression&&t.expression.interpolated}function Vr(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Fr(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function Dr(t){return t}function Lr(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Rr(t,e,r,n,i){return Lr(typeof r===i?n[r]:void 0,t.default,e.default)}function Or(t,e,r){if("number"!==Vr(r))return Lr(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=Ue(t.stops.map((function(t){return t[0]})),r);return t.stops[i][1]}function Ur(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==Vr(r))return Lr(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var a=Ue(t.stops.map((function(t){return t[0]})),r),o=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[a][0],t.stops[a+1][0]),s=t.stops[a][1],u=t.stops[a+1][1],l=Ne[e.type]||Dr;if(t.colorSpace&&"rgb"!==t.colorSpace){var p=rr[t.colorSpace];l=function(t,e){return p.reverse(p.interpolate(p.forward(t),p.forward(e),o))};}return "function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=u.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return l(r,n,o)}}:l(s,u,o)}function jr(t,e,r){return "color"===e.type?r=Wt.parse(r):"formatted"===e.type?r=ee.fromString(r.toString()):"resolvedImage"===e.type?r=re.fromString(r.toString()):Vr(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),Lr(r,t.default,e.default)}ve.register(Sr,{error:[{kind:"error"},[Lt],function(t,e){throw new ue(e[0].evaluate(t))}],typeof:[Lt,[jt],function(t,e){return Zt(ae(e[0].evaluate(t)))}],"to-rgba":[Gt(Dt,4),[Ot],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[Ot,[Dt,Dt,Dt],kr],rgba:[Ot,[Dt,Dt,Dt,Dt],kr],has:{type:Rt,overloads:[[[Lt],function(t,e){return Ir(e[0].evaluate(t),t.properties())}],[[Lt,Ut],function(t,e){var r=e[1];return Ir(e[0].evaluate(t),r.evaluate(t))}]]},get:{type:jt,overloads:[[[Lt],function(t,e){return zr(e[0].evaluate(t),t.properties())}],[[Lt,Ut],function(t,e){var r=e[1];return zr(e[0].evaluate(t),r.evaluate(t))}]]},"feature-state":[jt,[Lt],function(t,e){return zr(e[0].evaluate(t),t.featureState||{})}],properties:[Ut,[],function(t){return t.properties()}],"geometry-type":[Lt,[],function(t){return t.geometryType()}],id:[jt,[],function(t){return t.id()}],zoom:[Dt,[],function(t){return t.globals.zoom}],"heatmap-density":[Dt,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[Dt,[],function(t){return t.globals.lineProgress||0}],accumulated:[jt,[],function(t){return void 0===t.globals.accumulated?null:t.globals.accumulated}],"+":[Dt,Cr(Dt),function(t,e){for(var r=0,n=0,i=e;n<i.length;n+=1)r+=i[n].evaluate(t);return r}],"*":[Dt,Cr(Dt),function(t,e){for(var r=1,n=0,i=e;n<i.length;n+=1)r*=i[n].evaluate(t);return r}],"-":{type:Dt,overloads:[[[Dt,Dt],function(t,e){var r=e[1];return e[0].evaluate(t)-r.evaluate(t)}],[[Dt],function(t,e){return -e[0].evaluate(t)}]]},"/":[Dt,[Dt,Dt],function(t,e){var r=e[1];return e[0].evaluate(t)/r.evaluate(t)}],"%":[Dt,[Dt,Dt],function(t,e){var r=e[1];return e[0].evaluate(t)%r.evaluate(t)}],ln2:[Dt,[],function(){return Math.LN2}],pi:[Dt,[],function(){return Math.PI}],e:[Dt,[],function(){return Math.E}],"^":[Dt,[Dt,Dt],function(t,e){var r=e[1];return Math.pow(e[0].evaluate(t),r.evaluate(t))}],sqrt:[Dt,[Dt],function(t,e){return Math.sqrt(e[0].evaluate(t))}],log10:[Dt,[Dt],function(t,e){return Math.log(e[0].evaluate(t))/Math.LN10}],ln:[Dt,[Dt],function(t,e){return Math.log(e[0].evaluate(t))}],log2:[Dt,[Dt],function(t,e){return Math.log(e[0].evaluate(t))/Math.LN2}],sin:[Dt,[Dt],function(t,e){return Math.sin(e[0].evaluate(t))}],cos:[Dt,[Dt],function(t,e){return Math.cos(e[0].evaluate(t))}],tan:[Dt,[Dt],function(t,e){return Math.tan(e[0].evaluate(t))}],asin:[Dt,[Dt],function(t,e){return Math.asin(e[0].evaluate(t))}],acos:[Dt,[Dt],function(t,e){return Math.acos(e[0].evaluate(t))}],atan:[Dt,[Dt],function(t,e){return Math.atan(e[0].evaluate(t))}],min:[Dt,Cr(Dt),function(t,e){return Math.min.apply(Math,e.map((function(e){return e.evaluate(t)})))}],max:[Dt,Cr(Dt),function(t,e){return Math.max.apply(Math,e.map((function(e){return e.evaluate(t)})))}],abs:[Dt,[Dt],function(t,e){return Math.abs(e[0].evaluate(t))}],round:[Dt,[Dt],function(t,e){var r=e[0].evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Dt,[Dt],function(t,e){return Math.floor(e[0].evaluate(t))}],ceil:[Dt,[Dt],function(t,e){return Math.ceil(e[0].evaluate(t))}],"filter-==":[Rt,[Lt,jt],function(t,e){var r=e[0],n=e[1];return t.properties()[r.value]===n.value}],"filter-id-==":[Rt,[jt],function(t,e){var r=e[0];return t.id()===r.value}],"filter-type-==":[Rt,[Lt],function(t,e){var r=e[0];return t.geometryType()===r.value}],"filter-<":[Rt,[Lt,jt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<a}],"filter-id-<":[Rt,[jt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<i}],"filter->":[Rt,[Lt,jt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[Rt,[jt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[Rt,[Lt,jt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[Rt,[jt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[Rt,[Lt,jt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[Rt,[jt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[Rt,[jt],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[Rt,[],function(t){return null!==t.id()&&void 0!==t.id()}],"filter-type-in":[Rt,[Gt(Lt)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[Rt,[Gt(jt)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[Rt,[Lt,Gt(jt)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[Rt,[Lt,Gt(jt)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[r.value],n.value,0,n.value.length-1)}],all:{type:Rt,overloads:[[[Rt,Rt],function(t,e){var r=e[1];return e[0].evaluate(t)&&r.evaluate(t)}],[Cr(Rt),function(t,e){for(var r=0,n=e;r<n.length;r+=1)if(!n[r].evaluate(t))return !1;return !0}]]},any:{type:Rt,overloads:[[[Rt,Rt],function(t,e){var r=e[1];return e[0].evaluate(t)||r.evaluate(t)}],[Cr(Rt),function(t,e){for(var r=0,n=e;r<n.length;r+=1)if(n[r].evaluate(t))return !0;return !1}]]},"!":[Rt,[Rt],function(t,e){return !e[0].evaluate(t)}],"is-supported-script":[Rt,[Lt],function(t,e){var r=t.globals&&t.globals.isSupportedScript;return !r||r(e[0].evaluate(t))}],upcase:[Lt,[Lt],function(t,e){return e[0].evaluate(t).toUpperCase()}],downcase:[Lt,[Lt],function(t,e){return e[0].evaluate(t).toLowerCase()}],concat:[Lt,Cr(jt),function(t,e){return e.map((function(e){return oe(e.evaluate(t))})).join("")}],"resolved-locale":[Lt,[qt],function(t,e){return e[0].evaluate(t).resolvedLocale()}]});var qr=function(t,e){this.expression=t,this._warningHistory={},this._evaluator=new me,this._defaultValue=e?function(t){return "color"===t.type&&Fr(t.default)?new Wt(0,0,0,0):"color"===t.type?Wt.parse(t.default)||null:void 0===t.default?null:t.default}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null;};function Nr(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Sr}function Kr(t,e){var r=new Oe(Sr,[],e?function(t){var e={color:Ot,string:Lt,number:Dt,enum:Lt,boolean:Rt,formatted:Nt,resolvedImage:Kt};return "array"===t.type?Gt(e[t.value]||jt,t.length):e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?Mr(new qr(n,e)):Er(r.errors)}qr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a,this.expression.evaluate(this._evaluator)},qr.prototype.evaluate=function(t,e,r,n,i,a){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a||null;try{var o=this.expression.evaluate(this._evaluator);if(null==o||"number"==typeof o&&o!=o)return this._defaultValue;if(this._enumValues&&!(o in this._enumValues))throw new ue("Expected value to be one of "+Object.keys(this._enumValues).map((function(t){return JSON.stringify(t)})).join(", ")+", but found "+JSON.stringify(o)+" instead.");return o}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var Gr=function(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!De(e.expression);};Gr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,a)},Gr.prototype.evaluate=function(t,e,r,n,i,a){return this._styleExpression.evaluate(t,e,r,n,i,a)};var Zr=function(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!De(e.expression),this.interpolationType=n;};function Xr(t,e){if("error"===(t=Kr(t,e)).result)return t;var r=t.value.expression,n=Fe(r);if(!n&&!Tr(e))return Er([new Bt("","data expressions not supported")]);var i=Le(r,["zoom"]);if(!i&&!Pr(e))return Er([new Bt("","zoom expressions not supported")]);var a=function t(e){var r=null;if(e instanceof or)r=t(e.result);else if(e instanceof ar)for(var n=0,i=e.args;n<i.length&&!(r=t(i[n]));n+=1);else (e instanceof je||e instanceof nr)&&e.input instanceof ve&&"zoom"===e.input.name&&(r=e);return r instanceof Bt||e.eachChild((function(e){var n=t(e);n instanceof Bt?r=n:!r&&n?r=new Bt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):r&&n&&r!==n&&(r=new Bt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),r}(r);return a||i?a instanceof Bt?Er([a]):a instanceof nr&&!Br(e)?Er([new Bt("",'"interpolate" expressions cannot be used with this property')]):Mr(a?new Zr(n?"camera":"composite",t.value,a.labels,a instanceof nr?a.interpolation:void 0):new Gr(n?"constant":"source",t.value)):Er([new Bt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}Zr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,a)},Zr.prototype.evaluate=function(t,e,r,n,i,a){return this._styleExpression.evaluate(t,e,r,n,i,a)},Zr.prototype.interpolationFactor=function(t,e,r){return this.interpolationType?nr.interpolationFactor(this.interpolationType,t,e,r):0};var Jr=function(t,e){this._parameters=t,this._specification=e,Et(this,function t(e,r){var n,i,a,o="color"===r.type,s=e.stops&&"object"==typeof e.stops[0][0],u=s||!(s||void 0!==e.property),l=e.type||(Br(r)?"exponential":"interval");if(o&&((e=Et({},e)).stops&&(e.stops=e.stops.map((function(t){return [t[0],Wt.parse(t[1])]}))),e.default=Wt.parse(e.default?e.default:r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!rr[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===l)n=Ur;else if("interval"===l)n=Or;else if("categorical"===l){n=Rr,i=Object.create(null);for(var p=0,c=e.stops;p<c.length;p+=1){var h=c[p];i[h[0]]=h[1];}a=typeof e.stops[0][0];}else {if("identity"!==l)throw new Error('Unknown function type "'+l+'"');n=jr;}if(s){for(var f={},y=[],d=0;d<e.stops.length;d++){var m=e.stops[d],v=m[0].zoom;void 0===f[v]&&(f[v]={zoom:v,type:e.type,property:e.property,default:e.default,stops:[]},y.push(v)),f[v].stops.push([m[0].value,m[1]]);}for(var g=[],x=0,b=y;x<b.length;x+=1){var w=b[x];g.push([f[w].zoom,t(f[w],r)]);}var _={name:"linear"};return {kind:"composite",interpolationType:_,interpolationFactor:nr.interpolationFactor.bind(void 0,_),zoomStops:g.map((function(t){return t[0]})),evaluate:function(t,n){var i=t.zoom;return Ur({stops:g,base:e.base},r,i).evaluate(i,n)}}}if(u){var A="exponential"===l?{name:"exponential",base:void 0!==e.base?e.base:1}:null;return {kind:"camera",interpolationType:A,interpolationFactor:nr.interpolationFactor.bind(void 0,A),zoomStops:e.stops.map((function(t){return t[0]})),evaluate:function(t){return n(e,r,t.zoom,i,a)}}}return {kind:"source",evaluate:function(t,o){var s=o&&o.properties?o.properties[e.property]:void 0;return void 0===s?Lr(e.default,r.default):n(e,r,s,i,a)}}}(this._parameters,this._specification));};function Hr(t){var e=t.key,r=t.value,n=t.valueSpec||{},i=t.objectElementValidators||{},a=t.style,o=t.styleSpec,s=[],u=Vr(r);if("object"!==u)return [new Ct(e,r,"object expected, "+u+" found")];for(var l in r){var p=l.split(".")[0],c=n[p]||n["*"],h=void 0;if(i[p])h=i[p];else if(n[p])h=wn;else if(i["*"])h=i["*"];else {if(!n["*"]){s.push(new Ct(e,r[l],'unknown property "'+l+'"'));continue}h=wn;}s=s.concat(h({key:(e?e+".":e)+l,value:r[l],valueSpec:c,style:a,styleSpec:o,object:r,objectKey:l},r));}for(var f in n)i[f]||n[f].required&&void 0===n[f].default&&void 0===r[f]&&s.push(new Ct(e,r,'missing required property "'+f+'"'));return s}function Yr(t){var e=t.value,r=t.valueSpec,n=t.style,i=t.styleSpec,a=t.key,o=t.arrayElementValidator||wn;if("array"!==Vr(e))return [new Ct(a,e,"array expected, "+Vr(e)+" found")];if(r.length&&e.length!==r.length)return [new Ct(a,e,"array length "+r.length+" expected, length "+e.length+" found")];if(r["min-length"]&&e.length<r["min-length"])return [new Ct(a,e,"array length at least "+r["min-length"]+" expected, length "+e.length+" found")];var s={type:r.value,values:r.values};i.$version<7&&(s.function=r.function),"object"===Vr(r.value)&&(s=r.value);for(var u=[],l=0;l<e.length;l++)u=u.concat(o({array:e,arrayIndex:l,value:e[l],valueSpec:s,style:n,styleSpec:i,key:a+"["+l+"]"}));return u}function $r(t){var e=t.key,r=t.value,n=t.valueSpec,i=Vr(r);return "number"===i&&r!=r&&(i="NaN"),"number"!==i?[new Ct(e,r,"number expected, "+i+" found")]:"minimum"in n&&r<n.minimum?[new Ct(e,r,r+" is less than the minimum value "+n.minimum)]:"maximum"in n&&r>n.maximum?[new Ct(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function Wr(t){var e,r,n,i=t.valueSpec,a=Tt(t.value.type),o={},s="categorical"!==a&&void 0===t.value.property,u=!s,l="array"===Vr(t.value.stops)&&"array"===Vr(t.value.stops[0])&&"object"===Vr(t.value.stops[0][0]),p=Hr({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===a)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;return e=e.concat(Yr({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:c})),"array"===Vr(r)&&0===r.length&&e.push(new Ct(t.key,r,"array must have at least one stop")),e},default:function(t){return wn({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===a&&s&&p.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===a||t.value.stops||p.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===a&&t.valueSpec.expression&&!Br(t.valueSpec)&&p.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(u&&!Tr(t.valueSpec)?p.push(new Ct(t.key,t.value,"property functions not supported")):s&&!Pr(t.valueSpec)&&p.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==a&&!l||void 0!==t.value.property||p.push(new Ct(t.key,t.value,'"property" property is required')),p;function c(t){var e=[],a=t.value,s=t.key;if("array"!==Vr(a))return [new Ct(s,a,"array expected, "+Vr(a)+" found")];if(2!==a.length)return [new Ct(s,a,"array length 2 expected, length "+a.length+" found")];if(l){if("object"!==Vr(a[0]))return [new Ct(s,a,"object expected, "+Vr(a[0])+" found")];if(void 0===a[0].zoom)return [new Ct(s,a,"object stop key must have zoom")];if(void 0===a[0].value)return [new Ct(s,a,"object stop key must have value")];if(n&&n>Tt(a[0].zoom))return [new Ct(s,a[0].zoom,"stop zoom values must appear in ascending order")];Tt(a[0].zoom)!==n&&(n=Tt(a[0].zoom),r=void 0,o={}),e=e.concat(Hr({key:s+"[0]",value:a[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:$r,value:h}}));}else e=e.concat(h({key:s+"[0]",value:a[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},a));return Nr(Pt(a[1]))?e.concat([new Ct(s+"[1]",a[1],"expressions are not allowed in function stops.")]):e.concat(wn({key:s+"[1]",value:a[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function h(t,n){var s=Vr(t.value),u=Tt(t.value),l=null!==t.value?t.value:n;if(e){if(s!==e)return [new Ct(t.key,l,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return [new Ct(t.key,l,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==a){var p="number expected, "+s+" found";return Tr(i)&&void 0===a&&(p+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,l,p)]}return "categorical"!==a||"number"!==s||isFinite(u)&&Math.floor(u)===u?"categorical"!==a&&"number"===s&&void 0!==r&&u<r?[new Ct(t.key,l,"stop domain values must appear in ascending order")]:(r=u,"categorical"===a&&u in o?[new Ct(t.key,l,"stop domain values must be unique")]:(o[u]=!0,[])):[new Ct(t.key,l,"integer expected, found "+u)]}}function Qr(t){var e=("property"===t.expressionContext?Xr:Kr)(Pt(t.value),t.valueSpec);if("error"===e.result)return e.value.map((function(e){return new Ct(""+t.key+e.key,t.value,e.message)}));var r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,'Invalid data expression for "'+t.propertyKey+'". Output values must be contained as literals within the expression.')];if("property"===t.expressionContext&&"layout"===t.propertyType&&!De(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!De(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!Le(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Fe(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function tn(t){var e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(Tt(r))&&i.push(new Ct(e,r,"expected one of ["+n.values.join(", ")+"], "+JSON.stringify(r)+" found")):-1===Object.keys(n.values).indexOf(Tt(r))&&i.push(new Ct(e,r,"expected one of ["+Object.keys(n.values).join(", ")+"], "+JSON.stringify(r)+" found")),i}function en(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return !1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(var e=0,r=t.slice(1);e<r.length;e+=1){var n=r[e];if(!en(n)&&"boolean"!=typeof n)return !1}return !0;default:return !0}}Jr.deserialize=function(t){return new Jr(t._parameters,t._specification)},Jr.serialize=function(t){return {_parameters:t._parameters,_specification:t._specification}};var rn={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function nn(t){if(null==t)return {filter:function(){return !0},needGeometry:!1};en(t)||(t=on(t));var e=Kr(t,rn);if("error"===e.result)throw new Error(e.value.map((function(t){return t.key+": "+t.message})).join(", "));return {filter:function(t,r,n){return e.value.evaluate(t,r,{},n)},needGeometry:function t(e){if(!Array.isArray(e))return !1;if("within"===e[0])return !0;for(var r=1;r<e.length;r++)if(t(e[r]))return !0;return !1}(t)}}function an(t,e){return t<e?-1:t>e?1:0}function on(t){if(!t)return !0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?sn(t[1],t[2],"=="):"!="===r?pn(sn(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?sn(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(on))):"all"===r?["all"].concat(t.slice(1).map(on)):"none"===r?["all"].concat(t.slice(1).map(on).map(pn)):"in"===r?un(t[1],t.slice(2)):"!in"===r?pn(un(t[1],t.slice(2))):"has"===r?ln(t[1]):"!has"===r?pn(ln(t[1])):"within"!==r||t}function sn(t,e,r){switch(t){case"$type":return ["filter-type-"+r,e];case"$id":return ["filter-id-"+r,e];default:return ["filter-"+r,t,e]}}function un(t,e){if(0===e.length)return !1;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((function(t){return typeof t!=typeof e[0]}))?["filter-in-large",t,["literal",e.sort(an)]]:["filter-in-small",t,["literal",e]]}}function ln(t){switch(t){case"$type":return !0;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function pn(t){return ["!",t]}function cn(t){return en(Pt(t.value))?Qr(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value,n=e.key;if("array"!==Vr(r))return [new Ct(n,r,"array expected, "+Vr(r)+" found")];var i,a=e.styleSpec,o=[];if(r.length<1)return [new Ct(n,r,"filter array must have at least 1 element")];switch(o=o.concat(tn({key:n+"[0]",value:r[0],valueSpec:a.filter_operator,style:e.style,styleSpec:e.styleSpec})),Tt(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===Tt(r[1])&&o.push(new Ct(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&o.push(new Ct(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(i=Vr(r[1]))&&o.push(new Ct(n+"[1]",r[1],"string expected, "+i+" found"));for(var s=2;s<r.length;s++)i=Vr(r[s]),"$type"===Tt(r[1])?o=o.concat(tn({key:n+"["+s+"]",value:r[s],valueSpec:a.geometry_type,style:e.style,styleSpec:e.styleSpec})):"string"!==i&&"number"!==i&&"boolean"!==i&&o.push(new Ct(n+"["+s+"]",r[s],"string, number, or boolean expected, "+i+" found"));break;case"any":case"all":case"none":for(var u=1;u<r.length;u++)o=o.concat(t({key:n+"["+u+"]",value:r[u],style:e.style,styleSpec:e.styleSpec}));break;case"has":case"!has":i=Vr(r[1]),2!==r.length?o.push(new Ct(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"string"!==i&&o.push(new Ct(n+"[1]",r[1],"string expected, "+i+" found"));break;case"within":i=Vr(r[1]),2!==r.length?o.push(new Ct(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"object"!==i&&o.push(new Ct(n+"[1]",r[1],"object expected, "+i+" found"));}return o}(t)}function hn(t,e){var r=t.key,n=t.style,i=t.styleSpec,a=t.value,o=t.objectKey,s=i[e+"_"+t.layerType];if(!s)return [];var u=o.match(/^(.*)-transition$/);if("paint"===e&&u&&s[u[1]]&&s[u[1]].transition)return wn({key:r,value:a,valueSpec:i.transition,style:n,styleSpec:i});var l,p=t.valueSpec||s[o];if(!p)return [new Ct(r,a,'unknown property "'+o+'"')];if("string"===Vr(a)&&Tr(p)&&!p.tokens&&(l=/^{([^}]+)}$/.exec(a)))return [new Ct(r,a,'"'+o+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(l[1])+" }`.")];var c=[];return "symbol"===t.layerType&&("text-field"===o&&n&&!n.glyphs&&c.push(new Ct(r,a,'use of "text-field" requires a style "glyphs" property')),"text-font"===o&&Fr(Pt(a))&&"identity"===Tt(a.type)&&c.push(new Ct(r,a,'"text-font" does not support identity functions'))),c.concat(wn({key:t.key,value:a,valueSpec:p,style:n,styleSpec:i,expressionContext:"property",propertyType:e,propertyKey:o}))}function fn(t){return hn(t,"paint")}function yn(t){return hn(t,"layout")}function dn(t){var e=[],r=t.value,n=t.key,i=t.style,a=t.styleSpec;r.type||r.ref||e.push(new Ct(n,r,'either "type" or "ref" is required'));var o,s=Tt(r.type),u=Tt(r.ref);if(r.id)for(var l=Tt(r.id),p=0;p<t.arrayIndex;p++){var c=i.layers[p];Tt(c.id)===l&&e.push(new Ct(n,r.id,'duplicate layer id "'+r.id+'", previously used at line '+c.id.__line__));}if("ref"in r)["type","source","source-layer","filter","layout"].forEach((function(t){t in r&&e.push(new Ct(n,r[t],'"'+t+'" is prohibited for ref layers'));})),i.layers.forEach((function(t){Tt(t.id)===u&&(o=t);})),o?o.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):s=Tt(o.type):e.push(new Ct(n,r.ref,'ref layer "'+u+'" not found'));else if("background"!==s)if(r.source){var h=i.sources&&i.sources[r.source],f=h&&Tt(h.type);h?"vector"===f&&"raster"===s?e.push(new Ct(n,r.source,'layer "'+r.id+'" requires a raster source')):"raster"===f&&"raster"!==s?e.push(new Ct(n,r.source,'layer "'+r.id+'" requires a vector source')):"vector"!==f||r["source-layer"]?"raster-dem"===f&&"hillshade"!==s?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==s||!r.paint||!r.paint["line-gradient"]||"geojson"===f&&h.lineMetrics||e.push(new Ct(n,r,'layer "'+r.id+'" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')):e.push(new Ct(n,r,'layer "'+r.id+'" must specify a "source-layer"')):e.push(new Ct(n,r.source,'source "'+r.source+'" not found'));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Hr({key:n,value:r,valueSpec:a.layer,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(){return []},type:function(){return wn({key:n+".type",value:r.type,valueSpec:a.layer.type,style:t.style,styleSpec:t.styleSpec,object:r,objectKey:"type"})},filter:cn,layout:function(t){return Hr({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return yn(Et({layerType:s},t))}}})},paint:function(t){return Hr({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return fn(Et({layerType:s},t))}}})}}}))}function mn(t){var e=t.value,r=t.key,n=Vr(e);return "string"!==n?[new Ct(r,e,"string expected, "+n+" found")]:[]}var vn={promoteId:function(t){var e=t.key,r=t.value;if("string"===Vr(r))return mn({key:e,value:r});var n=[];for(var i in r)n.push.apply(n,mn({key:e+"."+i,value:r[i]}));return n}};function gn(t){var e=t.value,r=t.key,n=t.styleSpec,i=t.style;if(!e.type)return [new Ct(r,e,'"type" is required')];var a,o=Tt(e.type);switch(o){case"vector":case"raster":case"raster-dem":return Hr({key:r,value:e,valueSpec:n["source_"+o.replace("-","_")],style:t.style,styleSpec:n,objectElementValidators:vn});case"geojson":if(a=Hr({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,objectElementValidators:vn}),e.cluster)for(var s in e.clusterProperties){var u=e.clusterProperties[s],l=u[0],p="string"==typeof l?[l,["accumulated"],["get",s]]:l;a.push.apply(a,Qr({key:r+"."+s+".map",value:u[1],expressionContext:"cluster-map"})),a.push.apply(a,Qr({key:r+"."+s+".reduce",value:p,expressionContext:"cluster-reduce"}));}return a;case"video":return Hr({key:r,value:e,valueSpec:n.source_video,style:i,styleSpec:n});case"image":return Hr({key:r,value:e,valueSpec:n.source_image,style:i,styleSpec:n});case"canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return tn({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,styleSpec:n})}}function xn(t){var e=t.value,r=t.styleSpec,n=r.light,i=t.style,a=[],o=Vr(e);if(void 0===e)return a;if("object"!==o)return a.concat([new Ct("light",e,"object expected, "+o+" found")]);for(var s in e){var u=s.match(/^(.*)-transition$/);a=a.concat(u&&n[u[1]]&&n[u[1]].transition?wn({key:s,value:e[s],valueSpec:r.transition,style:i,styleSpec:r}):n[s]?wn({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],'unknown property "'+s+'"')]);}return a}var bn={"*":function(){return []},array:Yr,boolean:function(t){var e=t.value,r=t.key,n=Vr(e);return "boolean"!==n?[new Ct(r,e,"boolean expected, "+n+" found")]:[]},number:$r,color:function(t){var e=t.key,r=t.value,n=Vr(r);return "string"!==n?[new Ct(e,r,"color expected, "+n+" found")]:null===$t(r)?[new Ct(e,r,'color expected, "'+r+'" found')]:[]},constants:Mt,enum:tn,filter:cn,function:Wr,layer:dn,object:Hr,source:gn,light:xn,string:mn,formatted:function(t){return 0===mn(t).length?[]:Qr(t)},resolvedImage:function(t){return 0===mn(t).length?[]:Qr(t)}};function wn(t){var e=t.value,r=t.valueSpec,n=t.styleSpec;return r.expression&&Fr(Tt(e))?Wr(t):r.expression&&Nr(Pt(e))?Qr(t):r.type&&bn[r.type]?bn[r.type](t):Hr(Et({},t,{valueSpec:r.type?n[r.type]:r}))}function _n(t){var e=t.value,r=t.key,n=mn(t);return n.length||(-1===e.indexOf("{fontstack}")&&n.push(new Ct(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&n.push(new Ct(r,e,'"glyphs" url must include a "{range}" token'))),n}function An(t,e){void 0===e&&(e=zt);var r=[];return r=r.concat(wn({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:_n,"*":function(){return []}}})),t.constants&&(r=r.concat(Mt({key:"constants",value:t.constants,style:t,styleSpec:e}))),Sn(r)}function Sn(t){return [].concat(t).sort((function(t,e){return t.line-e.line}))}function kn(t){return function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return Sn(t.apply(this,e))}}An.source=kn(gn),An.light=kn(xn),An.layer=kn(dn),An.filter=kn(cn),An.paintProperty=kn(fn),An.layoutProperty=kn(yn);var In=An,zn=In.light,Cn=In.paintProperty,Mn=In.layoutProperty;function En(t,e){var r=!1;if(e&&e.length)for(var n=0,i=e;n<i.length;n+=1)t.fire(new kt(new Error(i[n].message))),r=!0;return r}var Tn=Pn;function Pn(t,e,r){var n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(var a=0;a<this.d*this.d;a++){var o=i[3+a],s=i[3+a+1];n.push(o===s?null:i.subarray(o,s));}var u=i[3+n.length+1];this.keys=i.subarray(i[3+n.length],u),this.bboxes=i.subarray(u),this.insert=this._insertReadonly;}else {this.d=e+2*r;for(var l=0;l<this.d*this.d;l++)n.push([]);this.keys=[],this.bboxes=[];}this.n=e,this.extent=t,this.padding=r,this.scale=e/t,this.uid=0;var p=r/e*t;this.min=-p,this.max=t+p;}Pn.prototype.insert=function(t,e,r,n,i){this._forEachCell(e,r,n,i,this._insertCell,this.uid++),this.keys.push(t),this.bboxes.push(e),this.bboxes.push(r),this.bboxes.push(n),this.bboxes.push(i);},Pn.prototype._insertReadonly=function(){throw "Cannot insert into a GridIndex created from an ArrayBuffer."},Pn.prototype._insertCell=function(t,e,r,n,i,a){this.cells[i].push(a);},Pn.prototype.query=function(t,e,r,n,i){var a=this.min,o=this.max;if(t<=a&&e<=a&&o<=r&&o<=n&&!i)return Array.prototype.slice.call(this.keys);var s=[];return this._forEachCell(t,e,r,n,this._queryCell,s,{},i),s},Pn.prototype._queryCell=function(t,e,r,n,i,a,o,s){var u=this.cells[i];if(null!==u)for(var l=this.keys,p=this.bboxes,c=0;c<u.length;c++){var h=u[c];if(void 0===o[h]){var f=4*h;(s?s(p[f+0],p[f+1],p[f+2],p[f+3]):t<=p[f+2]&&e<=p[f+3]&&r>=p[f+0]&&n>=p[f+1])?(o[h]=!0,a.push(l[h])):o[h]=!1;}}},Pn.prototype._forEachCell=function(t,e,r,n,i,a,o,s){for(var u=this._convertToCellCoord(t),l=this._convertToCellCoord(e),p=this._convertToCellCoord(r),c=this._convertToCellCoord(n),h=u;h<=p;h++)for(var f=l;f<=c;f++){var y=this.d*f+h;if((!s||s(this._convertFromCellCoord(h),this._convertFromCellCoord(f),this._convertFromCellCoord(h+1),this._convertFromCellCoord(f+1)))&&i.call(this,t,e,r,n,y,a,o,s))return}},Pn.prototype._convertFromCellCoord=function(t){return (t-this.padding)/this.scale},Pn.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},Pn.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=3+this.cells.length+1+1,r=0,n=0;n<this.cells.length;n++)r+=this.cells[n].length;var i=new Int32Array(e+r+this.keys.length+this.bboxes.length);i[0]=this.extent,i[1]=this.n,i[2]=this.padding;for(var a=e,o=0;o<t.length;o++){var s=t[o];i[3+o]=a,i.set(s,a),a+=s.length;}return i[3+t.length]=a,i.set(this.keys,a),i[3+t.length+1]=a+=this.keys.length,i.set(this.bboxes,a),a+=this.bboxes.length,i.buffer};var Bn=o.ImageData,Vn=o.ImageBitmap,Fn={};function Dn(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),Fn[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]};}for(var Ln in Dn("Object",Object),Tn.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),{buffer:r}},Tn.deserialize=function(t){return new Tn(t.buffer)},Dn("Grid",Tn),Dn("Color",Wt),Dn("Error",Error),Dn("ResolvedImage",re),Dn("StylePropertyFunction",Jr),Dn("StyleExpression",qr,{omit:["_evaluator"]}),Dn("ZoomDependentExpression",Zr),Dn("ZoomConstantExpression",Gr),Dn("CompoundExpression",ve,{omit:["_evaluate"]}),Sr)Sr[Ln]._classRegistryKey||Dn("Expression_"+Ln,Sr[Ln]);function Rn(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}function On(t){return Vn&&t instanceof Vn}function Un(t,e){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp)return t;if(Rn(t)||On(t))return e&&e.push(t),t;if(ArrayBuffer.isView(t)){var r=t;return e&&e.push(r.buffer),r}if(t instanceof Bn)return e&&e.push(t.data.buffer),t;if(Array.isArray(t)){for(var n=[],i=0,a=t;i<a.length;i+=1)n.push(Un(a[i],e));return n}if("object"==typeof t){var o=t.constructor,s=o._classRegistryKey;if(!s)throw new Error("can't serialize object of unregistered class");var u=o.serialize?o.serialize(t,e):{};if(!o.serialize){for(var l in t)if(t.hasOwnProperty(l)&&!(Fn[s].omit.indexOf(l)>=0)){var p=t[l];u[l]=Fn[s].shallow.indexOf(l)>=0?p:Un(p,e);}t instanceof Error&&(u.message=t.message);}if(u.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==s&&(u.$name=s),u}throw new Error("can't serialize object of type "+typeof t)}function jn(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||Rn(t)||On(t)||ArrayBuffer.isView(t)||t instanceof Bn)return t;if(Array.isArray(t))return t.map(jn);if("object"==typeof t){var e=t.$name||"Object",r=Fn[e].klass;if(!r)throw new Error("can't deserialize unregistered class "+e);if(r.deserialize)return r.deserialize(t);for(var n=Object.create(r.prototype),i=0,a=Object.keys(t);i<a.length;i+=1){var o=a[i];if("$name"!==o){var s=t[o];n[o]=Fn[e].shallow.indexOf(o)>=0?s:jn(s);}}return n}throw new Error("can't deserialize object of type "+typeof t)}var qn=function(){this.first=!0;};qn.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom<r&&(this.lastIntegerZoom=r,this.lastIntegerZoomTime=e),t!==this.lastZoom&&(this.lastZoom=t,this.lastFloorZoom=r,!0))};var Nn={"Latin-1 Supplement":function(t){return t>=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function Kn(t){for(var e=0,r=t;e<r.length;e+=1)if(Gn(r[e].charCodeAt(0)))return !0;return !1}function Gn(t){return !(746!==t&&747!==t&&(t<4352||!(Nn["Bopomofo Extended"](t)||Nn.Bopomofo(t)||Nn["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||Nn["CJK Compatibility Ideographs"](t)||Nn["CJK Compatibility"](t)||Nn["CJK Radicals Supplement"](t)||Nn["CJK Strokes"](t)||!(!Nn["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||Nn["CJK Unified Ideographs Extension A"](t)||Nn["CJK Unified Ideographs"](t)||Nn["Enclosed CJK Letters and Months"](t)||Nn["Hangul Compatibility Jamo"](t)||Nn["Hangul Jamo Extended-A"](t)||Nn["Hangul Jamo Extended-B"](t)||Nn["Hangul Jamo"](t)||Nn["Hangul Syllables"](t)||Nn.Hiragana(t)||Nn["Ideographic Description Characters"](t)||Nn.Kanbun(t)||Nn["Kangxi Radicals"](t)||Nn["Katakana Phonetic Extensions"](t)||Nn.Katakana(t)&&12540!==t||!(!Nn["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!Nn["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||Nn["Unified Canadian Aboriginal Syllabics"](t)||Nn["Unified Canadian Aboriginal Syllabics Extended"](t)||Nn["Vertical Forms"](t)||Nn["Yijing Hexagram Symbols"](t)||Nn["Yi Syllables"](t)||Nn["Yi Radicals"](t))))}function Zn(t){return !(Gn(t)||function(t){return !!(Nn["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||Nn["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||Nn["Letterlike Symbols"](t)||Nn["Number Forms"](t)||Nn["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||Nn["Control Pictures"](t)&&9251!==t||Nn["Optical Character Recognition"](t)||Nn["Enclosed Alphanumerics"](t)||Nn["Geometric Shapes"](t)||Nn["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||Nn["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||Nn["CJK Symbols and Punctuation"](t)||Nn.Katakana(t)||Nn["Private Use Area"](t)||Nn["CJK Compatibility Forms"](t)||Nn["Small Form Variants"](t)||Nn["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function Xn(t){return t>=1424&&t<=2303||Nn["Arabic Presentation Forms-A"](t)||Nn["Arabic Presentation Forms-B"](t)}function Jn(t,e){return !(!e&&Xn(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||Nn.Khmer(t))}function Hn(t){for(var e=0,r=t;e<r.length;e+=1)if(Xn(r[e].charCodeAt(0)))return !0;return !1}var Yn=null,$n="unavailable",Wn=null,Qn=function(t){t&&"string"==typeof t&&t.indexOf("NetworkError")>-1&&($n="error"),Yn&&Yn(t);};function ti(){ei.fire(new St("pluginStateChange",{pluginStatus:$n,pluginURL:Wn}));}var ei=new It,ri=function(){return $n},ni=function(){if("deferred"!==$n||!Wn)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");$n="loading",ti(),Wn&&xt({url:Wn},(function(t){t?Qn(t):($n="loaded",ti());}));},ii={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:function(){return "loaded"===$n||null!=ii.applyArabicShaping},isLoading:function(){return "loading"===$n},setState:function(t){$n=t.pluginStatus,Wn=t.pluginURL;},isParsed:function(){return null!=ii.applyArabicShaping&&null!=ii.processBidirectionalText&&null!=ii.processStyledBidirectionalText},getPluginURL:function(){return Wn}},ai=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new qn,this.transition={});};ai.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;r<n.length;r+=1)if(!Jn(n[r].charCodeAt(0),e))return !1;return !0}(t,ii.isLoaded())},ai.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)},ai.prototype.getCrossfadeParameters=function(){var t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}};var oi=function(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Fr(t))return new Jr(t,e);if(Nr(t)){var r=Xr(t,e);if("error"===r.result)throw new Error(r.value.map((function(t){return t.key+": "+t.message})).join(", "));return r.value}var n=t;return "string"==typeof t&&"color"===e.type&&(n=Wt.parse(t)),{kind:"constant",evaluate:function(){return n}}}(void 0===e?t.specification.default:e,t.specification);};oi.prototype.isDataDriven=function(){return "source"===this.expression.kind||"composite"===this.expression.kind},oi.prototype.possiblyEvaluate=function(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)};var si=function(t){this.property=t,this.value=new oi(t,void 0);};si.prototype.transitioned=function(t,e){return new li(this.property,this.value,e,c({},t.transition,this.transition),t.now)},si.prototype.untransitioned=function(){return new li(this.property,this.value,null,{},0)};var ui=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);};ui.prototype.getValue=function(t){return b(this._values[t].value.value)},ui.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new si(this._values[t].property)),this._values[t].value=new oi(this._values[t].property,null===e?void 0:b(e));},ui.prototype.getTransition=function(t){return b(this._values[t].transition)},ui.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new si(this._values[t].property)),this._values[t].transition=b(e)||void 0;},ui.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);var a=this.getTransition(n);void 0!==a&&(t[n+"-transition"]=a);}return t},ui.prototype.transitioned=function(t,e){for(var r=new pi(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var a=i[n];r._values[a]=this._values[a].transitioned(t,e._values[a]);}return r},ui.prototype.untransitioned=function(){for(var t=new pi(this._properties),e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e];t._values[n]=this._values[n].untransitioned();}return t};var li=function(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);};li.prototype.possiblyEvaluate=function(t,e,r){var n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),a=this.prior;if(a){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(n<this.begin)return a.possiblyEvaluate(t,e,r);var o=(n-this.begin)/(this.end-this.begin);return this.property.interpolate(a.possiblyEvaluate(t,e,r),i,function(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(o))}return i};var pi=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);};pi.prototype.possiblyEvaluate=function(t,e,r){for(var n=new fi(this._properties),i=0,a=Object.keys(this._values);i<a.length;i+=1){var o=a[i];n._values[o]=this._values[o].possiblyEvaluate(t,e,r);}return n},pi.prototype.hasTransition=function(){for(var t=0,e=Object.keys(this._values);t<e.length;t+=1)if(this._values[e[t]].prior)return !0;return !1};var ci=function(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues);};ci.prototype.getValue=function(t){return b(this._values[t].value)},ci.prototype.setValue=function(t,e){this._values[t]=new oi(this._values[t].property,null===e?void 0:b(e));},ci.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);}return t},ci.prototype.possiblyEvaluate=function(t,e,r){for(var n=new fi(this._properties),i=0,a=Object.keys(this._values);i<a.length;i+=1){var o=a[i];n._values[o]=this._values[o].possiblyEvaluate(t,e,r);}return n};var hi=function(t,e,r){this.property=t,this.value=e,this.parameters=r;};hi.prototype.isConstant=function(){return "constant"===this.value.kind},hi.prototype.constantOr=function(t){return "constant"===this.value.kind?this.value.value:t},hi.prototype.evaluate=function(t,e,r,n){return this.property.evaluate(this.value,this.parameters,t,e,r,n)};var fi=function(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues);};fi.prototype.get=function(t){return this._values[t]};var yi=function(t){this.specification=t;};yi.prototype.possiblyEvaluate=function(t,e){return t.expression.evaluate(e)},yi.prototype.interpolate=function(t,e,r){var n=Ne[this.specification.type];return n?n(t,e,r):t};var di=function(t,e){this.specification=t,this.overrides=e;};di.prototype.possiblyEvaluate=function(t,e,r,n){return new hi(this,"constant"===t.expression.kind||"camera"===t.expression.kind?{kind:"constant",value:t.expression.evaluate(e,null,{},r,n)}:t.expression,e)},di.prototype.interpolate=function(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new hi(this,{kind:"constant",value:void 0},t.parameters);var n=Ne[this.specification.type];return n?new hi(this,{kind:"constant",value:n(t.value.value,e.value.value,r)},t.parameters):t},di.prototype.evaluate=function(t,e,r,n,i,a){return "constant"===t.kind?t.value:t.evaluate(e,r,n,i,a)};var mi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.possiblyEvaluate=function(t,e,r,n){if(void 0===t.value)return new hi(this,{kind:"constant",value:void 0},e);if("constant"===t.expression.kind){var i=t.expression.evaluate(e,null,{},r,n),a="resolvedImage"===t.property.specification.type&&"string"!=typeof i?i.name:i,o=this._calculate(a,a,a,e);return new hi(this,{kind:"constant",value:o},e)}if("camera"===t.expression.kind){var s=this._calculate(t.expression.evaluate({zoom:e.zoom-1}),t.expression.evaluate({zoom:e.zoom}),t.expression.evaluate({zoom:e.zoom+1}),e);return new hi(this,{kind:"constant",value:s},e)}return new hi(this,t.expression,e)},e.prototype.evaluate=function(t,e,r,n,i,a){if("source"===t.kind){var o=t.evaluate(e,r,n,i,a);return this._calculate(o,o,o,e)}return "composite"===t.kind?this._calculate(t.evaluate({zoom:Math.floor(e.zoom)-1},r,n),t.evaluate({zoom:Math.floor(e.zoom)},r,n),t.evaluate({zoom:Math.floor(e.zoom)+1},r,n),e):t.value},e.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},e.prototype.interpolate=function(t){return t},e}(di),vi=function(t){this.specification=t;};vi.prototype.possiblyEvaluate=function(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){var i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new ai(Math.floor(e.zoom-1),e)),t.expression.evaluate(new ai(Math.floor(e.zoom),e)),t.expression.evaluate(new ai(Math.floor(e.zoom+1),e)),e)}},vi.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},vi.prototype.interpolate=function(t){return t};var gi=function(t){this.specification=t;};gi.prototype.possiblyEvaluate=function(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)},gi.prototype.interpolate=function(){return !1};var xi=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[],t){var r=t[e];r.specification.overridable&&this.overridableProperties.push(e);var n=this.defaultPropertyValues[e]=new oi(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new si(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}};Dn("DataDrivenProperty",di),Dn("DataConstantProperty",yi),Dn("CrossFadedDataDrivenProperty",mi),Dn("CrossFadedProperty",vi),Dn("ColorRampProperty",gi);var bi=function(t){function e(e,r){if(t.call(this),this.id=e.id,this.type=e.type,this._featureFilter={filter:function(){return !0},needGeometry:!1},"custom"!==e.type&&(this.metadata=(e=e).metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,"background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),r.layout&&(this._unevaluatedLayout=new ci(r.layout)),r.paint)){for(var n in this._transitionablePaint=new ui(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new fi(r.paint);}}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getCrossfadeParameters=function(){return this._crossfadeParameters},e.prototype.getLayoutProperty=function(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){void 0===r&&(r={}),null!=e&&this._validate(Mn,"layers."+this.id+".layout."+t,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);},e.prototype.getPaintProperty=function(t){return v(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(void 0===r&&(r={}),null!=e&&this._validate(Cn,"layers."+this.id+".paint."+t,t,e,r))return !1;if(v(t,"-transition"))return this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0),!1;var n=this._transitionablePaint._values[t],i="cross-faded-data-driven"===n.property.specification["property-type"],a=n.value.isDataDriven(),o=n.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);var s=this._transitionablePaint._values[t].value;return s.isDataDriven()||a||i||this._handleOverridablePaintPropertyUpdate(t,o,s)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){},e.prototype._handleOverridablePaintPropertyUpdate=function(t,e,r){return !1},e.prototype.isHidden=function(t){return !!(this.minzoom&&t<this.minzoom)||!!(this.maxzoom&&t>=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),x(t,(function(t,e){return !(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)}))},e.prototype._validate=function(t,e,r,n,i){return void 0===i&&(i={}),(!i||!1!==i.validate)&&En(this,t.call(In,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:zt,style:{glyphs:!0,sprite:!0}}))},e.prototype.is3D=function(){return !1},e.prototype.isTileClipped=function(){return !1},e.prototype.hasOffscreenPass=function(){return !1},e.prototype.resize=function(){},e.prototype.isStateDependent=function(){for(var t in this.paint._values){var e=this.paint.get(t);if(e instanceof hi&&Tr(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1},e}(It),wi={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},_i=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;},Ai=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0);};function Si(t,e){void 0===e&&(e=1);var r=0,n=0;return {members:t.map((function(t){var i=wi[t.type].BYTES_PER_ELEMENT,a=r=ki(r,Math.max(e,i)),o=t.components||1;return n=Math.max(n,i),r+=i*o,{name:t.name,type:t.type,components:o,offset:a}})),size:ki(r,Math.max(n,e)),alignment:e}}function ki(t,e){return Math.ceil(t/e)*e}Ai.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},Ai.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},Ai.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());},Ai.prototype.clear=function(){this.length=0;},Ai.prototype.resize=function(t){this.reserve(t),this.length=t;},Ai.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}},Ai.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var Ii=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t},e}(Ai);Ii.prototype.bytesPerElement=4,Dn("StructArrayLayout2i4",Ii);var zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,t},e}(Ai);zi.prototype.bytesPerElement=8,Dn("StructArrayLayout4i8",zi);var Ci=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(Ai);Ci.prototype.bytesPerElement=12,Dn("StructArrayLayout2i4i12",Ci);var Mi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=4*t,u=8*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.uint8[u+4]=n,this.uint8[u+5]=i,this.uint8[u+6]=a,this.uint8[u+7]=o,t},e}(Ai);Mi.prototype.bytesPerElement=8,Dn("StructArrayLayout2i4ub8",Mi);var Ei=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l){var p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,a,o,s,u,l)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p){var c=10*t;return this.uint16[c+0]=e,this.uint16[c+1]=r,this.uint16[c+2]=n,this.uint16[c+3]=i,this.uint16[c+4]=a,this.uint16[c+5]=o,this.uint16[c+6]=s,this.uint16[c+7]=u,this.uint16[c+8]=l,this.uint16[c+9]=p,t},e}(Ai);Ei.prototype.bytesPerElement=20,Dn("StructArrayLayout10ui20",Ei);var Ti=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c){var h=this.length;return this.resize(h+1),this.emplace(h,t,e,r,n,i,a,o,s,u,l,p,c)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=a,this.uint16[f+5]=o,this.uint16[f+6]=s,this.uint16[f+7]=u,this.int16[f+8]=l,this.int16[f+9]=p,this.int16[f+10]=c,this.int16[f+11]=h,t},e}(Ai);Ti.prototype.bytesPerElement=24,Dn("StructArrayLayout4i4ui4i24",Ti);var Pi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t},e}(Ai);Pi.prototype.bytesPerElement=12,Dn("StructArrayLayout3f12",Pi);var Bi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint32[1*t+0]=e,t},e}(Ai);Bi.prototype.bytesPerElement=4,Dn("StructArrayLayout1ul4",Bi);var Vi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u){var l=this.length;return this.resize(l+1),this.emplace(l,t,e,r,n,i,a,o,s,u)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l){var p=10*t,c=5*t;return this.int16[p+0]=e,this.int16[p+1]=r,this.int16[p+2]=n,this.int16[p+3]=i,this.int16[p+4]=a,this.int16[p+5]=o,this.uint32[c+3]=s,this.uint16[p+8]=u,this.uint16[p+9]=l,t},e}(Ai);Vi.prototype.bytesPerElement=20,Dn("StructArrayLayout6i1ul2ui20",Vi);var Fi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(Ai);Fi.prototype.bytesPerElement=12,Dn("StructArrayLayout2i2i2i12",Fi);var Di=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i){var a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i)},e.prototype.emplace=function(t,e,r,n,i,a){var o=4*t,s=8*t;return this.float32[o+0]=e,this.float32[o+1]=r,this.float32[o+2]=n,this.int16[s+6]=i,this.int16[s+7]=a,t},e}(Ai);Di.prototype.bytesPerElement=16,Dn("StructArrayLayout2f1f2i16",Di);var Li=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=12*t,o=3*t;return this.uint8[a+0]=e,this.uint8[a+1]=r,this.float32[o+1]=n,this.float32[o+2]=i,t},e}(Ai);Li.prototype.bytesPerElement=12,Dn("StructArrayLayout2ub2f12",Li);var Ri=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t},e}(Ai);Ri.prototype.bytesPerElement=6,Dn("StructArrayLayout3ui6",Ri);var Oi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m){var v=this.length;return this.resize(v+1),this.emplace(v,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v){var g=24*t,x=12*t,b=48*t;return this.int16[g+0]=e,this.int16[g+1]=r,this.uint16[g+2]=n,this.uint16[g+3]=i,this.uint32[x+2]=a,this.uint32[x+3]=o,this.uint32[x+4]=s,this.uint16[g+10]=u,this.uint16[g+11]=l,this.uint16[g+12]=p,this.float32[x+7]=c,this.float32[x+8]=h,this.uint8[b+36]=f,this.uint8[b+37]=y,this.uint8[b+38]=d,this.uint32[x+10]=m,this.int16[g+22]=v,t},e}(Ai);Oi.prototype.bytesPerElement=48,Dn("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Oi);var Ui=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z){var C=this.length;return this.resize(C+1),this.emplace(C,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z,C){var M=34*t,E=17*t;return this.int16[M+0]=e,this.int16[M+1]=r,this.int16[M+2]=n,this.int16[M+3]=i,this.int16[M+4]=a,this.int16[M+5]=o,this.int16[M+6]=s,this.int16[M+7]=u,this.uint16[M+8]=l,this.uint16[M+9]=p,this.uint16[M+10]=c,this.uint16[M+11]=h,this.uint16[M+12]=f,this.uint16[M+13]=y,this.uint16[M+14]=d,this.uint16[M+15]=m,this.uint16[M+16]=v,this.uint16[M+17]=g,this.uint16[M+18]=x,this.uint16[M+19]=b,this.uint16[M+20]=w,this.uint16[M+21]=_,this.uint16[M+22]=A,this.uint32[E+12]=S,this.float32[E+13]=k,this.float32[E+14]=I,this.float32[E+15]=z,this.float32[E+16]=C,t},e}(Ai);Ui.prototype.bytesPerElement=68,Dn("StructArrayLayout8i15ui1ul4f68",Ui);var ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.float32[1*t+0]=e,t},e}(Ai);ji.prototype.bytesPerElement=4,Dn("StructArrayLayout1f4",ji);var qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t},e}(Ai);qi.prototype.bytesPerElement=6,Dn("StructArrayLayout3i6",qi);var Ni=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t},e}(Ai);Ni.prototype.bytesPerElement=8,Dn("StructArrayLayout1ul2ui8",Ni);var Ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t},e}(Ai);Ki.prototype.bytesPerElement=4,Dn("StructArrayLayout2ui4",Ki);var Gi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint16[1*t+0]=e,t},e}(Ai);Gi.prototype.bytesPerElement=2,Dn("StructArrayLayout1ui2",Gi);var Zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t},e}(Ai);Zi.prototype.bytesPerElement=8,Dn("StructArrayLayout2f8",Zi);var Xi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.float32[a+3]=i,t},e}(Ai);Xi.prototype.bytesPerElement=16,Dn("StructArrayLayout4f16",Xi);var Ji=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.anchorPoint.get=function(){return new i(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(_i);Ji.prototype.size=20;var Hi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Ji(this,t)},e}(Vi);Dn("CollisionBoxArray",Hi);var Yi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},placedOrientation:{configurable:!0},hidden:{configurable:!0},crossTileID:{configurable:!0},associatedIconIndex:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.placedOrientation.get=function(){return this._structArray.uint8[this._pos1+37]},r.placedOrientation.set=function(t){this._structArray.uint8[this._pos1+37]=t;},r.hidden.get=function(){return this._structArray.uint8[this._pos1+38]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+38]=t;},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+10]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+10]=t;},r.associatedIconIndex.get=function(){return this._structArray.int16[this._pos2+22]},Object.defineProperties(e.prototype,r),e}(_i);Yi.prototype.size=48;var $i=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Yi(this,t)},e}(Oi);Dn("PlacedSymbolArray",$i);var Wi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},rightJustifiedTextSymbolIndex:{configurable:!0},centerJustifiedTextSymbolIndex:{configurable:!0},leftJustifiedTextSymbolIndex:{configurable:!0},verticalPlacedTextSymbolIndex:{configurable:!0},placedIconSymbolIndex:{configurable:!0},verticalPlacedIconSymbolIndex:{configurable:!0},key:{configurable:!0},textBoxStartIndex:{configurable:!0},textBoxEndIndex:{configurable:!0},verticalTextBoxStartIndex:{configurable:!0},verticalTextBoxEndIndex:{configurable:!0},iconBoxStartIndex:{configurable:!0},iconBoxEndIndex:{configurable:!0},verticalIconBoxStartIndex:{configurable:!0},verticalIconBoxEndIndex:{configurable:!0},featureIndex:{configurable:!0},numHorizontalGlyphVertices:{configurable:!0},numVerticalGlyphVertices:{configurable:!0},numIconVertices:{configurable:!0},numVerticalIconVertices:{configurable:!0},useRuntimeCollisionCircles:{configurable:!0},crossTileID:{configurable:!0},textBoxScale:{configurable:!0},textOffset0:{configurable:!0},textOffset1:{configurable:!0},collisionCircleDiameter:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.rightJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+2]},r.centerJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+3]},r.leftJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+4]},r.verticalPlacedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+5]},r.placedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+6]},r.verticalPlacedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+7]},r.key.get=function(){return this._structArray.uint16[this._pos2+8]},r.textBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.textBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+10]},r.verticalTextBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+11]},r.verticalTextBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+12]},r.iconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+13]},r.iconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+14]},r.verticalIconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+15]},r.verticalIconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+16]},r.featureIndex.get=function(){return this._structArray.uint16[this._pos2+17]},r.numHorizontalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+18]},r.numVerticalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+19]},r.numIconVertices.get=function(){return this._structArray.uint16[this._pos2+20]},r.numVerticalIconVertices.get=function(){return this._structArray.uint16[this._pos2+21]},r.useRuntimeCollisionCircles.get=function(){return this._structArray.uint16[this._pos2+22]},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+12]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+12]=t;},r.textBoxScale.get=function(){return this._structArray.float32[this._pos4+13]},r.textOffset0.get=function(){return this._structArray.float32[this._pos4+14]},r.textOffset1.get=function(){return this._structArray.float32[this._pos4+15]},r.collisionCircleDiameter.get=function(){return this._structArray.float32[this._pos4+16]},Object.defineProperties(e.prototype,r),e}(_i);Wi.prototype.size=68;var Qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Wi(this,t)},e}(Ui);Dn("SymbolInstanceArray",Qi);var ta=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e}(ji);Dn("GlyphOffsetArray",ta);var ea=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e}(qi);Dn("SymbolLineVertexArray",ea);var ra=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},Object.defineProperties(e.prototype,r),e}(_i);ra.prototype.size=8;var na=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new ra(this,t)},e}(Ni);Dn("FeatureIndexArray",na);var ia=Si([{name:"a_pos",components:2,type:"Int16"}],4).members,aa=function(t){void 0===t&&(t=[]),this.segments=t;};function oa(t,e){return 256*(t=l(Math.floor(t),0,255))+l(Math.floor(e),0,255)}aa.prototype.prepareSegment=function(t,e,r,n){var i=this.segments[this.segments.length-1];return t>aa.MAX_VERTEX_ARRAY_LENGTH&&_("Max vertices per segment is "+aa.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!i||i.vertexLength+t>aa.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i},aa.prototype.get=function(){return this.segments},aa.prototype.destroy=function(){for(var t=0,e=this.segments;t<e.length;t+=1){var r=e[t];for(var n in r.vaos)r.vaos[n].destroy();}},aa.simpleSegment=function(t,e,r,n){return new aa([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])},aa.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Dn("SegmentVector",aa);var sa=Si([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]),ua=e((function(t){t.exports=function(t,e){var r,n,i,a,o,s,u,l;for(n=t.length-(r=3&t.length),i=e,o=3432918353,s=461845907,l=0;l<n;)u=255&t.charCodeAt(l)|(255&t.charCodeAt(++l))<<8|(255&t.charCodeAt(++l))<<16|(255&t.charCodeAt(++l))<<24,++l,i=27492+(65535&(a=5*(65535&(i=(i^=u=(65535&(u=(u=(65535&u)*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(a>>>16)&65535)<<16);switch(u=0,r){case 3:u^=(255&t.charCodeAt(l+2))<<16;case 2:u^=(255&t.charCodeAt(l+1))<<8;case 1:i^=u=(65535&(u=(u=(65535&(u^=255&t.charCodeAt(l)))*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};})),la=e((function(t){t.exports=function(t,e){for(var r,n=t.length,i=e^n,a=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(a)|(255&t.charCodeAt(++a))<<8|(255&t.charCodeAt(++a))<<16|(255&t.charCodeAt(++a))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++a;switch(n){case 3:i^=(255&t.charCodeAt(a+2))<<16;case 2:i^=(255&t.charCodeAt(a+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(a)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};})),pa=ua,ca=la;pa.murmur3=ua,pa.murmur2=ca;var ha=function(){this.ids=[],this.positions=[],this.indexed=!1;};ha.prototype.add=function(t,e,r,n){this.ids.push(ya(t)),this.positions.push(e,r,n);},ha.prototype.getPositions=function(t){for(var e=ya(t),r=0,n=this.ids.length-1;r<n;){var i=r+n>>1;this.ids[i]>=e?n=i:r=i+1;}for(var a=[];this.ids[r]===e;)a.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return a},ha.serialize=function(t,e){var r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return function t(e,r,n,i){for(;n<i;){for(var a=e[n+i>>1],o=n-1,s=i+1;;){do{o++;}while(e[o]<a);do{s--;}while(e[s]>a);if(o>=s)break;da(e,o,s),da(r,3*o,3*s),da(r,3*o+1,3*s+1),da(r,3*o+2,3*s+2);}s-n<i-s?(t(e,r,n,s),n=s+1):(t(e,r,s+1,i),i=s);}}(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}},ha.deserialize=function(t){var e=new ha;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e};var fa=Math.pow(2,53)-1;function ya(t){var e=+t;return !isNaN(e)&&e<=fa?e:pa(String(t))}function da(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}Dn("FeaturePositionMap",ha);var ma=function(t,e){this.gl=t.gl,this.location=e;},va=function(t){function e(e,r){t.call(this,e,r),this.current=0;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){this.current!==t&&(this.current=t,this.gl.uniform1i(this.location,t));},e}(ma),ga=function(t){function e(e,r){t.call(this,e,r),this.current=0;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){this.current!==t&&(this.current=t,this.gl.uniform1f(this.location,t));},e}(ma),xa=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0];}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]||(this.current=t,this.gl.uniform2f(this.location,t[0],t[1]));},e}(ma),ba=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0,0];}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]||(this.current=t,this.gl.uniform3f(this.location,t[0],t[1],t[2]));},e}(ma),wa=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0,0,0];}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]&&t[3]===this.current[3]||(this.current=t,this.gl.uniform4f(this.location,t[0],t[1],t[2],t[3]));},e}(ma),_a=function(t){function e(e,r){t.call(this,e,r),this.current=Wt.transparent;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t.r===this.current.r&&t.g===this.current.g&&t.b===this.current.b&&t.a===this.current.a||(this.current=t,this.gl.uniform4f(this.location,t.r,t.g,t.b,t.a));},e}(ma),Aa=new Float32Array(16),Sa=function(t){function e(e,r){t.call(this,e,r),this.current=Aa;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){if(t[12]!==this.current[12]||t[0]!==this.current[0])return this.current=t,void this.gl.uniformMatrix4fv(this.location,!1,t);for(var e=1;e<16;e++)if(t[e]!==this.current[e]){this.current=t,this.gl.uniformMatrix4fv(this.location,!1,t);break}},e}(ma);function ka(t){return [oa(255*t.r,255*t.g),oa(255*t.b,255*t.a)]}var Ia=function(t,e,r){this.value=t,this.uniformNames=e.map((function(t){return "u_"+t})),this.type=r;};Ia.prototype.setUniform=function(t,e,r){t.set(r.constantOr(this.value));},Ia.prototype.getBinding=function(t,e,r){return "color"===this.type?new _a(t,e):new ga(t,e)};var za=function(t,e){this.uniformNames=e.map((function(t){return "u_"+t})),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;};za.prototype.setConstantPatternPositions=function(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;},za.prototype.setUniform=function(t,e,r,n){var i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);},za.prototype.getBinding=function(t,e,r){return "u_pattern"===r.substr(0,9)?new wa(t,e):new ga(t,e)};var Ca=function(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((function(t){return {name:"a_"+t,type:"Float32",components:"color"===r?2:1,offset:0}})),this.paintVertexArray=new n;};Ca.prototype.populatePaintArray=function(t,e,r,n,i){var a=this.paintVertexArray.length,o=this.expression.evaluate(new ai(0),e,{},n,[],i);this.paintVertexArray.resize(t),this._setPaintValue(a,t,o);},Ca.prototype.updatePaintArray=function(t,e,r,n){var i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i);},Ca.prototype._setPaintValue=function(t,e,r){if("color"===this.type)for(var n=ka(r),i=t;i<e;i++)this.paintVertexArray.emplace(i,n[0],n[1]);else {for(var a=t;a<e;a++)this.paintVertexArray.emplace(a,r);this.maxValue=Math.max(this.maxValue,Math.abs(r));}},Ca.prototype.upload=function(t){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent));},Ca.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();};var Ma=function(t,e,r,n,i,a){this.expression=t,this.uniformNames=e.map((function(t){return "u_"+t+"_t"})),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((function(t){return {name:"a_"+t,type:"Float32",components:"color"===r?4:2,offset:0}})),this.paintVertexArray=new a;};Ma.prototype.populatePaintArray=function(t,e,r,n,i){var a=this.expression.evaluate(new ai(this.zoom),e,{},n,[],i),o=this.expression.evaluate(new ai(this.zoom+1),e,{},n,[],i),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,a,o);},Ma.prototype.updatePaintArray=function(t,e,r,n){var i=this.expression.evaluate({zoom:this.zoom},r,n),a=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,a);},Ma.prototype._setPaintValue=function(t,e,r,n){if("color"===this.type)for(var i=ka(r),a=ka(n),o=t;o<e;o++)this.paintVertexArray.emplace(o,i[0],i[1],a[0],a[1]);else {for(var s=t;s<e;s++)this.paintVertexArray.emplace(s,r,n);this.maxValue=Math.max(this.maxValue,Math.abs(r),Math.abs(n));}},Ma.prototype.upload=function(t){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent));},Ma.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();},Ma.prototype.setUniform=function(t,e){var r=this.useIntegerZoom?Math.floor(e.zoom):e.zoom,n=l(this.expression.interpolationFactor(r,this.zoom,this.zoom+1),0,1);t.set(n);},Ma.prototype.getBinding=function(t,e,r){return new ga(t,e)};var Ea=function(t,e,r,n,i,a){this.expression=t,this.type=e,this.useIntegerZoom=r,this.zoom=n,this.layerId=a,this.zoomInPaintVertexArray=new i,this.zoomOutPaintVertexArray=new i;};Ea.prototype.populatePaintArray=function(t,e,r){var n=this.zoomInPaintVertexArray.length;this.zoomInPaintVertexArray.resize(t),this.zoomOutPaintVertexArray.resize(t),this._setPaintValues(n,t,e.patterns&&e.patterns[this.layerId],r);},Ea.prototype.updatePaintArray=function(t,e,r,n,i){this._setPaintValues(t,e,r.patterns&&r.patterns[this.layerId],i);},Ea.prototype._setPaintValues=function(t,e,r,n){if(n&&r){var i=n[r.min],a=n[r.mid],o=n[r.max];if(i&&a&&o)for(var s=t;s<e;s++)this.zoomInPaintVertexArray.emplace(s,a.tl[0],a.tl[1],a.br[0],a.br[1],i.tl[0],i.tl[1],i.br[0],i.br[1],a.pixelRatio,i.pixelRatio),this.zoomOutPaintVertexArray.emplace(s,a.tl[0],a.tl[1],a.br[0],a.br[1],o.tl[0],o.tl[1],o.br[0],o.br[1],a.pixelRatio,o.pixelRatio);}},Ea.prototype.upload=function(t){this.zoomInPaintVertexArray&&this.zoomInPaintVertexArray.arrayBuffer&&this.zoomOutPaintVertexArray&&this.zoomOutPaintVertexArray.arrayBuffer&&(this.zoomInPaintVertexBuffer=t.createVertexBuffer(this.zoomInPaintVertexArray,sa.members,this.expression.isStateDependent),this.zoomOutPaintVertexBuffer=t.createVertexBuffer(this.zoomOutPaintVertexArray,sa.members,this.expression.isStateDependent));},Ea.prototype.destroy=function(){this.zoomOutPaintVertexBuffer&&this.zoomOutPaintVertexBuffer.destroy(),this.zoomInPaintVertexBuffer&&this.zoomInPaintVertexBuffer.destroy();};var Ta=function(t,e,r){this.binders={},this._buffers=[];var n=[];for(var i in t.paint._values)if(r(i)){var a=t.paint.get(i);if(a instanceof hi&&Tr(a.property.specification)){var o=Ba(i,t.type),s=a.value,u=a.property.specification.type,l=a.property.useIntegerZoom,p=a.property.specification["property-type"],c="cross-faded"===p||"cross-faded-data-driven"===p;if("constant"===s.kind)this.binders[i]=c?new za(s.value,o):new Ia(s.value,o,u),n.push("/u_"+i);else if("source"===s.kind||c){var h=Va(i,u,"source");this.binders[i]=c?new Ea(s,u,l,e,h,t.id):new Ca(s,o,u,h),n.push("/a_"+i);}else {var f=Va(i,u,"composite");this.binders[i]=new Ma(s,o,u,l,e,f),n.push("/z_"+i);}}}this.cacheKey=n.sort().join("");};Ta.prototype.getMaxValue=function(t){var e=this.binders[t];return e instanceof Ca||e instanceof Ma?e.maxValue:0},Ta.prototype.populatePaintArrays=function(t,e,r,n,i){for(var a in this.binders){var o=this.binders[a];(o instanceof Ca||o instanceof Ma||o instanceof Ea)&&o.populatePaintArray(t,e,r,n,i);}},Ta.prototype.setConstantPatternPositions=function(t,e){for(var r in this.binders){var n=this.binders[r];n instanceof za&&n.setConstantPatternPositions(t,e);}},Ta.prototype.updatePaintArrays=function(t,e,r,n,i){var a=!1;for(var o in t)for(var s=0,u=e.getPositions(o);s<u.length;s+=1){var l=u[s],p=r.feature(l.index);for(var c in this.binders){var h=this.binders[c];if((h instanceof Ca||h instanceof Ma||h instanceof Ea)&&!0===h.expression.isStateDependent){var f=n.paint.get(c);h.expression=f.value,h.updatePaintArray(l.start,l.end,p,t[o],i),a=!0;}}}return a},Ta.prototype.defines=function(){var t=[];for(var e in this.binders){var r=this.binders[e];(r instanceof Ia||r instanceof za)&&t.push.apply(t,r.uniformNames.map((function(t){return "#define HAS_UNIFORM_"+t})));}return t},Ta.prototype.getBinderAttributes=function(){var t=[];for(var e in this.binders){var r=this.binders[e];if(r instanceof Ca||r instanceof Ma)for(var n=0;n<r.paintVertexAttributes.length;n++)t.push(r.paintVertexAttributes[n].name);else if(r instanceof Ea)for(var i=0;i<sa.members.length;i++)t.push(sa.members[i].name);}return t},Ta.prototype.getBinderUniforms=function(){var t=[];for(var e in this.binders){var r=this.binders[e];if(r instanceof Ia||r instanceof za||r instanceof Ma)for(var n=0,i=r.uniformNames;n<i.length;n+=1)t.push(i[n]);}return t},Ta.prototype.getPaintVertexBuffers=function(){return this._buffers},Ta.prototype.getUniforms=function(t,e){var r=[];for(var n in this.binders){var i=this.binders[n];if(i instanceof Ia||i instanceof za||i instanceof Ma)for(var a=0,o=i.uniformNames;a<o.length;a+=1){var s=o[a];if(e[s]){var u=i.getBinding(t,e[s],s);r.push({name:s,property:n,binding:u});}}}return r},Ta.prototype.setUniforms=function(t,e,r,n){for(var i=0,a=e;i<a.length;i+=1){var o=a[i],s=o.name,u=o.property;this.binders[u].setUniform(o.binding,n,r.get(u),s);}},Ta.prototype.updatePaintBuffers=function(t){for(var e in this._buffers=[],this.binders){var r=this.binders[e];if(t&&r instanceof Ea){var n=2===t.fromScale?r.zoomInPaintVertexBuffer:r.zoomOutPaintVertexBuffer;n&&this._buffers.push(n);}else (r instanceof Ca||r instanceof Ma)&&r.paintVertexBuffer&&this._buffers.push(r.paintVertexBuffer);}},Ta.prototype.upload=function(t){for(var e in this.binders){var r=this.binders[e];(r instanceof Ca||r instanceof Ma||r instanceof Ea)&&r.upload(t);}this.updatePaintBuffers();},Ta.prototype.destroy=function(){for(var t in this.binders){var e=this.binders[t];(e instanceof Ca||e instanceof Ma||e instanceof Ea)&&e.destroy();}};var Pa=function(t,e,r){void 0===r&&(r=function(){return !0}),this.programConfigurations={};for(var n=0,i=t;n<i.length;n+=1){var a=i[n];this.programConfigurations[a.id]=new Ta(a,e,r);}this.needsUpload=!1,this._featureMap=new ha,this._bufferOffset=0;};function Ba(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(e+"-","").replace(/-/g,"_")]}function Va(t,e,r){var n={color:{source:Zi,composite:Xi},number:{source:ji,composite:Zi}},i=function(t){return {"line-pattern":{source:Ei,composite:Ei},"fill-pattern":{source:Ei,composite:Ei},"fill-extrusion-pattern":{source:Ei,composite:Ei}}[t]}(t);return i&&i[r]||n[e][r]}Pa.prototype.populatePaintArrays=function(t,e,r,n,i,a){for(var o in this.programConfigurations)this.programConfigurations[o].populatePaintArrays(t,e,n,i,a);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;},Pa.prototype.updatePaintArrays=function(t,e,r,n){for(var i=0,a=r;i<a.length;i+=1){var o=a[i];this.needsUpload=this.programConfigurations[o.id].updatePaintArrays(t,this._featureMap,e,o,n)||this.needsUpload;}},Pa.prototype.get=function(t){return this.programConfigurations[t]},Pa.prototype.upload=function(t){if(this.needsUpload){for(var e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}},Pa.prototype.destroy=function(){for(var t in this.programConfigurations)this.programConfigurations[t].destroy();},Dn("ConstantBinder",Ia),Dn("CrossFadedConstantBinder",za),Dn("SourceExpressionBinder",Ca),Dn("CrossFadedCompositeBinder",Ea),Dn("CompositeExpressionBinder",Ma),Dn("ProgramConfiguration",Ta,{omit:["_buffers"]}),Dn("ProgramConfigurationSet",Pa);var Fa=Math.pow(2,14)-1,Da=-Fa-1;function La(t){for(var e=8192/t.extent,r=t.loadGeometry(),n=0;n<r.length;n++)for(var i=r[n],a=0;a<i.length;a++){var o=i[a],s=Math.round(o.x*e),u=Math.round(o.y*e);o.x=l(s,Da,Fa),o.y=l(u,Da,Fa),(s<o.x||s>o.x+1||u<o.y||u>o.y+1)&&_("Geometry exceeds allowed extent, reduce your vector tile buffer size");}return r}function Ra(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}var Oa=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ii,this.indexArray=new Ri,this.segments=new aa,this.programConfigurations=new Pa(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function Ua(t,e){for(var r=0;r<t.length;r++)if(Ha(e,t[r]))return !0;for(var n=0;n<e.length;n++)if(Ha(t,e[n]))return !0;return !!Ka(t,e)}function ja(t,e,r){return !!Ha(t,e)||!!Za(e,t,r)}function qa(t,e){if(1===t.length)return Ja(e,t[0]);for(var r=0;r<e.length;r++)for(var n=e[r],i=0;i<n.length;i++)if(Ha(t,n[i]))return !0;for(var a=0;a<t.length;a++)if(Ja(e,t[a]))return !0;for(var o=0;o<e.length;o++)if(Ka(t,e[o]))return !0;return !1}function Na(t,e,r){if(t.length>1){if(Ka(t,e))return !0;for(var n=0;n<e.length;n++)if(Za(e[n],t,r))return !0}for(var i=0;i<t.length;i++)if(Za(t[i],e,r))return !0;return !1}function Ka(t,e){if(0===t.length||0===e.length)return !1;for(var r=0;r<t.length-1;r++)for(var n=t[r],i=t[r+1],a=0;a<e.length-1;a++)if(Ga(n,i,e[a],e[a+1]))return !0;return !1}function Ga(t,e,r,n){return A(t,r,n)!==A(e,r,n)&&A(t,e,r)!==A(t,e,n)}function Za(t,e,r){var n=r*r;if(1===e.length)return t.distSqr(e[0])<n;for(var i=1;i<e.length;i++)if(Xa(t,e[i-1],e[i])<n)return !0;return !1}function Xa(t,e,r){var n=e.distSqr(r);if(0===n)return t.distSqr(e);var i=((t.x-e.x)*(r.x-e.x)+(t.y-e.y)*(r.y-e.y))/n;return t.distSqr(i<0?e:i>1?r:r.sub(e)._mult(i)._add(e))}function Ja(t,e){for(var r,n,i,a=!1,o=0;o<t.length;o++)for(var s=0,u=(r=t[o]).length-1;s<r.length;u=s++)(n=r[s]).y>e.y!=(i=r[u]).y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function Ha(t,e){for(var r=!1,n=0,i=t.length-1;n<t.length;i=n++){var a=t[n],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r);}return r}function Ya(t,e,r){var n=r[0],i=r[2];if(t.x<n.x&&e.x<n.x||t.x>i.x&&e.x>i.x||t.y<n.y&&e.y<n.y||t.y>i.y&&e.y>i.y)return !1;var a=A(t,e,r[0]);return a!==A(t,e,r[1])||a!==A(t,e,r[2])||a!==A(t,e,r[3])}function $a(t,e,r){var n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Wa(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Qa(t,e,r,n,a){if(!e[0]&&!e[1])return t;var o=i.convert(e)._mult(a);"viewport"===r&&o._rotate(-n);for(var s=[],u=0;u<t.length;u++)s.push(t[u].sub(o));return s}Oa.prototype.populate=function(t,e,r){var n=this.layers[0],i=[],a=null;"circle"===n.type&&(a=n.layout.get("circle-sort-key"));for(var o=0,s=t;o<s.length;o+=1){var u=s[o],l=u.feature,p=u.id,c=u.index,h=u.sourceLayerIndex,f=this.layers[0]._featureFilter.needGeometry,y={type:l.type,id:p,properties:l.properties,geometry:f?La(l):[]};if(this.layers[0]._featureFilter.filter(new ai(this.zoom),y,r)){f||(y.geometry=La(l));var d=a?a.evaluate(y,{},r):void 0;i.push({id:p,properties:l.properties,type:l.type,sourceLayerIndex:h,index:c,geometry:y.geometry,patterns:{},sortKey:d});}}a&&i.sort((function(t,e){return t.sortKey-e.sortKey}));for(var m=0,v=i;m<v.length;m+=1){var g=v[m],x=g.geometry,b=g.index,w=g.sourceLayerIndex,_=t[b].feature;this.addFeature(g,x,b,r),e.featureIndex.insert(_,x,b,w,this.index);}},Oa.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},Oa.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Oa.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},Oa.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ia),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},Oa.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},Oa.prototype.addFeature=function(t,e,r,n){for(var i=0,a=e;i<a.length;i+=1)for(var o=0,s=a[i];o<s.length;o+=1){var u=s[o],l=u.x,p=u.y;if(!(l<0||l>=8192||p<0||p>=8192)){var c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),h=c.vertexLength;Ra(this.layoutVertexArray,l,p,-1,-1),Ra(this.layoutVertexArray,l,p,1,-1),Ra(this.layoutVertexArray,l,p,1,1),Ra(this.layoutVertexArray,l,p,-1,1),this.indexArray.emplaceBack(h,h+1,h+2),this.indexArray.emplaceBack(h,h+3,h+2),c.vertexLength+=4,c.primitiveLength+=2;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{},n);},Dn("CircleBucket",Oa,{omit:["layers"]});var to=new xi({"circle-sort-key":new di(zt.layout_circle["circle-sort-key"])}),eo={paint:new xi({"circle-radius":new di(zt.paint_circle["circle-radius"]),"circle-color":new di(zt.paint_circle["circle-color"]),"circle-blur":new di(zt.paint_circle["circle-blur"]),"circle-opacity":new di(zt.paint_circle["circle-opacity"]),"circle-translate":new yi(zt.paint_circle["circle-translate"]),"circle-translate-anchor":new yi(zt.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new yi(zt.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new yi(zt.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new di(zt.paint_circle["circle-stroke-width"]),"circle-stroke-color":new di(zt.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new di(zt.paint_circle["circle-stroke-opacity"])}),layout:to},ro="undefined"!=typeof Float32Array?Float32Array:Array;function no(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function io(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],d=e[12],m=e[13],v=e[14],g=e[15],x=r[0],b=r[1],w=r[2],_=r[3];return t[0]=x*n+b*s+w*c+_*d,t[1]=x*i+b*u+w*h+_*m,t[2]=x*a+b*l+w*f+_*v,t[3]=x*o+b*p+w*y+_*g,t[4]=(x=r[4])*n+(b=r[5])*s+(w=r[6])*c+(_=r[7])*d,t[5]=x*i+b*u+w*h+_*m,t[6]=x*a+b*l+w*f+_*v,t[7]=x*o+b*p+w*y+_*g,t[8]=(x=r[8])*n+(b=r[9])*s+(w=r[10])*c+(_=r[11])*d,t[9]=x*i+b*u+w*h+_*m,t[10]=x*a+b*l+w*f+_*v,t[11]=x*o+b*p+w*y+_*g,t[12]=(x=r[12])*n+(b=r[13])*s+(w=r[14])*c+(_=r[15])*d,t[13]=x*i+b*u+w*h+_*m,t[14]=x*a+b*l+w*f+_*v,t[15]=x*o+b*p+w*y+_*g,t}Math.hypot||(Math.hypot=function(){for(var t=arguments,e=0,r=arguments.length;r--;)e+=t[r]*t[r];return Math.sqrt(e)});var ao,oo=io;function so(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}ao=new ro(3),ro!=Float32Array&&(ao[0]=0,ao[1]=0,ao[2]=0),function(){var t=new ro(4);ro!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0);}();var uo=(function(){var t=new ro(2);ro!=Float32Array&&(t[0]=0,t[1]=0);}(),function(t){function e(e){t.call(this,e,eo);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new Oa(t)},e.prototype.queryRadius=function(t){var e=t;return $a("circle-radius",this,e)+$a("circle-stroke-width",this,e)+Wa(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o,s){for(var u=Qa(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),a.angle,o),l=this.paint.get("circle-radius").evaluate(e,r)+this.paint.get("circle-stroke-width").evaluate(e,r),p="map"===this.paint.get("circle-pitch-alignment"),c=p?u:function(t,e){return t.map((function(t){return lo(t,e)}))}(u,s),h=p?l*o:l,f=0,y=n;f<y.length;f+=1)for(var d=0,m=y[f];d<m.length;d+=1){var v=m[d],g=p?v:lo(v,s),x=h,b=so([],[v.x,v.y,0,1],s);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?x*=b[3]/a.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(x*=a.cameraToCenterDistance/b[3]),ja(c,g,x))return !0}return !1},e}(bi));function lo(t,e){var r=so([],[t.x,t.y,0,1],e);return new i(r[0]/r[3],r[1]/r[3])}var po=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(Oa);function co(t,e,r,n){var i=e.width,a=e.height;if(n){if(n instanceof Uint8ClampedArray)n=new Uint8Array(n.buffer);else if(n.length!==i*a*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*a*r);return t.width=i,t.height=a,t.data=n,t}function ho(t,e,r){var n=e.width,i=e.height;if(n!==t.width||i!==t.height){var a=co({},{width:n,height:i},r);fo(t,a,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,n),height:Math.min(t.height,i)},r),t.width=n,t.height=i,t.data=a.data;}}function fo(t,e,r,n,i,a){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,u=0;u<i.height;u++)for(var l=((r.y+u)*t.width+r.x)*a,p=((n.y+u)*e.width+n.x)*a,c=0;c<i.width*a;c++)s[p+c]=o[l+c];return e}Dn("HeatmapBucket",po,{omit:["layers"]});var yo=function(t,e){co(this,t,1,e);};yo.prototype.resize=function(t){ho(this,t,1);},yo.prototype.clone=function(){return new yo({width:this.width,height:this.height},new Uint8Array(this.data))},yo.copy=function(t,e,r,n,i){fo(t,e,r,n,i,1);};var mo=function(t,e){co(this,t,4,e);};mo.prototype.resize=function(t){ho(this,t,4);},mo.prototype.replace=function(t,e){e?this.data.set(t):this.data=t instanceof Uint8ClampedArray?new Uint8Array(t.buffer):t;},mo.prototype.clone=function(){return new mo({width:this.width,height:this.height},new Uint8Array(this.data))},mo.copy=function(t,e,r,n,i){fo(t,e,r,n,i,4);},Dn("AlphaImage",yo),Dn("RGBAImage",mo);var vo={paint:new xi({"heatmap-radius":new di(zt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new di(zt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new yi(zt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new gi(zt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new yi(zt.paint_heatmap["heatmap-opacity"])})};function go(t,e){for(var r=new Uint8Array(1024),n={},i=0,a=0;i<256;i++,a+=4){n[e]=i/255;var o=t.evaluate(n);r[a+0]=Math.floor(255*o.r/o.a),r[a+1]=Math.floor(255*o.g/o.a),r[a+2]=Math.floor(255*o.b/o.a),r[a+3]=Math.floor(255*o.a);}return new mo({width:256,height:1},r)}var xo=function(t){function e(e){t.call(this,e,vo),this._updateColorRamp();}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new po(t)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){"heatmap-color"===t&&this._updateColorRamp();},e.prototype._updateColorRamp=function(){this.colorRamp=go(this._transitionablePaint._values["heatmap-color"].value.expression,"heatmapDensity"),this.colorRampTexture=null;},e.prototype.resize=function(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null);},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return !1},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("heatmap-opacity")&&"none"!==this.visibility},e}(bi),bo={paint:new xi({"hillshade-illumination-direction":new yi(zt.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new yi(zt.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new yi(zt.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new yi(zt.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new yi(zt.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new yi(zt.paint_hillshade["hillshade-accent-color"])})},wo=function(t){function e(e){t.call(this,e,bo);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("hillshade-exaggeration")&&"none"!==this.visibility},e}(bi),_o=Si([{name:"a_pos",components:2,type:"Int16"}],4).members,Ao=ko,So=ko;function ko(t,e,r){r=r||2;var n,i,a,o,s,u,l,p=e&&e.length,c=p?e[0]*r:t.length,h=Io(t,0,c,r,!0),f=[];if(!h||h.next===h.prev)return f;if(p&&(h=function(t,e,r,n){var i,a,o,s=[];for(i=0,a=e.length;i<a;i++)(o=Io(t,e[i]*n,i<a-1?e[i+1]*n:t.length,n,!1))===o.next&&(o.steiner=!0),s.push(Lo(o));for(s.sort(Bo),i=0;i<s.length;i++)Vo(s[i],r),r=zo(r,r.next);return r}(t,e,h,r)),t.length>80*r){n=a=t[0],i=o=t[1];for(var y=r;y<c;y+=r)(s=t[y])<n&&(n=s),(u=t[y+1])<i&&(i=u),s>a&&(a=s),u>o&&(o=u);l=0!==(l=Math.max(a-n,o-i))?1/l:0;}return Co(h,f,r,n,i,l),f}function Io(t,e,r,n,i){var a,o;if(i===Yo(t,e,r,n)>0)for(a=e;a<r;a+=n)o=Xo(a,t[a],t[a+1],o);else for(a=r-n;a>=e;a-=n)o=Xo(a,t[a],t[a+1],o);return o&&jo(o,o.next)&&(Jo(o),o=o.next),o}function zo(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!jo(n,n.next)&&0!==Uo(n.prev,n,n.next))n=n.next;else {if(Jo(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function Co(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Do(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,u,l=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e<l&&(s++,n=n.nextZ);e++);for(u=l;s>0||u>0&&n;)0!==s&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,u--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n;}a.nextZ=null,l*=2;}while(o>1)}(i);}(t,n,i,a);for(var s,u,l=t;t.prev!==t.next;)if(s=t.prev,u=t.next,a?Eo(t,n,i,a):Mo(t))e.push(s.i/r),e.push(t.i/r),e.push(u.i/r),Jo(t),t=u.next,l=u.next;else if((t=u)===l){o?1===o?Co(t=To(zo(t),e,r),e,r,n,i,a,2):2===o&&Po(t,e,r,n,i,a):Co(zo(t),e,r,n,i,a,1);break}}}function Mo(t){var e=t.prev,r=t,n=t.next;if(Uo(e,r,n)>=0)return !1;for(var i=t.next.next;i!==t.prev;){if(Ro(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Uo(i.prev,i,i.next)>=0)return !1;i=i.next;}return !0}function Eo(t,e,r,n){var i=t.prev,a=t,o=t.next;if(Uo(i,a,o)>=0)return !1;for(var s=i.x>a.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,u=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,l=Do(i.x<a.x?i.x<o.x?i.x:o.x:a.x<o.x?a.x:o.x,i.y<a.y?i.y<o.y?i.y:o.y:a.y<o.y?a.y:o.y,e,r,n),p=Do(s,u,e,r,n),c=t.prevZ,h=t.nextZ;c&&c.z>=l&&h&&h.z<=p;){if(c!==t.prev&&c!==t.next&&Ro(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Uo(c.prev,c,c.next)>=0)return !1;if(c=c.prevZ,h!==t.prev&&h!==t.next&&Ro(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Uo(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}for(;c&&c.z>=l;){if(c!==t.prev&&c!==t.next&&Ro(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Uo(c.prev,c,c.next)>=0)return !1;c=c.prevZ;}for(;h&&h.z<=p;){if(h!==t.prev&&h!==t.next&&Ro(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Uo(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}return !0}function To(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!jo(i,a)&&qo(i,n,n.next,a)&&Go(i,a)&&Go(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),Jo(n),Jo(n.next),n=t=a),n=n.next;}while(n!==t);return zo(n)}function Po(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&Oo(o,s)){var u=Zo(o,s);return o=zo(o,o.next),u=zo(u,u.next),Co(o,e,r,n,i,a),void Co(u,e,r,n,i,a)}s=s.next;}o=o.next;}while(o!==t)}function Bo(t,e){return t.x-e.x}function Vo(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x<n.next.x?n:n.next;}}n=n.next;}while(n!==e);if(!r)return null;if(i===o)return r;var u,l=r,p=r.x,c=r.y,h=1/0;n=r;do{i>=n.x&&n.x>=p&&i!==n.x&&Ro(a<c?i:o,a,p,c,a<c?o:i,a,n.x,n.y)&&(u=Math.abs(a-n.y)/(i-n.x),Go(n,t)&&(u<h||u===h&&(n.x>r.x||n.x===r.x&&Fo(r,n)))&&(r=n,h=u)),n=n.next;}while(n!==l);return r}(t,e)){var r=Zo(e,t);zo(e,e.next),zo(r,r.next);}}function Fo(t,e){return Uo(t.prev,t,e.prev)<0&&Uo(e.next,t,t.next)<0}function Do(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Lo(t){var e=t,r=t;do{(e.x<r.x||e.x===r.x&&e.y<r.y)&&(r=e),e=e.next;}while(e!==t);return r}function Ro(t,e,r,n,i,a,o,s){return (i-o)*(e-s)-(t-o)*(a-s)>=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function Oo(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&qo(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Go(t,e)&&Go(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Uo(t.prev,t,e.prev)||Uo(t,e.prev,e))||jo(t,e)&&Uo(t.prev,t,t.next)>0&&Uo(e.prev,e,e.next)>0)}function Uo(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function jo(t,e){return t.x===e.x&&t.y===e.y}function qo(t,e,r,n){var i=Ko(Uo(t,e,r)),a=Ko(Uo(t,e,n)),o=Ko(Uo(r,n,t)),s=Ko(Uo(r,n,e));return i!==a&&o!==s||!(0!==i||!No(t,r,e))||!(0!==a||!No(t,n,e))||!(0!==o||!No(r,t,n))||!(0!==s||!No(r,e,n))}function No(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function Ko(t){return t>0?1:t<0?-1:0}function Go(t,e){return Uo(t.prev,t,t.next)<0?Uo(t,e,t.next)>=0&&Uo(t,t.prev,e)>=0:Uo(t,e,t.prev)<0||Uo(t,t.next,e)<0}function Zo(t,e){var r=new Ho(t.i,t.x,t.y),n=new Ho(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function Xo(t,e,r,n){var i=new Ho(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Jo(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function Ho(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Yo(t,e,r,n){for(var i=0,a=e,o=r-n;a<r;a+=n)i+=(t[o]-t[a])*(t[a+1]+t[o+1]),o=a;return i}function $o(t,e,r,n,i){!function t(e,r,n,i,a){for(;i>n;){if(i-n>600){var o=i-n+1,s=r-n+1,u=Math.log(o),l=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*l*(o-l)/o)*(s-o/2<0?-1:1);t(e,r,Math.max(n,Math.floor(r-s*l/o+p)),Math.min(i,Math.floor(r+(o-s)*l/o+p)),a);}var c=e[r],h=n,f=i;for(Wo(e,n,r),a(e[i],c)>0&&Wo(e,n,i);h<f;){for(Wo(e,h,f),h++,f--;a(e[h],c)<0;)h++;for(;a(e[f],c)>0;)f--;}0===a(e[n],c)?Wo(e,n,f):Wo(e,++f,i),f<=r&&(n=f+1),r<=f&&(i=f-1);}}(t,e,r||0,n||t.length-1,i||Qo);}function Wo(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function Qo(t,e){return t<e?-1:t>e?1:0}function ts(t,e){var r=t.length;if(r<=1)return [t];for(var n,i,a=[],o=0;o<r;o++){var s=S(t[o]);0!==s&&(t[o].area=Math.abs(s),void 0===i&&(i=s<0),i===s<0?(n&&a.push(n),n=[t[o]]):n.push(t[o]));}if(n&&a.push(n),e>1)for(var u=0;u<a.length;u++)a[u].length<=e||($o(a[u],e,1,a[u].length-1,es),a[u]=a[u].slice(0,e));return a}function es(t,e){return e.area-t.area}function rs(t,e,r){for(var n=r.patternDependencies,i=!1,a=0,o=e;a<o.length;a+=1){var s=o[a].paint.get(t+"-pattern");s.isConstant()||(i=!0);var u=s.constantOr(null);u&&(i=!0,n[u.to]=!0,n[u.from]=!0);}return i}function ns(t,e,r,n,i){for(var a=i.patternDependencies,o=0,s=e;o<s.length;o+=1){var u=s[o],l=u.paint.get(t+"-pattern").value;if("constant"!==l.kind){var p=l.evaluate({zoom:n-1},r,{},i.availableImages),c=l.evaluate({zoom:n},r,{},i.availableImages),h=l.evaluate({zoom:n+1},r,{},i.availableImages);c=c&&c.name?c.name:c,h=h&&h.name?h.name:h,a[p=p&&p.name?p.name:p]=!0,a[c]=!0,a[h]=!0,r.patterns[u.id]={min:p,mid:c,max:h};}}return r}ko.deviation=function(t,e,r,n){var i=e&&e.length,a=Math.abs(Yo(t,0,i?e[0]*r:t.length,r));if(i)for(var o=0,s=e.length;o<s;o++)a-=Math.abs(Yo(t,e[o]*r,o<s-1?e[o+1]*r:t.length,r));var u=0;for(o=0;o<n.length;o+=3){var l=n[o]*r,p=n[o+1]*r,c=n[o+2]*r;u+=Math.abs((t[l]-t[c])*(t[p+1]-t[l+1])-(t[l]-t[p])*(t[c+1]-t[l+1]));}return 0===a&&0===u?0:Math.abs((u-a)/a)},ko.flatten=function(t){for(var e=t[0][0].length,r={vertices:[],holes:[],dimensions:e},n=0,i=0;i<t.length;i++){for(var a=0;a<t[i].length;a++)for(var o=0;o<e;o++)r.vertices.push(t[i][a][o]);i>0&&r.holes.push(n+=t[i-1].length);}return r},Ao.default=So;var is=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ii,this.indexArray=new Ri,this.indexArray2=new Ki,this.programConfigurations=new Pa(t.layers,t.zoom),this.segments=new aa,this.segments2=new aa,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};is.prototype.populate=function(t,e,r){this.hasPattern=rs("fill",this.layers,e);for(var n=this.layers[0].layout.get("fill-sort-key"),i=[],a=0,o=t;a<o.length;a+=1){var s=o[a],u=s.feature,l=s.id,p=s.index,c=s.sourceLayerIndex,h=this.layers[0]._featureFilter.needGeometry,f={type:u.type,id:l,properties:u.properties,geometry:h?La(u):[]};if(this.layers[0]._featureFilter.filter(new ai(this.zoom),f,r)){h||(f.geometry=La(u));var y=n?n.evaluate(f,{},r,e.availableImages):void 0;i.push({id:l,properties:u.properties,type:u.type,sourceLayerIndex:c,index:p,geometry:f.geometry,patterns:{},sortKey:y});}}n&&i.sort((function(t,e){return t.sortKey-e.sortKey}));for(var d=0,m=i;d<m.length;d+=1){var v=m[d],g=v.geometry,x=v.index,b=v.sourceLayerIndex;if(this.hasPattern){var w=ns("fill",this.layers,v,this.zoom,e);this.patternFeatures.push(w);}else this.addFeature(v,g,x,r,{});e.featureIndex.insert(t[x].feature,g,x,b,this.index);}},is.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},is.prototype.addFeatures=function(t,e,r){for(var n=0,i=this.patternFeatures;n<i.length;n+=1){var a=i[n];this.addFeature(a,a.geometry,a.index,e,r);}},is.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},is.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},is.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_o),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;},is.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());},is.prototype.addFeature=function(t,e,r,n,i){for(var a=0,o=ts(e,500);a<o.length;a+=1){for(var s=o[a],u=0,l=0,p=s;l<p.length;l+=1)u+=p[l].length;for(var c=this.segments.prepareSegment(u,this.layoutVertexArray,this.indexArray),h=c.vertexLength,f=[],y=[],d=0,m=s;d<m.length;d+=1){var v=m[d];if(0!==v.length){v!==s[0]&&y.push(f.length/2);var g=this.segments2.prepareSegment(v.length,this.layoutVertexArray,this.indexArray2),x=g.vertexLength;this.layoutVertexArray.emplaceBack(v[0].x,v[0].y),this.indexArray2.emplaceBack(x+v.length-1,x),f.push(v[0].x),f.push(v[0].y);for(var b=1;b<v.length;b++)this.layoutVertexArray.emplaceBack(v[b].x,v[b].y),this.indexArray2.emplaceBack(x+b-1,x+b),f.push(v[b].x),f.push(v[b].y);g.vertexLength+=v.length,g.primitiveLength+=v.length;}}for(var w=Ao(f,y),_=0;_<w.length;_+=3)this.indexArray.emplaceBack(h+w[_],h+w[_+1],h+w[_+2]);c.vertexLength+=u,c.primitiveLength+=w.length/3;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);},Dn("FillBucket",is,{omit:["layers","patternFeatures"]});var as=new xi({"fill-sort-key":new di(zt.layout_fill["fill-sort-key"])}),os={paint:new xi({"fill-antialias":new yi(zt.paint_fill["fill-antialias"]),"fill-opacity":new di(zt.paint_fill["fill-opacity"]),"fill-color":new di(zt.paint_fill["fill-color"]),"fill-outline-color":new di(zt.paint_fill["fill-outline-color"]),"fill-translate":new yi(zt.paint_fill["fill-translate"]),"fill-translate-anchor":new yi(zt.paint_fill["fill-translate-anchor"]),"fill-pattern":new mi(zt.paint_fill["fill-pattern"])}),layout:as},ss=function(t){function e(e){t.call(this,e,os);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r);var n=this.paint._values["fill-outline-color"];"constant"===n.value.kind&&void 0===n.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);},e.prototype.createBucket=function(t){return new is(t)},e.prototype.queryRadius=function(){return Wa(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o){return qa(Qa(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),a.angle,o),n)},e.prototype.isTileClipped=function(){return !0},e}(bi),us=Si([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4).members,ls=ps;function ps(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(cs,this,e);}function cs(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos<r;){var n=e._keys[t.readVarint()],i=e._values[t.readVarint()];e.properties[n]=i;}}(r,e):3==t?e.type=r.readVarint():4==t&&(e._geometry=r.pos);}function hs(t){for(var e,r,n=0,i=0,a=t.length,o=a-1;i<a;o=i++)n+=((r=t[o]).x-(e=t[i]).x)*(e.y+r.y);return n}ps.types=["Unknown","Point","LineString","Polygon"],ps.prototype.loadGeometry=function(){var t=this._pbf;t.pos=this._geometry;for(var e,r=t.readVarint()+t.pos,n=1,a=0,o=0,s=0,u=[];t.pos<r;){if(a<=0){var l=t.readVarint();n=7&l,a=l>>3;}if(a--,1===n||2===n)o+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&u.push(e),e=[]),e.push(new i(o,s));else {if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&u.push(e),u},ps.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,u=1/0,l=-1/0;t.pos<e;){if(n<=0){var p=t.readVarint();r=7&p,n=p>>3;}if(n--,1===r||2===r)(i+=t.readSVarint())<o&&(o=i),i>s&&(s=i),(a+=t.readSVarint())<u&&(u=a),a>l&&(l=a);else if(7!==r)throw new Error("unknown command "+r)}return [o,u,s,l]},ps.prototype.toGeoJSON=function(t,e,r){var n,i,a=this.extent*Math.pow(2,r),o=this.extent*t,s=this.extent*e,u=this.loadGeometry(),l=ps.types[this.type];function p(t){for(var e=0;e<t.length;e++){var r=t[e];t[e]=[360*(r.x+o)/a-180,360/Math.PI*Math.atan(Math.exp((180-360*(r.y+s)/a)*Math.PI/180))-90];}}switch(this.type){case 1:var c=[];for(n=0;n<u.length;n++)c[n]=u[n][0];p(u=c);break;case 2:for(n=0;n<u.length;n++)p(u[n]);break;case 3:for(u=function(t){var e=t.length;if(e<=1)return [t];for(var r,n,i=[],a=0;a<e;a++){var o=hs(t[a]);0!==o&&(void 0===n&&(n=o<0),n===o<0?(r&&i.push(r),r=[t[a]]):r.push(t[a]));}return r&&i.push(r),i}(u),n=0;n<u.length;n++)for(i=0;i<u[n].length;i++)p(u[n][i]);}1===u.length?u=u[0]:l="Multi"+l;var h={type:"Feature",geometry:{type:l,coordinates:u},properties:this.properties};return "id"in this&&(h.id=this.id),h};var fs=ys;function ys(t,e){this.version=1,this.name=null,this.extent=4096,this.length=0,this._pbf=t,this._keys=[],this._values=[],this._features=[],t.readFields(ds,this,e),this.length=this._features.length;}function ds(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){for(var e=null,r=t.readVarint()+t.pos;t.pos<r;){var n=t.readVarint()>>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}function ms(t,e,r){if(3===t){var n=new fs(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}ys.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new ls(this._pbf,e,this.extent,this._keys,this._values)};var vs={VectorTile:function(t,e){this.layers=t.readFields(ms,{},e);},VectorTileFeature:ls,VectorTileLayer:fs},gs=vs.VectorTileFeature.types,xs=Math.pow(2,13);function bs(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,2*Math.floor(n*xs)+o,i*xs*2,a*xs*2,Math.round(s));}var ws=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ci,this.indexArray=new Ri,this.programConfigurations=new Pa(t.layers,t.zoom),this.segments=new aa,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function _s(t,e){return t.x===e.x&&(t.x<0||t.x>8192)||t.y===e.y&&(t.y<0||t.y>8192)}ws.prototype.populate=function(t,e,r){this.features=[],this.hasPattern=rs("fill-extrusion",this.layers,e);for(var n=0,i=t;n<i.length;n+=1){var a=i[n],o=a.feature,s=a.id,u=a.index,l=a.sourceLayerIndex,p=this.layers[0]._featureFilter.needGeometry,c={type:o.type,id:s,properties:o.properties,geometry:p?La(o):[]};if(this.layers[0]._featureFilter.filter(new ai(this.zoom),c,r)){var h={id:s,sourceLayerIndex:l,index:u,geometry:p?c.geometry:La(o),properties:o.properties,type:o.type,patterns:{}};void 0!==o.id&&(h.id=o.id),this.hasPattern?this.features.push(ns("fill-extrusion",this.layers,h,this.zoom,e)):this.addFeature(h,h.geometry,u,r,{}),e.featureIndex.insert(o,h.geometry,u,l,this.index,!0);}}},ws.prototype.addFeatures=function(t,e,r){for(var n=0,i=this.features;n<i.length;n+=1){var a=i[n];this.addFeature(a,a.geometry,a.index,e,r);}},ws.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},ws.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},ws.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},ws.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,us),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},ws.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},ws.prototype.addFeature=function(t,e,r,n,i){for(var a=0,o=ts(e,500);a<o.length;a+=1){for(var s=o[a],u=0,l=0,p=s;l<p.length;l+=1)u+=p[l].length;for(var c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),h=0,f=s;h<f.length;h+=1){var y=f[h];if(0!==y.length&&!((P=y).every((function(t){return t.x<0}))||P.every((function(t){return t.x>8192}))||P.every((function(t){return t.y<0}))||P.every((function(t){return t.y>8192}))))for(var d=0,m=0;m<y.length;m++){var v=y[m];if(m>=1){var g=y[m-1];if(!_s(v,g)){c.vertexLength+4>aa.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var x=v.sub(g)._perp()._unit(),b=g.dist(v);d+b>32768&&(d=0),bs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,0,d),bs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,1,d),bs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,0,d+=b),bs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,1,d);var w=c.vertexLength;this.indexArray.emplaceBack(w,w+2,w+1),this.indexArray.emplaceBack(w+1,w+2,w+3),c.vertexLength+=4,c.primitiveLength+=2;}}}}if(c.vertexLength+u>aa.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(u,this.layoutVertexArray,this.indexArray)),"Polygon"===gs[t.type]){for(var _=[],A=[],S=c.vertexLength,k=0,I=s;k<I.length;k+=1){var z=I[k];if(0!==z.length){z!==s[0]&&A.push(_.length/2);for(var C=0;C<z.length;C++){var M=z[C];bs(this.layoutVertexArray,M.x,M.y,0,0,1,1,0),_.push(M.x),_.push(M.y);}}}for(var E=Ao(_,A),T=0;T<E.length;T+=3)this.indexArray.emplaceBack(S+E[T],S+E[T+2],S+E[T+1]);c.primitiveLength+=E.length/3,c.vertexLength+=u;}}var P;this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);},Dn("FillExtrusionBucket",ws,{omit:["layers","features"]});var As={paint:new xi({"fill-extrusion-opacity":new yi(zt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new di(zt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new yi(zt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new yi(zt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new mi(zt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new di(zt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new di(zt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new yi(zt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})},Ss=function(t){function e(e){t.call(this,e,As);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new ws(t)},e.prototype.queryRadius=function(){return Wa(this.paint.get("fill-extrusion-translate"))},e.prototype.is3D=function(){return !0},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s,u){var l=Qa(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),o.angle,s),p=this.paint.get("fill-extrusion-height").evaluate(e,r),c=this.paint.get("fill-extrusion-base").evaluate(e,r),h=function(t,e,r,n){for(var a=[],o=0,s=t;o<s.length;o+=1){var u=s[o],l=[u.x,u.y,0,1];so(l,l,e),a.push(new i(l[0]/l[3],l[1]/l[3]));}return a}(l,u),f=function(t,e,r,n){for(var a=[],o=[],s=n[8]*e,u=n[9]*e,l=n[10]*e,p=n[11]*e,c=n[8]*r,h=n[9]*r,f=n[10]*r,y=n[11]*r,d=0,m=t;d<m.length;d+=1){for(var v=[],g=[],x=0,b=m[d];x<b.length;x+=1){var w=b[x],_=w.x,A=w.y,S=n[0]*_+n[4]*A+n[12],k=n[1]*_+n[5]*A+n[13],I=n[2]*_+n[6]*A+n[14],z=n[3]*_+n[7]*A+n[15],C=I+l,M=z+p,E=S+c,T=k+h,P=I+f,B=z+y,V=new i((S+s)/M,(k+u)/M);V.z=C/M,v.push(V);var F=new i(E/B,T/B);F.z=P/B,g.push(F);}a.push(v),o.push(g);}return [a,o]}(n,c,p,u);return function(t,e,r){var n=1/0;qa(r,e)&&(n=Is(r,e[0]));for(var i=0;i<e.length;i++)for(var a=e[i],o=t[i],s=0;s<a.length-1;s++){var u=a[s],l=[u,a[s+1],o[s+1],o[s],u];Ua(r,l)&&(n=Math.min(n,Is(r,l)));}return n!==1/0&&n}(f[0],f[1],h)},e}(bi);function ks(t,e){return t.x*e.x+t.y*e.y}function Is(t,e){if(1===t.length){for(var r,n=0,i=e[n++];!r||i.equals(r);)if(!(r=e[n++]))return 1/0;for(;n<e.length;n++){var a=e[n],o=t[0],s=r.sub(i),u=a.sub(i),l=o.sub(i),p=ks(s,s),c=ks(s,u),h=ks(u,u),f=ks(l,s),y=ks(l,u),d=p*h-c*c,m=(h*f-c*y)/d,v=(p*y-c*f)/d,g=i.z*(1-m-v)+r.z*m+a.z*v;if(isFinite(g))return g}return 1/0}for(var x=1/0,b=0,w=e;b<w.length;b+=1)x=Math.min(x,w[b].z);return x}var zs=Si([{name:"a_pos_normal",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"}],4).members,Cs=vs.VectorTileFeature.types,Ms=Math.cos(Math.PI/180*37.5),Es=Math.pow(2,14)/.5,Ts=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Mi,this.indexArray=new Ri,this.programConfigurations=new Pa(t.layers,t.zoom),this.segments=new aa,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};Ts.prototype.populate=function(t,e,r){this.hasPattern=rs("line",this.layers,e);for(var n=this.layers[0].layout.get("line-sort-key"),i=[],a=0,o=t;a<o.length;a+=1){var s=o[a],u=s.feature,l=s.id,p=s.index,c=s.sourceLayerIndex,h=this.layers[0]._featureFilter.needGeometry,f={type:u.type,id:l,properties:u.properties,geometry:h?La(u):[]};if(this.layers[0]._featureFilter.filter(new ai(this.zoom),f,r)){h||(f.geometry=La(u));var y=n?n.evaluate(f,{},r):void 0;i.push({id:l,properties:u.properties,type:u.type,sourceLayerIndex:c,index:p,geometry:f.geometry,patterns:{},sortKey:y});}}n&&i.sort((function(t,e){return t.sortKey-e.sortKey}));for(var d=0,m=i;d<m.length;d+=1){var v=m[d],g=v.geometry,x=v.index,b=v.sourceLayerIndex;if(this.hasPattern){var w=ns("line",this.layers,v,this.zoom,e);this.patternFeatures.push(w);}else this.addFeature(v,g,x,r,{});e.featureIndex.insert(t[x].feature,g,x,b,this.index);}},Ts.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},Ts.prototype.addFeatures=function(t,e,r){for(var n=0,i=this.patternFeatures;n<i.length;n+=1){var a=i[n];this.addFeature(a,a.geometry,a.index,e,r);}},Ts.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Ts.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},Ts.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,zs),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},Ts.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},Ts.prototype.addFeature=function(t,e,r,n,i){for(var a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),s=a.get("line-cap"),u=a.get("line-miter-limit"),l=a.get("line-round-limit"),p=0,c=e;p<c.length;p+=1)this.addLine(c[p],t,o,s,u,l);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);},Ts.prototype.addLine=function(t,e,r,n,i,a){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,e.properties&&e.properties.hasOwnProperty("mapbox_clip_start")&&e.properties.hasOwnProperty("mapbox_clip_end")){this.clipStart=+e.properties.mapbox_clip_start,this.clipEnd=+e.properties.mapbox_clip_end;for(var o=0;o<t.length-1;o++)this.totalDistance+=t[o].dist(t[o+1]);this.updateScaledDistance();}for(var s="Polygon"===Cs[e.type],u=t.length;u>=2&&t[u-1].equals(t[u-2]);)u--;for(var l=0;l<u-1&&t[l].equals(t[l+1]);)l++;if(!(u<(s?3:2))){"bevel"===r&&(i=1.05);var p,c=this.overscaling<=16?122880/(512*this.overscaling):0,h=this.segments.prepareSegment(10*u,this.layoutVertexArray,this.indexArray),f=void 0,y=void 0,d=void 0,m=void 0;this.e1=this.e2=-1,s&&(m=t[l].sub(p=t[u-2])._unit()._perp());for(var v=l;v<u;v++)if(!(y=v===u-1?s?t[l+1]:void 0:t[v+1])||!t[v].equals(y)){m&&(d=m),p&&(f=p),p=t[v],m=y?y.sub(p)._unit()._perp():d;var g=(d=d||m).add(m);0===g.x&&0===g.y||g._unit();var x=d.x*m.x+d.y*m.y,b=g.x*m.x+g.y*m.y,w=0!==b?1/b:1/0,_=2*Math.sqrt(2-2*b),A=b<Ms&&f&&y,S=d.x*m.y-d.y*m.x>0;if(A&&v>l){var k=p.dist(f);if(k>2*c){var I=p.sub(p.sub(f)._mult(c/k)._round());this.updateDistance(f,I),this.addCurrentVertex(I,d,0,0,h),f=I;}}var z=f&&y,C=z?r:s?"butt":n;if(z&&"round"===C&&(w<a?C="miter":w<=2&&(C="fakeround")),"miter"===C&&w>i&&(C="bevel"),"bevel"===C&&(w>2&&(C="flipbevel"),w<i&&(C="miter")),f&&this.updateDistance(f,p),"miter"===C)g._mult(w),this.addCurrentVertex(p,g,0,0,h);else if("flipbevel"===C){if(w>100)g=m.mult(-1);else {var M=w*d.add(m).mag()/d.sub(m).mag();g._perp()._mult(M*(S?-1:1));}this.addCurrentVertex(p,g,0,0,h),this.addCurrentVertex(p,g.mult(-1),0,0,h);}else if("bevel"===C||"fakeround"===C){var E=-Math.sqrt(w*w-1),T=S?E:0,P=S?0:E;if(f&&this.addCurrentVertex(p,d,T,P,h),"fakeround"===C)for(var B=Math.round(180*_/Math.PI/20),V=1;V<B;V++){var F=V/B;if(.5!==F){var D=F-.5;F+=F*D*(F-1)*((1.0904+x*(x*(3.55645-1.43519*x)-3.2452))*D*D+(.848013+x*(.215638*x-1.06021)));}var L=m.sub(d)._mult(F)._add(d)._unit()._mult(S?-1:1);this.addHalfVertex(p,L.x,L.y,!1,S,0,h);}y&&this.addCurrentVertex(p,m,-T,-P,h);}else if("butt"===C)this.addCurrentVertex(p,g,0,0,h);else if("square"===C){var R=f?1:-1;this.addCurrentVertex(p,g,R,R,h);}else "round"===C&&(f&&(this.addCurrentVertex(p,d,0,0,h),this.addCurrentVertex(p,d,1,1,h,!0)),y&&(this.addCurrentVertex(p,m,-1,-1,h,!0),this.addCurrentVertex(p,m,0,0,h)));if(A&&v<u-1){var O=p.dist(y);if(O>2*c){var U=p.add(y.sub(p)._mult(c/O)._round());this.updateDistance(p,U),this.addCurrentVertex(U,m,0,0,h),p=U;}}}}},Ts.prototype.addCurrentVertex=function(t,e,r,n,i,a){void 0===a&&(a=!1);var o=e.y*n-e.x,s=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,a,!1,r,i),this.addHalfVertex(t,o,s,a,!0,-n,i),this.distance>Es/2&&0===this.totalDistance&&(this.distance=0,this.addCurrentVertex(t,e,r,n,i,a));},Ts.prototype.addHalfVertex=function(t,e,r,n,i,a,o){var s=.5*this.scaledDistance;this.layoutVertexArray.emplaceBack((t.x<<1)+(n?1:0),(t.y<<1)+(i?1:0),Math.round(63*e)+128,Math.round(63*r)+128,1+(0===a?0:a<0?-1:1)|(63&s)<<2,s>>6);var u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,u),o.primitiveLength++),i?this.e2=u:this.e1=u;},Ts.prototype.updateScaledDistance=function(){this.scaledDistance=this.totalDistance>0?(this.clipStart+(this.clipEnd-this.clipStart)*this.distance/this.totalDistance)*(Es-1):this.distance;},Ts.prototype.updateDistance=function(t,e){this.distance+=t.dist(e),this.updateScaledDistance();},Dn("LineBucket",Ts,{omit:["layers","patternFeatures"]});var Ps=new xi({"line-cap":new yi(zt.layout_line["line-cap"]),"line-join":new di(zt.layout_line["line-join"]),"line-miter-limit":new yi(zt.layout_line["line-miter-limit"]),"line-round-limit":new yi(zt.layout_line["line-round-limit"]),"line-sort-key":new di(zt.layout_line["line-sort-key"])}),Bs={paint:new xi({"line-opacity":new di(zt.paint_line["line-opacity"]),"line-color":new di(zt.paint_line["line-color"]),"line-translate":new yi(zt.paint_line["line-translate"]),"line-translate-anchor":new yi(zt.paint_line["line-translate-anchor"]),"line-width":new di(zt.paint_line["line-width"]),"line-gap-width":new di(zt.paint_line["line-gap-width"]),"line-offset":new di(zt.paint_line["line-offset"]),"line-blur":new di(zt.paint_line["line-blur"]),"line-dasharray":new vi(zt.paint_line["line-dasharray"]),"line-pattern":new mi(zt.paint_line["line-pattern"]),"line-gradient":new gi(zt.paint_line["line-gradient"])}),layout:Ps},Vs=new(function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new ai(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n,i){return r=c({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n,i)},e}(di))(Bs.paint.properties["line-width"].specification);Vs.useIntegerZoom=!0;var Fs=function(t){function e(e){t.call(this,e,Bs);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._handleSpecialPaintPropertyUpdate=function(t){"line-gradient"===t&&this._updateGradient();},e.prototype._updateGradient=function(){this.gradient=go(this._transitionablePaint._values["line-gradient"].value.expression,"lineProgress"),this.gradientTexture=null;},e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r),this.paint._values["line-floorwidth"]=Vs.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e);},e.prototype.createBucket=function(t){return new Ts(t)},e.prototype.queryRadius=function(t){var e=t,r=Ds($a("line-width",this,e),$a("line-gap-width",this,e)),n=$a("line-offset",this,e);return r/2+Math.abs(n)+Wa(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s){var u=Qa(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o.angle,s),l=s/2*Ds(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),p=this.paint.get("line-offset").evaluate(e,r);return p&&(n=function(t,e){for(var r=[],n=new i(0,0),a=0;a<t.length;a++){for(var o=t[a],s=[],u=0;u<o.length;u++){var l=o[u],p=o[u+1],c=0===u?n:l.sub(o[u-1])._unit()._perp(),h=u===o.length-1?n:p.sub(l)._unit()._perp(),f=c._add(h)._unit();f._mult(1/(f.x*h.x+f.y*h.y)),s.push(f._mult(e)._add(l));}r.push(s);}return r}(n,p*s)),function(t,e,r){for(var n=0;n<e.length;n++){var i=e[n];if(t.length>=3)for(var a=0;a<i.length;a++)if(Ha(t,i[a]))return !0;if(Na(t,i,r))return !0}return !1}(u,n,l)},e.prototype.isTileClipped=function(){return !0},e}(bi);function Ds(t,e){return e>0?e+2*t:t}var Ls=Si([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Rs=Si([{name:"a_projected_pos",components:3,type:"Float32"}],4),Os=(Si([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),Si([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"}])),Us=(Si([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]),Si([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),js=Si([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function qs(t,e,r){return t.sections.forEach((function(t){t.text=function(t,e,r){var n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),ii.applyArabicShaping&&(t=ii.applyArabicShaping(t)),t}(t.text,e,r);})),t}Si([{name:"triangle",components:3,type:"Uint16"}]),Si([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Si([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",components:2,name:"textOffset"},{type:"Float32",name:"collisionCircleDiameter"}]),Si([{type:"Float32",name:"offsetX"}]),Si([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);var Ns={"!":"︕","#":"",$:"","%":"","&":"","(":"︵",")":"︶","*":"","+":"",",":"︐","-":"︲",".":"・","/":"",":":"︓",";":"︔","<":"︿","=":"",">":"﹀","?":"︖","@":"","[":"﹇","\\":"","]":"﹈","^":"",_:"︳","`":"","{":"︷","|":"―","}":"︸","~":"","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","":"︲","—":"︱","":"﹃","":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","":"︹","":"︺","〖":"︗","〗":"︘","":"︕","":"︵","":"︶","":"︐","":"︲","":"・","":"︓","":"︔","":"︿","":"﹀","":"︖","":"﹇","":"﹈","_":"︳","":"︷","":"―","":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"},Ks=function(t,e,r,n,i){var a,o,s=8*i-n-1,u=(1<<s)-1,l=u>>1,p=-7,c=r?i-1:0,h=r?-1:1,f=t[e+c];for(c+=h,a=f&(1<<-p)-1,f>>=-p,p+=s;p>0;a=256*a+t[e+c],c+=h,p-=8);for(o=a&(1<<-p)-1,a>>=-p,p+=n;p>0;o=256*o+t[e+c],c+=h,p-=8);if(0===a)a=1-l;else {if(a===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),a-=l;}return (f?-1:1)*o*Math.pow(2,a-n)},Gs=function(t,e,r,n,i,a){var o,s,u,l=8*a-i-1,p=(1<<l)-1,c=p>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),(e+=o+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(o++,u/=2),o+c>=p?(s=0,o=p):o+c>=1?(s=(e*u-1)*Math.pow(2,i),o+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),o=0));i>=8;t[r+f]=255&s,f+=y,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;t[r+f]=255&o,f+=y,o/=256,l-=8);t[r+f-y]|=128*d;},Zs=Xs;function Xs(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}Xs.Varint=0,Xs.Fixed64=1,Xs.Bytes=2,Xs.Fixed32=5;var Js="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function Hs(t){return t.type===Xs.Bytes?t.readVarint()+t.pos:t.pos+1}function Ys(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function $s(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function Ws(t,e){for(var r=0;r<t.length;r++)e.writeVarint(t[r]);}function Qs(t,e){for(var r=0;r<t.length;r++)e.writeSVarint(t[r]);}function tu(t,e){for(var r=0;r<t.length;r++)e.writeFloat(t[r]);}function eu(t,e){for(var r=0;r<t.length;r++)e.writeDouble(t[r]);}function ru(t,e){for(var r=0;r<t.length;r++)e.writeBoolean(t[r]);}function nu(t,e){for(var r=0;r<t.length;r++)e.writeFixed32(t[r]);}function iu(t,e){for(var r=0;r<t.length;r++)e.writeSFixed32(t[r]);}function au(t,e){for(var r=0;r<t.length;r++)e.writeFixed64(t[r]);}function ou(t,e){for(var r=0;r<t.length;r++)e.writeSFixed64(t[r]);}function su(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+16777216*t[e+3]}function uu(t,e,r){t[r]=e,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function lu(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}function pu(t,e,r){1===t&&r.readMessage(cu,e);}function cu(t,e,r){if(3===t){var n=r.readMessage(hu,{}),i=n.width,a=n.height,o=n.left,s=n.top,u=n.advance;e.push({id:n.id,bitmap:new yo({width:i+6,height:a+6},n.bitmap),metrics:{width:i,height:a,left:o,top:s,advance:u}});}}function hu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}function fu(t){for(var e=0,r=0,n=0,i=t;n<i.length;n+=1){var a=i[n];e+=a.w*a.h,r=Math.max(r,a.w);}t.sort((function(t,e){return e.h-t.h}));for(var o=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}],s=0,u=0,l=0,p=t;l<p.length;l+=1)for(var c=p[l],h=o.length-1;h>=0;h--){var f=o[h];if(!(c.w>f.w||c.h>f.h)){if(c.x=f.x,c.y=f.y,u=Math.max(u,c.y+c.h),s=Math.max(s,c.x+c.w),c.w===f.w&&c.h===f.h){var y=o.pop();h<o.length&&(o[h]=y);}else c.h===f.h?(f.x+=c.w,f.w-=c.w):c.w===f.w?(f.y+=c.h,f.h-=c.h):(o.push({x:f.x+c.w,y:f.y,w:f.w-c.w,h:c.h}),f.y+=c.h,f.h-=c.h);break}}return {w:s,h:u,fill:e/(s*u)||0}}Xs.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos<r;){var n=this.readVarint(),i=n>>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=su(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=lu(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=su(this.buf,this.pos)+4294967296*su(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=su(this.buf,this.pos)+4294967296*lu(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=Ks(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=Ks(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,a=r.buf;if(n=(112&(i=a[r.pos++]))>>4,i<128)return Ys(t,n,e);if(n|=(127&(i=a[r.pos++]))<<3,i<128)return Ys(t,n,e);if(n|=(127&(i=a[r.pos++]))<<10,i<128)return Ys(t,n,e);if(n|=(127&(i=a[r.pos++]))<<17,i<128)return Ys(t,n,e);if(n|=(127&(i=a[r.pos++]))<<24,i<128)return Ys(t,n,e);if(n|=(1&(i=a[r.pos++]))<<31,i<128)return Ys(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Js?function(t,e,r){return Js.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i<r;){var a,o,s,u=t[i],l=null,p=u>239?4:u>223?3:u>191?2:1;if(i+p>r)break;1===p?u<128&&(l=u):2===p?128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)<=127&&(l=null):3===p?(o=t[i+2],128==(192&(a=t[i+1]))&&128==(192&o)&&((l=(15&u)<<12|(63&a)<<6|63&o)<=2047||l>=55296&&l<=57343)&&(l=null)):4===p&&(o=t[i+2],s=t[i+3],128==(192&(a=t[i+1]))&&128==(192&o)&&128==(192&s)&&((l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||l>=1114112)&&(l=null)),null===l?(l=65533,p=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=p;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==Xs.Bytes)return t.push(this.readVarint(e));var r=Hs(this);for(t=t||[];this.pos<r;)t.push(this.readVarint(e));return t},readPackedSVarint:function(t){if(this.type!==Xs.Bytes)return t.push(this.readSVarint());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readSVarint());return t},readPackedBoolean:function(t){if(this.type!==Xs.Bytes)return t.push(this.readBoolean());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readBoolean());return t},readPackedFloat:function(t){if(this.type!==Xs.Bytes)return t.push(this.readFloat());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readFloat());return t},readPackedDouble:function(t){if(this.type!==Xs.Bytes)return t.push(this.readDouble());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readDouble());return t},readPackedFixed32:function(t){if(this.type!==Xs.Bytes)return t.push(this.readFixed32());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readFixed32());return t},readPackedSFixed32:function(t){if(this.type!==Xs.Bytes)return t.push(this.readSFixed32());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed32());return t},readPackedFixed64:function(t){if(this.type!==Xs.Bytes)return t.push(this.readFixed64());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readFixed64());return t},readPackedSFixed64:function(t){if(this.type!==Xs.Bytes)return t.push(this.readSFixed64());var e=Hs(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed64());return t},skip:function(t){var e=7&t;if(e===Xs.Varint)for(;this.buf[this.pos++]>127;);else if(e===Xs.Bytes)this.pos=this.readVarint()+this.pos;else if(e===Xs.Fixed32)this.pos+=4;else {if(e!==Xs.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e<this.pos+t;)e*=2;if(e!==this.length){var r=new Uint8Array(e);r.set(this.buf),this.buf=r,this.length=e;}},finish:function(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)},writeFixed32:function(t){this.realloc(4),uu(this.buf,t,this.pos),this.pos+=4;},writeSFixed32:function(t){this.realloc(4),uu(this.buf,t,this.pos),this.pos+=4;},writeFixed64:function(t){this.realloc(8),uu(this.buf,-1&t,this.pos),uu(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeSFixed64:function(t){this.realloc(8),uu(this.buf,-1&t,this.pos),uu(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeVarint:function(t){(t=+t||0)>268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a<e.length;a++){if((n=e.charCodeAt(a))>55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&$s(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),Gs(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),Gs(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r<e;r++)this.buf[this.pos++]=t[r];},writeRawMessage:function(t,e){this.pos++;var r=this.pos;t(e,this);var n=this.pos-r;n>=128&&$s(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,Xs.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,Ws,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,Qs,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,ru,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,tu,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,eu,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,nu,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,iu,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,au,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,ou,e);},writeBytesField:function(t,e){this.writeTag(t,Xs.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,Xs.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,Xs.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,Xs.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,Xs.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,Xs.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,Xs.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,Xs.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,Xs.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,Xs.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var yu=function(t,e){var r=e.pixelRatio,n=e.version,i=e.stretchX,a=e.stretchY,o=e.content;this.paddedRect=t,this.pixelRatio=r,this.stretchX=i,this.stretchY=a,this.content=o,this.version=n;},du={tl:{configurable:!0},br:{configurable:!0},tlbr:{configurable:!0},displaySize:{configurable:!0}};du.tl.get=function(){return [this.paddedRect.x+1,this.paddedRect.y+1]},du.br.get=function(){return [this.paddedRect.x+this.paddedRect.w-1,this.paddedRect.y+this.paddedRect.h-1]},du.tlbr.get=function(){return this.tl.concat(this.br)},du.displaySize.get=function(){return [(this.paddedRect.w-2)/this.pixelRatio,(this.paddedRect.h-2)/this.pixelRatio]},Object.defineProperties(yu.prototype,du);var mu=function(t,e){var r={},n={};this.haveRenderCallbacks=[];var i=[];this.addImages(t,r,i),this.addImages(e,n,i);var a=fu(i),o=new mo({width:a.w||1,height:a.h||1});for(var s in t){var u=t[s],l=r[s].paddedRect;mo.copy(u.data,o,{x:0,y:0},{x:l.x+1,y:l.y+1},u.data);}for(var p in e){var c=e[p],h=n[p].paddedRect,f=h.x+1,y=h.y+1,d=c.data.width,m=c.data.height;mo.copy(c.data,o,{x:0,y:0},{x:f,y:y},c.data),mo.copy(c.data,o,{x:0,y:m-1},{x:f,y:y-1},{width:d,height:1}),mo.copy(c.data,o,{x:0,y:0},{x:f,y:y+m},{width:d,height:1}),mo.copy(c.data,o,{x:d-1,y:0},{x:f-1,y:y},{width:1,height:m}),mo.copy(c.data,o,{x:0,y:0},{x:f+d,y:y},{width:1,height:m});}this.image=o,this.iconPositions=r,this.patternPositions=n;};mu.prototype.addImages=function(t,e,r){for(var n in t){var i=t[n],a={x:0,y:0,w:i.data.width+2,h:i.data.height+2};r.push(a),e[n]=new yu(a,i),i.hasRenderCallback&&this.haveRenderCallbacks.push(n);}},mu.prototype.patchUpdatedImages=function(t,e){for(var r in t.dispatchRenderCallbacks(this.haveRenderCallbacks),t.updatedImages)this.patchUpdatedImage(this.iconPositions[r],t.getImage(r),e),this.patchUpdatedImage(this.patternPositions[r],t.getImage(r),e);},mu.prototype.patchUpdatedImage=function(t,e,r){if(t&&e&&t.version!==e.version){t.version=e.version;var n=t.tl;r.update(e.data,void 0,{x:n[0],y:n[1]});}},Dn("ImagePosition",yu),Dn("ImageAtlas",mu);var vu={horizontal:1,vertical:2,horizontalOnly:3},gu=function(){this.scale=1,this.fontStack="",this.imageName=null;};gu.forText=function(t,e){var r=new gu;return r.scale=t||1,r.fontStack=e,r},gu.forImage=function(t){var e=new gu;return e.imageName=t,e};var xu=function(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null;};function bu(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d){var m,v=xu.fromFeature(t,i);c===vu.vertical&&v.verticalizePunctuation();var g=ii.processBidirectionalText,x=ii.processStyledBidirectionalText;if(g&&1===v.sections.length){m=[];for(var b=0,w=g(v.toString(),zu(v,l,a,e,n,f,y));b<w.length;b+=1){var _=w[b],A=new xu;A.text=_,A.sections=v.sections;for(var S=0;S<_.length;S++)A.sectionIndex.push(0);m.push(A);}}else if(x){m=[];for(var k=0,I=x(v.text,v.sectionIndex,zu(v,l,a,e,n,f,y));k<I.length;k+=1){var z=I[k],C=new xu;C.text=z[0],C.sectionIndex=z[1],C.sections=v.sections,m.push(C);}}else m=function(t,e){for(var r=[],n=t.text,i=0,a=0,o=e;a<o.length;a+=1){var s=o[a];r.push(t.substring(i,s)),i=s;}return i<n.length&&r.push(t.substring(i,n.length)),r}(v,zu(v,l,a,e,n,f,y));var M=[],E={positionedLines:M,text:v.toString(),top:p[1],bottom:p[1],left:p[0],right:p[0],writingMode:c,iconsInText:!1,verticalizable:!1};return function(t,e,r,n,i,a,o,s,u,l,p,c){for(var h=0,f=-17,y=0,d=0,m="right"===s?1:"left"===s?0:.5,v=0,g=0,x=i;g<x.length;g+=1){var b=x[g];b.trim();var w=b.getMaxScale(),_=24*(w-1),A={positionedGlyphs:[],lineOffset:0};t.positionedLines[v]=A;var S=A.positionedGlyphs,k=0;if(b.length()){for(var I=0;I<b.length();I++){var z=b.getSection(I),C=b.getSectionIndex(I),M=b.getCharCode(I),E=0,T=null,P=null,B=null,V=24,F=!(u===vu.horizontal||!p&&!Gn(M)||p&&(wu[M]||(K=M,Nn.Arabic(K)||Nn["Arabic Supplement"](K)||Nn["Arabic Extended-A"](K)||Nn["Arabic Presentation Forms-A"](K)||Nn["Arabic Presentation Forms-B"](K))));if(z.imageName){var D=n[z.imageName];if(!D)continue;B=z.imageName,t.iconsInText=t.iconsInText||!0,P=D.paddedRect;var L=D.displaySize;z.scale=24*z.scale/c,E=_+(24-L[1]*z.scale),V=(T={width:L[0],height:L[1],left:1,top:-3,advance:F?L[1]:L[0]}).advance;var R=F?L[0]*z.scale-24*w:L[1]*z.scale-24*w;R>0&&R>k&&(k=R);}else {var O=r[z.fontStack],U=O&&O[M];if(U&&U.rect)P=U.rect,T=U.metrics;else {var j=e[z.fontStack],q=j&&j[M];if(!q)continue;T=q.metrics;}E=24*(w-z.scale);}F?(t.verticalizable=!0,S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=V*z.scale+l):(S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=T.advance*z.scale+l);}0!==S.length&&(y=Math.max(h-l,y),Mu(S,0,S.length-1,m,k)),h=0;var N=a*w+k;A.lineOffset=Math.max(k,_),f+=N,d=Math.max(N,d),++v;}else f+=a,++v;}var K,G=f- -17,Z=Cu(o),X=Z.horizontalAlign,J=Z.verticalAlign;(function(t,e,r,n,i,a,o,s,u){var l,p=(e-r)*i;l=a!==o?-s*n- -17:(-n*u+.5)*o;for(var c=0,h=t;c<h.length;c+=1)for(var f=0,y=h[c].positionedGlyphs;f<y.length;f+=1){var d=y[f];d.x+=p,d.y+=l;}})(t.positionedLines,m,X,J,y,d,a,G,i.length),t.top+=-J*G,t.bottom=t.top+G,t.left+=-X*y,t.right=t.left+y;}(E,e,r,n,m,o,s,u,c,l,h,d),!function(t){for(var e=0,r=t;e<r.length;e+=1)if(0!==r[e].positionedGlyphs.length)return !1;return !0}(M)&&E}xu.fromFeature=function(t,e){for(var r=new xu,n=0;n<t.sections.length;n++){var i=t.sections[n];i.image?r.addImageSection(i):r.addTextSection(i,e);}return r},xu.prototype.length=function(){return this.text.length},xu.prototype.getSection=function(t){return this.sections[this.sectionIndex[t]]},xu.prototype.getSectionIndex=function(t){return this.sectionIndex[t]},xu.prototype.getCharCode=function(t){return this.text.charCodeAt(t)},xu.prototype.verticalizePunctuation=function(){this.text=function(t){for(var e="",r=0;r<t.length;r++){var n=t.charCodeAt(r+1)||null,i=t.charCodeAt(r-1)||null;e+=n&&Zn(n)&&!Ns[t[r+1]]||i&&Zn(i)&&!Ns[t[r-1]]||!Ns[t[r]]?t[r]:Ns[t[r]];}return e}(this.text);},xu.prototype.trim=function(){for(var t=0,e=0;e<this.text.length&&wu[this.text.charCodeAt(e)];e++)t++;for(var r=this.text.length,n=this.text.length-1;n>=0&&n>=t&&wu[this.text.charCodeAt(n)];n--)r--;this.text=this.text.substring(t,r),this.sectionIndex=this.sectionIndex.slice(t,r);},xu.prototype.substring=function(t,e){var r=new xu;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r},xu.prototype.toString=function(){return this.text},xu.prototype.getMaxScale=function(){var t=this;return this.sectionIndex.reduce((function(e,r){return Math.max(e,t.sections[r].scale)}),0)},xu.prototype.addTextSection=function(t,e){this.text+=t.text,this.sections.push(gu.forText(t.scale,t.fontStack||e));for(var r=this.sections.length-1,n=0;n<t.text.length;++n)this.sectionIndex.push(r);},xu.prototype.addImageSection=function(t){var e=t.image?t.image.name:"";if(0!==e.length){var r=this.getNextImageSectionCharCode();r?(this.text+=String.fromCharCode(r),this.sections.push(gu.forImage(e)),this.sectionIndex.push(this.sections.length-1)):_("Reached maximum number of images 6401");}else _("Can't add FormattedSection with an empty image.");},xu.prototype.getNextImageSectionCharCode=function(){return this.imageSectionID?this.imageSectionID>=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)};var wu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},_u={};function Au(t,e,r,n,i,a){if(e.imageName){var o=n[e.imageName];return o?o.displaySize[0]*e.scale*24/a+i:0}var s=r[e.fontStack],u=s&&s[t];return u?u.metrics.advance*e.scale+i:0}function Su(t,e,r,n){var i=Math.pow(t-e,2);return n?t<e?i/2:2*i:i+Math.abs(r)*r}function ku(t,e,r){var n=0;return 10===t&&(n-=1e4),r&&(n+=150),40!==t&&65288!==t||(n+=50),41!==e&&65289!==e||(n+=50),n}function Iu(t,e,r,n,i,a){for(var o=null,s=Su(e,r,i,a),u=0,l=n;u<l.length;u+=1){var p=l[u],c=Su(e-p.x,r,i,a)+p.badness;c<=s&&(o=p,s=c);}return {index:t,x:e,priorBreak:o,badness:s}}function zu(t,e,r,n,i,a,o){if("point"!==a)return [];if(!t)return [];for(var s,u=[],l=function(t,e,r,n,i,a){for(var o=0,s=0;s<t.length();s++){var u=t.getSection(s);o+=Au(t.getCharCode(s),u,n,i,e,a);}return o/Math.max(1,Math.ceil(o/r))}(t,e,r,n,i,o),p=t.text.indexOf("")>=0,c=0,h=0;h<t.length();h++){var f=t.getSection(h),y=t.getCharCode(h);if(wu[y]||(c+=Au(y,f,n,i,e,o)),h<t.length()-1){var d=!((s=y)<11904||!(Nn["Bopomofo Extended"](s)||Nn.Bopomofo(s)||Nn["CJK Compatibility Forms"](s)||Nn["CJK Compatibility Ideographs"](s)||Nn["CJK Compatibility"](s)||Nn["CJK Radicals Supplement"](s)||Nn["CJK Strokes"](s)||Nn["CJK Symbols and Punctuation"](s)||Nn["CJK Unified Ideographs Extension A"](s)||Nn["CJK Unified Ideographs"](s)||Nn["Enclosed CJK Letters and Months"](s)||Nn["Halfwidth and Fullwidth Forms"](s)||Nn.Hiragana(s)||Nn["Ideographic Description Characters"](s)||Nn["Kangxi Radicals"](s)||Nn["Katakana Phonetic Extensions"](s)||Nn.Katakana(s)||Nn["Vertical Forms"](s)||Nn["Yi Radicals"](s)||Nn["Yi Syllables"](s)));(_u[y]||d||f.imageName)&&u.push(Iu(h+1,c,l,u,ku(y,t.getCharCode(h+1),d&&p),!1));}}return function t(e){return e?t(e.priorBreak).concat(e.index):[]}(Iu(t.length(),c,l,u,0,!0))}function Cu(t){var e=.5,r=.5;switch(t){case"right":case"top-right":case"bottom-right":e=1;break;case"left":case"top-left":case"bottom-left":e=0;}switch(t){case"bottom":case"bottom-right":case"bottom-left":r=1;break;case"top":case"top-right":case"top-left":r=0;}return {horizontalAlign:e,verticalAlign:r}}function Mu(t,e,r,n,i){if(n||i)for(var a=t[r],o=(t[r].x+a.metrics.advance*a.scale)*n,s=e;s<=r;s++)t[s].x-=o,t[s].y+=i;}function Eu(t,e,r,n,i,a){var o,s=t.image;if(s.content){var u=s.content,l=s.pixelRatio||1;o=[u[0]/l,u[1]/l,s.displaySize[0]-u[2]/l,s.displaySize[1]-u[3]/l];}var p,c,h,f,y=e.left*a,d=e.right*a;"width"===r||"both"===r?(f=i[0]+y-n[3],c=i[0]+d+n[1]):c=(f=i[0]+(y+d-s.displaySize[0])/2)+s.displaySize[0];var m=e.top*a,v=e.bottom*a;return "height"===r||"both"===r?(p=i[1]+m-n[0],h=i[1]+v+n[2]):h=(p=i[1]+(m+v-s.displaySize[1])/2)+s.displaySize[1],{image:s,top:p,right:c,bottom:h,left:f,collisionPadding:o}}_u[10]=!0,_u[32]=!0,_u[38]=!0,_u[40]=!0,_u[41]=!0,_u[43]=!0,_u[45]=!0,_u[47]=!0,_u[173]=!0,_u[183]=!0,_u[8203]=!0,_u[8208]=!0,_u[8211]=!0,_u[8231]=!0;var Tu=function(t){function e(e,r,n,i){t.call(this,e,r),this.angle=n,void 0!==i&&(this.segment=i);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.clone=function(){return new e(this.x,this.y,this.angle,this.segment)},e}(i);function Pu(t,e){var r=e.expression;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new ai(t+1))};if("source"===r.kind)return {kind:"source"};for(var n=r.zoomStops,i=r.interpolationType,a=0;a<n.length&&n[a]<=t;)a++;for(var o=a=Math.max(0,a-1);o<n.length&&n[o]<t+1;)o++;o=Math.min(n.length-1,o);var s=n[a],u=n[o];return "composite"===r.kind?{kind:"composite",minZoom:s,maxZoom:u,interpolationType:i}:{kind:"camera",minZoom:s,maxZoom:u,minSize:r.evaluate(new ai(s)),maxSize:r.evaluate(new ai(u)),interpolationType:i}}function Bu(t,e,r){var n=e.uSize,i=r.lowerSize;return "source"===t.kind?i/128:"composite"===t.kind?qe(i/128,r.upperSize/128,e.uSizeT):n}function Vu(t,e){var r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){var i=t.interpolationType,a=i?l(nr.interpolationFactor(i,e,t.minZoom,t.maxZoom),0,1):0;"camera"===t.kind?n=qe(t.minSize,t.maxSize,a):r=a;}return {uSizeT:r,uSize:n}}Dn("Anchor",Tu);var Fu=Object.freeze({__proto__:null,getSizeData:Pu,evaluateSizeForFeature:Bu,evaluateSizeForZoom:Vu,SIZE_PACK_FACTOR:128});function Du(t,e,r,n,i){if(void 0===e.segment)return !0;for(var a=e,o=e.segment+1,s=0;s>-r/2;){if(--o<0)return !1;s-=t[o].dist(a),a=t[o];}s+=t[o].dist(t[o+1]),o++;for(var u=[],l=0;s<r/2;){var p=t[o],c=t[o+1];if(!c)return !1;var h=t[o-1].angleTo(p)-p.angleTo(c);for(h=Math.abs((h+3*Math.PI)%(2*Math.PI)-Math.PI),u.push({distance:s,angleDelta:h}),l+=h;s-u[0].distance>n;)l-=u.shift().angleDelta;if(l>i)return !1;o++,s+=p.dist(c);}return !0}function Lu(t){for(var e=0,r=0;r<t.length-1;r++)e+=t[r].dist(t[r+1]);return e}function Ru(t,e,r){return t?.6*e*r:0}function Ou(t,e){return Math.max(t?t.right-t.left:0,e?e.right-e.left:0)}function Uu(t,e,r,n,i,a){for(var o=Ru(r,i,a),s=Ou(r,n)*a,u=0,l=Lu(t)/2,p=0;p<t.length-1;p++){var c=t[p],h=t[p+1],f=c.dist(h);if(u+f>l){var y=(l-u)/f,d=qe(c.x,h.x,y),m=qe(c.y,h.y,y),v=new Tu(d,m,h.angleTo(c),p);return v._round(),!o||Du(t,v,s,o,e)?v:void 0}u+=f;}}function ju(t,e,r,n,i,a,o,s,u){var l=Ru(n,a,o),p=Ou(n,i),c=p*o,h=0===t[0].x||t[0].x===u||0===t[0].y||t[0].y===u;return e-c<e/4&&(e=c+e/4),function t(e,r,n,i,a,o,s,u,l){for(var p=o/2,c=Lu(e),h=0,f=r-n,y=[],d=0;d<e.length-1;d++){for(var m=e[d],v=e[d+1],g=m.dist(v),x=v.angleTo(m);f+n<h+g;){var b=((f+=n)-h)/g,w=qe(m.x,v.x,b),_=qe(m.y,v.y,b);if(w>=0&&w<l&&_>=0&&_<l&&f-p>=0&&f+p<=c){var A=new Tu(w,_,x,d);A._round(),i&&!Du(e,A,o,i,a)||y.push(A);}}h+=g;}return u||y.length||s||(y=t(e,h/2,n,i,a,o,s,!0,l)),y}(t,h?e/2*s%e:(p/2+2*a)*o*s%e,e,l,r,c,h,!1,u)}function qu(t,e,r,n,a){for(var o=[],s=0;s<t.length;s++)for(var u=t[s],l=void 0,p=0;p<u.length-1;p++){var c=u[p],h=u[p+1];c.x<e&&h.x<e||(c.x<e?c=new i(e,c.y+(e-c.x)/(h.x-c.x)*(h.y-c.y))._round():h.x<e&&(h=new i(e,c.y+(e-c.x)/(h.x-c.x)*(h.y-c.y))._round()),c.y<r&&h.y<r||(c.y<r?c=new i(c.x+(r-c.y)/(h.y-c.y)*(h.x-c.x),r)._round():h.y<r&&(h=new i(c.x+(r-c.y)/(h.y-c.y)*(h.x-c.x),r)._round()),c.x>=n&&h.x>=n||(c.x>=n?c=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round():h.x>=n&&(h=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round()),c.y>=a&&h.y>=a||(c.y>=a?c=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round():h.y>=a&&(h=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round()),l&&c.equals(l[l.length-1])||o.push(l=[c]),l.push(h)))));}return o}function Nu(t,e,r,n){var a=[],o=t.image,s=o.pixelRatio,u=o.paddedRect.w-2,l=o.paddedRect.h-2,p=t.right-t.left,c=t.bottom-t.top,h=o.stretchX||[[0,u]],f=o.stretchY||[[0,l]],y=function(t,e){return t+e[1]-e[0]},d=h.reduce(y,0),m=f.reduce(y,0),v=u-d,g=l-m,x=0,b=d,w=0,_=m,A=0,S=v,k=0,I=g;if(o.content&&n){var z=o.content;x=Ku(h,0,z[0]),w=Ku(f,0,z[1]),b=Ku(h,z[0],z[2]),_=Ku(f,z[1],z[3]),A=z[0]-x,k=z[1]-w,S=z[2]-z[0]-b,I=z[3]-z[1]-_;}var C=function(n,a,u,l){var h=Zu(n.stretch-x,b,p,t.left),f=Xu(n.fixed-A,S,n.stretch,d),y=Zu(a.stretch-w,_,c,t.top),v=Xu(a.fixed-k,I,a.stretch,m),g=Zu(u.stretch-x,b,p,t.left),z=Xu(u.fixed-A,S,u.stretch,d),C=Zu(l.stretch-w,_,c,t.top),M=Xu(l.fixed-k,I,l.stretch,m),E=new i(h,y),T=new i(g,y),P=new i(g,C),B=new i(h,C),V=new i(f/s,v/s),F=new i(z/s,M/s),D=e*Math.PI/180;if(D){var L=Math.sin(D),R=Math.cos(D),O=[R,-L,L,R];E._matMult(O),T._matMult(O),B._matMult(O),P._matMult(O);}var U=n.stretch+n.fixed,j=a.stretch+a.fixed;return {tl:E,tr:T,bl:B,br:P,tex:{x:o.paddedRect.x+1+U,y:o.paddedRect.y+1+j,w:u.stretch+u.fixed-U,h:l.stretch+l.fixed-j},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:V,pixelOffsetBR:F,minFontScaleX:S/s/p,minFontScaleY:I/s/c,isSDF:r}};if(n&&(o.stretchX||o.stretchY))for(var M=Gu(h,v,d),E=Gu(f,g,m),T=0;T<M.length-1;T++)for(var P=M[T],B=M[T+1],V=0;V<E.length-1;V++)a.push(C(P,E[V],B,E[V+1]));else a.push(C({fixed:0,stretch:-1},{fixed:0,stretch:-1},{fixed:0,stretch:u+1},{fixed:0,stretch:l+1}));return a}function Ku(t,e,r){for(var n=0,i=0,a=t;i<a.length;i+=1){var o=a[i];n+=Math.max(e,Math.min(r,o[1]))-Math.max(e,Math.min(r,o[0]));}return n}function Gu(t,e,r){for(var n=[{fixed:-1,stretch:0}],i=0,a=t;i<a.length;i+=1){var o=a[i],s=o[0],u=o[1],l=n[n.length-1];n.push({fixed:s-l.stretch,stretch:l.stretch}),n.push({fixed:s-l.stretch,stretch:l.stretch+(u-s)});}return n.push({fixed:e+1,stretch:r}),n}function Zu(t,e,r,n){return t/e*r+n}function Xu(t,e,r,n){return t-e*r/n}var Ju=function(t,e,r,n,a,o,s,u,l,p){if(this.boxStartIndex=t.length,l){var c=o.top,h=o.bottom,f=o.collisionPadding;f&&(c-=f[1],h+=f[3]);var y=h-c;y>0&&(y=Math.max(10,y),this.circleDiameter=y);}else {var d=o.top*s-u,m=o.bottom*s+u,v=o.left*s-u,g=o.right*s+u,x=o.collisionPadding;if(x&&(v-=x[0]*s,d-=x[1]*s,g+=x[2]*s,m+=x[3]*s),p){var b=new i(v,d),w=new i(g,d),_=new i(v,m),A=new i(g,m),S=p*Math.PI/180;b._rotate(S),w._rotate(S),_._rotate(S),A._rotate(S),v=Math.min(b.x,w.x,_.x,A.x),g=Math.max(b.x,w.x,_.x,A.x),d=Math.min(b.y,w.y,_.y,A.y),m=Math.max(b.y,w.y,_.y,A.y);}t.emplaceBack(e.x,e.y,v,d,g,m,r,n,a);}this.boxEndIndex=t.length;},Hu=function(t,e){if(void 0===t&&(t=[]),void 0===e&&(e=Yu),this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r);};function Yu(t,e){return t<e?-1:t>e?1:0}function $u(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var n=1/0,a=1/0,o=-1/0,s=-1/0,u=t[0],l=0;l<u.length;l++){var p=u[l];(!l||p.x<n)&&(n=p.x),(!l||p.y<a)&&(a=p.y),(!l||p.x>o)&&(o=p.x),(!l||p.y>s)&&(s=p.y);}var c=Math.min(o-n,s-a),h=c/2,f=new Hu([],Wu);if(0===c)return new i(n,a);for(var y=n;y<o;y+=c)for(var d=a;d<s;d+=c)f.push(new Qu(y+h,d+h,h,t));for(var m=function(t){for(var e=0,r=0,n=0,i=t[0],a=0,o=i.length,s=o-1;a<o;s=a++){var u=i[a],l=i[s],p=u.x*l.y-l.x*u.y;r+=(u.x+l.x)*p,n+=(u.y+l.y)*p,e+=3*p;}return new Qu(r/e,n/e,0,t)}(t),v=f.length;f.length;){var g=f.pop();(g.d>m.d||!m.d)&&(m=g,r&&console.log("found best %d after %d probes",Math.round(1e4*g.d)/1e4,v)),g.max-m.d<=e||(f.push(new Qu(g.p.x-(h=g.h/2),g.p.y-h,h,t)),f.push(new Qu(g.p.x+h,g.p.y-h,h,t)),f.push(new Qu(g.p.x-h,g.p.y+h,h,t)),f.push(new Qu(g.p.x+h,g.p.y+h,h,t)),v+=4);}return r&&(console.log("num probes: "+v),console.log("best distance: "+m.d)),m.p}function Wu(t,e){return e.max-t.max}function Qu(t,e,r,n){this.p=new i(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;i<e.length;i++)for(var a=e[i],o=0,s=a.length,u=s-1;o<s;u=o++){var l=a[o],p=a[u];l.y>t.y!=p.y>t.y&&t.x<(p.x-l.x)*(t.y-l.y)/(p.y-l.y)+l.x&&(r=!r),n=Math.min(n,Xa(t,l,p));}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}Hu.prototype.push=function(t){this.data.push(t),this.length++,this._up(this.length-1);},Hu.prototype.pop=function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}},Hu.prototype.peek=function(){return this.data[0]},Hu.prototype._up=function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i;}e[t]=n;},Hu.prototype._down=function(t){for(var e=this.data,r=this.compare,n=this.length>>1,i=e[t];t<n;){var a=1+(t<<1),o=e[a],s=a+1;if(s<this.length&&r(e[s],o)<0&&(a=s,o=e[s]),r(o,i)>=0)break;e[t]=o,t=a;}e[t]=i;};var tl=Number.POSITIVE_INFINITY;function el(t,e){return e[1]!==tl?function(t,e,r){var n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-7;break;case"bottom-right":case"bottom-left":case"bottom":i=7-r;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){var r=0,n=0;e<0&&(e=0);var i=e/Math.sqrt(2);switch(t){case"top-right":case"top-left":n=i-7;break;case"bottom-right":case"bottom-left":n=7-i;break;case"bottom":n=7-e;break;case"top":n=e-7;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function rl(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}function nl(t,e,r,n,a,o,s,u,l,p,c,h,f,y,d){var m=function(t,e,r,n,a,o,s,u){for(var l=n.layout.get("text-rotate").evaluate(o,{})*Math.PI/180,p=[],c=0,h=e.positionedLines;c<h.length;c+=1)for(var f=h[c],y=0,d=f.positionedGlyphs;y<d.length;y+=1){var m=d[y];if(m.rect){var v=m.rect||{},g=4,x=!0,b=1,w=0,_=(a||u)&&m.vertical,A=m.metrics.advance*m.scale/2;if(u&&e.verticalizable&&(w=f.lineOffset/2-(m.imageName?-(24-m.metrics.width*m.scale)/2:24*(m.scale-1))),m.imageName){var S=s[m.imageName];x=S.sdf,g=1/(b=S.pixelRatio);}var k=a?[m.x+A,m.y]:[0,0],I=a?[0,0]:[m.x+A+r[0],m.y+r[1]-w],z=[0,0];_&&(z=I,I=[0,0]);var C=(m.metrics.left-g)*m.scale-A+I[0],M=(-m.metrics.top-g)*m.scale+I[1],E=C+v.w*m.scale/b,T=M+v.h*m.scale/b,P=new i(C,M),B=new i(E,M),V=new i(C,T),F=new i(E,T);if(_){var D=new i(-A,A- -17),L=-Math.PI/2,R=12-A,O=new i(22-R,-(m.imageName?R:0)),U=new(Function.prototype.bind.apply(i,[null].concat(z)));P._rotateAround(L,D)._add(O)._add(U),B._rotateAround(L,D)._add(O)._add(U),V._rotateAround(L,D)._add(O)._add(U),F._rotateAround(L,D)._add(O)._add(U);}if(l){var j=Math.sin(l),q=Math.cos(l),N=[q,-j,j,q];P._matMult(N),B._matMult(N),V._matMult(N),F._matMult(N);}var K=new i(0,0),G=new i(0,0);p.push({tl:P,tr:B,bl:V,br:F,tex:v,writingMode:e.writingMode,glyphOffset:k,sectionIndex:m.sectionIndex,isSDF:x,pixelOffsetTL:K,pixelOffsetBR:G,minFontScaleX:0,minFontScaleY:0});}}return p}(0,r,u,a,o,s,n,t.allowVerticalPlacement),v=t.textSizeData,g=null;"source"===v.kind?(g=[128*a.layout.get("text-size").evaluate(s,{})])[0]>32640&&_(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'):"composite"===v.kind&&((g=[128*y.compositeTextSizes[0].evaluate(s,{},d),128*y.compositeTextSizes[1].evaluate(s,{},d)])[0]>32640||g[1]>32640)&&_(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'),t.addSymbols(t.text,m,g,u,o,s,p,e,l.lineStartIndex,l.lineLength,f,d);for(var x=0,b=c;x<b.length;x+=1)h[b[x]]=t.text.placedSymbolArray.length-1;return 4*m.length}function il(t){for(var e in t)return t[e];return null}function al(t,e,r,n){var i=t.compareText;if(e in i){for(var a=i[e],o=a.length-1;o>=0;o--)if(n.dist(a[o])<r)return !0}else i[e]=[];return i[e].push(n),!1}var ol=vs.VectorTileFeature.types,sl=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}];function ul(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=s?Math.min(32640,Math.round(s[0])):0,y=s?Math.min(32640,Math.round(s[1])):0;t.emplaceBack(e,r,Math.round(32*n),Math.round(32*i),a,o,(f<<1)+(u?1:0),y,16*l,16*p,256*c,256*h);}function ll(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r);}function pl(t){for(var e=0,r=t.sections;e<r.length;e+=1)if(Hn(r[e].text))return !0;return !1}var cl=function(t){this.layoutVertexArray=new Ti,this.indexArray=new Ri,this.programConfigurations=t,this.segments=new aa,this.dynamicLayoutVertexArray=new Pi,this.opacityVertexArray=new Bi,this.placedSymbolArray=new $i;};cl.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length&&0===this.indexArray.length&&0===this.dynamicLayoutVertexArray.length&&0===this.opacityVertexArray.length},cl.prototype.upload=function(t,e,r,n){this.isEmpty()||(r&&(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Ls.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,Rs.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,sl,!0),this.opacityVertexBuffer.itemSize=1),(r||n)&&this.programConfigurations.upload(t));},cl.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy());},Dn("SymbolBuffers",cl);var hl=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new aa,this.collisionVertexArray=new Li;};hl.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,Os.members,!0);},hl.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy());},Dn("CollisionBuffers",hl);var fl=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=no([]),this.placementViewportMatrix=no([]);var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Pu(this.zoom,e["text-size"]),this.iconSizeData=Pu(this.zoom,e["icon-size"]);var r=this.layers[0].layout,n=r.get("symbol-sort-key"),i=r.get("symbol-z-order");this.sortFeaturesByKey="viewport-y"!==i&&void 0!==n.constantOr(1),this.sortFeaturesByY=("viewport-y"===i||"auto"===i&&!this.sortFeaturesByKey)&&(r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")),"point"===r.get("symbol-placement")&&(this.writingModes=r.get("text-writing-mode").map((function(t){return vu[t]}))),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id})),this.sourceID=t.sourceID;};fl.prototype.createArrays=function(){this.text=new cl(new Pa(this.layers,this.zoom,(function(t){return /^text/.test(t)}))),this.icon=new cl(new Pa(this.layers,this.zoom,(function(t){return /^icon/.test(t)}))),this.glyphOffsetArray=new ta,this.lineVertexArray=new ea,this.symbolInstances=new Qi;},fl.prototype.calculateGlyphDependencies=function(t,e,r,n,i){for(var a=0;a<t.length;a++)if(e[t.charCodeAt(a)]=!0,(r||n)&&i){var o=Ns[t.charAt(a)];o&&(e[o.charCodeAt(0)]=!0);}},fl.prototype.populate=function(t,e,r){var n=this.layers[0],i=n.layout,a=i.get("text-font"),o=i.get("text-field"),s=i.get("icon-image"),u=("constant"!==o.value.kind||o.value.value instanceof ee&&!o.value.value.isEmpty()||o.value.value.toString().length>0)&&("constant"!==a.value.kind||a.value.value.length>0),l="constant"!==s.value.kind||!!s.value.value||Object.keys(s.parameters).length>0,p=i.get("symbol-sort-key");if(this.features=[],u||l){for(var c=e.iconDependencies,h=e.glyphDependencies,f=e.availableImages,y=new ai(this.zoom),d=0,m=t;d<m.length;d+=1){var v=m[d],g=v.feature,x=v.id,b=v.index,w=v.sourceLayerIndex,_=n._featureFilter.needGeometry,A={type:g.type,id:x,properties:g.properties,geometry:_?La(g):[]};if(n._featureFilter.filter(y,A,r)){_||(A.geometry=La(g));var S=void 0;if(u){var k=n.getValueAndResolveTokens("text-field",A,r,f),I=ee.factory(k);pl(I)&&(this.hasRTLText=!0),(!this.hasRTLText||"unavailable"===ri()||this.hasRTLText&&ii.isParsed())&&(S=qs(I,n,A));}var z=void 0;if(l){var C=n.getValueAndResolveTokens("icon-image",A,r,f);z=C instanceof re?C:re.fromString(C);}if(S||z){var M=this.sortFeaturesByKey?p.evaluate(A,{},r):void 0,E={id:x,text:S,icon:z,index:b,sourceLayerIndex:w,geometry:La(g),properties:g.properties,type:ol[g.type],sortKey:M};if(this.features.push(E),z&&(c[z.name]=!0),S){var T=a.evaluate(A,{},r).join(","),P="map"===i.get("text-rotation-alignment")&&"point"!==i.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(vu.vertical)>=0;for(var B=0,V=S.sections;B<V.length;B+=1){var F=V[B];if(F.image)c[F.image.name]=!0;else {var D=Kn(S.toString()),L=F.fontStack||T,R=h[L]=h[L]||{};this.calculateGlyphDependencies(F.text,R,P,this.allowVerticalPlacement,D);}}}}}}"line"===i.get("symbol-placement")&&(this.features=function(t){var e={},r={},n=[],i=0;function a(e){n.push(t[e]),i++;}function o(t,e,i){var a=r[t];return delete r[t],r[e]=a,n[a].geometry[0].pop(),n[a].geometry[0]=n[a].geometry[0].concat(i[0]),a}function s(t,r,i){var a=e[r];return delete e[r],e[t]=a,n[a].geometry[0].shift(),n[a].geometry[0]=i[0].concat(n[a].geometry[0]),a}function u(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var l=0;l<t.length;l++){var p=t[l],c=p.geometry,h=p.text?p.text.toString():null;if(h){var f=u(h,c),y=u(h,c,!0);if(f in r&&y in e&&r[f]!==e[y]){var d=s(f,y,c),m=o(f,y,n[d].geometry);delete e[f],delete r[y],r[u(h,n[m].geometry,!0)]=m,n[d].geometry=null;}else f in r?o(f,y,c):y in e?s(f,y,c):(a(l),e[f]=i-1,r[y]=i-1);}else a(l);}return n.filter((function(t){return t.geometry}))}(this.features)),this.sortFeaturesByKey&&this.features.sort((function(t,e){return t.sortKey-e.sortKey}));}},fl.prototype.update=function(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r));},fl.prototype.isEmpty=function(){return 0===this.symbolInstances.length&&!this.hasRTLText},fl.prototype.uploadPending=function(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload},fl.prototype.upload=function(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;},fl.prototype.destroyDebugData=function(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();},fl.prototype.destroy=function(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();},fl.prototype.addToLineVertexArray=function(t,e){var r=this.lineVertexArray.length;if(void 0!==t.segment){for(var n=t.dist(e[t.segment+1]),i=t.dist(e[t.segment]),a={},o=t.segment+1;o<e.length;o++)a[o]={x:e[o].x,y:e[o].y,tileUnitDistanceFromAnchor:n},o<e.length-1&&(n+=e[o+1].dist(e[o]));for(var s=t.segment||0;s>=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var u=0;u<e.length;u++){var l=a[u];this.lineVertexArray.emplaceBack(l.x,l.y,l.tileUnitDistanceFromAnchor);}}return {lineStartIndex:r,lineLength:this.lineVertexArray.length-r}},fl.prototype.addSymbols=function(t,e,r,n,i,a,o,s,u,l,p,c){for(var h=t.indexArray,f=t.layoutVertexArray,y=t.segments.prepareSegment(4*e.length,f,h,a.sortKey),d=this.glyphOffsetArray.length,m=y.vertexLength,v=this.allowVerticalPlacement&&o===vu.vertical?Math.PI/2:0,g=a.text&&a.text.sections,x=0;x<e.length;x++){var b=e[x],w=b.tl,_=b.tr,A=b.bl,S=b.br,k=b.tex,I=b.pixelOffsetTL,z=b.pixelOffsetBR,C=b.minFontScaleX,M=b.minFontScaleY,E=b.glyphOffset,T=b.isSDF,P=b.sectionIndex,B=y.vertexLength,V=E[1];ul(f,s.x,s.y,w.x,V+w.y,k.x,k.y,r,T,I.x,I.y,C,M),ul(f,s.x,s.y,_.x,V+_.y,k.x+k.w,k.y,r,T,z.x,I.y,C,M),ul(f,s.x,s.y,A.x,V+A.y,k.x,k.y+k.h,r,T,I.x,z.y,C,M),ul(f,s.x,s.y,S.x,V+S.y,k.x+k.w,k.y+k.h,r,T,z.x,z.y,C,M),ll(t.dynamicLayoutVertexArray,s,v),h.emplaceBack(B,B+1,B+2),h.emplaceBack(B+1,B+2,B+3),y.vertexLength+=4,y.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(E[0]),x!==e.length-1&&P===e[x+1].sectionIndex||t.programConfigurations.populatePaintArrays(f.length,a,a.index,{},c,g&&g[P]);}t.placedSymbolArray.emplaceBack(s.x,s.y,d,this.glyphOffsetArray.length-d,m,u,l,s.segment,r?r[0]:0,r?r[1]:0,n[0],n[1],o,0,!1,0,p);},fl.prototype._addCollisionDebugVertex=function(t,e,r,n,i,a){return e.emplaceBack(0,0),t.emplaceBack(r.x,r.y,n,i,Math.round(a.x),Math.round(a.y))},fl.prototype.addCollisionDebugVertices=function(t,e,r,n,a,o,s){var u=a.segments.prepareSegment(4,a.layoutVertexArray,a.indexArray),l=u.vertexLength,p=a.layoutVertexArray,c=a.collisionVertexArray,h=s.anchorX,f=s.anchorY;this._addCollisionDebugVertex(p,c,o,h,f,new i(t,e)),this._addCollisionDebugVertex(p,c,o,h,f,new i(r,e)),this._addCollisionDebugVertex(p,c,o,h,f,new i(r,n)),this._addCollisionDebugVertex(p,c,o,h,f,new i(t,n)),u.vertexLength+=4;var y=a.indexArray;y.emplaceBack(l,l+1),y.emplaceBack(l+1,l+2),y.emplaceBack(l+2,l+3),y.emplaceBack(l+3,l),u.primitiveLength+=4;},fl.prototype.addDebugCollisionBoxes=function(t,e,r,n){for(var i=t;i<e;i++){var a=this.collisionBoxArray.get(i);this.addCollisionDebugVertices(a.x1,a.y1,a.x2,a.y2,n?this.textCollisionBox:this.iconCollisionBox,a.anchorPoint,r);}},fl.prototype.generateCollisionDebugBuffers=function(){this.hasDebugData()&&this.destroyDebugData(),this.textCollisionBox=new hl(Fi,Us.members,Ki),this.iconCollisionBox=new hl(Fi,Us.members,Ki);for(var t=0;t<this.symbolInstances.length;t++){var e=this.symbolInstances.get(t);this.addDebugCollisionBoxes(e.textBoxStartIndex,e.textBoxEndIndex,e,!0),this.addDebugCollisionBoxes(e.verticalTextBoxStartIndex,e.verticalTextBoxEndIndex,e,!0),this.addDebugCollisionBoxes(e.iconBoxStartIndex,e.iconBoxEndIndex,e,!1),this.addDebugCollisionBoxes(e.verticalIconBoxStartIndex,e.verticalIconBoxEndIndex,e,!1);}},fl.prototype._deserializeCollisionBoxesForSymbol=function(t,e,r,n,i,a,o,s,u){for(var l={},p=e;p<r;p++){var c=t.get(p);l.textBox={x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,anchorPointX:c.anchorPointX,anchorPointY:c.anchorPointY},l.textFeatureIndex=c.featureIndex;break}for(var h=n;h<i;h++){var f=t.get(h);l.verticalTextBox={x1:f.x1,y1:f.y1,x2:f.x2,y2:f.y2,anchorPointX:f.anchorPointX,anchorPointY:f.anchorPointY},l.verticalTextFeatureIndex=f.featureIndex;break}for(var y=a;y<o;y++){var d=t.get(y);l.iconBox={x1:d.x1,y1:d.y1,x2:d.x2,y2:d.y2,anchorPointX:d.anchorPointX,anchorPointY:d.anchorPointY},l.iconFeatureIndex=d.featureIndex;break}for(var m=s;m<u;m++){var v=t.get(m);l.verticalIconBox={x1:v.x1,y1:v.y1,x2:v.x2,y2:v.y2,anchorPointX:v.anchorPointX,anchorPointY:v.anchorPointY},l.verticalIconFeatureIndex=v.featureIndex;break}return l},fl.prototype.deserializeCollisionBoxes=function(t){this.collisionArrays=[];for(var e=0;e<this.symbolInstances.length;e++){var r=this.symbolInstances.get(e);this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(t,r.textBoxStartIndex,r.textBoxEndIndex,r.verticalTextBoxStartIndex,r.verticalTextBoxEndIndex,r.iconBoxStartIndex,r.iconBoxEndIndex,r.verticalIconBoxStartIndex,r.verticalIconBoxEndIndex));}},fl.prototype.hasTextData=function(){return this.text.segments.get().length>0},fl.prototype.hasIconData=function(){return this.icon.segments.get().length>0},fl.prototype.hasDebugData=function(){return this.textCollisionBox&&this.iconCollisionBox},fl.prototype.hasTextCollisionBoxData=function(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0},fl.prototype.hasIconCollisionBoxData=function(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0},fl.prototype.addIndicesForPlacedSymbol=function(t,e){for(var r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs,i=r.vertexStartIndex;i<n;i+=4)t.indexArray.emplaceBack(i,i+1,i+2),t.indexArray.emplaceBack(i+1,i+2,i+3);},fl.prototype.getSortedSymbolIndexes=function(t){if(this.sortedAngle===t&&void 0!==this.symbolInstanceIndexes)return this.symbolInstanceIndexes;for(var e=Math.sin(t),r=Math.cos(t),n=[],i=[],a=[],o=0;o<this.symbolInstances.length;++o){a.push(o);var s=this.symbolInstances.get(o);n.push(0|Math.round(e*s.anchorX+r*s.anchorY)),i.push(s.featureIndex);}return a.sort((function(t,e){return n[t]-n[e]||i[e]-i[t]})),a},fl.prototype.addToSortKeyRanges=function(t,e){var r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});},fl.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var r=0,n=this.symbolInstanceIndexes;r<n.length;r+=1){var i=this.symbolInstances.get(n[r]);this.featureSortOrder.push(i.featureIndex),[i.rightJustifiedTextSymbolIndex,i.centerJustifiedTextSymbolIndex,i.leftJustifiedTextSymbolIndex].forEach((function(t,r,n){t>=0&&n.indexOf(t)===r&&e.addIndicesForPlacedSymbol(e.text,t);})),i.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,i.verticalPlacedTextSymbolIndex),i.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.placedIconSymbolIndex),i.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}},Dn("SymbolBucket",fl,{omit:["layers","collisionBoxArray","features","compareText"]}),fl.MAX_GLYPHS=65535,fl.addDynamicAttributes=ll;var yl=new xi({"symbol-placement":new yi(zt.layout_symbol["symbol-placement"]),"symbol-spacing":new yi(zt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new yi(zt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new di(zt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new yi(zt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new yi(zt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new yi(zt.layout_symbol["icon-ignore-placement"]),"icon-optional":new yi(zt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new yi(zt.layout_symbol["icon-rotation-alignment"]),"icon-size":new di(zt.layout_symbol["icon-size"]),"icon-text-fit":new yi(zt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new yi(zt.layout_symbol["icon-text-fit-padding"]),"icon-image":new di(zt.layout_symbol["icon-image"]),"icon-rotate":new di(zt.layout_symbol["icon-rotate"]),"icon-padding":new yi(zt.layout_symbol["icon-padding"]),"icon-keep-upright":new yi(zt.layout_symbol["icon-keep-upright"]),"icon-offset":new di(zt.layout_symbol["icon-offset"]),"icon-anchor":new di(zt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new yi(zt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new yi(zt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new yi(zt.layout_symbol["text-rotation-alignment"]),"text-field":new di(zt.layout_symbol["text-field"]),"text-font":new di(zt.layout_symbol["text-font"]),"text-size":new di(zt.layout_symbol["text-size"]),"text-max-width":new di(zt.layout_symbol["text-max-width"]),"text-line-height":new yi(zt.layout_symbol["text-line-height"]),"text-letter-spacing":new di(zt.layout_symbol["text-letter-spacing"]),"text-justify":new di(zt.layout_symbol["text-justify"]),"text-radial-offset":new di(zt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new yi(zt.layout_symbol["text-variable-anchor"]),"text-anchor":new di(zt.layout_symbol["text-anchor"]),"text-max-angle":new yi(zt.layout_symbol["text-max-angle"]),"text-writing-mode":new yi(zt.layout_symbol["text-writing-mode"]),"text-rotate":new di(zt.layout_symbol["text-rotate"]),"text-padding":new yi(zt.layout_symbol["text-padding"]),"text-keep-upright":new yi(zt.layout_symbol["text-keep-upright"]),"text-transform":new di(zt.layout_symbol["text-transform"]),"text-offset":new di(zt.layout_symbol["text-offset"]),"text-allow-overlap":new yi(zt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new yi(zt.layout_symbol["text-ignore-placement"]),"text-optional":new yi(zt.layout_symbol["text-optional"])}),dl={paint:new xi({"icon-opacity":new di(zt.paint_symbol["icon-opacity"]),"icon-color":new di(zt.paint_symbol["icon-color"]),"icon-halo-color":new di(zt.paint_symbol["icon-halo-color"]),"icon-halo-width":new di(zt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new di(zt.paint_symbol["icon-halo-blur"]),"icon-translate":new yi(zt.paint_symbol["icon-translate"]),"icon-translate-anchor":new yi(zt.paint_symbol["icon-translate-anchor"]),"text-opacity":new di(zt.paint_symbol["text-opacity"]),"text-color":new di(zt.paint_symbol["text-color"],{runtimeType:Ot,getOverride:function(t){return t.textColor},hasOverride:function(t){return !!t.textColor}}),"text-halo-color":new di(zt.paint_symbol["text-halo-color"]),"text-halo-width":new di(zt.paint_symbol["text-halo-width"]),"text-halo-blur":new di(zt.paint_symbol["text-halo-blur"]),"text-translate":new yi(zt.paint_symbol["text-translate"]),"text-translate-anchor":new yi(zt.paint_symbol["text-translate-anchor"])}),layout:yl},ml=function(t){this.type=t.property.overrides?t.property.overrides.runtimeType:Ft,this.defaultValue=t;};ml.prototype.evaluate=function(t){if(t.formattedSection){var e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default},ml.prototype.eachChild=function(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);},ml.prototype.outputDefined=function(){return !1},ml.prototype.serialize=function(){return null},Dn("FormatSectionOverride",ml,{omit:["defaultValue"]});var vl=function(t){function e(e){t.call(this,e,dl);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.recalculate=function(e,r){if(t.prototype.recalculate.call(this,e,r),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){var n=this.layout.get("text-writing-mode");if(n){for(var i=[],a=0,o=n;a<o.length;a+=1){var s=o[a];i.indexOf(s)<0&&i.push(s);}this.layout._values["text-writing-mode"]=i;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();},e.prototype.getValueAndResolveTokens=function(t,e,r,n){var i=this.layout.get(t).evaluate(e,{},r,n),a=this._unevaluatedLayout._values[t];return a.isDataDriven()||Nr(a.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,(function(e,r){return r in t?String(t[r]):""}))}(e.properties,i)},e.prototype.createBucket=function(t){return new fl(t)},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return !1},e.prototype._setPaintOverrides=function(){for(var t=0,r=dl.paint.overridableProperties;t<r.length;t+=1){var n=r[t];if(e.hasPaintOverride(this.layout,n)){var i,a=this.paint.get(n),o=new ml(a),s=new qr(o,a.property.specification);i="constant"===a.value.kind||"source"===a.value.kind?new Gr("source",s):new Zr("composite",s,a.value.zoomStops,a.value._interpolationType),this.paint._values[n]=new hi(a.property,i,a.parameters);}}},e.prototype._handleOverridablePaintPropertyUpdate=function(t,r,n){return !(!this.layout||r.isDataDriven()||n.isDataDriven())&&e.hasPaintOverride(this.layout,t)},e.hasPaintOverride=function(t,e){var r=t.get("text-field"),n=dl.paint.properties[e],i=!1,a=function(t){for(var e=0,r=t;e<r.length;e+=1)if(n.overrides&&n.overrides.hasOverride(r[e]))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof ee)a(r.value.value.sections);else if("source"===r.value.kind){var o=function(t){i||(t instanceof se&&ae(t.value)===Nt?a(t.value.sections):t instanceof ce?a(t.sections):t.eachChild(o));},s=r.value;s._styleExpression&&o(s._styleExpression.expression);}return i},e}(bi),gl={paint:new xi({"background-color":new yi(zt.paint_background["background-color"]),"background-pattern":new vi(zt.paint_background["background-pattern"]),"background-opacity":new yi(zt.paint_background["background-opacity"])})},xl=function(t){function e(e){t.call(this,e,gl);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(bi),bl={paint:new xi({"raster-opacity":new yi(zt.paint_raster["raster-opacity"]),"raster-hue-rotate":new yi(zt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new yi(zt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new yi(zt.paint_raster["raster-brightness-max"]),"raster-saturation":new yi(zt.paint_raster["raster-saturation"]),"raster-contrast":new yi(zt.paint_raster["raster-contrast"]),"raster-resampling":new yi(zt.paint_raster["raster-resampling"]),"raster-fade-duration":new yi(zt.paint_raster["raster-fade-duration"])})},wl=function(t){function e(e){t.call(this,e,bl);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(bi),_l=function(t){function e(e){t.call(this,e,{}),this.implementation=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.is3D=function(){return "3d"===this.implementation.renderingMode},e.prototype.hasOffscreenPass=function(){return void 0!==this.implementation.prerender},e.prototype.recalculate=function(){},e.prototype.updateTransitions=function(){},e.prototype.hasTransition=function(){},e.prototype.serialize=function(){},e.prototype.onAdd=function(t){this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},e.prototype.onRemove=function(t){this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},e}(bi),Al={circle:uo,heatmap:xo,hillshade:wo,fill:ss,"fill-extrusion":Ss,line:Fs,symbol:vl,background:xl,raster:wl},Sl=o.HTMLImageElement,kl=o.HTMLCanvasElement,Il=o.HTMLVideoElement,zl=o.ImageData,Cl=o.ImageBitmap,Ml=function(t,e,r,n){this.context=t,this.format=r,this.texture=t.gl.createTexture(),this.update(e,n);};Ml.prototype.update=function(t,e,r){var n=t.width,i=t.height,a=!(this.size&&this.size[0]===n&&this.size[1]===i||r),o=this.context,s=o.gl;if(this.useMipmap=Boolean(e&&e.useMipmap),s.bindTexture(s.TEXTURE_2D,this.texture),o.pixelStoreUnpackFlipY.set(!1),o.pixelStoreUnpack.set(1),o.pixelStoreUnpackPremultiplyAlpha.set(this.format===s.RGBA&&(!e||!1!==e.premultiply)),a)this.size=[n,i],t instanceof Sl||t instanceof kl||t instanceof Il||t instanceof zl||Cl&&t instanceof Cl?s.texImage2D(s.TEXTURE_2D,0,this.format,this.format,s.UNSIGNED_BYTE,t):s.texImage2D(s.TEXTURE_2D,0,this.format,n,i,0,this.format,s.UNSIGNED_BYTE,t.data);else {var u=r||{x:0,y:0},l=u.x,p=u.y;t instanceof Sl||t instanceof kl||t instanceof Il||t instanceof zl||Cl&&t instanceof Cl?s.texSubImage2D(s.TEXTURE_2D,0,l,p,s.RGBA,s.UNSIGNED_BYTE,t):s.texSubImage2D(s.TEXTURE_2D,0,l,p,n,i,s.RGBA,s.UNSIGNED_BYTE,t.data);}this.useMipmap&&this.isSizePowerOfTwo()&&s.generateMipmap(s.TEXTURE_2D);},Ml.prototype.bind=function(t,e,r){var n=this.context.gl;n.bindTexture(n.TEXTURE_2D,this.texture),r!==n.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(r=n.LINEAR),t!==this.filter&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,t),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,r||t),this.filter=t),e!==this.wrap&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e),this.wrap=e);},Ml.prototype.isSizePowerOfTwo=function(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0},Ml.prototype.destroy=function(){this.context.gl.deleteTexture(this.texture),this.texture=null;};var El=function(t){var e=this;this._callback=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=function(){e._triggered=!1,e._callback();});};El.prototype.trigger=function(){var t=this;this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((function(){t._triggered=!1,t._callback();}),0));},El.prototype.remove=function(){delete this._channel,this._callback=function(){};};var Tl=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.tasks={},this.taskQueue=[],this.cancelCallbacks={},m(["receive","process"],this),this.invoker=new El(this.process),this.target.addEventListener("message",this.receive,!1),this.globalScope=k()?t:o;};function Pl(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}Tl.prototype.send=function(t,e,r,n,i){var a=this;void 0===i&&(i=!1);var o=Math.round(1e18*Math.random()).toString(36).substring(0,10);r&&(this.callbacks[o]=r);var s=C(this.globalScope)?void 0:[];return this.target.postMessage({id:o,type:t,hasCallback:!!r,targetMapId:n,mustQueue:i,sourceMapId:this.mapId,data:Un(e,s)},s),{cancel:function(){r&&delete a.callbacks[o],a.target.postMessage({id:o,type:"<cancel>",targetMapId:n,sourceMapId:a.mapId});}}},Tl.prototype.receive=function(t){var e=t.data,r=e.id;if(r&&(!e.targetMapId||this.mapId===e.targetMapId))if("<cancel>"===e.type){delete this.tasks[r];var n=this.cancelCallbacks[r];delete this.cancelCallbacks[r],n&&n();}else k()||e.mustQueue?(this.tasks[r]=e,this.taskQueue.push(r),this.invoker.trigger()):this.processTask(r,e);},Tl.prototype.process=function(){if(this.taskQueue.length){var t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length&&this.invoker.trigger(),e&&this.processTask(t,e);}},Tl.prototype.processTask=function(t,e){var r=this;if("<response>"===e.type){var n=this.callbacks[t];delete this.callbacks[t],n&&(e.error?n(jn(e.error)):n(null,jn(e.data)));}else {var i=!1,a=C(this.globalScope)?void 0:[],o=e.hasCallback?function(e,n){i=!0,delete r.cancelCallbacks[t],r.target.postMessage({id:t,type:"<response>",sourceMapId:r.mapId,error:e?Un(e):null,data:Un(n,a)},a);}:function(t){i=!0;},s=null,u=jn(e.data);if(this.parent[e.type])s=this.parent[e.type](e.sourceMapId,u,o);else if(this.parent.getWorkerSource){var l=e.type.split(".");s=this.parent.getWorkerSource(e.sourceMapId,l[0],u.source)[l[1]](u,o);}else o(new Error("Could not find function "+e.type));!i&&s&&s.cancel&&(this.cancelCallbacks[t]=s.cancel);}},Tl.prototype.remove=function(){this.invoker.remove(),this.target.removeEventListener("message",this.receive,!1);};var Bl=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));};Bl.prototype.setNorthEast=function(t){return this._ne=t instanceof Vl?new Vl(t.lng,t.lat):Vl.convert(t),this},Bl.prototype.setSouthWest=function(t){return this._sw=t instanceof Vl?new Vl(t.lng,t.lat):Vl.convert(t),this},Bl.prototype.extend=function(t){var e,r,n=this._sw,i=this._ne;if(t instanceof Vl)e=t,r=t;else {if(!(t instanceof Bl))return Array.isArray(t)?4===t.length||t.every(Array.isArray)?this.extend(Bl.convert(t)):this.extend(Vl.convert(t)):this;if(r=t._ne,!(e=t._sw)||!r)return this}return n||i?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),i.lng=Math.max(r.lng,i.lng),i.lat=Math.max(r.lat,i.lat)):(this._sw=new Vl(e.lng,e.lat),this._ne=new Vl(r.lng,r.lat)),this},Bl.prototype.getCenter=function(){return new Vl((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},Bl.prototype.getSouthWest=function(){return this._sw},Bl.prototype.getNorthEast=function(){return this._ne},Bl.prototype.getNorthWest=function(){return new Vl(this.getWest(),this.getNorth())},Bl.prototype.getSouthEast=function(){return new Vl(this.getEast(),this.getSouth())},Bl.prototype.getWest=function(){return this._sw.lng},Bl.prototype.getSouth=function(){return this._sw.lat},Bl.prototype.getEast=function(){return this._ne.lng},Bl.prototype.getNorth=function(){return this._ne.lat},Bl.prototype.toArray=function(){return [this._sw.toArray(),this._ne.toArray()]},Bl.prototype.toString=function(){return "LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},Bl.prototype.isEmpty=function(){return !(this._sw&&this._ne)},Bl.prototype.contains=function(t){var e=Vl.convert(t),r=e.lng,n=e.lat,i=this._sw.lng<=r&&r<=this._ne.lng;return this._sw.lng>this._ne.lng&&(i=this._sw.lng>=r&&r>=this._ne.lng),this._sw.lat<=n&&n<=this._ne.lat&&i},Bl.convert=function(t){return !t||t instanceof Bl?t:new Bl(t)};var Vl=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};Vl.prototype.wrap=function(){return new Vl(p(this.lng,-180,180),this.lat)},Vl.prototype.toArray=function(){return [this.lng,this.lat]},Vl.prototype.toString=function(){return "LngLat("+this.lng+", "+this.lat+")"},Vl.prototype.distanceTo=function(t){var e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return 6371008.8*Math.acos(Math.min(i,1))},Vl.prototype.toBounds=function(t){void 0===t&&(t=0);var e=360*t/40075017,r=e/Math.cos(Math.PI/180*this.lat);return new Bl(new Vl(this.lng-r,this.lat-e),new Vl(this.lng+r,this.lat+e))},Vl.convert=function(t){if(t instanceof Vl)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Vl(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Vl(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]")};var Fl=2*Math.PI*6371008.8;function Dl(t){return Fl*Math.cos(t*Math.PI/180)}function Ll(t){return (180+t)/360}function Rl(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Ol(t,e){return t/Dl(e)}function Ul(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}var jl=function(t,e,r){void 0===r&&(r=0),this.x=+t,this.y=+e,this.z=+r;};jl.fromLngLat=function(t,e){void 0===e&&(e=0);var r=Vl.convert(t);return new jl(Ll(r.lng),Rl(r.lat),Ol(e,r.lat))},jl.prototype.toLngLat=function(){return new Vl(360*this.x-180,Ul(this.y))},jl.prototype.toAltitude=function(){return this.z*Dl(Ul(this.y))},jl.prototype.meterInMercatorCoordinateUnits=function(){return 1/Fl*(t=Ul(this.y),1/Math.cos(t*Math.PI/180));var t;};var ql=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Gl(0,t,t,e,r);};ql.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},ql.prototype.url=function(t,e){var r,n,i,a,o,s=(n=this.y,i=this.z,a=Pl(256*(r=this.x),256*(n=Math.pow(2,i)-n-1),i),o=Pl(256*(r+1),256*(n+1),i),a[0]+","+a[1]+","+o[0]+","+o[1]),u=function(t,e,r){for(var n,i="",a=t;a>0;a--)i+=(e&(n=1<<a-1)?1:0)+(r&n?2:0);return i}(this.z,this.x,this.y);return t[(this.x+this.y)%t.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace("{z}",String(this.z)).replace("{x}",String(this.x)).replace("{y}",String("tms"===e?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",u).replace("{bbox-epsg-3857}",s)},ql.prototype.getTilePoint=function(t){var e=Math.pow(2,this.z);return new i(8192*(t.x*e-this.x),8192*(t.y*e-this.y))},ql.prototype.toString=function(){return this.z+"/"+this.x+"/"+this.y};var Nl=function(t,e){this.wrap=t,this.canonical=e,this.key=Gl(t,e.z,e.z,e.x,e.y);},Kl=function(t,e,r,n,i){this.overscaledZ=t,this.wrap=e,this.canonical=new ql(r,+n,+i),this.key=Gl(e,t,r,n,i);};function Gl(t,e,r,n,i){(t*=2)<0&&(t=-1*t-1);var a=1<<r;return (a*a*t+a*i+n).toString(36)+r.toString(36)+e.toString(36)}Kl.prototype.equals=function(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)},Kl.prototype.scaledTo=function(t){var e=this.canonical.z-t;return t>this.canonical.z?new Kl(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Kl(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},Kl.prototype.calculateScaledKey=function(t,e){var r=this.canonical.z-t;return t>this.canonical.z?Gl(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Gl(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)},Kl.prototype.isChildOf=function(t){if(t.wrap!==this.wrap)return !1;var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ<this.overscaledZ&&t.canonical.x===this.canonical.x>>e&&t.canonical.y===this.canonical.y>>e},Kl.prototype.children=function(t){if(this.overscaledZ>=t)return [new Kl(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new Kl(e,this.wrap,e,r,n),new Kl(e,this.wrap,e,r+1,n),new Kl(e,this.wrap,e,r,n+1),new Kl(e,this.wrap,e,r+1,n+1)]},Kl.prototype.isLessThan=function(t){return this.wrap<t.wrap||!(this.wrap>t.wrap)&&(this.overscaledZ<t.overscaledZ||!(this.overscaledZ>t.overscaledZ)&&(this.canonical.x<t.canonical.x||!(this.canonical.x>t.canonical.x)&&this.canonical.y<t.canonical.y))},Kl.prototype.wrapped=function(){return new Kl(this.overscaledZ,0,this.canonical.z,this.canonical.x,this.canonical.y)},Kl.prototype.unwrapTo=function(t){return new Kl(this.overscaledZ,t,this.canonical.z,this.canonical.x,this.canonical.y)},Kl.prototype.overscaleFactor=function(){return Math.pow(2,this.overscaledZ-this.canonical.z)},Kl.prototype.toUnwrapped=function(){return new Nl(this.wrap,this.canonical)},Kl.prototype.toString=function(){return this.overscaledZ+"/"+this.canonical.x+"/"+this.canonical.y},Kl.prototype.getTilePoint=function(t){return this.canonical.getTilePoint(new jl(t.x-this.wrap,t.y))},Dn("CanonicalTileID",ql),Dn("OverscaledTileID",Kl,{omit:["posMatrix"]});var Zl=function(t,e,r){if(this.uid=t,e.height!==e.width)throw new RangeError("DEM tiles must be square");if(r&&"mapbox"!==r&&"terrarium"!==r)return _('"'+r+'" is not a valid encoding type. Valid types include "mapbox" and "terrarium".');this.stride=e.height;var n=this.dim=e.height-2;this.data=new Uint32Array(e.data.buffer),this.encoding=r||"mapbox";for(var i=0;i<n;i++)this.data[this._idx(-1,i)]=this.data[this._idx(0,i)],this.data[this._idx(n,i)]=this.data[this._idx(n-1,i)],this.data[this._idx(i,-1)]=this.data[this._idx(i,0)],this.data[this._idx(i,n)]=this.data[this._idx(i,n-1)];this.data[this._idx(-1,-1)]=this.data[this._idx(0,0)],this.data[this._idx(n,-1)]=this.data[this._idx(n-1,0)],this.data[this._idx(-1,n)]=this.data[this._idx(0,n-1)],this.data[this._idx(n,n)]=this.data[this._idx(n-1,n-1)];};Zl.prototype.get=function(t,e){var r=new Uint8Array(this.data.buffer),n=4*this._idx(t,e);return ("terrarium"===this.encoding?this._unpackTerrarium:this._unpackMapbox)(r[n],r[n+1],r[n+2])},Zl.prototype.getUnpackVector=function(){return "terrarium"===this.encoding?[256,1,1/256,32768]:[6553.6,25.6,.1,1e4]},Zl.prototype._idx=function(t,e){if(t<-1||t>=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)},Zl.prototype._unpackMapbox=function(t,e,r){return (256*t*256+256*e+r)/10-1e4},Zl.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Zl.prototype.getPixels=function(){return new mo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))},Zl.prototype.backfillBorder=function(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");var n=e*this.dim,i=e*this.dim+this.dim,a=r*this.dim,o=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:a=o-1;break;case 1:o=a+1;}for(var s=-e*this.dim,u=-r*this.dim,l=a;l<o;l++)for(var p=n;p<i;p++)this.data[this._idx(p,l)]=t.data[this._idx(p+s,l+u)];},Dn("DEMData",Zl);var Xl=function(t){this._stringToNumber={},this._numberToString=[];for(var e=0;e<t.length;e++){var r=t[e];this._stringToNumber[r]=e,this._numberToString[e]=r;}};Xl.prototype.encode=function(t){return this._stringToNumber[t]},Xl.prototype.decode=function(t){return this._numberToString[t]};var Jl=function(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;},Hl={geometry:{configurable:!0}};Hl.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},Hl.geometry.set=function(t){this._geometry=t;},Jl.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(Jl.prototype,Hl);var Yl=function(){this.state={},this.stateChanges={},this.deletedStates={};};Yl.prototype.updateState=function(t,e,r){var n=String(e);if(this.stateChanges[t]=this.stateChanges[t]||{},this.stateChanges[t][n]=this.stateChanges[t][n]||{},c(this.stateChanges[t][n],r),null===this.deletedStates[t])for(var i in this.deletedStates[t]={},this.state[t])i!==n&&(this.deletedStates[t][i]=null);else if(this.deletedStates[t]&&null===this.deletedStates[t][n])for(var a in this.deletedStates[t][n]={},this.state[t][n])r[a]||(this.deletedStates[t][n][a]=null);else for(var o in r)this.deletedStates[t]&&this.deletedStates[t][n]&&null===this.deletedStates[t][n][o]&&delete this.deletedStates[t][n][o];},Yl.prototype.removeFeatureState=function(t,e,r){if(null!==this.deletedStates[t]){var n=String(e);if(this.deletedStates[t]=this.deletedStates[t]||{},r&&void 0!==e)null!==this.deletedStates[t][n]&&(this.deletedStates[t][n]=this.deletedStates[t][n]||{},this.deletedStates[t][n][r]=null);else if(void 0!==e)if(this.stateChanges[t]&&this.stateChanges[t][n])for(r in this.deletedStates[t][n]={},this.stateChanges[t][n])this.deletedStates[t][n][r]=null;else this.deletedStates[t][n]=null;else this.deletedStates[t]=null;}},Yl.prototype.getState=function(t,e){var r=String(e),n=c({},(this.state[t]||{})[r],(this.stateChanges[t]||{})[r]);if(null===this.deletedStates[t])return {};if(this.deletedStates[t]){var i=this.deletedStates[t][e];if(null===i)return {};for(var a in i)delete n[a];}return n},Yl.prototype.initializeTileState=function(t,e){t.setFeatureState(this.state,e);},Yl.prototype.coalesceChanges=function(t,e){var r={};for(var n in this.stateChanges){this.state[n]=this.state[n]||{};var i={};for(var a in this.stateChanges[n])this.state[n][a]||(this.state[n][a]={}),c(this.state[n][a],this.stateChanges[n][a]),i[a]=this.state[n][a];r[n]=i;}for(var o in this.deletedStates){this.state[o]=this.state[o]||{};var s={};if(null===this.deletedStates[o])for(var u in this.state[o])s[u]={},this.state[o][u]={};else for(var l in this.deletedStates[o]){if(null===this.deletedStates[o][l])this.state[o][l]={};else for(var p=0,h=Object.keys(this.deletedStates[o][l]);p<h.length;p+=1)delete this.state[o][l][h[p]];s[l]=this.state[o][l];}r[o]=r[o]||{},c(r[o],s);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(var f in t)t[f].setFeatureState(r,e);};var $l=function(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new Tn(8192,16,0),this.grid3D=new Tn(8192,16,0),this.featureIndexArray=new na,this.promoteId=e;};function Wl(t,e,r,n,i){return g(t,(function(t,a){var o=e instanceof fi?e.get(a):null;return o&&o.evaluate?o.evaluate(r,n,i):o}))}function Ql(t){for(var e=1/0,r=1/0,n=-1/0,i=-1/0,a=0,o=t;a<o.length;a+=1){var s=o[a];e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);}return {minX:e,minY:r,maxX:n,maxY:i}}function tp(t,e){return e-t}$l.prototype.insert=function(t,e,r,n,i,a){var o=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);for(var s=a?this.grid3D:this.grid,u=0;u<e.length;u++){for(var l=e[u],p=[1/0,1/0,-1/0,-1/0],c=0;c<l.length;c++){var h=l[c];p[0]=Math.min(p[0],h.x),p[1]=Math.min(p[1],h.y),p[2]=Math.max(p[2],h.x),p[3]=Math.max(p[3],h.y);}p[0]<8192&&p[1]<8192&&p[2]>=0&&p[3]>=0&&s.insert(o,p[0],p[1],p[2],p[3]);}},$l.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new vs.VectorTile(new Zs(this.rawTileData)).layers,this.sourceLayerCoder=new Xl(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},$l.prototype.query=function(t,e,r,n){var a=this;this.loadVTLayers();for(var o=t.params||{},s=8192/t.tileSize/t.scale,u=nn(o.filter),l=t.queryGeometry,p=t.queryPadding*s,c=Ql(l),h=this.grid.query(c.minX-p,c.minY-p,c.maxX+p,c.maxY+p),f=Ql(t.cameraQueryGeometry),y=this.grid3D.query(f.minX-p,f.minY-p,f.maxX+p,f.maxY+p,(function(e,r,n,a){return function(t,e,r,n,a){for(var o=0,s=t;o<s.length;o+=1){var u=s[o];if(e<=u.x&&r<=u.y&&n>=u.x&&a>=u.y)return !0}var l=[new i(e,r),new i(e,a),new i(n,a),new i(n,r)];if(t.length>2)for(var p=0,c=l;p<c.length;p+=1)if(Ha(t,c[p]))return !0;for(var h=0;h<t.length-1;h++)if(Ya(t[h],t[h+1],l))return !0;return !1}(t.cameraQueryGeometry,e-p,r-p,n+p,a+p)})),d=0,m=y;d<m.length;d+=1)h.push(m[d]);h.sort(tp);for(var v,g={},x=function(i){var p=h[i];if(p!==v){v=p;var c=a.featureIndexArray.get(p),f=null;a.loadMatchingFeature(g,c.bucketIndex,c.sourceLayerIndex,c.featureIndex,u,o.layers,o.availableImages,e,r,n,(function(e,r,n){return f||(f=La(e)),r.queryIntersectsFeature(l,e,n,f,a.z,t.transform,s,t.pixelPosMatrix)}));}},b=0;b<h.length;b++)x(b);return g},$l.prototype.loadMatchingFeature=function(t,e,r,n,i,a,o,s,u,l,p){var c=this.bucketLayerIDs[e];if(!a||function(t,e){for(var r=0;r<t.length;r++)if(e.indexOf(t[r])>=0)return !0;return !1}(a,c)){var h=this.sourceLayerCoder.decode(r),f=this.vtLayers[h].feature(n);if(i.filter(new ai(this.tileID.overscaledZ),f))for(var y=this.getId(f,h),d=0;d<c.length;d++){var m=c[d];if(!(a&&a.indexOf(m)<0)){var v=s[m];if(v){var g={};void 0!==y&&l&&(g=l.getState(v.sourceLayer||"_geojsonTileLayer",y));var x=u[m];x.paint=Wl(x.paint,v.paint,f,g,o),x.layout=Wl(x.layout,v.layout,f,g,o);var b=!p||p(f,v,g);if(b){var w=new Jl(f,this.z,this.x,this.y,y);w.layer=x;var _=t[m];void 0===_&&(_=t[m]=[]),_.push({featureIndex:n,feature:w,intersectionZ:b});}}}}}},$l.prototype.lookupSymbolFeatures=function(t,e,r,n,i,a,o,s){var u={};this.loadVTLayers();for(var l=nn(i),p=0,c=t;p<c.length;p+=1)this.loadMatchingFeature(u,r,n,c[p],l,a,o,s,e);return u},$l.prototype.hasLayer=function(t){for(var e=0,r=this.bucketLayerIDs;e<r.length;e+=1)for(var n=0,i=r[e];n<i.length;n+=1)if(t===i[n])return !0;return !1},$l.prototype.getId=function(t,e){var r=t.id;return this.promoteId&&"boolean"==typeof(r=t.properties["string"==typeof this.promoteId?this.promoteId:this.promoteId[e]])&&(r=Number(r)),r},Dn("FeatureIndex",$l,{omit:["rawTileData","sourceLayerCoder"]});var ep=function(t,e){this.tileID=t,this.uid=f(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.expiredRequestCount=0,this.state="loading";};ep.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<L.now()||this.fadeEndTime&&e<this.fadeEndTime||(this.fadeEndTime=e);},ep.prototype.wasRequested=function(){return "errored"===this.state||"loaded"===this.state||"reloading"===this.state},ep.prototype.loadVectorData=function(t,e,r){if(this.hasData()&&this.unloadVectorData(),this.state="loaded",t){for(var n in t.featureIndex&&(this.latestFeatureIndex=t.featureIndex,t.rawTileData?(this.latestRawTileData=t.rawTileData,this.latestFeatureIndex.rawTileData=t.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=t.collisionBoxArray,this.buckets=function(t,e){var r={};if(!e)return r;for(var n=function(){var t=a[i],n=t.layerIds.map((function(t){return e.getLayer(t)})).filter(Boolean);if(0!==n.length){t.layers=n,t.stateDependentLayerIds&&(t.stateDependentLayers=t.stateDependentLayerIds.map((function(t){return n.filter((function(e){return e.id===t}))[0]})));for(var o=0,s=n;o<s.length;o+=1)r[s[o].id]=t;}},i=0,a=t;i<a.length;i+=1)n();return r}(t.buckets,e.style),this.hasSymbolBuckets=!1,this.buckets){var i=this.buckets[n];if(i instanceof fl){if(this.hasSymbolBuckets=!0,!r)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(var a in this.buckets){var o=this.buckets[a];if(o instanceof fl&&o.hasRTLText){this.hasRTLText=!0,ii.isLoading()||ii.isLoaded()||"deferred"!==ri()||ni();break}}for(var s in this.queryPadding=0,this.buckets){var u=this.buckets[s];this.queryPadding=Math.max(this.queryPadding,e.style.getLayer(s).queryRadius(u));}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage);}else this.collisionBoxArray=new Hi;},ep.prototype.unloadVectorData=function(){for(var t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";},ep.prototype.getBucket=function(t){return this.buckets[t.id]},ep.prototype.upload=function(t){for(var e in this.buckets){var r=this.buckets[e];r.uploadPending()&&r.upload(t);}var n=t.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new Ml(t,this.imageAtlas.image,n.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new Ml(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null);},ep.prototype.prepare=function(t){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture);},ep.prototype.queryRenderedFeatures=function(t,e,r,n,i,a,o,s,u,l){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:n,cameraQueryGeometry:i,scale:a,tileSize:this.tileSize,pixelPosMatrix:l,transform:s,params:o,queryPadding:this.queryPadding*u},t,e,r):{}},ep.prototype.querySourceFeatures=function(t,e){var r=this.latestFeatureIndex;if(r&&r.rawTileData){var n=r.loadVTLayers(),i=e?e.sourceLayer:"",a=n._geojsonTileLayer||n[i];if(a)for(var o=nn(e&&e.filter),s=this.tileID.canonical,u=s.z,l=s.x,p=s.y,c={z:u,x:l,y:p},h=0;h<a.length;h++){var f=a.feature(h);if(o.filter(new ai(this.tileID.overscaledZ),f)){var y=r.getId(f,i),d=new Jl(f,u,l,p,y);d.tile=c,t.push(d);}}}},ep.prototype.hasData=function(){return "loaded"===this.state||"reloading"===this.state||"expired"===this.state},ep.prototype.patternsLoaded=function(){return this.imageAtlas&&!!Object.keys(this.imageAtlas.patternPositions).length},ep.prototype.setExpiryData=function(t){var e=this.expirationTime;if(t.cacheControl){var r=I(t.cacheControl);r["max-age"]&&(this.expirationTime=Date.now()+1e3*r["max-age"]);}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){var n=Date.now(),i=!1;if(this.expirationTime>n)i=!1;else if(e)if(this.expirationTime<e)i=!0;else {var a=this.expirationTime-e;a?this.expirationTime=n+Math.max(a,3e4):i=!0;}else i=!0;i?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0;}},ep.prototype.getExpiryTimeout=function(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-(new Date).getTime(),Math.pow(2,31)-1)},ep.prototype.setFeatureState=function(t,e){if(this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData&&0!==Object.keys(t).length){var r=this.latestFeatureIndex.loadVTLayers();for(var n in this.buckets)if(e.style.hasLayer(n)){var i=this.buckets[n],a=i.layers[0].sourceLayer||"_geojsonTileLayer",o=r[a],s=t[a];if(o&&s&&0!==Object.keys(s).length){i.update(s,o,this.imageAtlas&&this.imageAtlas.patternPositions||{});var u=e&&e.style&&e.style.getLayer(n);u&&(this.queryPadding=Math.max(this.queryPadding,u.queryRadius(i)));}}}},ep.prototype.holdingForFade=function(){return void 0!==this.symbolFadeHoldUntil},ep.prototype.symbolFadeFinished=function(){return !this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<L.now()},ep.prototype.clearFadeHold=function(){this.symbolFadeHoldUntil=void 0;},ep.prototype.setHoldDuration=function(t){this.symbolFadeHoldUntil=L.now()+t;},ep.prototype.setDependencies=function(t,e){for(var r={},n=0,i=e;n<i.length;n+=1)r[i[n]]=!0;this.dependencies[t]=r;},ep.prototype.hasDependency=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=this.dependencies[n[r]];if(i)for(var a=0,o=e;a<o.length;a+=1)if(i[o[a]])return !0}return !1};var rp=o.performance,np=function(t){this._marks={start:[t.url,"start"].join("#"),end:[t.url,"end"].join("#"),measure:t.url.toString()},rp.mark(this._marks.start);};np.prototype.finish=function(){rp.mark(this._marks.end);var t=rp.getEntriesByName(this._marks.measure);return 0===t.length&&(rp.measure(this._marks.measure,this._marks.start,this._marks.end),t=rp.getEntriesByName(this._marks.measure),rp.clearMarks(this._marks.start),rp.clearMarks(this._marks.end),rp.clearMeasures(this._marks.measure)),t},t.Actor=Tl,t.AlphaImage=yo,t.CanonicalTileID=ql,t.CollisionBoxArray=Hi,t.Color=Wt,t.DEMData=Zl,t.DataConstantProperty=yi,t.DictionaryCoder=Xl,t.EXTENT=8192,t.ErrorEvent=kt,t.EvaluationParameters=ai,t.Event=St,t.Evented=It,t.FeatureIndex=$l,t.FillBucket=is,t.FillExtrusionBucket=ws,t.ImageAtlas=mu,t.ImagePosition=yu,t.LineBucket=Ts,t.LngLat=Vl,t.LngLatBounds=Bl,t.MercatorCoordinate=jl,t.ONE_EM=24,t.OverscaledTileID=Kl,t.Point=i,t.Point$1=i,t.Properties=xi,t.Protobuf=Zs,t.RGBAImage=mo,t.RequestManager=K,t.RequestPerformance=np,t.ResourceType=ft,t.SegmentVector=aa,t.SourceFeatureState=Yl,t.StructArrayLayout1ui2=Gi,t.StructArrayLayout2f1f2i16=Di,t.StructArrayLayout2i4=Ii,t.StructArrayLayout3ui6=Ri,t.StructArrayLayout4i8=zi,t.SymbolBucket=fl,t.Texture=Ml,t.Tile=ep,t.Transitionable=ui,t.Uniform1f=ga,t.Uniform1i=va,t.Uniform2f=xa,t.Uniform3f=ba,t.Uniform4f=wa,t.UniformColor=_a,t.UniformMatrix4f=Sa,t.UnwrappedTileID=Nl,t.ValidationError=Ct,t.WritingMode=vu,t.ZoomHistory=qn,t.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t},t.addDynamicAttributes=ll,t.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),a=null;t.forEach((function(t,o){e(t,(function(t,e){t&&(a=t),i[o]=e,0==--n&&r(a,i);}));}));},t.bezier=s,t.bindAll=m,t.browser=L,t.cacheEntryPossiblyAdded=function(t){++ct>st&&(t.getActor().send("enforceCacheSizeLimit",ot),ct=0);},t.clamp=l,t.clearTileCache=function(t){var e=o.caches.delete("mapbox-tiles");t&&e.catch(t).then((function(){return t()}));},t.clipLine=qu,t.clone=function(t){var e=new ro(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.clone$1=b,t.clone$2=function(t){var e=new ro(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.collisionCircleLayout=js,t.config=R,t.create=function(){var t=new ro(16);return ro!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.create$1=function(){var t=new ro(9);return ro!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t},t.create$2=function(){var t=new ro(4);return ro!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t},t.createCommonjsModule=e,t.createExpression=Kr,t.createLayout=Si,t.createStyleLayer=function(t){return "custom"===t.type?new _l(t):new Al[t.type](t)},t.cross=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],u=r[2];return t[0]=i*u-a*s,t[1]=a*o-n*u,t[2]=n*s-i*o,t},t.deepEqual=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(var n=0;n<e.length;n++)if(!t(e[n],r[n]))return !1;return !0}if("object"==typeof e&&null!==e&&null!==r){if("object"!=typeof r)return !1;if(Object.keys(e).length!==Object.keys(r).length)return !1;for(var i in e)if(!t(e[i],r[i]))return !1;return !0}return e===r},t.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.dot$1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]},t.ease=u,t.emitValidationErrors=En,t.endsWith=v,t.enforceCacheSizeLimit=function(t){ut(),Q&&Q.then((function(e){e.keys().then((function(r){for(var n=0;n<r.length-t;n++)e.delete(r[n]);}));}));},t.evaluateSizeForFeature=Bu,t.evaluateSizeForZoom=Vu,t.evaluateVariableOffset=el,t.evented=ei,t.extend=c,t.featureFilter=nn,t.filterObject=x,t.fromRotation=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},t.getAnchorAlignment=Cu,t.getAnchorJustification=rl,t.getArrayBuffer=xt,t.getImage=wt,t.getJSON=function(t,e){return gt(c(t,{type:"json"}),e)},t.getRTLTextPluginStatus=ri,t.getReferrer=dt,t.getVideo=function(t,e){var r,n,i=o.document.createElement("video");i.muted=!0,i.onloadstart=function(){e(null,i);};for(var a=0;a<t.length;a++){var s=o.document.createElement("source");r=t[a],n=void 0,(n=o.document.createElement("a")).href=r,(n.protocol!==o.document.location.protocol||n.host!==o.document.location.host)&&(i.crossOrigin="Anonymous"),s.src=t[a],i.appendChild(s);}return {cancel:function(){}}},t.identity=no,t.invert=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],u=e[6],l=e[7],p=e[8],c=e[9],h=e[10],f=e[11],y=e[12],d=e[13],m=e[14],v=e[15],g=r*s-n*o,x=r*u-i*o,b=r*l-a*o,w=n*u-i*s,_=n*l-a*s,A=i*l-a*u,S=p*d-c*y,k=p*m-h*y,I=p*v-f*y,z=c*m-h*d,C=c*v-f*d,M=h*v-f*m,E=g*M-x*C+b*z+w*I-_*k+A*S;return E?(t[0]=(s*M-u*C+l*z)*(E=1/E),t[1]=(i*C-n*M-a*z)*E,t[2]=(d*A-m*_+v*w)*E,t[3]=(h*_-c*A-f*w)*E,t[4]=(u*I-o*M-l*k)*E,t[5]=(r*M-i*I+a*k)*E,t[6]=(m*b-y*A-v*x)*E,t[7]=(p*A-h*b+f*x)*E,t[8]=(o*C-s*I+l*S)*E,t[9]=(n*I-r*C-a*S)*E,t[10]=(y*_-d*b+v*g)*E,t[11]=(c*b-p*_-f*g)*E,t[12]=(s*k-o*z-u*S)*E,t[13]=(r*z-n*k+i*S)*E,t[14]=(d*x-y*w-m*g)*E,t[15]=(p*w-c*x+h*g)*E,t):null},t.isChar=Nn,t.isMapboxURL=G,t.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},t.makeRequest=gt,t.mapObject=g,t.mercatorXfromLng=Ll,t.mercatorYfromLat=Rl,t.mercatorZfromAltitude=Ol,t.mul=oo,t.multiply=io,t.mvt=vs,t.normalize=function(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a)),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a,t},t.number=qe,t.offscreenCanvasSupported=ht,t.ortho=function(t,e,r,n,i,a,o){var s=1/(e-r),u=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*u,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*u,t[14]=(o+a)*l,t[15]=1,t},t.parseGlyphPBF=function(t){return new Zs(t).readFields(pu,[])},t.pbf=Zs,t.performSymbolLayout=function(t,e,r,n,i,a,o){t.createArrays(),t.tilePixelRatio=8192/(512*t.overscaling),t.compareText={},t.iconsNeedLinear=!1;var s=t.layers[0].layout,u=t.layers[0]._unevaluatedLayout._values,l={};if("composite"===t.textSizeData.kind){var p=t.textSizeData,c=p.maxZoom;l.compositeTextSizes=[u["text-size"].possiblyEvaluate(new ai(p.minZoom),o),u["text-size"].possiblyEvaluate(new ai(c),o)];}if("composite"===t.iconSizeData.kind){var h=t.iconSizeData,f=h.maxZoom;l.compositeIconSizes=[u["icon-size"].possiblyEvaluate(new ai(h.minZoom),o),u["icon-size"].possiblyEvaluate(new ai(f),o)];}l.layoutTextSize=u["text-size"].possiblyEvaluate(new ai(t.zoom+1),o),l.layoutIconSize=u["icon-size"].possiblyEvaluate(new ai(t.zoom+1),o),l.textMaxSize=u["text-size"].possiblyEvaluate(new ai(18));for(var y=24*s.get("text-line-height"),d="map"===s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement"),m=s.get("text-keep-upright"),v=s.get("text-size"),g=function(){var a=b[x],u=s.get("text-font").evaluate(a,{},o).join(","),p=v.evaluate(a,{},o),c=l.layoutTextSize.evaluate(a,{},o),h=l.layoutIconSize.evaluate(a,{},o),f={horizontal:{},vertical:void 0},g=a.text,w=[0,0];if(g){var A=g.toString(),S=24*s.get("text-letter-spacing").evaluate(a,{},o),k=function(t){for(var e=0,r=t;e<r.length;e+=1)if(n=r[e].charCodeAt(0),Nn.Arabic(n)||Nn["Arabic Supplement"](n)||Nn["Arabic Extended-A"](n)||Nn["Arabic Presentation Forms-A"](n)||Nn["Arabic Presentation Forms-B"](n))return !1;var n;return !0}(A)?S:0,I=s.get("text-anchor").evaluate(a,{},o),z=s.get("text-variable-anchor");if(!z){var C=s.get("text-radial-offset").evaluate(a,{},o);w=C?el(I,[24*C,tl]):s.get("text-offset").evaluate(a,{},o).map((function(t){return 24*t}));}var M=d?"center":s.get("text-justify").evaluate(a,{},o),E=s.get("symbol-placement"),T="point"===E?24*s.get("text-max-width").evaluate(a,{},o):0,P=function(){t.allowVerticalPlacement&&Kn(A)&&(f.vertical=bu(g,e,r,i,u,T,y,I,"left",k,w,vu.vertical,!0,E,c,p));};if(!d&&z){for(var B="auto"===M?z.map((function(t){return rl(t)})):[M],V=!1,F=0;F<B.length;F++){var D=B[F];if(!f.horizontal[D])if(V)f.horizontal[D]=f.horizontal[0];else {var L=bu(g,e,r,i,u,T,y,"center",D,k,w,vu.horizontal,!1,E,c,p);L&&(f.horizontal[D]=L,V=1===L.positionedLines.length);}}P();}else {"auto"===M&&(M=rl(I));var R=bu(g,e,r,i,u,T,y,I,M,k,w,vu.horizontal,!1,E,c,p);R&&(f.horizontal[M]=R),P(),Kn(A)&&d&&m&&(f.vertical=bu(g,e,r,i,u,T,y,I,M,k,w,vu.vertical,!1,E,c,p));}}var O=void 0,U=!1;if(a.icon&&a.icon.name){var j=n[a.icon.name];j&&(O=function(t,e,r){var n=Cu(r),i=e[0]-t.displaySize[0]*n.horizontalAlign,a=e[1]-t.displaySize[1]*n.verticalAlign;return {image:t,top:a,bottom:a+t.displaySize[1],left:i,right:i+t.displaySize[0]}}(i[a.icon.name],s.get("icon-offset").evaluate(a,{},o),s.get("icon-anchor").evaluate(a,{},o)),U=j.sdf,void 0===t.sdfIcons?t.sdfIcons=j.sdf:t.sdfIcons!==j.sdf&&_("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(j.pixelRatio!==t.pixelRatio||0!==s.get("icon-rotate").constantOr(1))&&(t.iconsNeedLinear=!0));}var q=il(f.horizontal)||f.vertical;t.iconsInText=!!q&&q.iconsInText,(q||O)&&function(t,e,r,n,i,a,o,s,u,l,p){var c=a.textMaxSize.evaluate(e,{});void 0===c&&(c=o);var h,f=t.layers[0].layout,y=f.get("icon-offset").evaluate(e,{},p),d=il(r.horizontal),m=o/24,v=t.tilePixelRatio*m,g=t.tilePixelRatio*c/24,x=t.tilePixelRatio*s,b=t.tilePixelRatio*f.get("symbol-spacing"),w=f.get("text-padding")*t.tilePixelRatio,A=f.get("icon-padding")*t.tilePixelRatio,S=f.get("text-max-angle")/180*Math.PI,k="map"===f.get("text-rotation-alignment")&&"point"!==f.get("symbol-placement"),I="map"===f.get("icon-rotation-alignment")&&"point"!==f.get("symbol-placement"),z=f.get("symbol-placement"),C=b/2,M=f.get("icon-text-fit");n&&"none"!==M&&(t.allowVerticalPlacement&&r.vertical&&(h=Eu(n,r.vertical,M,f.get("icon-text-fit-padding"),y,m)),d&&(n=Eu(n,d,M,f.get("icon-text-fit-padding"),y,m)));var E=function(s,c){c.x<0||c.x>=8192||c.y<0||c.y>=8192||function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,A,S,k){var I,z,C,M,E,T=t.addToLineVertexArray(e,r),P=0,B=0,V=0,F=0,D=-1,L=-1,R={},O=pa(""),U=0,j=0;if(void 0===s._unevaluatedLayout.getValue("text-radial-offset")?(U=(I=s.layout.get("text-offset").evaluate(b,{},S).map((function(t){return 24*t})))[0],j=I[1]):(U=24*s.layout.get("text-radial-offset").evaluate(b,{},S),j=tl),t.allowVerticalPlacement&&n.vertical){var q=s.layout.get("text-rotate").evaluate(b,{},S)+90;M=new Ju(u,e,l,p,c,n.vertical,h,f,y,q),o&&(E=new Ju(u,e,l,p,c,o,m,v,y,q));}if(i){var N=s.layout.get("icon-rotate").evaluate(b,{}),K="none"!==s.layout.get("icon-text-fit"),G=Nu(i,N,A,K),Z=o?Nu(o,N,A,K):void 0;C=new Ju(u,e,l,p,c,i,m,v,!1,N),P=4*G.length;var X=t.iconSizeData,J=null;"source"===X.kind?(J=[128*s.layout.get("icon-size").evaluate(b,{})])[0]>32640&&_(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'):"composite"===X.kind&&((J=[128*w.compositeIconSizes[0].evaluate(b,{},S),128*w.compositeIconSizes[1].evaluate(b,{},S)])[0]>32640||J[1]>32640)&&_(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'),t.addSymbols(t.icon,G,J,x,g,b,!1,e,T.lineStartIndex,T.lineLength,-1,S),D=t.icon.placedSymbolArray.length-1,Z&&(B=4*Z.length,t.addSymbols(t.icon,Z,J,x,g,b,vu.vertical,e,T.lineStartIndex,T.lineLength,-1,S),L=t.icon.placedSymbolArray.length-1);}for(var H in n.horizontal){var Y=n.horizontal[H];if(!z){O=pa(Y.text);var $=s.layout.get("text-rotate").evaluate(b,{},S);z=new Ju(u,e,l,p,c,Y,h,f,y,$);}var W=1===Y.positionedLines.length;if(V+=nl(t,e,Y,a,s,y,b,d,T,n.vertical?vu.horizontal:vu.horizontalOnly,W?Object.keys(n.horizontal):[H],R,D,w,S),W)break}n.vertical&&(F+=nl(t,e,n.vertical,a,s,y,b,d,T,vu.vertical,["vertical"],R,L,w,S));var Q=z?z.boxStartIndex:t.collisionBoxArray.length,tt=z?z.boxEndIndex:t.collisionBoxArray.length,et=M?M.boxStartIndex:t.collisionBoxArray.length,rt=M?M.boxEndIndex:t.collisionBoxArray.length,nt=C?C.boxStartIndex:t.collisionBoxArray.length,it=C?C.boxEndIndex:t.collisionBoxArray.length,at=E?E.boxStartIndex:t.collisionBoxArray.length,ot=E?E.boxEndIndex:t.collisionBoxArray.length,st=-1,ut=function(t,e){return t&&t.circleDiameter?Math.max(t.circleDiameter,e):e};st=ut(z,st),st=ut(M,st),st=ut(C,st);var lt=(st=ut(E,st))>-1?1:0;lt&&(st*=k/24),t.glyphOffsetArray.length>=fl.MAX_GLYPHS&&_("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==b.sortKey&&t.addToSortKeyRanges(t.symbolInstances.length,b.sortKey),t.symbolInstances.emplaceBack(e.x,e.y,R.right>=0?R.right:-1,R.center>=0?R.center:-1,R.left>=0?R.left:-1,R.vertical||-1,D,L,O,Q,tt,et,rt,nt,it,at,ot,l,V,F,P,B,lt,0,h,U,j,st);}(t,c,s,r,n,i,h,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,v,w,k,u,x,A,I,y,e,a,l,p,o);};if("line"===z)for(var T=0,P=qu(e.geometry,0,0,8192,8192);T<P.length;T+=1)for(var B=P[T],V=0,F=ju(B,b,S,r.vertical||d,n,24,g,t.overscaling,8192);V<F.length;V+=1){var D=F[V];d&&al(t,d.text,C,D)||E(B,D);}else if("line-center"===z)for(var L=0,R=e.geometry;L<R.length;L+=1){var O=R[L];if(O.length>1){var U=Uu(O,S,r.vertical||d,n,24,g);U&&E(O,U);}}else if("Polygon"===e.type)for(var j=0,q=ts(e.geometry,0);j<q.length;j+=1){var N=q[j],K=$u(N,16);E(N[0],new Tu(K.x,K.y,0));}else if("LineString"===e.type)for(var G=0,Z=e.geometry;G<Z.length;G+=1){var X=Z[G];E(X,new Tu(X[0].x,X[0].y,0));}else if("Point"===e.type)for(var J=0,H=e.geometry;J<H.length;J+=1)for(var Y=0,$=H[J];Y<$.length;Y+=1){var W=$[Y];E([W],new Tu(W.x,W.y,0));}}(t,a,f,O,n,l,c,h,w,U,o);},x=0,b=t.features;x<b.length;x+=1)g();a&&t.generateCollisionDebugBuffers();},t.perspective=function(t,e,r,n,i){var a,o=1/Math.tan(e/2);return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0?(t[10]=(i+n)*(a=1/(n-i)),t[14]=2*i*n*a):(t[10]=-1,t[14]=-2*n),t},t.pick=function(t,e){for(var r={},n=0;n<e.length;n++){var i=e[n];i in t&&(r[i]=t[i]);}return r},t.plugin=ii,t.polygonIntersectsPolygon=Ua,t.postMapLoadEvent=at,t.postTurnstileEvent=nt,t.potpack=fu,t.refProperties=["type","source","source-layer","minzoom","maxzoom","filter","layout"],t.register=Dn,t.registerForPluginStateChange=function(t){return t({pluginStatus:$n,pluginURL:Wn}),ei.on("pluginStateChange",t),t},t.rotate=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),u=Math.cos(r);return t[0]=n*u+a*s,t[1]=i*u+o*s,t[2]=n*-s+a*u,t[3]=i*-s+o*u,t},t.rotateX=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],u=e[7],l=e[8],p=e[9],c=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+l*n,t[5]=o*i+p*n,t[6]=s*i+c*n,t[7]=u*i+h*n,t[8]=l*i-a*n,t[9]=p*i-o*n,t[10]=c*i-s*n,t[11]=h*i-u*n,t},t.rotateZ=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],u=e[3],l=e[4],p=e[5],c=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+l*n,t[1]=o*i+p*n,t[2]=s*i+c*n,t[3]=u*i+h*n,t[4]=l*i-a*n,t[5]=p*i-o*n,t[6]=c*i-s*n,t[7]=h*i-u*n,t},t.scale=function(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.scale$1=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.scale$2=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t},t.setCacheLimits=function(t,e){ot=t,st=e;},t.setRTLTextPlugin=function(t,e,r){if(void 0===r&&(r=!1),"deferred"===$n||"loading"===$n||"loaded"===$n)throw new Error("setRTLTextPlugin cannot be called multiple times.");Wn=L.resolveURL(t),$n="deferred",Yn=e,ti(),r||ni();},t.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},t.sqrLen=function(t){var e=t[0],r=t[1];return e*e+r*r},t.styleSpec=zt,t.sub=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.symbolSize=Fu,t.transformMat3=function(t,e,r){var n=e[0],i=e[1],a=e[2];return t[0]=n*r[0]+i*r[3]+a*r[6],t[1]=n*r[1]+i*r[4]+a*r[7],t[2]=n*r[2]+i*r[5]+a*r[8],t},t.transformMat4=so,t.translate=function(t,e,r){var n,i,a,o,s,u,l,p,c,h,f,y,d=r[0],m=r[1],v=r[2];return e===t?(t[12]=e[0]*d+e[4]*m+e[8]*v+e[12],t[13]=e[1]*d+e[5]*m+e[9]*v+e[13],t[14]=e[2]*d+e[6]*m+e[10]*v+e[14],t[15]=e[3]*d+e[7]*m+e[11]*v+e[15]):(i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],t[0]=n=e[0],t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=u,t[6]=l,t[7]=p,t[8]=c,t[9]=h,t[10]=f,t[11]=y,t[12]=n*d+s*m+c*v+e[12],t[13]=i*d+u*m+h*v+e[13],t[14]=a*d+l*m+f*v+e[14],t[15]=o*d+p*m+y*v+e[15]),t},t.triggerPluginCompletionEvent=Qn,t.uniqueId=f,t.validateCustomStyleLayer=function(t){var e=[],r=t.id;return void 0===r&&e.push({message:"layers."+r+': missing required property "id"'}),void 0===t.render&&e.push({message:"layers."+r+': missing required method "render"'}),t.renderingMode&&"2d"!==t.renderingMode&&"3d"!==t.renderingMode&&e.push({message:"layers."+r+': property "renderingMode" must be either "2d" or "3d"'}),e},t.validateLight=zn,t.validateStyle=In,t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.vectorTile=vs,t.version="1.11.0",t.warnOnce=_,t.webpSupported=O,t.window=o,t.wrap=p;}));
define(["./shared"],(function(e){"use strict";function t(e){var r=typeof e;if("number"===r||"boolean"===r||"string"===r||null==e)return JSON.stringify(e);if(Array.isArray(e)){for(var i="[",o=0,n=e;o<n.length;o+=1)i+=t(n[o])+",";return i+"]"}for(var s=Object.keys(e).sort(),a="{",l=0;l<s.length;l++)a+=JSON.stringify(s[l])+":"+t(e[s[l]])+",";return a+"}"}function r(r){for(var i="",o=0,n=e.refProperties;o<n.length;o+=1)i+="/"+t(r[n[o]]);return i}var i=function(e){this.keyCache={},e&&this.replace(e);};i.prototype.replace=function(e){this._layerConfigs={},this._layers={},this.update(e,[]);},i.prototype.update=function(t,i){for(var o=this,n=0,s=t;n<s.length;n+=1){var a=s[n];this._layerConfigs[a.id]=a;var l=this._layers[a.id]=e.createStyleLayer(a);l._featureFilter=e.featureFilter(l.filter),this.keyCache[a.id]&&delete this.keyCache[a.id];}for(var u=0,h=i;u<h.length;u+=1){var c=h[u];delete this.keyCache[c],delete this._layerConfigs[c],delete this._layers[c];}this.familiesBySource={};for(var p=0,f=function(e,t){for(var i={},o=0;o<e.length;o++){var n=t&&t[e[o].id]||r(e[o]);t&&(t[e[o].id]=n);var s=i[n];s||(s=i[n]=[]),s.push(e[o]);}var a=[];for(var l in i)a.push(i[l]);return a}(e.values(this._layerConfigs),this.keyCache);p<f.length;p+=1){var d=f[p].map((function(e){return o._layers[e.id]})),g=d[0];if("none"!==g.visibility){var m=g.source||"",v=this.familiesBySource[m];v||(v=this.familiesBySource[m]={});var y=g.sourceLayer||"_geojsonTileLayer",x=v[y];x||(x=v[y]=[]),x.push(d);}}};var o=function(t){var r={},i=[];for(var o in t){var n=t[o],s=r[o]={};for(var a in n){var l=n[+a];if(l&&0!==l.bitmap.width&&0!==l.bitmap.height){var u={x:0,y:0,w:l.bitmap.width+2,h:l.bitmap.height+2};i.push(u),s[a]={rect:u,metrics:l.metrics};}}}var h=e.potpack(i),c=new e.AlphaImage({width:h.w||1,height:h.h||1});for(var p in t){var f=t[p];for(var d in f){var g=f[+d];if(g&&0!==g.bitmap.width&&0!==g.bitmap.height){var m=r[p][d].rect;e.AlphaImage.copy(g.bitmap,c,{x:0,y:0},{x:m.x+1,y:m.y+1},g.bitmap);}}}this.image=c,this.positions=r;};e.register("GlyphAtlas",o);var n=function(t){this.tileID=new e.OverscaledTileID(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId;};function s(t,r,i){for(var o=new e.EvaluationParameters(r),n=0,s=t;n<s.length;n+=1)s[n].recalculate(o,i);}function a(t,r){var i=e.getArrayBuffer(t.request,(function(t,i,o,n){t?r(t):i&&r(null,{vectorTile:new e.vectorTile.VectorTile(new e.pbf(i)),rawData:i,cacheControl:o,expires:n});}));return function(){i.cancel(),r();}}n.prototype.parse=function(t,r,i,n,a){var l=this;this.status="parsing",this.data=t,this.collisionBoxArray=new e.CollisionBoxArray;var u=new e.DictionaryCoder(Object.keys(t.layers).sort()),h=new e.FeatureIndex(this.tileID,this.promoteId);h.bucketLayerIDs=[];var c,p,f,d,g={},m={featureIndex:h,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:i},v=r.familiesBySource[this.source];for(var y in v){var x=t.layers[y];if(x){1===x.version&&e.warnOnce('Vector tile source "'+this.source+'" layer "'+y+'" does not use vector tile spec v2 and therefore may have some rendering errors.');for(var w=u.encode(y),S=[],I=0;I<x.length;I++){var M=x.feature(I),b=h.getId(M,y);S.push({feature:M,id:b,index:I,sourceLayerIndex:w});}for(var _=0,k=v[y];_<k.length;_+=1){var P=k[_],T=P[0];T.minzoom&&this.zoom<Math.floor(T.minzoom)||T.maxzoom&&this.zoom>=T.maxzoom||"none"!==T.visibility&&(s(P,this.zoom,i),(g[T.id]=T.createBucket({index:h.bucketLayerIDs.length,layers:P,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:w,sourceID:this.source})).populate(S,m,this.tileID.canonical),h.bucketLayerIDs.push(P.map((function(e){return e.id}))));}}}var C=e.mapObject(m.glyphDependencies,(function(e){return Object.keys(e).map(Number)}));Object.keys(C).length?n.send("getGlyphs",{uid:this.uid,stacks:C},(function(e,t){c||(c=e,p=t,z.call(l));})):p={};var D=Object.keys(m.iconDependencies);D.length?n.send("getImages",{icons:D,source:this.source,tileID:this.tileID,type:"icons"},(function(e,t){c||(c=e,f=t,z.call(l));})):f={};var L=Object.keys(m.patternDependencies);function z(){if(c)return a(c);if(p&&f&&d){var t=new o(p),r=new e.ImageAtlas(f,d);for(var n in g){var l=g[n];l instanceof e.SymbolBucket?(s(l.layers,this.zoom,i),e.performSymbolLayout(l,p,t.positions,f,r.iconPositions,this.showCollisionBoxes,this.tileID.canonical)):l.hasPattern&&(l instanceof e.LineBucket||l instanceof e.FillBucket||l instanceof e.FillExtrusionBucket)&&(s(l.layers,this.zoom,i),l.addFeatures(m,this.tileID.canonical,r.patternPositions));}this.status="done",a(null,{buckets:e.values(g).filter((function(e){return !e.isEmpty()})),featureIndex:h,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,imageAtlas:r,glyphMap:this.returnDependencies?p:null,iconMap:this.returnDependencies?f:null,glyphPositions:this.returnDependencies?t.positions:null});}}L.length?n.send("getImages",{icons:L,source:this.source,tileID:this.tileID,type:"patterns"},(function(e,t){c||(c=e,d=t,z.call(l));})):d={},z.call(this);};var l=function(e,t,r,i){this.actor=e,this.layerIndex=t,this.availableImages=r,this.loadVectorData=i||a,this.loading={},this.loaded={};};l.prototype.loadTile=function(t,r){var i=this,o=t.uid;this.loading||(this.loading={});var s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.RequestPerformance(t.request),a=this.loading[o]=new n(t);a.abort=this.loadVectorData(t,(function(t,n){if(delete i.loading[o],t||!n)return a.status="done",i.loaded[o]=a,r(t);var l=n.rawData,u={};n.expires&&(u.expires=n.expires),n.cacheControl&&(u.cacheControl=n.cacheControl);var h={};if(s){var c=s.finish();c&&(h.resourceTiming=JSON.parse(JSON.stringify(c)));}a.vectorTile=n.vectorTile,a.parse(n.vectorTile,i.layerIndex,i.availableImages,i.actor,(function(t,i){if(t||!i)return r(t);r(null,e.extend({rawTileData:l.slice(0)},i,u,h));})),i.loaded=i.loaded||{},i.loaded[o]=a;}));},l.prototype.reloadTile=function(e,t){var r=this,i=this.loaded,o=e.uid,n=this;if(i&&i[o]){var s=i[o];s.showCollisionBoxes=e.showCollisionBoxes;var a=function(e,i){var o=s.reloadCallback;o&&(delete s.reloadCallback,s.parse(s.vectorTile,n.layerIndex,r.availableImages,n.actor,o)),t(e,i);};"parsing"===s.status?s.reloadCallback=a:"done"===s.status&&(s.vectorTile?s.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor,a):a());}},l.prototype.abortTile=function(e,t){var r=this.loading,i=e.uid;r&&r[i]&&r[i].abort&&(r[i].abort(),delete r[i]),t();},l.prototype.removeTile=function(e,t){var r=this.loaded,i=e.uid;r&&r[i]&&delete r[i],t();};var u=e.window.ImageBitmap,h=function(){this.loaded={};};function c(e,t){if(0!==e.length){p(e[0],t);for(var r=1;r<e.length;r++)p(e[r],!t);}}function p(e,t){for(var r=0,i=0,o=e.length,n=o-1;i<o;n=i++)r+=(e[i][0]-e[n][0])*(e[n][1]+e[i][1]);r>=0!=!!t&&e.reverse();}h.prototype.loadTile=function(t,r){var i=t.uid,o=t.encoding,n=t.rawImageData,s=u&&n instanceof u?this.getImageData(n):n,a=new e.DEMData(i,s,o);this.loaded=this.loaded||{},this.loaded[i]=a,r(null,a);},h.prototype.getImageData=function(t){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(t.width,t.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d")),this.offscreenCanvas.width=t.width,this.offscreenCanvas.height=t.height,this.offscreenCanvasContext.drawImage(t,0,0,t.width,t.height);var r=this.offscreenCanvasContext.getImageData(-1,-1,t.width+2,t.height+2);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),new e.RGBAImage({width:r.width,height:r.height},r.data)},h.prototype.removeTile=function(e){var t=this.loaded,r=e.uid;t&&t[r]&&delete t[r];};var f=e.vectorTile.VectorTileFeature.prototype.toGeoJSON,d=function(t){this._feature=t,this.extent=e.EXTENT,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));};d.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],r=0,i=this._feature.geometry;r<i.length;r+=1){var o=i[r];t.push([new e.Point$1(o[0],o[1])]);}return t}for(var n=[],s=0,a=this._feature.geometry;s<a.length;s+=1){for(var l=[],u=0,h=a[s];u<h.length;u+=1){var c=h[u];l.push(new e.Point$1(c[0],c[1]));}n.push(l);}return n},d.prototype.toGeoJSON=function(e,t,r){return f.call(this,e,t,r)};var g=function(t){this.layers={_geojsonTileLayer:this},this.name="_geojsonTileLayer",this.extent=e.EXTENT,this.length=t.length,this._features=t;};g.prototype.feature=function(e){return new d(this._features[e])};var m=e.vectorTile.VectorTileFeature,v=y;function y(e,t){this.options=t||{},this.features=e,this.length=e.length;}function x(e,t){this.id="number"==typeof e.id?e.id:void 0,this.type=e.type,this.rawGeometry=1===e.type?[e.geometry]:e.geometry,this.properties=e.tags,this.extent=t||4096;}y.prototype.feature=function(e){return new x(this.features[e],this.options.extent)},x.prototype.loadGeometry=function(){var t=this.rawGeometry;this.geometry=[];for(var r=0;r<t.length;r++){for(var i=t[r],o=[],n=0;n<i.length;n++)o.push(new e.Point$1(i[n][0],i[n][1]));this.geometry.push(o);}return this.geometry},x.prototype.bbox=function(){this.geometry||this.loadGeometry();for(var e=this.geometry,t=1/0,r=-1/0,i=1/0,o=-1/0,n=0;n<e.length;n++)for(var s=e[n],a=0;a<s.length;a++){var l=s[a];t=Math.min(t,l.x),r=Math.max(r,l.x),i=Math.min(i,l.y),o=Math.max(o,l.y);}return [t,i,r,o]},x.prototype.toGeoJSON=m.prototype.toGeoJSON;var w=I,S=v;function I(t){var r=new e.pbf;return function(e,t){for(var r in e.layers)t.writeMessage(3,M,e.layers[r]);}(t,r),r.finish()}function M(e,t){var r;t.writeVarintField(15,e.version||1),t.writeStringField(1,e.name||""),t.writeVarintField(5,e.extent||4096);var i={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r<e.length;r++)i.feature=e.feature(r),t.writeMessage(2,b,i);var o=i.keys;for(r=0;r<o.length;r++)t.writeStringField(3,o[r]);var n=i.values;for(r=0;r<n.length;r++)t.writeMessage(4,C,n[r]);}function b(e,t){var r=e.feature;void 0!==r.id&&t.writeVarintField(1,r.id),t.writeMessage(2,_,e),t.writeVarintField(3,r.type),t.writeMessage(4,T,r);}function _(e,t){var r=e.feature,i=e.keys,o=e.values,n=e.keycache,s=e.valuecache;for(var a in r.properties){var l=n[a];void 0===l&&(i.push(a),n[a]=l=i.length-1),t.writeVarint(l);var u=r.properties[a],h=typeof u;"string"!==h&&"boolean"!==h&&"number"!==h&&(u=JSON.stringify(u));var c=h+":"+u,p=s[c];void 0===p&&(o.push(u),s[c]=p=o.length-1),t.writeVarint(p);}}function k(e,t){return (t<<3)+(7&e)}function P(e){return e<<1^e>>31}function T(e,t){for(var r=e.loadGeometry(),i=e.type,o=0,n=0,s=r.length,a=0;a<s;a++){var l=r[a],u=1;1===i&&(u=l.length),t.writeVarint(k(1,u));for(var h=3===i?l.length-1:l.length,c=0;c<h;c++){1===c&&1!==i&&t.writeVarint(k(2,h-1));var p=l[c].x-o,f=l[c].y-n;t.writeVarint(P(p)),t.writeVarint(P(f)),o+=p,n+=f;}3===i&&t.writeVarint(k(7,1));}}function C(e,t){var r=typeof e;"string"===r?t.writeStringField(1,e):"boolean"===r?t.writeBooleanField(7,e):"number"===r&&(e%1!=0?t.writeDoubleField(3,e):e<0?t.writeSVarintField(6,e):t.writeVarintField(5,e));}function D(e,t,r,i){L(e,r,i),L(t,2*r,2*i),L(t,2*r+1,2*i+1);}function L(e,t,r){var i=e[t];e[t]=e[r],e[r]=i;}function z(e,t,r,i){var o=e-r,n=t-i;return o*o+n*n}w.fromVectorTileJs=I,w.fromGeojsonVt=function(e,t){t=t||{};var r={};for(var i in e)r[i]=new v(e[i].features,t),r[i].name=i,r[i].version=t.version,r[i].extent=t.extent;return I({layers:r})},w.GeoJSONWrapper=S;var O=function(e){return e[0]},E=function(e){return e[1]},F=function(e,t,r,i,o){void 0===t&&(t=O),void 0===r&&(r=E),void 0===i&&(i=64),void 0===o&&(o=Float64Array),this.nodeSize=i,this.points=e;for(var n=e.length<65536?Uint16Array:Uint32Array,s=this.ids=new n(e.length),a=this.coords=new o(2*e.length),l=0;l<e.length;l++)s[l]=l,a[2*l]=t(e[l]),a[2*l+1]=r(e[l]);!function e(t,r,i,o,n,s){if(!(n-o<=i)){var a=o+n>>1;!function e(t,r,i,o,n,s){for(;n>o;){if(n-o>600){var a=n-o+1,l=i-o+1,u=Math.log(a),h=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*h*(a-h)/a)*(l-a/2<0?-1:1);e(t,r,i,Math.max(o,Math.floor(i-l*h/a+c)),Math.min(n,Math.floor(i+(a-l)*h/a+c)),s);}var p=r[2*i+s],f=o,d=n;for(D(t,r,o,i),r[2*n+s]>p&&D(t,r,o,n);f<d;){for(D(t,r,f,d),f++,d--;r[2*f+s]<p;)f++;for(;r[2*d+s]>p;)d--;}r[2*o+s]===p?D(t,r,o,d):D(t,r,++d,n),d<=i&&(o=d+1),i<=d&&(n=d-1);}}(t,r,a,o,n,s%2),e(t,r,i,o,a-1,s+1),e(t,r,i,a+1,n,s+1);}}(s,a,i,0,s.length-1,0);};F.prototype.range=function(e,t,r,i){return function(e,t,r,i,o,n,s){for(var a,l,u=[0,e.length-1,0],h=[];u.length;){var c=u.pop(),p=u.pop(),f=u.pop();if(p-f<=s)for(var d=f;d<=p;d++)l=t[2*d+1],(a=t[2*d])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[d]);else {var g=Math.floor((f+p)/2);l=t[2*g+1],(a=t[2*g])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[g]);var m=(c+1)%2;(0===c?r<=a:i<=l)&&(u.push(f),u.push(g-1),u.push(m)),(0===c?o>=a:n>=l)&&(u.push(g+1),u.push(p),u.push(m));}}return h}(this.ids,this.coords,e,t,r,i,this.nodeSize)},F.prototype.within=function(e,t,r){return function(e,t,r,i,o,n){for(var s=[0,e.length-1,0],a=[],l=o*o;s.length;){var u=s.pop(),h=s.pop(),c=s.pop();if(h-c<=n)for(var p=c;p<=h;p++)z(t[2*p],t[2*p+1],r,i)<=l&&a.push(e[p]);else {var f=Math.floor((c+h)/2),d=t[2*f],g=t[2*f+1];z(d,g,r,i)<=l&&a.push(e[f]);var m=(u+1)%2;(0===u?r-o<=d:i-o<=g)&&(s.push(c),s.push(f-1),s.push(m)),(0===u?r+o>=d:i+o>=g)&&(s.push(f+1),s.push(h),s.push(m));}}return a}(this.ids,this.coords,e,t,r,this.nodeSize)};var N={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:function(e){return e}},J=function(e){this.options=V(Object.create(N),e),this.trees=new Array(this.options.maxZoom+1);};function Z(e,t,r,i,o){return {x:e,y:t,zoom:1/0,id:r,parentId:-1,numPoints:i,properties:o}}function A(e,t){var r=e.geometry.coordinates,i=r[1];return {x:Y(r[0]),y:j(i),zoom:1/0,index:t,parentId:-1}}function B(e){return {type:"Feature",id:e.id,properties:G(e),geometry:{type:"Point",coordinates:[(i=e.x,360*(i-.5)),(t=e.y,r=(180-360*t)*Math.PI/180,360*Math.atan(Math.exp(r))/Math.PI-90)]}};var t,r,i;}function G(e){var t=e.numPoints,r=t>=1e4?Math.round(t/1e3)+"k":t>=1e3?Math.round(t/100)/10+"k":t;return V(V({},e.properties),{cluster:!0,cluster_id:e.id,point_count:t,point_count_abbreviated:r})}function Y(e){return e/360+.5}function j(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function V(e,t){for(var r in t)e[r]=t[r];return e}function X(e){return e.x}function W(e){return e.y}function R(e,t,r,i,o,n){var s=o-r,a=n-i;if(0!==s||0!==a){var l=((e-r)*s+(t-i)*a)/(s*s+a*a);l>1?(r=o,i=n):l>0&&(r+=s*l,i+=a*l);}return (s=e-r)*s+(a=t-i)*a}function q(e,t,r,i){var o={id:void 0===e?null:e,type:t,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,r=e.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)U(e,t);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i<t.length;i++)U(e,t[i]);else if("MultiPolygon"===r)for(i=0;i<t.length;i++)for(var o=0;o<t[i].length;o++)U(e,t[i][o]);}(o),o}function U(e,t){for(var r=0;r<t.length;r+=3)e.minX=Math.min(e.minX,t[r]),e.minY=Math.min(e.minY,t[r+1]),e.maxX=Math.max(e.maxX,t[r]),e.maxY=Math.max(e.maxY,t[r+1]);}function $(e,t,r,i){if(t.geometry){var o=t.geometry.coordinates,n=t.geometry.type,s=Math.pow(r.tolerance/((1<<r.maxZoom)*r.extent),2),a=[],l=t.id;if(r.promoteId?l=t.properties[r.promoteId]:r.generateId&&(l=i||0),"Point"===n)H(o,a);else if("MultiPoint"===n)for(var u=0;u<o.length;u++)H(o[u],a);else if("LineString"===n)K(o,a,s,!1);else if("MultiLineString"===n){if(r.lineMetrics){for(u=0;u<o.length;u++)K(o[u],a=[],s,!1),e.push(q(l,"LineString",a,t.properties));return}Q(o,a,s,!1);}else if("Polygon"===n)Q(o,a,s,!0);else {if("MultiPolygon"!==n){if("GeometryCollection"===n){for(u=0;u<t.geometry.geometries.length;u++)$(e,{id:l,geometry:t.geometry.geometries[u],properties:t.properties},r,i);return}throw new Error("Input data is not a valid GeoJSON object.")}for(u=0;u<o.length;u++){var h=[];Q(o[u],h,s,!0),a.push(h);}}e.push(q(l,n,a,t.properties));}}function H(e,t){t.push(ee(e[0])),t.push(te(e[1])),t.push(0);}function K(e,t,r,i){for(var o,n,s=0,a=0;a<e.length;a++){var l=ee(e[a][0]),u=te(e[a][1]);t.push(l),t.push(u),t.push(0),a>0&&(s+=i?(o*u-l*n)/2:Math.sqrt(Math.pow(l-o,2)+Math.pow(u-n,2))),o=l,n=u;}var h=t.length-3;t[2]=1,function e(t,r,i,o){for(var n,s=o,a=i-r>>1,l=i-r,u=t[r],h=t[r+1],c=t[i],p=t[i+1],f=r+3;f<i;f+=3){var d=R(t[f],t[f+1],u,h,c,p);if(d>s)n=f,s=d;else if(d===s){var g=Math.abs(f-a);g<l&&(n=f,l=g);}}s>o&&(n-r>3&&e(t,r,n,o),t[n+2]=s,i-n>3&&e(t,n,i,o));}(t,0,h,r),t[h+2]=1,t.size=Math.abs(s),t.start=0,t.end=t.size;}function Q(e,t,r,i){for(var o=0;o<e.length;o++){var n=[];K(e[o],n,r,i),t.push(n);}}function ee(e){return e/360+.5}function te(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function re(e,t,r,i,o,n,s,a){if(i/=t,n>=(r/=t)&&s<i)return e;if(s<r||n>=i)return null;for(var l=[],u=0;u<e.length;u++){var h=e[u],c=h.geometry,p=h.type,f=0===o?h.minX:h.minY,d=0===o?h.maxX:h.maxY;if(f>=r&&d<i)l.push(h);else if(!(d<r||f>=i)){var g=[];if("Point"===p||"MultiPoint"===p)ie(c,g,r,i,o);else if("LineString"===p)oe(c,g,r,i,o,!1,a.lineMetrics);else if("MultiLineString"===p)se(c,g,r,i,o,!1);else if("Polygon"===p)se(c,g,r,i,o,!0);else if("MultiPolygon"===p)for(var m=0;m<c.length;m++){var v=[];se(c[m],v,r,i,o,!0),v.length&&g.push(v);}if(g.length){if(a.lineMetrics&&"LineString"===p){for(m=0;m<g.length;m++)l.push(q(h.id,p,g[m],h.tags));continue}"LineString"!==p&&"MultiLineString"!==p||(1===g.length?(p="LineString",g=g[0]):p="MultiLineString"),"Point"!==p&&"MultiPoint"!==p||(p=3===g.length?"Point":"MultiPoint"),l.push(q(h.id,p,g,h.tags));}}}return l.length?l:null}function ie(e,t,r,i,o){for(var n=0;n<e.length;n+=3){var s=e[n+o];s>=r&&s<=i&&(t.push(e[n]),t.push(e[n+1]),t.push(e[n+2]));}}function oe(e,t,r,i,o,n,s){for(var a,l,u=ne(e),h=0===o?le:ue,c=e.start,p=0;p<e.length-3;p+=3){var f=e[p],d=e[p+1],g=e[p+2],m=e[p+3],v=e[p+4],y=0===o?f:d,x=0===o?m:v,w=!1;s&&(a=Math.sqrt(Math.pow(f-m,2)+Math.pow(d-v,2))),y<r?x>r&&(l=h(u,f,d,m,v,r),s&&(u.start=c+a*l)):y>i?x<i&&(l=h(u,f,d,m,v,i),s&&(u.start=c+a*l)):ae(u,f,d,g),x<r&&y>=r&&(l=h(u,f,d,m,v,r),w=!0),x>i&&y<=i&&(l=h(u,f,d,m,v,i),w=!0),!n&&w&&(s&&(u.end=c+a*l),t.push(u),u=ne(e)),s&&(c+=a);}var S=e.length-3;f=e[S],d=e[S+1],g=e[S+2],(y=0===o?f:d)>=r&&y<=i&&ae(u,f,d,g),S=u.length-3,n&&S>=3&&(u[S]!==u[0]||u[S+1]!==u[1])&&ae(u,u[0],u[1],u[2]),u.length&&t.push(u);}function ne(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function se(e,t,r,i,o,n){for(var s=0;s<e.length;s++)oe(e[s],t,r,i,o,n,!1);}function ae(e,t,r,i){e.push(t),e.push(r),e.push(i);}function le(e,t,r,i,o,n){var s=(n-t)/(i-t);return e.push(n),e.push(r+(o-r)*s),e.push(1),s}function ue(e,t,r,i,o,n){var s=(n-r)/(o-r);return e.push(t+(i-t)*s),e.push(n),e.push(1),s}function he(e,t){for(var r=[],i=0;i<e.length;i++){var o,n=e[i],s=n.type;if("Point"===s||"MultiPoint"===s||"LineString"===s)o=ce(n.geometry,t);else if("MultiLineString"===s||"Polygon"===s){o=[];for(var a=0;a<n.geometry.length;a++)o.push(ce(n.geometry[a],t));}else if("MultiPolygon"===s)for(o=[],a=0;a<n.geometry.length;a++){for(var l=[],u=0;u<n.geometry[a].length;u++)l.push(ce(n.geometry[a][u],t));o.push(l);}r.push(q(n.id,s,o,n.tags));}return r}function ce(e,t){var r=[];r.size=e.size,void 0!==e.start&&(r.start=e.start,r.end=e.end);for(var i=0;i<e.length;i+=3)r.push(e[i]+t,e[i+1],e[i+2]);return r}function pe(e,t){if(e.transformed)return e;var r,i,o,n=1<<e.z,s=e.x,a=e.y;for(r=0;r<e.features.length;r++){var l=e.features[r],u=l.geometry,h=l.type;if(l.geometry=[],1===h)for(i=0;i<u.length;i+=2)l.geometry.push(fe(u[i],u[i+1],t,n,s,a));else for(i=0;i<u.length;i++){var c=[];for(o=0;o<u[i].length;o+=2)c.push(fe(u[i][o],u[i][o+1],t,n,s,a));l.geometry.push(c);}}return e.transformed=!0,e}function fe(e,t,r,i,o,n){return [Math.round(r*(e*i-o)),Math.round(r*(t*i-n))]}function de(e,t,r,i,o){for(var n=t===o.maxZoom?0:o.tolerance/((1<<t)*o.extent),s={features:[],numPoints:0,numSimplified:0,numFeatures:0,source:null,x:r,y:i,z:t,transformed:!1,minX:2,minY:1,maxX:-1,maxY:0},a=0;a<e.length;a++){s.numFeatures++,ge(s,e[a],n,o);var l=e[a].minX,u=e[a].minY,h=e[a].maxX,c=e[a].maxY;l<s.minX&&(s.minX=l),u<s.minY&&(s.minY=u),h>s.maxX&&(s.maxX=h),c>s.maxY&&(s.maxY=c);}return s}function ge(e,t,r,i){var o=t.geometry,n=t.type,s=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a<o.length;a+=3)s.push(o[a]),s.push(o[a+1]),e.numPoints++,e.numSimplified++;else if("LineString"===n)me(s,o,e,r,!1,!1);else if("MultiLineString"===n||"Polygon"===n)for(a=0;a<o.length;a++)me(s,o[a],e,r,"Polygon"===n,0===a);else if("MultiPolygon"===n)for(var l=0;l<o.length;l++){var u=o[l];for(a=0;a<u.length;a++)me(s,u[a],e,r,!0,0===a);}if(s.length){var h=t.tags||null;if("LineString"===n&&i.lineMetrics){for(var c in h={},t.tags)h[c]=t.tags[c];h.mapbox_clip_start=o.start/o.size,h.mapbox_clip_end=o.end/o.size;}var p={geometry:s,type:"Polygon"===n||"MultiPolygon"===n?3:"LineString"===n||"MultiLineString"===n?2:1,tags:h};null!==t.id&&(p.id=t.id),e.features.push(p);}}function me(e,t,r,i,o,n){var s=i*i;if(i>0&&t.size<(o?s:i))r.numPoints+=t.length/3;else {for(var a=[],l=0;l<t.length;l+=3)(0===i||t[l+2]>s)&&(r.numSimplified++,a.push(t[l]),a.push(t[l+1])),r.numPoints++;o&&function(e,t){for(var r=0,i=0,o=e.length,n=o-2;i<o;n=i,i+=2)r+=(e[i]-e[n])*(e[i+1]+e[n+1]);if(r>0===t)for(i=0,o=e.length;i<o/2;i+=2){var s=e[i],a=e[i+1];e[i]=e[o-2-i],e[i+1]=e[o-1-i],e[o-2-i]=s,e[o-1-i]=a;}}(a,n),e.push(a);}}function ve(e,t){var r=(t=this.options=function(e,t){for(var r in t)e[r]=t[r];return e}(Object.create(this.options),t)).debug;if(r&&console.time("preprocess data"),t.maxZoom<0||t.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");var i=function(e,t){var r=[];if("FeatureCollection"===e.type)for(var i=0;i<e.features.length;i++)$(r,e.features[i],t,i);else $(r,"Feature"===e.type?e:{geometry:e},t);return r}(e,t);this.tiles={},this.tileCoords=[],r&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",t.indexMaxZoom,t.indexMaxPoints),console.time("generate tiles"),this.stats={},this.total=0),(i=function(e,t){var r=t.buffer/t.extent,i=e,o=re(e,1,-1-r,r,0,-1,2,t),n=re(e,1,1-r,2+r,0,-1,2,t);return (o||n)&&(i=re(e,1,-r,1+r,0,-1,2,t)||[],o&&(i=he(o,1).concat(i)),n&&(i=i.concat(he(n,-1)))),i}(i,t)).length&&this.splitTile(i,0,0,0),r&&(i.length&&console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints),console.timeEnd("generate tiles"),console.log("tiles generated:",this.total,JSON.stringify(this.stats)));}function ye(e,t,r){return 32*((1<<e)*r+t)+e}function xe(e,t){var r=e.tileID.canonical;if(!this._geoJSONIndex)return t(null,null);var i=this._geoJSONIndex.getTile(r.z,r.x,r.y);if(!i)return t(null,null);var o=new g(i.features),n=w(o);0===n.byteOffset&&n.byteLength===n.buffer.byteLength||(n=new Uint8Array(n)),t(null,{vectorTile:o,rawData:n.buffer});}J.prototype.load=function(e){var t=this.options,r=t.log,i=t.minZoom,o=t.maxZoom,n=t.nodeSize;r&&console.time("total time");var s="prepare "+e.length+" points";r&&console.time(s),this.points=e;for(var a=[],l=0;l<e.length;l++)e[l].geometry&&a.push(A(e[l],l));this.trees[o+1]=new F(a,X,W,n,Float32Array),r&&console.timeEnd(s);for(var u=o;u>=i;u--){var h=+Date.now();a=this._cluster(a,u),this.trees[u]=new F(a,X,W,n,Float32Array),r&&console.log("z%d: %d clusters in %dms",u,a.length,+Date.now()-h);}return r&&console.timeEnd("total time"),this},J.prototype.getClusters=function(e,t){var r=((e[0]+180)%360+360)%360-180,i=Math.max(-90,Math.min(90,e[1])),o=180===e[2]?180:((e[2]+180)%360+360)%360-180,n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)r=-180,o=180;else if(r>o){var s=this.getClusters([r,i,180,n],t),a=this.getClusters([-180,i,o,n],t);return s.concat(a)}for(var l=this.trees[this._limitZoom(t)],u=[],h=0,c=l.range(Y(r),j(n),Y(o),j(i));h<c.length;h+=1){var p=l.points[c[h]];u.push(p.numPoints?B(p):this.points[p.index]);}return u},J.prototype.getChildren=function(e){var t=this._getOriginId(e),r=this._getOriginZoom(e),i="No cluster with the specified id.",o=this.trees[r];if(!o)throw new Error(i);var n=o.points[t];if(!n)throw new Error(i);for(var s=this.options.radius/(this.options.extent*Math.pow(2,r-1)),a=[],l=0,u=o.within(n.x,n.y,s);l<u.length;l+=1){var h=o.points[u[l]];h.parentId===e&&a.push(h.numPoints?B(h):this.points[h.index]);}if(0===a.length)throw new Error(i);return a},J.prototype.getLeaves=function(e,t,r){var i=[];return this._appendLeaves(i,e,t=t||10,r=r||0,0),i},J.prototype.getTile=function(e,t,r){var i=this.trees[this._limitZoom(e)],o=Math.pow(2,e),n=this.options,s=n.radius/n.extent,a=(r-s)/o,l=(r+1+s)/o,u={features:[]};return this._addTileFeatures(i.range((t-s)/o,a,(t+1+s)/o,l),i.points,t,r,o,u),0===t&&this._addTileFeatures(i.range(1-s/o,a,1,l),i.points,o,r,o,u),t===o-1&&this._addTileFeatures(i.range(0,a,s/o,l),i.points,-1,r,o,u),u.features.length?u:null},J.prototype.getClusterExpansionZoom=function(e){for(var t=this._getOriginZoom(e)-1;t<=this.options.maxZoom;){var r=this.getChildren(e);if(t++,1!==r.length)break;e=r[0].properties.cluster_id;}return t},J.prototype._appendLeaves=function(e,t,r,i,o){for(var n=0,s=this.getChildren(t);n<s.length;n+=1){var a=s[n],l=a.properties;if(l&&l.cluster?o+l.point_count<=i?o+=l.point_count:o=this._appendLeaves(e,l.cluster_id,r,i,o):o<i?o++:e.push(a),e.length===r)break}return o},J.prototype._addTileFeatures=function(e,t,r,i,o,n){for(var s=0,a=e;s<a.length;s+=1){var l=t[a[s]],u=l.numPoints,h={type:1,geometry:[[Math.round(this.options.extent*(l.x*o-r)),Math.round(this.options.extent*(l.y*o-i))]],tags:u?G(l):this.points[l.index].properties},c=void 0;u?c=l.id:this.options.generateId?c=l.index:this.points[l.index].id&&(c=this.points[l.index].id),void 0!==c&&(h.id=c),n.features.push(h);}},J.prototype._limitZoom=function(e){return Math.max(this.options.minZoom,Math.min(+e,this.options.maxZoom+1))},J.prototype._cluster=function(e,t){for(var r=[],i=this.options,o=i.reduce,n=i.minPoints,s=i.radius/(i.extent*Math.pow(2,t)),a=0;a<e.length;a++){var l=e[a];if(!(l.zoom<=t)){l.zoom=t;for(var u=this.trees[t+1],h=u.within(l.x,l.y,s),c=l.numPoints||1,p=c,f=0,d=h;f<d.length;f+=1){var g=u.points[d[f]];g.zoom>t&&(p+=g.numPoints||1);}if(p>=n){for(var m=l.x*c,v=l.y*c,y=o&&c>1?this._map(l,!0):null,x=(a<<5)+(t+1)+this.points.length,w=0,S=h;w<S.length;w+=1){var I=u.points[S[w]];if(!(I.zoom<=t)){I.zoom=t;var M=I.numPoints||1;m+=I.x*M,v+=I.y*M,I.parentId=x,o&&(y||(y=this._map(l,!0)),o(y,this._map(I)));}}l.parentId=x,r.push(Z(m/p,v/p,x,p,y));}else if(r.push(l),p>1)for(var b=0,_=h;b<_.length;b+=1){var k=u.points[_[b]];k.zoom<=t||(k.zoom=t,r.push(k));}}}return r},J.prototype._getOriginId=function(e){return e-this.points.length>>5},J.prototype._getOriginZoom=function(e){return (e-this.points.length)%32},J.prototype._map=function(e,t){if(e.numPoints)return t?V({},e.properties):e.properties;var r=this.points[e.index].properties,i=this.options.map(r);return t&&i===r?V({},i):i},ve.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0},ve.prototype.splitTile=function(e,t,r,i,o,n,s){for(var a=[e,t,r,i],l=this.options,u=l.debug;a.length;){i=a.pop(),r=a.pop(),t=a.pop(),e=a.pop();var h=1<<t,c=ye(t,r,i),p=this.tiles[c];if(!p&&(u>1&&console.time("creation"),p=this.tiles[c]=de(e,t,r,i,l),this.tileCoords.push({z:t,x:r,y:i}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,r,i,p.numFeatures,p.numPoints,p.numSimplified),console.timeEnd("creation"));var f="z"+t;this.stats[f]=(this.stats[f]||0)+1,this.total++;}if(p.source=e,o){if(t===l.maxZoom||t===o)continue;var d=1<<o-t;if(r!==Math.floor(n/d)||i!==Math.floor(s/d))continue}else if(t===l.indexMaxZoom||p.numPoints<=l.indexMaxPoints)continue;if(p.source=null,0!==e.length){u>1&&console.time("clipping");var g,m,v,y,x,w,S=.5*l.buffer/l.extent,I=.5-S,M=.5+S,b=1+S;g=m=v=y=null,x=re(e,h,r-S,r+M,0,p.minX,p.maxX,l),w=re(e,h,r+I,r+b,0,p.minX,p.maxX,l),e=null,x&&(g=re(x,h,i-S,i+M,1,p.minY,p.maxY,l),m=re(x,h,i+I,i+b,1,p.minY,p.maxY,l),x=null),w&&(v=re(w,h,i-S,i+M,1,p.minY,p.maxY,l),y=re(w,h,i+I,i+b,1,p.minY,p.maxY,l),w=null),u>1&&console.timeEnd("clipping"),a.push(g||[],t+1,2*r,2*i),a.push(m||[],t+1,2*r,2*i+1),a.push(v||[],t+1,2*r+1,2*i),a.push(y||[],t+1,2*r+1,2*i+1);}}},ve.prototype.getTile=function(e,t,r){var i=this.options,o=i.extent,n=i.debug;if(e<0||e>24)return null;var s=1<<e,a=ye(e,t=(t%s+s)%s,r);if(this.tiles[a])return pe(this.tiles[a],o);n>1&&console.log("drilling down to z%d-%d-%d",e,t,r);for(var l,u=e,h=t,c=r;!l&&u>0;)u--,h=Math.floor(h/2),c=Math.floor(c/2),l=this.tiles[ye(u,h,c)];return l&&l.source?(n>1&&console.log("found parent tile z%d-%d-%d",u,h,c),n>1&&console.time("drilling down"),this.splitTile(l.source,u,h,c,e,t,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?pe(this.tiles[a],o):null):null};var we=function(t){function r(e,r,i,o){t.call(this,e,r,i,xe),o&&(this.loadGeoJSON=o);}return t&&(r.__proto__=t),(r.prototype=Object.create(t&&t.prototype)).constructor=r,r.prototype.loadData=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=t,this._pendingLoadDataParams=e,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData());},r.prototype._loadData=function(){var t=this;if(this._pendingCallback&&this._pendingLoadDataParams){var r=this._pendingCallback,i=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams;var o=!!(i&&i.request&&i.request.collectResourceTiming)&&new e.RequestPerformance(i.request);this.loadGeoJSON(i,(function(n,s){if(n||!s)return r(n);if("object"!=typeof s)return r(new Error("Input data given to '"+i.source+"' is not a valid GeoJSON object."));!function e(t,r){var i,o=t&&t.type;if("FeatureCollection"===o)for(i=0;i<t.features.length;i++)e(t.features[i],r);else if("GeometryCollection"===o)for(i=0;i<t.geometries.length;i++)e(t.geometries[i],r);else if("Feature"===o)e(t.geometry,r);else if("Polygon"===o)c(t.coordinates,r);else if("MultiPolygon"===o)for(i=0;i<t.coordinates.length;i++)c(t.coordinates[i],r);return t}(s,!0);try{t._geoJSONIndex=i.cluster?new J(function(t){var r=t.superclusterOptions,i=t.clusterProperties;if(!i||!r)return r;for(var o={},n={},s={accumulated:null,zoom:0},a={properties:null},l=Object.keys(i),u=0,h=l;u<h.length;u+=1){var c=h[u],p=i[c],f=p[0],d=e.createExpression(p[1]),g=e.createExpression("string"==typeof f?[f,["accumulated"],["get",c]]:f);o[c]=d.value,n[c]=g.value;}return r.map=function(e){a.properties=e;for(var t={},r=0,i=l;r<i.length;r+=1){var n=i[r];t[n]=o[n].evaluate(s,a);}return t},r.reduce=function(e,t){a.properties=t;for(var r=0,i=l;r<i.length;r+=1){var o=i[r];s.accumulated=e[o],e[o]=n[o].evaluate(s,a);}},r}(i)).load(s.features):function(e,t){return new ve(e,t)}(s,i.geojsonVtOptions);}catch(n){return r(n)}t.loaded={};var a={};if(o){var l=o.finish();l&&(a.resourceTiming={},a.resourceTiming[i.source]=JSON.parse(JSON.stringify(l)));}r(null,a);}));}},r.prototype.coalesce=function(){"Coalescing"===this._state?this._state="Idle":"NeedsLoadData"===this._state&&(this._state="Coalescing",this._loadData());},r.prototype.reloadTile=function(e,r){var i=this.loaded;return i&&i[e.uid]?t.prototype.reloadTile.call(this,e,r):this.loadTile(e,r)},r.prototype.loadGeoJSON=function(t,r){if(t.request)e.getJSON(t.request,r);else {if("string"!=typeof t.data)return r(new Error("Input data given to '"+t.source+"' is not a valid GeoJSON object."));try{return r(null,JSON.parse(t.data))}catch(e){return r(new Error("Input data given to '"+t.source+"' is not a valid GeoJSON object."))}}},r.prototype.removeSource=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),t();},r.prototype.getClusterExpansionZoom=function(e,t){try{t(null,this._geoJSONIndex.getClusterExpansionZoom(e.clusterId));}catch(e){t(e);}},r.prototype.getClusterChildren=function(e,t){try{t(null,this._geoJSONIndex.getChildren(e.clusterId));}catch(e){t(e);}},r.prototype.getClusterLeaves=function(e,t){try{t(null,this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset));}catch(e){t(e);}},r}(l),Se=function(t){var r=this;this.self=t,this.actor=new e.Actor(t,this),this.layerIndexes={},this.availableImages={},this.workerSourceTypes={vector:l,geojson:we},this.workerSources={},this.demWorkerSources={},this.self.registerWorkerSource=function(e,t){if(r.workerSourceTypes[e])throw new Error('Worker source with name "'+e+'" already registered.');r.workerSourceTypes[e]=t;},this.self.registerRTLTextPlugin=function(t){if(e.plugin.isParsed())throw new Error("RTL text plugin already registered.");e.plugin.applyArabicShaping=t.applyArabicShaping,e.plugin.processBidirectionalText=t.processBidirectionalText,e.plugin.processStyledBidirectionalText=t.processStyledBidirectionalText;};};return Se.prototype.setReferrer=function(e,t){this.referrer=t;},Se.prototype.setImages=function(e,t,r){for(var i in this.availableImages[e]=t,this.workerSources[e]){var o=this.workerSources[e][i];for(var n in o)o[n].availableImages=t;}r();},Se.prototype.setLayers=function(e,t,r){this.getLayerIndex(e).replace(t),r();},Se.prototype.updateLayers=function(e,t,r){this.getLayerIndex(e).update(t.layers,t.removedIds),r();},Se.prototype.loadTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).loadTile(t,r);},Se.prototype.loadDEMTile=function(e,t,r){this.getDEMWorkerSource(e,t.source).loadTile(t,r);},Se.prototype.reloadTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).reloadTile(t,r);},Se.prototype.abortTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).abortTile(t,r);},Se.prototype.removeTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).removeTile(t,r);},Se.prototype.removeDEMTile=function(e,t){this.getDEMWorkerSource(e,t.source).removeTile(t);},Se.prototype.removeSource=function(e,t,r){if(this.workerSources[e]&&this.workerSources[e][t.type]&&this.workerSources[e][t.type][t.source]){var i=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],void 0!==i.removeSource?i.removeSource(t,r):r();}},Se.prototype.loadWorkerSource=function(e,t,r){try{this.self.importScripts(t.url),r();}catch(e){r(e.toString());}},Se.prototype.syncRTLPluginState=function(t,r,i){try{e.plugin.setState(r);var o=e.plugin.getPluginURL();if(e.plugin.isLoaded()&&!e.plugin.isParsed()&&null!=o){this.self.importScripts(o);var n=e.plugin.isParsed();i(n?void 0:new Error("RTL Text Plugin failed to import scripts from "+o),n);}}catch(e){i(e.toString());}},Se.prototype.getAvailableImages=function(e){var t=this.availableImages[e];return t||(t=[]),t},Se.prototype.getLayerIndex=function(e){var t=this.layerIndexes[e];return t||(t=this.layerIndexes[e]=new i),t},Se.prototype.getWorkerSource=function(e,t,r){var i=this;return this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),this.workerSources[e][t][r]||(this.workerSources[e][t][r]=new this.workerSourceTypes[t]({send:function(t,r,o){i.actor.send(t,r,o,e);}},this.getLayerIndex(e),this.getAvailableImages(e))),this.workerSources[e][t][r]},Se.prototype.getDEMWorkerSource=function(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new h),this.demWorkerSources[e][t]},Se.prototype.enforceCacheSizeLimit=function(t,r){e.enforceCacheSizeLimit(r);},"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope&&(self.worker=new Se(self)),Se}));
define(["./shared"],(function(t){"use strict";var e=t.createCommonjsModule((function(t){function e(t){return !i(t)}function i(t){return "undefined"==typeof window||"undefined"==typeof document?"not a browser":Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.lastIndexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.prototype.reduceRight&&Array.isArray?Function.prototype&&Function.prototype.bind?Object.keys&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.isSealed&&Object.isFrozen&&Object.isExtensible&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.defineProperties&&Object.seal&&Object.freeze&&Object.preventExtensions?"JSON"in window&&"parse"in JSON&&"stringify"in JSON?function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return !1;var t,e,i=new Blob([""],{type:"text/javascript"}),o=URL.createObjectURL(i);try{e=new Worker(o),t=!0;}catch(e){t=!1;}return e&&e.terminate(),URL.revokeObjectURL(o),t}()?"Uint8ClampedArray"in window?ArrayBuffer.isView?function(){var t=document.createElement("canvas");t.width=t.height=1;var e=t.getContext("2d");if(!e)return !1;var i=e.getImageData(0,0,1,1);return i&&i.width===t.width}()?(void 0===o[i=t&&t.failIfMajorPerformanceCaveat]&&(o[i]=function(t){var i=function(t){var i=document.createElement("canvas"),o=Object.create(e.webGLContextAttributes);return o.failIfMajorPerformanceCaveat=t,i.probablySupportsContext?i.probablySupportsContext("webgl",o)||i.probablySupportsContext("experimental-webgl",o):i.supportsContext?i.supportsContext("webgl",o)||i.supportsContext("experimental-webgl",o):i.getContext("webgl",o)||i.getContext("experimental-webgl",o)}(t);if(!i)return !1;var o=i.createShader(i.VERTEX_SHADER);return !(!o||i.isContextLost())&&(i.shaderSource(o,"void main() {}"),i.compileShader(o),!0===i.getShaderParameter(o,i.COMPILE_STATUS))}(i)),o[i]?void 0:"insufficient WebGL support"):"insufficient Canvas/getImageData support":"insufficient ArrayBuffer support":"insufficient Uint8ClampedArray support":"insufficient worker support":"insufficient JSON support":"insufficient Object support":"insufficient Function support":"insufficent Array support";var i;}t.exports?t.exports=e:window&&(window.mapboxgl=window.mapboxgl||{},window.mapboxgl.supported=e,window.mapboxgl.notSupportedReason=i);var o={};e.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0};})),i={create:function(e,i,o){var r=t.window.document.createElement(e);return void 0!==i&&(r.className=i),o&&o.appendChild(r),r},createNS:function(e,i){return t.window.document.createElementNS(e,i)}},o=t.window.document&&t.window.document.documentElement.style;function r(t){if(!o)return t[0];for(var e=0;e<t.length;e++)if(t[e]in o)return t[e];return t[0]}var a,n=r(["userSelect","MozUserSelect","WebkitUserSelect","msUserSelect"]);i.disableDrag=function(){o&&n&&(a=o[n],o[n]="none");},i.enableDrag=function(){o&&n&&(o[n]=a);};var s=r(["transform","WebkitTransform"]);i.setTransform=function(t,e){t.style[s]=e;};var l=!1;try{var c=Object.defineProperty({},"passive",{get:function(){l=!0;}});t.window.addEventListener("test",c,c),t.window.removeEventListener("test",c,c);}catch(t){l=!1;}i.addEventListener=function(t,e,i,o){void 0===o&&(o={}),t.addEventListener(e,i,"passive"in o&&l?o:o.capture);},i.removeEventListener=function(t,e,i,o){void 0===o&&(o={}),t.removeEventListener(e,i,"passive"in o&&l?o:o.capture);};var u=function(e){e.preventDefault(),e.stopPropagation(),t.window.removeEventListener("click",u,!0);};function h(t){var e=t.userImage;return !!(e&&e.render&&e.render())&&(t.data.replace(new Uint8Array(e.data.buffer)),!0)}i.suppressClick=function(){t.window.addEventListener("click",u,!0),t.window.setTimeout((function(){t.window.removeEventListener("click",u,!0);}),0);},i.mousePos=function(e,i){var o=e.getBoundingClientRect();return new t.Point(i.clientX-o.left-e.clientLeft,i.clientY-o.top-e.clientTop)},i.touchPos=function(e,i){for(var o=e.getBoundingClientRect(),r=[],a=0;a<i.length;a++)r.push(new t.Point(i[a].clientX-o.left-e.clientLeft,i[a].clientY-o.top-e.clientTop));return r},i.mouseButton=function(e){return void 0!==t.window.InstallTrigger&&2===e.button&&e.ctrlKey&&t.window.navigator.platform.toUpperCase().indexOf("MAC")>=0?0:e.button},i.remove=function(t){t.parentNode&&t.parentNode.removeChild(t);};var p=function(e){function i(){e.call(this),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.RGBAImage({width:1,height:1}),this.dirty=!0;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.isLoaded=function(){return this.loaded},i.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,i=this.requestors;e<i.length;e+=1){var o=i[e];this._notify(o.ids,o.callback);}this.requestors=[];}},i.prototype.getImage=function(t){return this.images[t]},i.prototype.addImage=function(t,e){this._validate(t,e)&&(this.images[t]=e);},i.prototype._validate=function(e,i){var o=!0;return this._validateStretch(i.stretchX,i.data&&i.data.width)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "stretchX" value'))),o=!1),this._validateStretch(i.stretchY,i.data&&i.data.height)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "stretchY" value'))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "content" value'))),o=!1),o},i.prototype._validateStretch=function(t,e){if(!t)return !0;for(var i=0,o=0,r=t;o<r.length;o+=1){var a=r[o];if(a[0]<i||a[1]<a[0]||e<a[1])return !1;i=a[1];}return !0},i.prototype._validateContent=function(t,e){return !(t&&(4!==t.length||t[0]<0||e.data.width<t[0]||t[1]<0||e.data.height<t[1]||t[2]<0||e.data.width<t[2]||t[3]<0||e.data.height<t[3]||t[2]<t[0]||t[3]<t[1]))},i.prototype.updateImage=function(t,e){e.version=this.images[t].version+1,this.images[t]=e,this.updatedImages[t]=!0;},i.prototype.removeImage=function(t){var e=this.images[t];delete this.images[t],delete this.patterns[t],e.userImage&&e.userImage.onRemove&&e.userImage.onRemove();},i.prototype.listImages=function(){return Object.keys(this.images)},i.prototype.getImages=function(t,e){var i=!0;if(!this.isLoaded())for(var o=0,r=t;o<r.length;o+=1)this.images[r[o]]||(i=!1);this.isLoaded()||i?this._notify(t,e):this.requestors.push({ids:t,callback:e});},i.prototype._notify=function(e,i){for(var o={},r=0,a=e;r<a.length;r+=1){var n=a[r];this.images[n]||this.fire(new t.Event("styleimagemissing",{id:n}));var s=this.images[n];s?o[n]={data:s.data.clone(),pixelRatio:s.pixelRatio,sdf:s.sdf,version:s.version,stretchX:s.stretchX,stretchY:s.stretchY,content:s.content,hasRenderCallback:Boolean(s.userImage&&s.userImage.render)}:t.warnOnce('Image "'+n+'" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.');}i(null,o);},i.prototype.getPixelSize=function(){var t=this.atlasImage;return {width:t.width,height:t.height}},i.prototype.getPattern=function(e){var i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {var r={w:o.data.width+2,h:o.data.height+2,x:0,y:0},a=new t.ImagePosition(r,o);this.patterns[e]={bin:r,position:a};}return this._updatePatternAtlas(),this.patterns[e].position},i.prototype.bind=function(e){var i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.Texture(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);},i.prototype._updatePatternAtlas=function(){var e=[];for(var i in this.patterns)e.push(this.patterns[i].bin);var o=t.potpack(e),r=o.w,a=o.h,n=this.atlasImage;for(var s in n.resize({width:r||1,height:a||1}),this.patterns){var l=this.patterns[s].bin,c=l.x+1,u=l.y+1,h=this.images[s].data,p=h.width,d=h.height;t.RGBAImage.copy(h,n,{x:0,y:0},{x:c,y:u},{width:p,height:d}),t.RGBAImage.copy(h,n,{x:0,y:d-1},{x:c,y:u-1},{width:p,height:1}),t.RGBAImage.copy(h,n,{x:0,y:0},{x:c,y:u+d},{width:p,height:1}),t.RGBAImage.copy(h,n,{x:p-1,y:0},{x:c-1,y:u},{width:1,height:d}),t.RGBAImage.copy(h,n,{x:0,y:0},{x:c+p,y:u},{width:1,height:d});}this.dirty=!0;},i.prototype.beginFrame=function(){this.callbackDispatchedThisFrame={};},i.prototype.dispatchRenderCallbacks=function(t){for(var e=0,i=t;e<i.length;e+=1){var o=i[e];if(!this.callbackDispatchedThisFrame[o]){this.callbackDispatchedThisFrame[o]=!0;var r=this.images[o];h(r)&&this.updateImage(o,r);}}},i}(t.Evented),d=m,_=m,f=1e20;function m(t,e,i,o,r,a){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=o||.25,this.fontFamily=r||"sans-serif",this.fontWeight=a||"normal",this.radius=i||8;var n=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=n,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.d=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Int16Array(n),this.middle=Math.round(n/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1));}function g(t,e,i,o,r,a,n){for(var s=0;s<e;s++){for(var l=0;l<i;l++)o[l]=t[l*e+s];for(v(o,r,a,n,i),l=0;l<i;l++)t[l*e+s]=r[l];}for(l=0;l<i;l++){for(s=0;s<e;s++)o[s]=t[l*e+s];for(v(o,r,a,n,e),s=0;s<e;s++)t[l*e+s]=Math.sqrt(r[s]);}}function v(t,e,i,o,r){i[0]=0,o[0]=-f,o[1]=+f;for(var a=1,n=0;a<r;a++){for(var s=(t[a]+a*a-(t[i[n]]+i[n]*i[n]))/(2*a-2*i[n]);s<=o[n];)n--,s=(t[a]+a*a-(t[i[n]]+i[n]*i[n]))/(2*a-2*i[n]);i[++n]=a,o[n]=s,o[n+1]=+f;}for(a=0,n=0;a<r;a++){for(;o[n+1]<a;)n++;e[a]=(a-i[n])*(a-i[n])+t[i[n]];}}m.prototype.draw=function(t){this.ctx.clearRect(0,0,this.size,this.size),this.ctx.fillText(t,this.buffer,this.middle);for(var e=this.ctx.getImageData(0,0,this.size,this.size),i=new Uint8ClampedArray(this.size*this.size),o=0;o<this.size*this.size;o++){var r=e.data[4*o+3]/255;this.gridOuter[o]=1===r?0:0===r?f:Math.pow(Math.max(0,.5-r),2),this.gridInner[o]=1===r?f:0===r?0:Math.pow(Math.max(0,r-.5),2);}for(g(this.gridOuter,this.size,this.size,this.f,this.d,this.v,this.z),g(this.gridInner,this.size,this.size,this.f,this.d,this.v,this.z),o=0;o<this.size*this.size;o++)i[o]=Math.max(0,Math.min(255,Math.round(255-255*((this.gridOuter[o]-this.gridInner[o])/this.radius+this.cutoff))));return i},d.default=_;var y=function(t,e){this.requestManager=t,this.localIdeographFontFamily=e,this.entries={};};y.prototype.setURL=function(t){this.url=t;},y.prototype.getGlyphs=function(e,i){var o=this,r=[];for(var a in e)for(var n=0,s=e[a];n<s.length;n+=1)r.push({stack:a,id:s[n]});t.asyncAll(r,(function(t,e){var i=t.stack,r=t.id,a=o.entries[i];a||(a=o.entries[i]={glyphs:{},requests:{},ranges:{}});var n=a.glyphs[r];if(void 0===n){if(n=o._tinySDF(a,i,r))return a.glyphs[r]=n,void e(null,{stack:i,id:r,glyph:n});var s=Math.floor(r/256);if(256*s>65535)e(new Error("glyphs > 65535 not supported"));else if(a.ranges[s])e(null,{stack:i,id:r,glyph:n});else {var l=a.requests[s];l||(l=a.requests[s]=[],y.loadGlyphRange(i,s,o.url,o.requestManager,(function(t,e){if(e){for(var i in e)o._doesCharSupportLocalGlyph(+i)||(a.glyphs[+i]=e[+i]);a.ranges[s]=!0;}for(var r=0,n=l;r<n.length;r+=1)(0,n[r])(t,e);delete a.requests[s];}))),l.push((function(t,o){t?e(t):o&&e(null,{stack:i,id:r,glyph:o[r]||null});}));}}else e(null,{stack:i,id:r,glyph:n});}),(function(t,e){if(t)i(t);else if(e){for(var o={},r=0,a=e;r<a.length;r+=1){var n=a[r],s=n.stack,l=n.id,c=n.glyph;(o[s]||(o[s]={}))[l]=c&&{id:c.id,bitmap:c.bitmap.clone(),metrics:c.metrics};}i(null,o);}}));},y.prototype._doesCharSupportLocalGlyph=function(e){return !!this.localIdeographFontFamily&&(t.isChar["CJK Unified Ideographs"](e)||t.isChar["Hangul Syllables"](e)||t.isChar.Hiragana(e)||t.isChar.Katakana(e))},y.prototype._tinySDF=function(e,i,o){var r=this.localIdeographFontFamily;if(r&&this._doesCharSupportLocalGlyph(o)){var a=e.tinySDF;if(!a){var n="400";/bold/i.test(i)?n="900":/medium/i.test(i)?n="500":/light/i.test(i)&&(n="200"),a=e.tinySDF=new y.TinySDF(24,3,8,.25,r,n);}return {id:o,bitmap:new t.AlphaImage({width:30,height:30},a.draw(String.fromCharCode(o))),metrics:{width:24,height:24,left:0,top:-8,advance:24}}}},y.loadGlyphRange=function(e,i,o,r,a){var n=256*i,s=n+255,l=r.transformRequest(r.normalizeGlyphsURL(o).replace("{fontstack}",e).replace("{range}",n+"-"+s),t.ResourceType.Glyphs);t.getArrayBuffer(l,(function(e,i){if(e)a(e);else if(i){for(var o={},r=0,n=t.parseGlyphPBF(i);r<n.length;r+=1){var s=n[r];o[s.id]=s;}a(null,o);}}));},y.TinySDF=d;var x=function(){this.specification=t.styleSpec.light.position;};x.prototype.possiblyEvaluate=function(e,i){return t.sphericalToCartesian(e.expression.evaluate(i))},x.prototype.interpolate=function(e,i,o){return {x:t.number(e.x,i.x,o),y:t.number(e.y,i.y,o),z:t.number(e.z,i.z,o)}};var b=new t.Properties({anchor:new t.DataConstantProperty(t.styleSpec.light.anchor),position:new x,color:new t.DataConstantProperty(t.styleSpec.light.color),intensity:new t.DataConstantProperty(t.styleSpec.light.intensity)}),w=function(e){function i(i){e.call(this),this._transitionable=new t.Transitionable(b),this.setLight(i),this._transitioning=this._transitionable.untransitioned();}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getLight=function(){return this._transitionable.serialize()},i.prototype.setLight=function(e,i){if(void 0===i&&(i={}),!this._validate(t.validateLight,e,i))for(var o in e){var r=e[o];t.endsWith(o,"-transition")?this._transitionable.setTransition(o.slice(0,-"-transition".length),r):this._transitionable.setValue(o,r);}},i.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning);},i.prototype.hasTransition=function(){return this._transitioning.hasTransition()},i.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t);},i.prototype._validate=function(e,i,o){return (!o||!1!==o.validate)&&t.emitValidationErrors(this,e.call(t.validateStyle,t.extend({value:i,style:{glyphs:!0,sprite:!0},styleSpec:t.styleSpec})))},i}(t.Evented),T=function(t,e){this.width=t,this.height=e,this.nextRow=0,this.data=new Uint8Array(this.width*this.height),this.dashEntry={};};T.prototype.getDash=function(t,e){var i=t.join(",")+String(e);return this.dashEntry[i]||(this.dashEntry[i]=this.addDash(t,e)),this.dashEntry[i]},T.prototype.getDashRanges=function(t,e,i){var o=[],r=t.length%2==1?-t[t.length-1]*i:0,a=t[0]*i,n=!0;o.push({left:r,right:a,isDash:n,zeroLength:0===t[0]});for(var s=t[0],l=1;l<t.length;l++){var c=t[l];o.push({left:r=s*i,right:a=(s+=c)*i,isDash:n=!n,zeroLength:0===c});}return o},T.prototype.addRoundDash=function(t,e,i){for(var o=e/2,r=-i;r<=i;r++)for(var a=this.width*(this.nextRow+i+r),n=0,s=t[n],l=0;l<this.width;l++){l/s.right>1&&(s=t[++n]);var c=Math.abs(l-s.left),u=Math.abs(l-s.right),h=Math.min(c,u),p=void 0,d=r/i*(o+1);if(s.isDash){var _=o-Math.abs(d);p=Math.sqrt(h*h+_*_);}else p=o-Math.sqrt(h*h+d*d);this.data[a+l]=Math.max(0,Math.min(255,p+128));}},T.prototype.addRegularDash=function(t){for(var e=t.length-1;e>=0;--e){var i=t[e],o=t[e+1];i.zeroLength?t.splice(e,1):o&&o.isDash===i.isDash&&(o.left=i.left,t.splice(e,1));}var r=t[0],a=t[t.length-1];r.isDash===a.isDash&&(r.left=a.left-this.width,a.right=r.right+this.width);for(var n=this.width*this.nextRow,s=0,l=t[s],c=0;c<this.width;c++){c/l.right>1&&(l=t[++s]);var u=Math.abs(c-l.left),h=Math.abs(c-l.right),p=Math.min(u,h);this.data[n+c]=Math.max(0,Math.min(255,(l.isDash?p:-p)+128));}},T.prototype.addDash=function(e,i){var o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var a=0,n=0;n<e.length;n++)a+=e[n];if(0!==a){var s=this.width/a,l=this.getDashRanges(e,this.width,s);i?this.addRoundDash(l,s,o):this.addRegularDash(l);}var c={y:(this.nextRow+o+.5)/this.height,height:2*o/this.height,width:a};return this.nextRow+=r,this.dirty=!0,c},T.prototype.bind=function(t){var e=t.gl;this.texture?(e.bindTexture(e.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.width,this.height,e.ALPHA,e.UNSIGNED_BYTE,this.data))):(this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.ALPHA,this.width,this.height,0,e.ALPHA,e.UNSIGNED_BYTE,this.data));};var E=function e(i,o){this.workerPool=i,this.actors=[],this.currentActor=0,this.id=t.uniqueId();for(var r=this.workerPool.acquire(this.id),a=0;a<r.length;a++){var n=new e.Actor(r[a],o,this.id);n.name="Worker "+a,this.actors.push(n);}};function I(e,i,o){var r=function(r,a){if(r)return o(r);if(a){var n=t.pick(t.extend(a,e),["tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","scheme","tileSize","encoding"]);a.vector_layers&&(n.vectorLayers=a.vector_layers,n.vectorLayerIds=n.vectorLayers.map((function(t){return t.id}))),n.tiles=i.canonicalizeTileset(n,e.url),o(null,n);}};return e.url?t.getJSON(i.transformRequest(i.normalizeSourceURL(e.url),t.ResourceType.Source),r):t.browser.frame((function(){return r(null,e)}))}E.prototype.broadcast=function(e,i,o){t.asyncAll(this.actors,(function(t,o){t.send(e,i,o);}),o=o||function(){});},E.prototype.getActor=function(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]},E.prototype.remove=function(){this.actors.forEach((function(t){t.remove();})),this.actors=[],this.workerPool.release(this.id);},E.Actor=t.Actor;var P=function(e,i,o){this.bounds=t.LngLatBounds.convert(this.validateBounds(e)),this.minzoom=i||0,this.maxzoom=o||24;};P.prototype.validateBounds=function(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]},P.prototype.contains=function(e){var i=Math.pow(2,e.z),o=Math.floor(t.mercatorXfromLng(this.bounds.getWest())*i),r=Math.floor(t.mercatorYfromLat(this.bounds.getNorth())*i),a=Math.ceil(t.mercatorXfromLng(this.bounds.getEast())*i),n=Math.ceil(t.mercatorYfromLat(this.bounds.getSouth())*i);return e.x>=o&&e.x<a&&e.y>=r&&e.y<n};var S=function(e){function i(i,o,r,a){if(e.call(this),this.id=i,this.dispatcher=r,this.type="vector",this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,this._loaded=!1,t.extend(this,t.pick(o,["url","scheme","tileSize","promoteId"])),this._options=t.extend({type:"vector"},o),this._collectResourceTiming=o.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(a);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=I(this._options,this.map._requestManager,(function(i,o){e._tileJSONRequest=null,e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(t.extend(e,o),o.bounds&&(e.tileBounds=new P(o.bounds,e.minzoom,e.maxzoom)),t.postTurnstileEvent(o.tiles,e.map._requestManager._customAccessToken),t.postMapLoadEvent(o.tiles,e.map._getMapId(),e.map._requestManager._skuToken,e.map._requestManager._customAccessToken),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.hasTile=function(t){return !this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.onRemove=function(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.loadTile=function(e,i){var o=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme)),r={request:this.map._requestManager.transformRequest(o,t.ResourceType.Tile),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};function a(o,r){return delete e.request,e.aborted?i(null):o&&404!==o.status?i(o):(r&&r.resourceTiming&&(e.resourceTiming=r.resourceTiming),this.map._refreshExpiredTiles&&r&&e.setExpiryData(r),e.loadVectorData(r,this.map.painter),t.cacheEntryPossiblyAdded(this.dispatcher),i(null),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}r.request.collectResourceTiming=this._collectResourceTiming,e.actor&&"expired"!==e.state?"loading"===e.state?e.reloadCallback=i:e.request=e.actor.send("reloadTile",r,a.bind(this)):(e.actor=this.dispatcher.getActor(),e.request=e.actor.send("loadTile",r,a.bind(this)));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.actor&&t.actor.send("abortTile",{uid:t.uid,type:this.type,source:this.id},void 0);},i.prototype.unloadTile=function(t){t.unloadVectorData(),t.actor&&t.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id},void 0);},i.prototype.hasTransition=function(){return !1},i}(t.Evented),C=function(e){function i(i,o,r,a){e.call(this),this.id=i,this.dispatcher=r,this.setEventedParent(a),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({type:"raster"},o),t.extend(this,t.pick(o,["url","scheme","tileSize"]));}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=I(this._options,this.map._requestManager,(function(i,o){e._tileJSONRequest=null,e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(t.extend(e,o),o.bounds&&(e.tileBounds=new P(o.bounds,e.minzoom,e.maxzoom)),t.postTurnstileEvent(o.tiles),t.postMapLoadEvent(o.tiles,e.map._getMapId(),e.map._requestManager._skuToken),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.onRemove=function(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.hasTile=function(t){return !this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.loadTile=function(e,i){var o=this,r=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),this.tileSize);e.request=t.getImage(this.map._requestManager.transformRequest(r,t.ResourceType.Tile),(function(r,a){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(r)e.state="errored",i(r);else if(a){o.map._refreshExpiredTiles&&e.setExpiryData(a),delete a.cacheControl,delete a.expires;var n=o.map.painter.context,s=n.gl;e.texture=o.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.Texture(n,a,s.RGBA,{useMipmap:!0}),e.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),n.extTextureFilterAnisotropic&&s.texParameterf(s.TEXTURE_2D,n.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,n.extTextureFilterAnisotropicMax)),e.state="loaded",t.cacheEntryPossiblyAdded(o.dispatcher),i(null);}}));},i.prototype.abortTile=function(t,e){t.request&&(t.request.cancel(),delete t.request),e();},i.prototype.unloadTile=function(t,e){t.texture&&this.map.painter.saveTileTexture(t.texture),e();},i.prototype.hasTransition=function(){return !1},i}(t.Evented),z=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({type:"raster-dem"},o),this.encoding=o.encoding||"mapbox";}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.serialize=function(){return {type:"raster-dem",url:this.url,tileSize:this.tileSize,tiles:this.tiles,bounds:this.bounds,encoding:this.encoding}},i.prototype.loadTile=function(e,i){var o=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),this.tileSize);function r(t,o){t&&(e.state="errored",i(t)),o&&(e.dem=o,e.needsHillshadePrepare=!0,e.state="loaded",i(null));}e.request=t.getImage(this.map._requestManager.transformRequest(o,t.ResourceType.Tile),function(o,a){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(o)e.state="errored",i(o);else if(a){this.map._refreshExpiredTiles&&e.setExpiryData(a),delete a.cacheControl,delete a.expires;var n=t.window.ImageBitmap&&a instanceof t.window.ImageBitmap&&t.offscreenCanvasSupported()?a:t.browser.getImageData(a,1),s={uid:e.uid,coord:e.tileID,source:this.id,rawImageData:n,encoding:this.encoding};e.actor&&"expired"!==e.state||(e.actor=this.dispatcher.getActor(),e.actor.send("loadDEMTile",s,r.bind(this)));}}.bind(this)),e.neighboringTiles=this._getNeighboringTiles(e.tileID);},i.prototype._getNeighboringTiles=function(e){var i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,n=(i.x+1+o)%o,s=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y).key]={backfilled:!1},i.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y-1).key]={backfilled:!1}),i.y+1<o&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y+1).key]={backfilled:!1}),l},i.prototype.unloadTile=function(t){t.demTexture&&this.map.painter.saveTileTexture(t.demTexture),t.fbo&&(t.fbo.destroy(),delete t.fbo),t.dem&&delete t.dem,delete t.neighboringTiles,t.state="unloaded",t.actor&&t.actor.send("removeDEMTile",{uid:t.uid,source:this.id});},i}(C),D=function(e){function i(i,o,r,a){e.call(this),this.id=i,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this._loaded=!1,this.actor=r.getActor(),this.setEventedParent(a),this._data=o.data,this._options=t.extend({},o),this._collectResourceTiming=o.collectResourceTiming,this._resourceTiming=[],void 0!==o.maxzoom&&(this.maxzoom=o.maxzoom),o.type&&(this.type=o.type),o.attribution&&(this.attribution=o.attribution),this.promoteId=o.promoteId;var n=t.EXTENT/this.tileSize;this.workerOptions=t.extend({source:this.id,cluster:o.cluster||!1,geojsonVtOptions:{buffer:(void 0!==o.buffer?o.buffer:128)*n,tolerance:(void 0!==o.tolerance?o.tolerance:.375)*n,extent:t.EXTENT,maxZoom:this.maxzoom,lineMetrics:o.lineMetrics||!1,generateId:o.generateId||!1},superclusterOptions:{maxZoom:void 0!==o.clusterMaxZoom?Math.min(o.clusterMaxZoom,this.maxzoom-1):this.maxzoom-1,minPoints:Math.max(2,o.clusterMinPoints||2),extent:t.EXTENT,radius:(o.clusterRadius||50)*n,log:!1,generateId:o.generateId||!1},clusterProperties:o.clusterProperties},o.workerOptions);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(i){if(i)e.fire(new t.ErrorEvent(i));else {var o={dataType:"source",sourceDataType:"metadata"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(o.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",o));}}));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setData=function(e){var i=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(e){if(e)i.fire(new t.ErrorEvent(e));else {var o={dataType:"source",sourceDataType:"content"};i._collectResourceTiming&&i._resourceTiming&&i._resourceTiming.length>0&&(o.resourceTiming=i._resourceTiming,i._resourceTiming=[]),i.fire(new t.Event("data",o));}})),this},i.prototype.getClusterExpansionZoom=function(t,e){return this.actor.send("geojson.getClusterExpansionZoom",{clusterId:t,source:this.id},e),this},i.prototype.getClusterChildren=function(t,e){return this.actor.send("geojson.getClusterChildren",{clusterId:t,source:this.id},e),this},i.prototype.getClusterLeaves=function(t,e,i,o){return this.actor.send("geojson.getClusterLeaves",{source:this.id,clusterId:t,limit:e,offset:i},o),this},i.prototype._updateWorkerData=function(e){var i=this;this._loaded=!1;var o=t.extend({},this.workerOptions),r=this._data;"string"==typeof r?(o.request=this.map._requestManager.transformRequest(t.browser.resolveURL(r),t.ResourceType.Source),o.request.collectResourceTiming=this._collectResourceTiming):o.data=JSON.stringify(r),this.actor.send(this.type+".loadData",o,(function(t,r){i._removed||r&&r.abandoned||(i._loaded=!0,r&&r.resourceTiming&&r.resourceTiming[i.id]&&(i._resourceTiming=r.resourceTiming[i.id].slice(0)),i.actor.send(i.type+".coalesce",{source:o.source},null),e(t));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.loadTile=function(e,i){var o=this,r=e.actor?"reloadTile":"loadTile";e.actor=this.actor,e.request=this.actor.send(r,{type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId},(function(t,a){return delete e.request,e.unloadVectorData(),e.aborted?i(null):t?i(t):(e.loadVectorData(a,o.map.painter,"reloadTile"===r),i(null))}));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.aborted=!0;},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id});},i.prototype.onRemove=function(){this._removed=!0,this.actor.send("removeSource",{type:this.type,source:this.id});},i.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},i.prototype.hasTransition=function(){return !1},i}(t.Evented),M=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),L=function(e){function i(t,i,o,r){e.call(this),this.id=t,this.dispatcher=o,this.coordinates=i.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=i;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(e,i){var o=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._requestManager.transformRequest(this.url,t.ResourceType.Image),(function(r,a){o._loaded=!0,r?o.fire(new t.ErrorEvent(r)):a&&(o.image=a,e&&(o.coordinates=e),i&&i(),o._finishLoading());}));},i.prototype.loaded=function(){return this._loaded},i.prototype.updateImage=function(t){var e=this;return this.image&&t.url?(this.options.url=t.url,this.load(t.coordinates,(function(){e.texture=null;})),this):this},i.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setCoordinates=function(e){var i=this;this.coordinates=e;var o=e.map(t.MercatorCoordinate.fromLngLat);this.tileID=function(e){for(var i=1/0,o=1/0,r=-1/0,a=-1/0,n=0,s=e;n<s.length;n+=1){var l=s[n];i=Math.min(i,l.x),o=Math.min(o,l.y),r=Math.max(r,l.x),a=Math.max(a,l.y);}var c=Math.max(r-i,a-o),u=Math.max(0,Math.floor(-Math.log(c)/Math.LN2)),h=Math.pow(2,u);return new t.CanonicalTileID(u,Math.floor((i+r)/2*h),Math.floor((o+a)/2*h))}(o),this.minzoom=this.maxzoom=this.tileID.z;var r=o.map((function(t){return i.tileID.getTilePoint(t)._round()}));return this._boundsArray=new t.StructArrayLayout4i8,this._boundsArray.emplaceBack(r[0].x,r[0].y,0,0),this._boundsArray.emplaceBack(r[1].x,r[1].y,t.EXTENT,0),this._boundsArray.emplaceBack(r[3].x,r[3].y,0,t.EXTENT),this._boundsArray.emplaceBack(r[2].x,r[2].y,t.EXTENT,t.EXTENT),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this},i.prototype.prepare=function(){if(0!==Object.keys(this.tiles).length&&this.image){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture||(this.texture=new t.Texture(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.loadTile=function(t,e){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={},e(null)):(t.state="errored",e(null));},i.prototype.serialize=function(){return {type:"image",url:this.options.url,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return !1},i}(t.Evented),A=function(e){function i(t,i,o,r){e.call(this,t,i,o,r),this.roundZoom=!0,this.type="video",this.options=i;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1;var i=this.options;this.urls=[];for(var o=0,r=i.urls;o<r.length;o+=1)this.urls.push(this.map._requestManager.transformRequest(r[o],t.ResourceType.Source).url);t.getVideo(this.urls,(function(i,o){e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(e.video=o,e.video.loop=!0,e.video.addEventListener("playing",(function(){e.map.triggerRepaint();})),e.map&&e.video.play(),e._finishLoading());}));},i.prototype.pause=function(){this.video&&this.video.pause();},i.prototype.play=function(){this.video&&this.video.play();},i.prototype.seek=function(e){if(this.video){var i=this.video.seekable;e<i.start(0)||e>i.end(0)?this.fire(new t.ErrorEvent(new t.ValidationError("sources."+this.id,null,"Playback for this video can be set only between the "+i.start(0)+" and "+i.end(0)+"-second mark."))):this.video.currentTime=e;}},i.prototype.getVideo=function(){return this.video},i.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));},i.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.Texture(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"video",urls:this.urls,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this.video&&!this.video.paused},i}(L),R=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),o.coordinates?Array.isArray(o.coordinates)&&4===o.coordinates.length&&!o.coordinates.some((function(t){return !Array.isArray(t)||2!==t.length||t.some((function(t){return "number"!=typeof t}))}))||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "coordinates"'))),o.animate&&"boolean"!=typeof o.animate&&this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'optional "animate" property must be a boolean value'))),o.canvas?"string"==typeof o.canvas||o.canvas instanceof t.window.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "canvas"'))),this.options=o,this.animate=void 0===o.animate||o.animate;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof t.window.HTMLCanvasElement?this.options.canvas:t.window.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());},i.prototype.getCanvas=function(){return this.canvas},i.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();},i.prototype.onRemove=function(){this.pause();},i.prototype.prepare=function(){var e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var i=this.map.painter.context,o=i.gl;for(var r in this.boundsBuffer||(this.boundsBuffer=i.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.Texture(i,this.canvas,o.RGBA,{premultiply:!0}),this.tiles){var a=this.tiles[r];"loaded"!==a.state&&(a.state="loaded",a.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"canvas",coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this._playing},i.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t<e.length;t+=1){var i=e[t];if(isNaN(i)||i<=0)return !0}return !1},i}(L),k={vector:S,raster:C,"raster-dem":z,geojson:D,video:A,image:L,canvas:R};function B(e,i){var o=t.identity([]);return t.translate(o,o,[1,1,0]),t.scale(o,o,[.5*e.width,.5*e.height,1]),t.multiply(o,o,e.calculatePosMatrix(i.toUnwrapped()))}function O(t,e,i,o,r,a){var n=function(t,e,i){if(t)for(var o=0,r=t;o<r.length;o+=1){var a=e[r[o]];if(a&&a.source===i&&"fill-extrusion"===a.type)return !0}else for(var n in e){var s=e[n];if(s.source===i&&"fill-extrusion"===s.type)return !0}return !1}(r&&r.layers,e,t.id),s=a.maxPitchScaleFactor(),l=t.tilesIn(o,s,n);l.sort(F);for(var c=[],u=0,h=l;u<h.length;u+=1){var p=h[u];c.push({wrappedTileID:p.tileID.wrapped().key,queryResults:p.tile.queryRenderedFeatures(e,i,t._state,p.queryGeometry,p.cameraQueryGeometry,p.scale,r,a,s,B(t.transform,p.tileID))});}var d=function(t){for(var e={},i={},o=0,r=t;o<r.length;o+=1){var a=r[o],n=a.queryResults,s=a.wrappedTileID,l=i[s]=i[s]||{};for(var c in n)for(var u=n[c],h=l[c]=l[c]||{},p=e[c]=e[c]||[],d=0,_=u;d<_.length;d+=1){var f=_[d];h[f.featureIndex]||(h[f.featureIndex]=!0,p.push(f));}}return e}(c);for(var _ in d)d[_].forEach((function(e){var i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}));return d}function F(t,e){var i=t.tileID,o=e.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}var U=function(t,e){this.max=t,this.onRemove=e,this.reset();};U.prototype.reset=function(){for(var t in this.data)for(var e=0,i=this.data[t];e<i.length;e+=1){var o=i[e];o.timeout&&clearTimeout(o.timeout),this.onRemove(o.value);}return this.data={},this.order=[],this},U.prototype.add=function(t,e,i){var o=this,r=t.wrapped().key;void 0===this.data[r]&&(this.data[r]=[]);var a={value:e,timeout:void 0};if(void 0!==i&&(a.timeout=setTimeout((function(){o.remove(t,a);}),i)),this.data[r].push(a),this.order.push(r),this.order.length>this.max){var n=this._getAndRemoveByKey(this.order[0]);n&&this.onRemove(n);}return this},U.prototype.has=function(t){return t.wrapped().key in this.data},U.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},U.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},U.prototype.getByKey=function(t){var e=this.data[t];return e?e[0].value:null},U.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},U.prototype.remove=function(t,e){if(!this.has(t))return this;var i=t.wrapped().key,o=void 0===e?0:this.data[i].indexOf(e),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this},U.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this},U.prototype.filter=function(t){var e=[];for(var i in this.data)for(var o=0,r=this.data[i];o<r.length;o+=1){var a=r[o];t(a.value)||e.push(a);}for(var n=0,s=e;n<s.length;n+=1){var l=s[n];this.remove(l.value.tileID,l);}};var N=function(t,e,i){this.context=t;var o=t.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),t.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};N.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer);},N.prototype.updateData=function(t){var e=this.context.gl;this.context.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer);},N.prototype.destroy=function(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);};var Z={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},j=function(t,e,i,o){this.length=e.length,this.attributes=i,this.itemSize=e.bytesPerElement,this.dynamicDraw=o,this.context=t;var r=t.gl;this.buffer=r.createBuffer(),t.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};j.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer);},j.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer);},j.prototype.enableAttributes=function(t,e){for(var i=0;i<this.attributes.length;i++){var o=e.attributes[this.attributes[i].name];void 0!==o&&t.enableVertexAttribArray(o);}},j.prototype.setVertexAttribPointers=function(t,e,i){for(var o=0;o<this.attributes.length;o++){var r=this.attributes[o],a=e.attributes[r.name];void 0!==a&&t.vertexAttribPointer(a,r.components,t[Z[r.type]],!1,this.itemSize,r.offset+this.itemSize*(i||0));}},j.prototype.destroy=function(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);};var q=function(t){this.gl=t.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1;};q.prototype.get=function(){return this.current},q.prototype.set=function(t){},q.prototype.getDefault=function(){return this.default},q.prototype.setDefault=function(){this.set(this.default);};var V=function(e){function i(){e.apply(this,arguments);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getDefault=function(){return t.Color.transparent},i.prototype.set=function(t){var e=this.current;(t.r!==e.r||t.g!==e.g||t.b!==e.b||t.a!==e.a||this.dirty)&&(this.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1);},i}(q),G=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 1},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.clearDepth(t),this.current=t,this.dirty=!1);},e}(q),W=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.clearStencil(t),this.current=t,this.dirty=!1);},e}(q),X=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return [!0,!0,!0,!0]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||t[3]!==e[3]||this.dirty)&&(this.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1);},e}(q),H=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.depthMask(t),this.current=t,this.dirty=!1);},e}(q),K=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 255},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.stencilMask(t),this.current=t,this.dirty=!1);},e}(q),Y=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return {func:this.gl.ALWAYS,ref:0,mask:255}},e.prototype.set=function(t){var e=this.current;(t.func!==e.func||t.ref!==e.ref||t.mask!==e.mask||this.dirty)&&(this.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t,this.dirty=!1);},e}(q),J=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [t.KEEP,t.KEEP,t.KEEP]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||this.dirty)&&(this.gl.stencilOp(t[0],t[1],t[2]),this.current=t,this.dirty=!1);},e}(q),Q=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t,this.dirty=!1;}},e}(q),$=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return [0,1]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||this.dirty)&&(this.gl.depthRange(t[0],t[1]),this.current=t,this.dirty=!1);},e}(q),tt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t,this.dirty=!1;}},e}(q),et=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.LESS},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.depthFunc(t),this.current=t,this.dirty=!1);},e}(q),it=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t,this.dirty=!1;}},e}(q),ot=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [t.ONE,t.ZERO]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||this.dirty)&&(this.gl.blendFunc(t[0],t[1]),this.current=t,this.dirty=!1);},e}(q),rt=function(e){function i(){e.apply(this,arguments);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getDefault=function(){return t.Color.transparent},i.prototype.set=function(t){var e=this.current;(t.r!==e.r||t.g!==e.g||t.b!==e.b||t.a!==e.a||this.dirty)&&(this.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1);},i}(q),at=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.FUNC_ADD},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.blendEquation(t),this.current=t,this.dirty=!1);},e}(q),nt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this.current=t,this.dirty=!1;}},e}(q),st=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.BACK},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.cullFace(t),this.current=t,this.dirty=!1);},e}(q),lt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.CCW},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.frontFace(t),this.current=t,this.dirty=!1);},e}(q),ct=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.useProgram(t),this.current=t,this.dirty=!1);},e}(q),ut=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.TEXTURE0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.activeTexture(t),this.current=t,this.dirty=!1);},e}(q),ht=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [0,0,t.drawingBufferWidth,t.drawingBufferHeight]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||t[3]!==e[3]||this.dirty)&&(this.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1);},e}(q),pt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t,this.dirty=!1;}},e}(q),dt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t,this.dirty=!1;}},e}(q),_t=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t,this.dirty=!1;}},e}(q),ft=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t,this.dirty=!1;}},e}(q),mt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){var e=this.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t,this.dirty=!1;},e}(q),gt=function(t){function e(e){t.call(this,e),this.vao=e.extVertexArrayObject;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){this.vao&&(t!==this.current||this.dirty)&&(this.vao.bindVertexArrayOES(t),this.current=t,this.dirty=!1);},e}(q),vt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 4},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t,this.dirty=!1;}},e}(q),yt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t,this.dirty=!1;}},e}(q),xt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t),this.current=t,this.dirty=!1;}},e}(q),bt=function(t){function e(e,i){t.call(this,e),this.context=e,this.parent=i;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e}(q),wt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.setDirty=function(){this.dirty=!0;},e.prototype.set=function(t){if(t!==this.current||this.dirty){this.context.bindFramebuffer.set(this.parent);var e=this.gl;e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1;}},e}(bt),Tt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){if(t!==this.current||this.dirty){this.context.bindFramebuffer.set(this.parent);var e=this.gl;e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t,this.dirty=!1;}},e}(bt),Et=function(t,e,i,o){this.context=t,this.width=e,this.height=i;var r=this.framebuffer=t.gl.createFramebuffer();this.colorAttachment=new wt(t,r),o&&(this.depthAttachment=new Tt(t,r));};Et.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();if(e&&t.deleteTexture(e),this.depthAttachment){var i=this.depthAttachment.get();i&&t.deleteRenderbuffer(i);}t.deleteFramebuffer(this.framebuffer);};var It=function(t,e,i){this.func=t,this.mask=e,this.range=i;};It.ReadOnly=!1,It.ReadWrite=!0,It.disabled=new It(519,It.ReadOnly,[0,1]);var Pt=function(t,e,i,o,r,a){this.test=t,this.ref=e,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;};Pt.disabled=new Pt({func:519,mask:0},0,0,7680,7680,7680);var St=function(t,e,i){this.blendFunction=t,this.blendColor=e,this.mask=i;};St.disabled=new St(St.Replace=[1,0],t.Color.transparent,[!1,!1,!1,!1]),St.unblended=new St(St.Replace,t.Color.transparent,[!0,!0,!0,!0]),St.alphaBlended=new St([1,771],t.Color.transparent,[!0,!0,!0,!0]);var Ct=function(t,e,i){this.enable=t,this.mode=e,this.frontFace=i;};Ct.disabled=new Ct(!1,1029,2305),Ct.backCCW=new Ct(!0,1029,2305);var zt=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.clearColor=new V(this),this.clearDepth=new G(this),this.clearStencil=new W(this),this.colorMask=new X(this),this.depthMask=new H(this),this.stencilMask=new K(this),this.stencilFunc=new Y(this),this.stencilOp=new J(this),this.stencilTest=new Q(this),this.depthRange=new $(this),this.depthTest=new tt(this),this.depthFunc=new et(this),this.blend=new it(this),this.blendFunc=new ot(this),this.blendColor=new rt(this),this.blendEquation=new at(this),this.cullFace=new nt(this),this.cullFaceSide=new st(this),this.frontFace=new lt(this),this.program=new ct(this),this.activeTexture=new ut(this),this.viewport=new ht(this),this.bindFramebuffer=new pt(this),this.bindRenderbuffer=new dt(this),this.bindTexture=new _t(this),this.bindVertexBuffer=new ft(this),this.bindElementBuffer=new mt(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new gt(this),this.pixelStoreUnpack=new vt(this),this.pixelStoreUnpackPremultiplyAlpha=new yt(this),this.pixelStoreUnpackFlipY=new xt(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&(t.getExtension("OES_texture_half_float_linear"),this.extRenderToTextureHalfFloat=t.getExtension("EXT_color_buffer_half_float")),this.extTimerQuery=t.getExtension("EXT_disjoint_timer_query");};zt.prototype.setDefault=function(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault();},zt.prototype.setDirty=function(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.extVertexArrayObject&&(this.bindVertexArrayOES.dirty=!0),this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0;},zt.prototype.createIndexBuffer=function(t,e){return new N(this,t,e)},zt.prototype.createVertexBuffer=function(t,e,i){return new j(this,t,e,i)},zt.prototype.createRenderbuffer=function(t,e,i){var o=this.gl,r=o.createRenderbuffer();return this.bindRenderbuffer.set(r),o.renderbufferStorage(o.RENDERBUFFER,t,e,i),this.bindRenderbuffer.set(null),r},zt.prototype.createFramebuffer=function(t,e,i){return new Et(this,t,e,i)},zt.prototype.clear=function(t){var e=t.color,i=t.depth,o=this.gl,r=0;e&&(r|=o.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==i&&(r|=o.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(i),this.depthMask.set(!0)),o.clear(r);},zt.prototype.setCullFace=function(t){!1===t.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(t.mode),this.frontFace.set(t.frontFace));},zt.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1);},zt.prototype.setStencilMode=function(t){t.test.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1);},zt.prototype.setColorMode=function(e){t.deepEqual(e.blendFunction,St.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask);},zt.prototype.unbindVAO=function(){this.extVertexArrayObject&&this.bindVertexArrayOES.set(null);};var Dt=function(e){function i(i,o,r){var a=this;e.call(this),this.id=i,this.dispatcher=r,this.on("data",(function(t){"source"===t.dataType&&"metadata"===t.sourceDataType&&(a._sourceLoaded=!0),a._sourceLoaded&&!a._paused&&"source"===t.dataType&&"content"===t.sourceDataType&&(a.reload(),a.transform&&a.update(a.transform));})),this.on("error",(function(){a._sourceErrored=!0;})),this._source=function(e,i,o,r){var a=new k[i.type](e,i,o,r);if(a.id!==e)throw new Error("Expected Source id to be "+e+" instead of "+a.id);return t.bindAll(["load","abort","unload","serialize","prepare"],a),a}(i,o,r,this),this._tiles={},this._cache=new U(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new t.SourceFeatureState;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.onAdd=function(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._source&&this._source.onAdd&&this._source.onAdd(t);},i.prototype.onRemove=function(t){this._source&&this._source.onRemove&&this._source.onRemove(t);},i.prototype.loaded=function(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;for(var t in this._tiles){var e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return !1}return !0},i.prototype.getSource=function(){return this._source},i.prototype.pause=function(){this._paused=!0;},i.prototype.resume=function(){if(this._paused){var t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform);}},i.prototype._loadTile=function(t,e){return this._source.loadTile(t,e)},i.prototype._unloadTile=function(t){if(this._source.unloadTile)return this._source.unloadTile(t,(function(){}))},i.prototype._abortTile=function(t){if(this._source.abortTile)return this._source.abortTile(t,(function(){}))},i.prototype.serialize=function(){return this._source.serialize()},i.prototype.prepare=function(t){for(var e in this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null),this._tiles){var i=this._tiles[e];i.upload(t),i.prepare(this.map.style.imageManager);}},i.prototype.getIds=function(){return t.values(this._tiles).map((function(t){return t.tileID})).sort(Mt).map((function(t){return t.key}))},i.prototype.getRenderableIds=function(e){var i=this,o=[];for(var r in this._tiles)this._isIdRenderable(r,e)&&o.push(this._tiles[r]);return e?o.sort((function(e,o){var r=e.tileID,a=o.tileID,n=new t.Point(r.canonical.x,r.canonical.y)._rotate(i.transform.angle),s=new t.Point(a.canonical.x,a.canonical.y)._rotate(i.transform.angle);return r.overscaledZ-a.overscaledZ||s.y-n.y||s.x-n.x})).map((function(t){return t.tileID.key})):o.map((function(t){return t.tileID})).sort(Mt).map((function(t){return t.key}))},i.prototype.hasRenderableParent=function(t){var e=this.findLoadedParent(t,0);return !!e&&this._isIdRenderable(e.tileID.key)},i.prototype._isIdRenderable=function(t,e){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]&&(e||!this._tiles[t].holdingForFade())},i.prototype.reload=function(){if(this._paused)this._shouldReloadOnResume=!0;else for(var t in this._cache.reset(),this._tiles)"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");},i.prototype._reloadTile=function(t,e){var i=this._tiles[t];i&&("loading"!==i.state&&(i.state=e),this._loadTile(i,this._tileLoaded.bind(this,i,t,e)));},i.prototype._tileLoaded=function(e,i,o,r){if(r)return e.state="errored",void(404!==r.status?this._source.fire(new t.ErrorEvent(r,{tile:e})):this.update(this.transform));e.timeAdded=t.browser.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID}));},i.prototype._backfillDEM=function(t){for(var e=this.getRenderableIds(),i=0;i<e.length;i++){var o=e[i];if(t.neighboringTiles&&t.neighboringTiles[o]){var r=this.getTileByID(o);a(t,r),a(r,t);}}function a(t,e){t.needsHillshadePrepare=!0;var i=e.tileID.canonical.x-t.tileID.canonical.x,o=e.tileID.canonical.y-t.tileID.canonical.y,r=Math.pow(2,t.tileID.canonical.z),a=e.tileID.key;0===i&&0===o||Math.abs(o)>1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,o),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)));}},i.prototype.getTile=function(t){return this.getTileByID(t.key)},i.prototype.getTileByID=function(t){return this._tiles[t]},i.prototype._retainLoadedChildren=function(t,e,i,o){for(var r in this._tiles){var a=this._tiles[r];if(!(o[r]||!a.hasData()||a.tileID.overscaledZ<=e||a.tileID.overscaledZ>i)){for(var n=a.tileID;a&&a.tileID.overscaledZ>e+1;){var s=a.tileID.scaledTo(a.tileID.overscaledZ-1);(a=this._tiles[s.key])&&a.hasData()&&(n=s);}for(var l=n;l.overscaledZ>e;)if(t[(l=l.scaledTo(l.overscaledZ-1)).key]){o[n.key]=n;break}}}},i.prototype.findLoadedParent=function(t,e){if(t.key in this._loadedParentTiles){var i=this._loadedParentTiles[t.key];return i&&i.tileID.overscaledZ>=e?i:null}for(var o=t.overscaledZ-1;o>=e;o--){var r=t.scaledTo(o),a=this._getLoadedTile(r);if(a)return a}},i.prototype._getLoadedTile=function(t){var e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(t.wrapped().key)},i.prototype.updateCacheSize=function(t){var e=Math.ceil(t.width/this._source.tileSize)+1,i=Math.ceil(t.height/this._source.tileSize)+1,o=Math.floor(e*i*5),r="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(r);},i.prototype.handleWrapJump=function(t){var e=Math.round((t-(void 0===this._prevLng?t:this._prevLng))/360);if(this._prevLng=t,e){var i={};for(var o in this._tiles){var r=this._tiles[o];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+e),i[r.tileID.key]=r;}for(var a in this._tiles=i,this._timers)clearTimeout(this._timers[a]),delete this._timers[a];for(var n in this._tiles)this._setTileReloadTimer(n,this._tiles[n]);}},i.prototype.update=function(e){var o=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var r;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)})):(r=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(r=r.filter((function(t){return o._source.hasTile(t)})))):r=[];var a=e.coveringZoomLevel(this._source),n=Math.max(a-i.maxOverzooming,this._source.minzoom),s=Math.max(a+i.maxUnderzooming,this._source.minzoom),l=this._updateRetainedTiles(r,a);if(Lt(this._source.type)){for(var c={},u={},h=0,p=Object.keys(l);h<p.length;h+=1){var d=p[h],_=l[d],f=this._tiles[d];if(f&&!(f.fadeEndTime&&f.fadeEndTime<=t.browser.now())){var m=this.findLoadedParent(_,n);m&&(this._addTile(m.tileID),c[m.tileID.key]=m.tileID),u[d]=_;}}for(var g in this._retainLoadedChildren(u,a,s,l),c)l[g]||(this._coveredTiles[g]=!0,l[g]=c[g]);}for(var v in l)this._tiles[v].clearFadeHold();for(var y=0,x=t.keysDifference(this._tiles,l);y<x.length;y+=1){var b=x[y],w=this._tiles[b];w.hasSymbolBuckets&&!w.holdingForFade()?w.setHoldDuration(this.map._fadeDuration):w.hasSymbolBuckets&&!w.symbolFadeFinished()||this._removeTile(b);}this._updateLoadedParentTileCache();}},i.prototype.releaseSymbolFadeTiles=function(){for(var t in this._tiles)this._tiles[t].holdingForFade()&&this._removeTile(t);},i.prototype._updateRetainedTiles=function(t,e){for(var o={},r={},a=Math.max(e-i.maxOverzooming,this._source.minzoom),n=Math.max(e+i.maxUnderzooming,this._source.minzoom),s={},l=0,c=t;l<c.length;l+=1){var u=c[l],h=this._addTile(u);o[u.key]=u,h.hasData()||e<this._source.maxzoom&&(s[u.key]=u);}this._retainLoadedChildren(s,e,n,o);for(var p=0,d=t;p<d.length;p+=1){var _=d[p],f=this._tiles[_.key];if(!f.hasData()){if(e+1>this._source.maxzoom){var m=_.children(this._source.maxzoom)[0],g=this.getTile(m);if(g&&g.hasData()){o[m.key]=m;continue}}else {var v=_.children(this._source.maxzoom);if(o[v[0].key]&&o[v[1].key]&&o[v[2].key]&&o[v[3].key])continue}for(var y=f.wasRequested(),x=_.overscaledZ-1;x>=a;--x){var b=_.scaledTo(x);if(r[b.key])break;if(r[b.key]=!0,!(f=this.getTile(b))&&y&&(f=this._addTile(b)),f&&(o[b.key]=b,y=f.wasRequested(),f.hasData()))break}}}return o},i.prototype._updateLoadedParentTileCache=function(){for(var t in this._loadedParentTiles={},this._tiles){for(var e=[],i=void 0,o=this._tiles[t].tileID;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}e.push(o.key);var r=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(r))break;o=r;}for(var a=0,n=e;a<n.length;a+=1)this._loadedParentTiles[n[a]]=i;}},i.prototype._addTile=function(e){var i=this._tiles[e.key];if(i)return i;(i=this._cache.getAndRemove(e))&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));var o=Boolean(i);return o||(i=new t.Tile(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,this._tileLoaded.bind(this,i,e.key,i.state))),i?(i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.Event("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i):null},i.prototype._setTileReloadTimer=function(t,e){var i=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var o=e.getExpiryTimeout();o&&(this._timers[t]=setTimeout((function(){i._reloadTile(t,"expired"),delete i._timers[t];}),o));},i.prototype._removeTile=function(t){var e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()&&"reloading"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));},i.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset();},i.prototype.tilesIn=function(e,i,o){var r=this,a=[],n=this.transform;if(!n)return a;for(var s=o?n.getCameraQueryGeometry(e):e,l=e.map((function(t){return n.pointCoordinate(t)})),c=s.map((function(t){return n.pointCoordinate(t)})),u=this.getIds(),h=1/0,p=1/0,d=-1/0,_=-1/0,f=0,m=c;f<m.length;f+=1){var g=m[f];h=Math.min(h,g.x),p=Math.min(p,g.y),d=Math.max(d,g.x),_=Math.max(_,g.y);}for(var v=function(e){var o=r._tiles[u[e]];if(!o.holdingForFade()){var s=o.tileID,f=Math.pow(2,n.zoom-o.tileID.overscaledZ),m=i*o.queryPadding*t.EXTENT/o.tileSize/f,g=[s.getTilePoint(new t.MercatorCoordinate(h,p)),s.getTilePoint(new t.MercatorCoordinate(d,_))];if(g[0].x-m<t.EXTENT&&g[0].y-m<t.EXTENT&&g[1].x+m>=0&&g[1].y+m>=0){var v=l.map((function(t){return s.getTilePoint(t)})),y=c.map((function(t){return s.getTilePoint(t)}));a.push({tile:o,tileID:s,queryGeometry:v,cameraQueryGeometry:y,scale:f});}}},y=0;y<u.length;y++)v(y);return a},i.prototype.getVisibleCoordinates=function(t){for(var e=this,i=this.getRenderableIds(t).map((function(t){return e._tiles[t].tileID})),o=0,r=i;o<r.length;o+=1){var a=r[o];a.posMatrix=this.transform.calculatePosMatrix(a.toUnwrapped());}return i},i.prototype.hasTransition=function(){if(this._source.hasTransition())return !0;if(Lt(this._source.type))for(var e in this._tiles){var i=this._tiles[e];if(void 0!==i.fadeEndTime&&i.fadeEndTime>=t.browser.now())return !0}return !1},i.prototype.setFeatureState=function(t,e,i){this._state.updateState(t=t||"_geojsonTileLayer",e,i);},i.prototype.removeFeatureState=function(t,e,i){this._state.removeFeatureState(t=t||"_geojsonTileLayer",e,i);},i.prototype.getFeatureState=function(t,e){return this._state.getState(t=t||"_geojsonTileLayer",e)},i.prototype.setDependencies=function(t,e,i){var o=this._tiles[t];o&&o.setDependencies(e,i);},i.prototype.reloadTilesForDependencies=function(t,e){for(var i in this._tiles)this._tiles[i].hasDependency(t,e)&&this._reloadTile(i,"reloading");this._cache.filter((function(i){return !i.hasDependency(t,e)}));},i}(t.Evented);function Mt(t,e){var i=Math.abs(2*t.wrap)-+(t.wrap<0),o=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||o-i||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function Lt(t){return "raster"===t||"image"===t||"video"===t}function At(){return new t.window.Worker(Hr.workerUrl)}Dt.maxOverzooming=10,Dt.maxUnderzooming=3;var Rt="mapboxgl_preloaded_worker_pool",kt=function(){this.active={};};kt.prototype.acquire=function(t){if(!this.workers)for(this.workers=[];this.workers.length<kt.workerCount;)this.workers.push(new At);return this.active[t]=!0,this.workers.slice()},kt.prototype.release=function(t){delete this.active[t],0===this.numActive()&&(this.workers.forEach((function(t){t.terminate();})),this.workers=null);},kt.prototype.isPreloaded=function(){return !!this.active[Rt]},kt.prototype.numActive=function(){return Object.keys(this.active).length};var Bt,Ot=Math.floor(t.browser.hardwareConcurrency/2);function Ft(){return Bt||(Bt=new kt),Bt}function Ut(e,i){var o={};for(var r in e)"ref"!==r&&(o[r]=e[r]);return t.refProperties.forEach((function(t){t in i&&(o[t]=i[t]);})),o}function Nt(t){t=t.slice();for(var e=Object.create(null),i=0;i<t.length;i++)e[t[i].id]=t[i];for(var o=0;o<t.length;o++)"ref"in t[o]&&(t[o]=Ut(t[o],e[t[o].ref]));return t}kt.workerCount=Math.max(Math.min(Ot,6),1);var Zt={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight"};function jt(t,e,i){i.push({command:Zt.addSource,args:[t,e[t]]});}function qt(t,e,i){e.push({command:Zt.removeSource,args:[t]}),i[t]=!0;}function Vt(t,e,i,o){qt(t,i,o),jt(t,e,i);}function Gt(e,i,o){var r;for(r in e[o])if(e[o].hasOwnProperty(r)&&"data"!==r&&!t.deepEqual(e[o][r],i[o][r]))return !1;for(r in i[o])if(i[o].hasOwnProperty(r)&&"data"!==r&&!t.deepEqual(e[o][r],i[o][r]))return !1;return !0}function Wt(e,i,o,r,a,n){var s;for(s in i=i||{},e=e||{})e.hasOwnProperty(s)&&(t.deepEqual(e[s],i[s])||o.push({command:n,args:[r,s,i[s],a]}));for(s in i)i.hasOwnProperty(s)&&!e.hasOwnProperty(s)&&(t.deepEqual(e[s],i[s])||o.push({command:n,args:[r,s,i[s],a]}));}function Xt(t){return t.id}function Ht(t,e){return t[e.id]=e,t}var Kt=function(t,e){this.reset(t,e);};Kt.prototype.reset=function(t,e){this.points=t||[],this._distances=[0];for(var i=1;i<this.points.length;i++)this._distances[i]=this._distances[i-1]+this.points[i].dist(this.points[i-1]);this.length=this._distances[this._distances.length-1],this.padding=Math.min(e||0,.5*this.length),this.paddedLength=this.length-2*this.padding;},Kt.prototype.lerp=function(e){if(1===this.points.length)return this.points[0];e=t.clamp(e,0,1);for(var i=1,o=this._distances[i],r=e*this.paddedLength+this.padding;o<r&&i<this._distances.length;)o=this._distances[++i];var a=i-1,n=this._distances[a],s=o-n,l=s>0?(r-n)/s:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))};var Yt=function(t,e,i){var o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(var a=0;a<this.xCellCount*this.yCellCount;a++)o.push([]),r.push([]);this.circleKeys=[],this.boxKeys=[],this.bboxes=[],this.circles=[],this.width=t,this.height=e,this.xScale=this.xCellCount/t,this.yScale=this.yCellCount/e,this.boxUid=0,this.circleUid=0;};function Jt(e,i,o,r,a){var n=t.create();return i?(t.scale(n,n,[1/a,1/a,1]),o||t.rotateZ(n,n,r.angle)):t.multiply(n,r.labelPlaneMatrix,e),n}function Qt(e,i,o,r,a){if(i){var n=t.clone(e);return t.scale(n,n,[a,a,1]),o||t.rotateZ(n,n,-r.angle),n}return r.glCoordMatrix}function $t(e,i){var o=[e.x,e.y,0,1];ue(o,o,i);var r=o[3];return {point:new t.Point(o[0]/r,o[1]/r),signedDistanceFromCamera:r}}function te(t,e){return .5+t/e*.5}function ee(t,e){var i=t[0]/t[3],o=t[1]/t[3];return i>=-e[0]&&i<=e[0]&&o>=-e[1]&&o<=e[1]}function ie(e,i,o,r,a,n,s,l){var c=r?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,o.transform.zoom),h=[256/o.width*2+1,256/o.height*2+1],p=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;p.clear();for(var d=e.lineVertexArray,_=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,f=o.transform.width/o.transform.height,m=!1,g=0;g<_.length;g++){var v=_.get(g);if(v.hidden||v.writingMode===t.WritingMode.vertical&&!m)ce(v.numGlyphs,p);else {m=!1;var y=[v.anchorX,v.anchorY,0,1];if(t.transformMat4(y,y,i),ee(y,h)){var x=te(o.transform.cameraToCenterDistance,y[3]),b=t.evaluateSizeForFeature(c,u,v),w=s?b/x:b*x,T=new t.Point(v.anchorX,v.anchorY),E=$t(T,a).point,I={},P=ae(v,w,!1,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f);m=P.useVertical,(P.notEnoughRoom||m||P.needsFlipping&&ae(v,w,!0,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f).notEnoughRoom)&&ce(v.numGlyphs,p);}else ce(v.numGlyphs,p);}}r?e.text.dynamicLayoutVertexBuffer.updateData(p):e.icon.dynamicLayoutVertexBuffer.updateData(p);}function oe(t,e,i,o,r,a,n,s,l,c,u){var h=s.glyphStartIndex+s.numGlyphs,p=s.lineStartIndex,d=s.lineStartIndex+s.lineLength,_=e.getoffsetX(s.glyphStartIndex),f=e.getoffsetX(h-1),m=se(t*_,i,o,r,a,n,s.segment,p,d,l,c,u);if(!m)return null;var g=se(t*f,i,o,r,a,n,s.segment,p,d,l,c,u);return g?{first:m,last:g}:null}function re(e,i,o,r){return e===t.WritingMode.horizontal&&Math.abs(o.y-i.y)>Math.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.WritingMode.vertical?i.y<o.y:i.x>o.x)?{needsFlipping:!0}:null}function ae(e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=i/24,g=e.lineOffsetX*m,v=e.lineOffsetY*m;if(e.numGlyphs>1){var y=e.glyphStartIndex+e.numGlyphs,x=e.lineStartIndex,b=e.lineStartIndex+e.lineLength,w=oe(m,l,g,v,o,h,p,e,c,n,d);if(!w)return {notEnoughRoom:!0};var T=$t(w.first.point,s).point,E=$t(w.last.point,s).point;if(r&&!o){var I=re(e.writingMode,T,E,_);if(I)return I}f=[w.first];for(var P=e.glyphStartIndex+1;P<y-1;P++)f.push(se(m*l.getoffsetX(P),g,v,o,h,p,e.segment,x,b,c,n,d));f.push(w.last);}else {if(r&&!o){var S=$t(p,a).point,C=e.lineStartIndex+e.segment+1,z=new t.Point(c.getx(C),c.gety(C)),D=$t(z,a),M=D.signedDistanceFromCamera>0?D.point:ne(p,z,S,1,a),L=re(e.writingMode,S,M,_);if(L)return L}var A=se(m*l.getoffsetX(e.glyphStartIndex),g,v,o,h,p,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,n,d);if(!A)return {notEnoughRoom:!0};f=[A];}for(var R=0,k=f;R<k.length;R+=1){var B=k[R];t.addDynamicAttributes(u,B.point,B.angle);}return {}}function ne(t,e,i,o,r){var a=$t(t.add(t.sub(e)._unit()),r).point,n=i.sub(a);return i.add(n._mult(o/n.mag()))}function se(e,i,o,r,a,n,s,l,c,u,h,p){var d=r?e-i:e+i,_=d>0?1:-1,f=0;r&&(_*=-1,f=Math.PI),_<0&&(f+=Math.PI);for(var m=_>0?l+s:l+s+1,g=a,v=a,y=0,x=0,b=Math.abs(d),w=[];y+x<=b;){if((m+=_)<l||m>=c)return null;if(v=g,w.push(g),void 0===(g=p[m])){var T=new t.Point(u.getx(m),u.gety(m)),E=$t(T,h);if(E.signedDistanceFromCamera>0)g=p[m]=E.point;else {var I=m-_;g=ne(0===y?n:new t.Point(u.getx(I),u.gety(I)),T,v,b-y+1,h);}}y+=x,x=v.dist(g);}var P=(b-y)/x,S=g.sub(v),C=S.mult(P)._add(v);C._add(S._unit()._perp()._mult(o*_));var z=f+Math.atan2(g.y-v.y,g.x-v.x);return w.push(C),{point:C,angle:z,path:w}}Yt.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},Yt.prototype.insert=function(t,e,i,o,r){this._forEachCell(e,i,o,r,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(i),this.bboxes.push(o),this.bboxes.push(r);},Yt.prototype.insertCircle=function(t,e,i,o){this._forEachCell(e-o,i-o,e+o,i+o,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(i),this.circles.push(o);},Yt.prototype._insertBoxCell=function(t,e,i,o,r,a){this.boxCells[r].push(a);},Yt.prototype._insertCircleCell=function(t,e,i,o,r,a){this.circleCells[r].push(a);},Yt.prototype._query=function(t,e,i,o,r,a){if(i<0||t>this.width||o<0||e>this.height)return !r&&[];var n=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=o){if(r)return !0;for(var s=0;s<this.boxKeys.length;s++)n.push({key:this.boxKeys[s],x1:this.bboxes[4*s],y1:this.bboxes[4*s+1],x2:this.bboxes[4*s+2],y2:this.bboxes[4*s+3]});for(var l=0;l<this.circleKeys.length;l++){var c=this.circles[3*l],u=this.circles[3*l+1],h=this.circles[3*l+2];n.push({key:this.circleKeys[l],x1:c-h,y1:u-h,x2:c+h,y2:u+h});}return a?n.filter(a):n}return this._forEachCell(t,e,i,o,this._queryCell,n,{hitTest:r,seenUids:{box:{},circle:{}}},a),r?n.length>0:n},Yt.prototype._queryCircle=function(t,e,i,o,r){var a=t-i,n=t+i,s=e-i,l=e+i;if(n<0||a>this.width||l<0||s>this.height)return !o&&[];var c=[];return this._forEachCell(a,s,n,l,this._queryCellCircle,c,{hitTest:o,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}},r),o?c.length>0:c},Yt.prototype.query=function(t,e,i,o,r){return this._query(t,e,i,o,!1,r)},Yt.prototype.hitTest=function(t,e,i,o,r){return this._query(t,e,i,o,!0,r)},Yt.prototype.hitTestCircle=function(t,e,i,o){return this._queryCircle(t,e,i,!0,o)},Yt.prototype._queryCell=function(t,e,i,o,r,a,n,s){var l=n.seenUids,c=this.boxCells[r];if(null!==c)for(var u=this.bboxes,h=0,p=c;h<p.length;h+=1){var d=p[h];if(!l.box[d]){l.box[d]=!0;var _=4*d;if(t<=u[_+2]&&e<=u[_+3]&&i>=u[_+0]&&o>=u[_+1]&&(!s||s(this.boxKeys[d]))){if(n.hitTest)return a.push(!0),!0;a.push({key:this.boxKeys[d],x1:u[_],y1:u[_+1],x2:u[_+2],y2:u[_+3]});}}}var f=this.circleCells[r];if(null!==f)for(var m=this.circles,g=0,v=f;g<v.length;g+=1){var y=v[g];if(!l.circle[y]){l.circle[y]=!0;var x=3*y;if(this._circleAndRectCollide(m[x],m[x+1],m[x+2],t,e,i,o)&&(!s||s(this.circleKeys[y]))){if(n.hitTest)return a.push(!0),!0;var b=m[x],w=m[x+1],T=m[x+2];a.push({key:this.circleKeys[y],x1:b-T,y1:w-T,x2:b+T,y2:w+T});}}}},Yt.prototype._queryCellCircle=function(t,e,i,o,r,a,n,s){var l=n.circle,c=n.seenUids,u=this.boxCells[r];if(null!==u)for(var h=this.bboxes,p=0,d=u;p<d.length;p+=1){var _=d[p];if(!c.box[_]){c.box[_]=!0;var f=4*_;if(this._circleAndRectCollide(l.x,l.y,l.radius,h[f+0],h[f+1],h[f+2],h[f+3])&&(!s||s(this.boxKeys[_])))return a.push(!0),!0}}var m=this.circleCells[r];if(null!==m)for(var g=this.circles,v=0,y=m;v<y.length;v+=1){var x=y[v];if(!c.circle[x]){c.circle[x]=!0;var b=3*x;if(this._circlesCollide(g[b],g[b+1],g[b+2],l.x,l.y,l.radius)&&(!s||s(this.circleKeys[x])))return a.push(!0),!0}}},Yt.prototype._forEachCell=function(t,e,i,o,r,a,n,s){for(var l=this._convertToXCellCoord(t),c=this._convertToYCellCoord(e),u=this._convertToXCellCoord(i),h=this._convertToYCellCoord(o),p=l;p<=u;p++)for(var d=c;d<=h;d++)if(r.call(this,t,e,i,o,this.xCellCount*d+p,a,n,s))return},Yt.prototype._convertToXCellCoord=function(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))},Yt.prototype._convertToYCellCoord=function(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))},Yt.prototype._circlesCollide=function(t,e,i,o,r,a){var n=o-t,s=r-e,l=i+a;return l*l>n*n+s*s},Yt.prototype._circleAndRectCollide=function(t,e,i,o,r,a,n){var s=(a-o)/2,l=Math.abs(t-(o+s));if(l>s+i)return !1;var c=(n-r)/2,u=Math.abs(e-(r+c));if(u>c+i)return !1;if(l<=s||u<=c)return !0;var h=l-s,p=u-c;return h*h+p*p<=i*i};var le=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function ce(t,e){for(var i=0;i<t;i++){var o=e.length;e.resize(o+4),e.float32.set(le,3*o);}}function ue(t,e,i){var o=e[0],r=e[1];return t[0]=i[0]*o+i[4]*r+i[12],t[1]=i[1]*o+i[5]*r+i[13],t[3]=i[3]*o+i[7]*r+i[15],t}var he=function(t,e,i){void 0===e&&(e=new Yt(t.width+200,t.height+200,25)),void 0===i&&(i=new Yt(t.width+200,t.height+200,25)),this.transform=t,this.grid=e,this.ignoredGrid=i,this.pitchfactor=Math.cos(t._pitch)*t.cameraToCenterDistance,this.screenRightBoundary=t.width+100,this.screenBottomBoundary=t.height+100,this.gridRightBoundary=t.width+200,this.gridBottomBoundary=t.height+200;};function pe(e,i,o){return i*(t.EXTENT/(e.tileSize*Math.pow(2,o-e.tileID.overscaledZ)))}he.prototype.placeCollisionBox=function(t,e,i,o,r){var a=this.projectAndGetPerspectiveRatio(o,t.anchorPointX,t.anchorPointY),n=i*a.perspectiveRatio,s=t.x1*n+a.point.x,l=t.y1*n+a.point.y,c=t.x2*n+a.point.x,u=t.y2*n+a.point.y;return !this.isInsideGrid(s,l,c,u)||!e&&this.grid.hitTest(s,l,c,u,r)?{box:[],offscreen:!1}:{box:[s,l,c,u],offscreen:this.isOffscreen(s,l,c,u)}},he.prototype.placeCollisionCircles=function(e,i,o,r,a,n,s,l,c,u,h,p,d){var _=[],f=new t.Point(i.anchorX,i.anchorY),m=$t(f,n),g=te(this.transform.cameraToCenterDistance,m.signedDistanceFromCamera),v=(u?a/g:a*g)/t.ONE_EM,y=$t(f,s).point,x=oe(v,r,i.lineOffsetX*v,i.lineOffsetY*v,!1,y,f,i,o,s,{}),b=!1,w=!1,T=!0;if(x){for(var E=.5*p*g+d,I=new t.Point(-100,-100),P=new t.Point(this.screenRightBoundary,this.screenBottomBoundary),S=new Kt,C=x.first,z=x.last,D=[],M=C.path.length-1;M>=1;M--)D.push(C.path[M]);for(var L=1;L<z.path.length;L++)D.push(z.path[L]);var A=2.5*E;if(l){var R=D.map((function(t){return $t(t,l)}));D=R.some((function(t){return t.signedDistanceFromCamera<=0}))?[]:R.map((function(t){return t.point}));}var k=[];if(D.length>0){for(var B=D[0].clone(),O=D[0].clone(),F=1;F<D.length;F++)B.x=Math.min(B.x,D[F].x),B.y=Math.min(B.y,D[F].y),O.x=Math.max(O.x,D[F].x),O.y=Math.max(O.y,D[F].y);k=B.x>=I.x&&O.x<=P.x&&B.y>=I.y&&O.y<=P.y?[D]:O.x<I.x||B.x>P.x||O.y<I.y||B.y>P.y?[]:t.clipLine([D],I.x,I.y,P.x,P.y);}for(var U=0,N=k;U<N.length;U+=1){var Z;S.reset(N[U],.25*E),Z=S.length<=.5*E?1:Math.ceil(S.paddedLength/A)+1;for(var j=0;j<Z;j++){var q=j/Math.max(Z-1,1),V=S.lerp(q),G=V.x+100,W=V.y+100;_.push(G,W,E,0);var X=G-E,H=W-E,K=G+E,Y=W+E;if(T=T&&this.isOffscreen(X,H,K,Y),w=w||this.isInsideGrid(X,H,K,Y),!e&&this.grid.hitTestCircle(G,W,E,h)&&(b=!0,!c))return {circles:[],offscreen:!1,collisionDetected:b}}}}return {circles:!c&&b||!w?[]:_,offscreen:T,collisionDetected:b}},he.prototype.queryRenderedSymbols=function(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};for(var i=[],o=1/0,r=1/0,a=-1/0,n=-1/0,s=0,l=e;s<l.length;s+=1){var c=l[s],u=new t.Point(c.x+100,c.y+100);o=Math.min(o,u.x),r=Math.min(r,u.y),a=Math.max(a,u.x),n=Math.max(n,u.y),i.push(u);}for(var h={},p={},d=0,_=this.grid.query(o,r,a,n).concat(this.ignoredGrid.query(o,r,a,n));d<_.length;d+=1){var f=_[d],m=f.key;if(void 0===h[m.bucketInstanceId]&&(h[m.bucketInstanceId]={}),!h[m.bucketInstanceId][m.featureIndex]){var g=[new t.Point(f.x1,f.y1),new t.Point(f.x2,f.y1),new t.Point(f.x2,f.y2),new t.Point(f.x1,f.y2)];t.polygonIntersectsPolygon(i,g)&&(h[m.bucketInstanceId][m.featureIndex]=!0,void 0===p[m.bucketInstanceId]&&(p[m.bucketInstanceId]=[]),p[m.bucketInstanceId].push(m.featureIndex));}}return p},he.prototype.insertCollisionBox=function(t,e,i,o,r){(e?this.ignoredGrid:this.grid).insert({bucketInstanceId:i,featureIndex:o,collisionGroupID:r},t[0],t[1],t[2],t[3]);},he.prototype.insertCollisionCircles=function(t,e,i,o,r){for(var a=e?this.ignoredGrid:this.grid,n={bucketInstanceId:i,featureIndex:o,collisionGroupID:r},s=0;s<t.length;s+=4)a.insertCircle(n,t[s],t[s+1],t[s+2]);},he.prototype.projectAndGetPerspectiveRatio=function(e,i,o){var r=[i,o,0,1];return ue(r,r,e),{point:new t.Point((r[0]/r[3]+1)/2*this.transform.width+100,(-r[1]/r[3]+1)/2*this.transform.height+100),perspectiveRatio:.5+this.transform.cameraToCenterDistance/r[3]*.5}},he.prototype.isOffscreen=function(t,e,i,o){return i<100||t>=this.screenRightBoundary||o<100||e>this.screenBottomBoundary},he.prototype.isInsideGrid=function(t,e,i,o){return i>=0&&t<this.gridRightBoundary&&o>=0&&e<this.gridBottomBoundary},he.prototype.getViewportMatrix=function(){var e=t.identity([]);return t.translate(e,e,[-100,-100,0]),e};var de=function(t,e,i,o){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):o&&i?1:0,this.placed=i;};de.prototype.isHidden=function(){return 0===this.opacity&&!this.placed};var _e=function(t,e,i,o,r){this.text=new de(t?t.text:null,e,i,r),this.icon=new de(t?t.icon:null,e,o,r);};_e.prototype.isHidden=function(){return this.text.isHidden()&&this.icon.isHidden()};var fe=function(t,e,i){this.text=t,this.icon=e,this.skipFade=i;},me=function(){this.invProjMatrix=t.create(),this.viewportMatrix=t.create(),this.circles=[];},ge=function(t,e,i,o,r){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;},ve=function(t){this.crossSourceCollisions=t,this.maxGroupID=0,this.collisionGroups={};};function ye(e,i,o,r,a){var n=t.getAnchorAlignment(e),s=-(n.horizontalAlign-.5)*i,l=-(n.verticalAlign-.5)*o,c=t.evaluateVariableOffset(e,r);return new t.Point(s+c[0]*a,l+c[1]*a)}function xe(e,i,o,r,a,n){var s=e.x1,l=e.x2,c=e.y1,u=e.y2,h=e.anchorPointX,p=e.anchorPointY,d=new t.Point(i,o);return r&&d._rotate(a?n:-n),{x1:s+d.x,y1:c+d.y,x2:l+d.x,y2:u+d.y,anchorPointX:h,anchorPointY:p}}ve.prototype.get=function(t){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[t]){var e=++this.maxGroupID;this.collisionGroups[t]={ID:e,predicate:function(t){return t.collisionGroupID===e}};}return this.collisionGroups[t]};var be=function(t,e,i,o){this.transform=t.clone(),this.collisionIndex=new he(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=e,this.retainedQueryData={},this.collisionGroups=new ve(i),this.collisionCircleArrays={},this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={};};function we(t,e,i,o,r){t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0);}be.prototype.getBucketParts=function(e,i,o,r){var a=o.getBucket(i),n=o.latestFeatureIndex;if(a&&n&&i.id===a.layerIds[0]){var s=o.collisionBoxArray,l=a.layers[0].layout,c=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.EXTENT,h=this.transform.calculatePosMatrix(o.tileID.toUnwrapped()),p="map"===l.get("text-pitch-alignment"),d="map"===l.get("text-rotation-alignment"),_=pe(o,1,this.transform.zoom),f=Jt(h,p,d,this.transform,_),m=null;if(p){var g=Qt(h,p,d,this.transform,_);m=t.multiply([],this.transform.labelPlaneMatrix,g);}this.retainedQueryData[a.bucketInstanceId]=new ge(a.bucketInstanceId,n,a.sourceLayerIndex,a.index,o.tileID);var v={bucket:a,layout:l,posMatrix:h,textLabelPlaneMatrix:f,labelToScreenMatrix:m,scale:c,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:s,partiallyEvaluatedTextSize:t.evaluateSizeForZoom(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(var y=0,x=a.sortKeyRanges;y<x.length;y+=1){var b=x[y];e.push({sortKey:b.sortKey,symbolInstanceStart:b.symbolInstanceStart,symbolInstanceEnd:b.symbolInstanceEnd,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}},be.prototype.attemptAnchorPlacement=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=[h.textOffset0,h.textOffset1],g=ye(t,i,o,m,r),v=this.collisionIndex.placeCollisionBox(xe(e,g.x,g.y,a,n,this.transform.angle),u,s,l,c.predicate);if(!_||0!==this.collisionIndex.placeCollisionBox(xe(_,g.x,g.y,a,n,this.transform.angle),u,s,l,c.predicate).box.length)return v.box.length>0?(this.prevPlacement&&this.prevPlacement.variableOffsets[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID].text&&(f=this.prevPlacement.variableOffsets[h.crossTileID].anchor),this.variableOffsets[h.crossTileID]={textOffset:m,width:i,height:o,anchor:t,textBoxScale:r,prevAnchor:f},this.markUsedJustification(p,t,h,d),p.allowVerticalPlacement&&(this.markUsedOrientation(p,d,h),this.placedOrientations[h.crossTileID]=d),{shift:g,placedGlyphBoxes:v}):void 0},be.prototype.placeLayerBucketPart=function(e,i,o){var r=this,a=e.parameters,n=a.bucket,s=a.layout,l=a.posMatrix,c=a.textLabelPlaneMatrix,u=a.labelToScreenMatrix,h=a.textPixelRatio,p=a.holdingForFade,d=a.collisionBoxArray,_=a.partiallyEvaluatedTextSize,f=a.collisionGroup,m=s.get("text-optional"),g=s.get("icon-optional"),v=s.get("text-allow-overlap"),y=s.get("icon-allow-overlap"),x="map"===s.get("text-rotation-alignment"),b="map"===s.get("text-pitch-alignment"),w="none"!==s.get("icon-text-fit"),T="viewport-y"===s.get("symbol-z-order"),E=v&&(y||!n.hasIconData()||g),I=y&&(v||!n.hasTextData()||m);!n.collisionArrays&&d&&n.deserializeCollisionBoxes(d);var P=function(e,a){if(!i[e.crossTileID])if(p)r.placements[e.crossTileID]=new fe(!1,!1,!1);else {var d,T=!1,P=!1,S=!0,C=null,z={box:null,offscreen:null},D={box:null,offscreen:null},M=null,L=null,A=0,R=0,k=0;a.textFeatureIndex?A=a.textFeatureIndex:e.useRuntimeCollisionCircles&&(A=e.featureIndex),a.verticalTextFeatureIndex&&(R=a.verticalTextFeatureIndex);var B=a.textBox;if(B){var O=function(i){var o=t.WritingMode.horizontal;if(n.allowVerticalPlacement&&!i&&r.prevPlacement){var a=r.prevPlacement.placedOrientations[e.crossTileID];a&&(r.placedOrientations[e.crossTileID]=a,r.markUsedOrientation(n,o=a,e));}return o},F=function(i,o){if(n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&a.verticalTextBox)for(var r=0,s=n.writingModes;r<s.length&&(s[r]===t.WritingMode.vertical?(z=o(),D=z):z=i(),!(z&&z.box&&z.box.length));r+=1);else z=i();};if(s.get("text-variable-anchor")){var U=s.get("text-variable-anchor");if(r.prevPlacement&&r.prevPlacement.variableOffsets[e.crossTileID]){var N=r.prevPlacement.variableOffsets[e.crossTileID];U.indexOf(N.anchor)>0&&(U=U.filter((function(t){return t!==N.anchor}))).unshift(N.anchor);}var Z=function(t,i,o){for(var a=t.x2-t.x1,s=t.y2-t.y1,c=e.textBoxScale,u=w&&!y?i:null,p={box:[],offscreen:!1},d=v?2*U.length:U.length,_=0;_<d;++_){var m=r.attemptAnchorPlacement(U[_%U.length],t,a,s,c,x,b,h,l,f,_>=U.length,e,n,o,u);if(m&&(p=m.placedGlyphBoxes)&&p.box&&p.box.length){T=!0,C=m.shift;break}}return p};F((function(){return Z(B,a.iconBox,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&!(z&&z.box&&z.box.length)&&e.numVerticalGlyphVertices>0&&i?Z(i,a.verticalIconBox,t.WritingMode.vertical):{box:null,offscreen:null}})),z&&(T=z.box,S=z.offscreen);var j=O(z&&z.box);if(!T&&r.prevPlacement){var q=r.prevPlacement.variableOffsets[e.crossTileID];q&&(r.variableOffsets[e.crossTileID]=q,r.markUsedJustification(n,q.anchor,e,j));}}else {var V=function(t,i){var o=r.collisionIndex.placeCollisionBox(t,v,h,l,f.predicate);return o&&o.box&&o.box.length&&(r.markUsedOrientation(n,i,e),r.placedOrientations[e.crossTileID]=i),o};F((function(){return V(B,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?V(i,t.WritingMode.vertical):{box:null,offscreen:null}})),O(z&&z.box&&z.box.length);}}if(T=(d=z)&&d.box&&d.box.length>0,S=d&&d.offscreen,e.useRuntimeCollisionCircles){var G=n.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),W=t.evaluateSizeForFeature(n.textSizeData,_,G),X=s.get("text-padding");M=r.collisionIndex.placeCollisionCircles(v,G,n.lineVertexArray,n.glyphOffsetArray,W,l,c,u,o,b,f.predicate,e.collisionCircleDiameter,X),T=v||M.circles.length>0&&!M.collisionDetected,S=S&&M.offscreen;}if(a.iconFeatureIndex&&(k=a.iconFeatureIndex),a.iconBox){var H=function(t){var e=w&&C?xe(t,C.x,C.y,x,b,r.transform.angle):t;return r.collisionIndex.placeCollisionBox(e,y,h,l,f.predicate)};P=D&&D.box&&D.box.length&&a.verticalIconBox?(L=H(a.verticalIconBox)).box.length>0:(L=H(a.iconBox)).box.length>0,S=S&&L.offscreen;}var K=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,Y=g||0===e.numIconVertices;if(K||Y?Y?K||(P=P&&T):T=P&&T:P=T=P&&T,T&&d&&d.box&&r.collisionIndex.insertCollisionBox(d.box,s.get("text-ignore-placement"),n.bucketInstanceId,D&&D.box&&R?R:A,f.ID),P&&L&&r.collisionIndex.insertCollisionBox(L.box,s.get("icon-ignore-placement"),n.bucketInstanceId,k,f.ID),M&&(T&&r.collisionIndex.insertCollisionCircles(M.circles,s.get("text-ignore-placement"),n.bucketInstanceId,A,f.ID),o)){var J=n.bucketInstanceId,Q=r.collisionCircleArrays[J];void 0===Q&&(Q=r.collisionCircleArrays[J]=new me);for(var $=0;$<M.circles.length;$+=4)Q.circles.push(M.circles[$+0]),Q.circles.push(M.circles[$+1]),Q.circles.push(M.circles[$+2]),Q.circles.push(M.collisionDetected?1:0);}r.placements[e.crossTileID]=new fe(T||E,P||I,S||n.justReloaded),i[e.crossTileID]=!0;}};if(T)for(var S=n.getSortedSymbolIndexes(this.transform.angle),C=S.length-1;C>=0;--C){var z=S[C];P(n.symbolInstances.get(z),n.collisionArrays[z]);}else for(var D=e.symbolInstanceStart;D<e.symbolInstanceEnd;D++)P(n.symbolInstances.get(D),n.collisionArrays[D]);if(o&&n.bucketInstanceId in this.collisionCircleArrays){var M=this.collisionCircleArrays[n.bucketInstanceId];t.invert(M.invProjMatrix,l),M.viewportMatrix=this.collisionIndex.getViewportMatrix();}n.justReloaded=!1;},be.prototype.markUsedJustification=function(e,i,o,r){var a;a=r===t.WritingMode.vertical?o.verticalPlacedTextSymbolIndex:{left:o.leftJustifiedTextSymbolIndex,center:o.centerJustifiedTextSymbolIndex,right:o.rightJustifiedTextSymbolIndex}[t.getAnchorJustification(i)];for(var n=0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex,o.verticalPlacedTextSymbolIndex];n<s.length;n+=1){var l=s[n];l>=0&&(e.text.placedSymbolArray.get(l).crossTileID=a>=0&&l!==a?0:o.crossTileID);}},be.prototype.markUsedOrientation=function(e,i,o){for(var r=i===t.WritingMode.horizontal||i===t.WritingMode.horizontalOnly?i:0,a=i===t.WritingMode.vertical?i:0,n=0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];n<s.length;n+=1)e.text.placedSymbolArray.get(s[n]).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);},be.prototype.commit=function(t){this.commitTime=t,this.zoomAtLastRecencyCheck=this.transform.zoom;var e=this.prevPlacement,i=!1;this.prevZoomAdjustment=e?e.zoomAdjustment(this.transform.zoom):0;var o=e?e.symbolFadeChange(t):1,r=e?e.opacities:{},a=e?e.variableOffsets:{},n=e?e.placedOrientations:{};for(var s in this.placements){var l=this.placements[s],c=r[s];c?(this.opacities[s]=new _e(c,o,l.text,l.icon),i=i||l.text!==c.text.placed||l.icon!==c.icon.placed):(this.opacities[s]=new _e(null,o,l.text,l.icon,l.skipFade),i=i||l.text||l.icon);}for(var u in r){var h=r[u];if(!this.opacities[u]){var p=new _e(h,o,!1,!1);p.isHidden()||(this.opacities[u]=p,i=i||h.text.placed||h.icon.placed);}}for(var d in a)this.variableOffsets[d]||!this.opacities[d]||this.opacities[d].isHidden()||(this.variableOffsets[d]=a[d]);for(var _ in n)this.placedOrientations[_]||!this.opacities[_]||this.opacities[_].isHidden()||(this.placedOrientations[_]=n[_]);i?this.lastPlacementChangeTime=t:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=e?e.lastPlacementChangeTime:t);},be.prototype.updateLayerOpacities=function(t,e){for(var i={},o=0,r=e;o<r.length;o+=1){var a=r[o],n=a.getBucket(t);n&&a.latestFeatureIndex&&t.id===n.layerIds[0]&&this.updateBucketOpacities(n,i,a.collisionBoxArray);}},be.prototype.updateBucketOpacities=function(e,i,o){var r=this;e.hasTextData()&&e.text.opacityVertexArray.clear(),e.hasIconData()&&e.icon.opacityVertexArray.clear(),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();var a=e.layers[0].layout,n=new _e(null,0,!1,!1,!0),s=a.get("text-allow-overlap"),l=a.get("icon-allow-overlap"),c=a.get("text-variable-anchor"),u="map"===a.get("text-rotation-alignment"),h="map"===a.get("text-pitch-alignment"),p="none"!==a.get("icon-text-fit"),d=new _e(null,0,s&&(l||!e.hasIconData()||a.get("icon-optional")),l&&(s||!e.hasTextData()||a.get("text-optional")),!0);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(o);for(var _=function(t,e,i){for(var o=0;o<e/4;o++)t.opacityVertexArray.emplaceBack(i);},f=function(o){var a=e.symbolInstances.get(o),s=a.numHorizontalGlyphVertices,l=a.numVerticalGlyphVertices,f=a.crossTileID,m=r.opacities[f];i[f]?m=n:m||(r.opacities[f]=m=d),i[f]=!0;var g=a.numIconVertices>0,v=r.placedOrientations[a.crossTileID],y=v===t.WritingMode.vertical,x=v===t.WritingMode.horizontal||v===t.WritingMode.horizontalOnly;if(s>0||l>0){var b=De(m.text);_(e.text,s,y?Me:b),_(e.text,l,x?Me:b);var w=m.text.isHidden();[a.rightJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.leftJustifiedTextSymbolIndex].forEach((function(t){t>=0&&(e.text.placedSymbolArray.get(t).hidden=w||y?1:0);})),a.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).hidden=w||x?1:0);var T=r.variableOffsets[a.crossTileID];T&&r.markUsedJustification(e,T.anchor,a,v);var E=r.placedOrientations[a.crossTileID];E&&(r.markUsedJustification(e,"left",a,E),r.markUsedOrientation(e,E,a));}if(g){var I=De(m.icon),P=!(p&&a.verticalPlacedIconSymbolIndex&&y);a.placedIconSymbolIndex>=0&&(_(e.icon,a.numIconVertices,P?I:Me),e.icon.placedSymbolArray.get(a.placedIconSymbolIndex).hidden=m.icon.isHidden()),a.verticalPlacedIconSymbolIndex>=0&&(_(e.icon,a.numVerticalIconVertices,P?Me:I),e.icon.placedSymbolArray.get(a.verticalPlacedIconSymbolIndex).hidden=m.icon.isHidden());}if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){var S=e.collisionArrays[o];if(S){var C=new t.Point(0,0);if(S.textBox||S.verticalTextBox){var z=!0;if(c){var D=r.variableOffsets[f];D?(C=ye(D.anchor,D.width,D.height,D.textOffset,D.textBoxScale),u&&C._rotate(h?r.transform.angle:-r.transform.angle)):z=!1;}S.textBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||y,C.x,C.y),S.verticalTextBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||x,C.x,C.y);}var M=Boolean(!x&&S.verticalIconBox);S.iconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,M,p?C.x:0,p?C.y:0),S.verticalIconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,!M,p?C.x:0,p?C.y:0);}}},m=0;m<e.symbolInstances.length;m++)f(m);if(e.sortFeatures(this.transform.angle),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.bucketInstanceId in this.collisionCircleArrays){var g=this.collisionCircleArrays[e.bucketInstanceId];e.placementInvProjMatrix=g.invProjMatrix,e.placementViewportMatrix=g.viewportMatrix,e.collisionCircleArray=g.circles,delete this.collisionCircleArrays[e.bucketInstanceId];}},be.prototype.symbolFadeChange=function(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment},be.prototype.zoomAdjustment=function(t){return Math.max(0,(this.transform.zoom-t)/1.5)},be.prototype.hasTransitions=function(t){return this.stale||t-this.lastPlacementChangeTime<this.fadeDuration},be.prototype.stillRecent=function(t,e){var i=this.zoomAtLastRecencyCheck===e?1-this.zoomAdjustment(e):1;return this.zoomAtLastRecencyCheck=e,this.commitTime+this.fadeDuration*i>t},be.prototype.setStale=function(){this.stale=!0;};var Te=Math.pow(2,25),Ee=Math.pow(2,24),Ie=Math.pow(2,17),Pe=Math.pow(2,16),Se=Math.pow(2,9),Ce=Math.pow(2,8),ze=Math.pow(2,1);function De(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*Te+e*Ee+i*Ie+e*Pe+i*Se+e*Ce+i*ze+e}var Me=0,Le=function(t){this._sortAcrossTiles="viewport-y"!==t.layout.get("symbol-z-order")&&void 0!==t.layout.get("symbol-sort-key").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];};Le.prototype.continuePlacement=function(t,e,i,o,r){for(var a=this._bucketParts;this._currentTileIndex<t.length;)if(e.getBucketParts(a,o,t[this._currentTileIndex],this._sortAcrossTiles),this._currentTileIndex++,r())return !0;for(this._sortAcrossTiles&&(this._sortAcrossTiles=!1,a.sort((function(t,e){return t.sortKey-e.sortKey})));this._currentPartIndex<a.length;)if(e.placeLayerBucketPart(a[this._currentPartIndex],this._seenCrossTileIDs,i),this._currentPartIndex++,r())return !0;return !1};var Ae=function(t,e,i,o,r,a,n){this.placement=new be(t,r,a,n),this._currentPlacementIndex=e.length-1,this._forceFullPlacement=i,this._showCollisionBoxes=o,this._done=!1;};Ae.prototype.isDone=function(){return this._done},Ae.prototype.continuePlacement=function(e,i,o){for(var r=this,a=t.browser.now(),n=function(){var e=t.browser.now()-a;return !r._forceFullPlacement&&e>2};this._currentPlacementIndex>=0;){var s=i[e[this._currentPlacementIndex]],l=this.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(this._inProgressLayer||(this._inProgressLayer=new Le(s)),this._inProgressLayer.continuePlacement(o[s.source],this.placement,this._showCollisionBoxes,s,n))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;},Ae.prototype.commit=function(t){return this.placement.commit(t),this.placement};var Re=512/t.EXTENT/2,ke=function(t,e,i){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=i;for(var o=0;o<e.length;o++){var r=e.get(o),a=r.key;this.indexedSymbolInstances[a]||(this.indexedSymbolInstances[a]=[]),this.indexedSymbolInstances[a].push({crossTileID:r.crossTileID,coord:this.getScaledCoordinates(r,t)});}};ke.prototype.getScaledCoordinates=function(e,i){var o=Re/Math.pow(2,i.canonical.z-this.tileID.canonical.z);return {x:Math.floor((i.canonical.x*t.EXTENT+e.anchorX)*o),y:Math.floor((i.canonical.y*t.EXTENT+e.anchorY)*o)}},ke.prototype.findMatches=function(t,e,i){for(var o=this.tileID.canonical.z<e.canonical.z?1:Math.pow(2,this.tileID.canonical.z-e.canonical.z),r=0;r<t.length;r++){var a=t.get(r);if(!a.crossTileID){var n=this.indexedSymbolInstances[a.key];if(n)for(var s=this.getScaledCoordinates(a,e),l=0,c=n;l<c.length;l+=1){var u=c[l];if(Math.abs(u.coord.x-s.x)<=o&&Math.abs(u.coord.y-s.y)<=o&&!i[u.crossTileID]){i[u.crossTileID]=!0,a.crossTileID=u.crossTileID;break}}}}};var Be=function(){this.maxCrossTileID=0;};Be.prototype.generate=function(){return ++this.maxCrossTileID};var Oe=function(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;};Oe.prototype.handleWrapJump=function(t){var e=Math.round((t-this.lng)/360);if(0!==e)for(var i in this.indexes){var o=this.indexes[i],r={};for(var a in o){var n=o[a];n.tileID=n.tileID.unwrapTo(n.tileID.wrap+e),r[n.tileID.key]=n;}this.indexes[i]=r;}this.lng=t;},Oe.prototype.addBucket=function(t,e,i){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key]);}for(var o=0;o<e.symbolInstances.length;o++)e.symbolInstances.get(o).crossTileID=0;this.usedCrossTileIDs[t.overscaledZ]||(this.usedCrossTileIDs[t.overscaledZ]={});var r=this.usedCrossTileIDs[t.overscaledZ];for(var a in this.indexes){var n=this.indexes[a];if(Number(a)>t.overscaledZ)for(var s in n){var l=n[s];l.tileID.isChildOf(t)&&l.findMatches(e.symbolInstances,t,r);}else {var c=n[t.scaledTo(Number(a)).key];c&&c.findMatches(e.symbolInstances,t,r);}}for(var u=0;u<e.symbolInstances.length;u++){var h=e.symbolInstances.get(u);h.crossTileID||(h.crossTileID=i.generate(),r[h.crossTileID]=!0);}return void 0===this.indexes[t.overscaledZ]&&(this.indexes[t.overscaledZ]={}),this.indexes[t.overscaledZ][t.key]=new ke(t,e.symbolInstances,e.bucketInstanceId),!0},Oe.prototype.removeBucketCrossTileIDs=function(t,e){for(var i in e.indexedSymbolInstances)for(var o=0,r=e.indexedSymbolInstances[i];o<r.length;o+=1)delete this.usedCrossTileIDs[t][r[o].crossTileID];},Oe.prototype.removeStaleBuckets=function(t){var e=!1;for(var i in this.indexes){var o=this.indexes[i];for(var r in o)t[o[r].bucketInstanceId]||(this.removeBucketCrossTileIDs(i,o[r]),delete o[r],e=!0);}return e};var Fe=function(){this.layerIndexes={},this.crossTileIDs=new Be,this.maxBucketInstanceId=0,this.bucketsInCurrentPlacement={};};Fe.prototype.addLayer=function(t,e,i){var o=this.layerIndexes[t.id];void 0===o&&(o=this.layerIndexes[t.id]=new Oe);var r=!1,a={};o.handleWrapJump(i);for(var n=0,s=e;n<s.length;n+=1){var l=s[n],c=l.getBucket(t);c&&t.id===c.layerIds[0]&&(c.bucketInstanceId||(c.bucketInstanceId=++this.maxBucketInstanceId),o.addBucket(l.tileID,c,this.crossTileIDs)&&(r=!0),a[c.bucketInstanceId]=!0);}return o.removeStaleBuckets(a)&&(r=!0),r},Fe.prototype.pruneUnusedLayers=function(t){var e={};for(var i in t.forEach((function(t){e[t]=!0;})),this.layerIndexes)e[i]||delete this.layerIndexes[i];};var Ue=function(e,i){return t.emitValidationErrors(e,i&&i.filter((function(t){return "source.canvas"!==t.identifier})))},Ne=t.pick(Zt,["addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData"]),Ze=t.pick(Zt,["setCenter","setZoom","setBearing","setPitch"]),je=function(){var e={},i=t.styleSpec.$version;for(var o in t.styleSpec.$root){var r,a=t.styleSpec.$root[o];if(a.required)null!=(r="version"===o?i:"array"===a.type?[]:{})&&(e[o]=r);}return e}(),qe=function(e){function i(o,r){var a=this;void 0===r&&(r={}),e.call(this),this.map=o,this.dispatcher=new E(Ft(),this),this.imageManager=new p,this.imageManager.setEventedParent(this),this.glyphManager=new y(o._requestManager,r.localIdeographFontFamily),this.lineAtlas=new T(256,512),this.crossTileSymbolIndex=new Fe,this._layers={},this._serializedLayers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.ZoomHistory,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("setReferrer",t.getReferrer());var n=this;this._rtlTextPluginCallback=i.registerForPluginStateChange((function(e){n.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:e.pluginStatus,pluginURL:e.pluginURL},(function(e,i){if(t.triggerPluginCompletionEvent(e),i&&i.every((function(t){return t})))for(var o in n.sourceCaches)n.sourceCaches[o].reload();}));})),this.on("data",(function(t){if("source"===t.dataType&&"metadata"===t.sourceDataType){var e=a.sourceCaches[t.sourceId];if(e){var i=e.getSource();if(i&&i.vectorLayerIds)for(var o in a._layers){var r=a._layers[o];r.source===i.id&&a._validateLayer(r);}}}}));}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.loadURL=function(e,i){var o=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"}));var r="boolean"==typeof i.validate?i.validate:!t.isMapboxURL(e);e=this.map._requestManager.normalizeStyleURL(e,i.accessToken);var a=this.map._requestManager.transformRequest(e,t.ResourceType.Style);this._request=t.getJSON(a,(function(e,i){o._request=null,e?o.fire(new t.ErrorEvent(e)):i&&o._load(i,r);}));},i.prototype.loadJSON=function(e,i){var o=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"})),this._request=t.browser.frame((function(){o._request=null,o._load(e,!1!==i.validate);}));},i.prototype.loadEmpty=function(){this.fire(new t.Event("dataloading",{dataType:"style"})),this._load(je,!1);},i.prototype._load=function(e,i){if(!i||!Ue(this,t.validateStyle(e))){for(var o in this._loaded=!0,this.stylesheet=e,e.sources)this.addSource(o,e.sources[o],{validate:!1});e.sprite?this._loadSprite(e.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(e.glyphs);var r=Nt(this.stylesheet.layers);this._order=r.map((function(t){return t.id})),this._layers={},this._serializedLayers={};for(var a=0,n=r;a<n.length;a+=1){var s=n[a];(s=t.createStyleLayer(s)).setEventedParent(this,{layer:{id:s.id}}),this._layers[s.id]=s,this._serializedLayers[s.id]=s.serialize();}this.dispatcher.broadcast("setLayers",this._serializeLayers(this._order)),this.light=new w(this.stylesheet.light),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"));}},i.prototype._loadSprite=function(e){var i=this;this._spriteRequest=function(e,i,o){var r,a,n,s=t.browser.devicePixelRatio>1?"@2x":"",l=t.getJSON(i.transformRequest(i.normalizeSpriteURL(e,s,".json"),t.ResourceType.SpriteJSON),(function(t,e){l=null,n||(n=t,r=e,u());})),c=t.getImage(i.transformRequest(i.normalizeSpriteURL(e,s,".png"),t.ResourceType.SpriteImage),(function(t,e){c=null,n||(n=t,a=e,u());}));function u(){if(n)o(n);else if(r&&a){var e=t.browser.getImageData(a),i={};for(var s in r){var l=r[s],c=l.width,u=l.height,h=l.x,p=l.y,d=l.sdf,_=l.pixelRatio,f=l.stretchX,m=l.stretchY,g=l.content,v=new t.RGBAImage({width:c,height:u});t.RGBAImage.copy(e,v,{x:h,y:p},{x:0,y:0},{width:c,height:u}),i[s]={data:v,pixelRatio:_,sdf:d,stretchX:f,stretchY:m,content:g};}o(null,i);}}return {cancel:function(){l&&(l.cancel(),l=null),c&&(c.cancel(),c=null);}}}(e,this.map._requestManager,(function(e,o){if(i._spriteRequest=null,e)i.fire(new t.ErrorEvent(e));else if(o)for(var r in o)i.imageManager.addImage(r,o[r]);i.imageManager.setLoaded(!0),i._availableImages=i.imageManager.listImages(),i.dispatcher.broadcast("setImages",i._availableImages),i.fire(new t.Event("data",{dataType:"style"}));}));},i.prototype._validateLayer=function(e){var i=this.sourceCaches[e.source];if(i){var o=e.sourceLayer;if(o){var r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+o+'" does not exist on source "'+r.id+'" as specified by style layer "'+e.id+'"')));}}},i.prototype.loaded=function(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return !1;return !!this.imageManager.isLoaded()},i.prototype._serializeLayers=function(t){for(var e=[],i=0,o=t;i<o.length;i+=1){var r=this._layers[o[i]];"custom"!==r.type&&e.push(r.serialize());}return e},i.prototype.hasTransitions=function(){if(this.light&&this.light.hasTransition())return !0;for(var t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return !0;for(var e in this._layers)if(this._layers[e].hasTransition())return !0;return !1},i.prototype._checkLoaded=function(){if(!this._loaded)throw new Error("Style is not done loading")},i.prototype.update=function(e){if(this._loaded){var i=this._changed;if(this._changed){var o=Object.keys(this._updatedLayers),r=Object.keys(this._removedLayers);for(var a in (o.length||r.length)&&this._updateWorkerLayers(o,r),this._updatedSources){var n=this._updatedSources[a];"reload"===n?this._reloadSource(a):"clear"===n&&this._clearSource(a);}for(var s in this._updateTilesForChangedImages(),this._updatedPaintProps)this._layers[s].updateTransitions(e);this.light.updateTransitions(e),this._resetUpdates();}for(var l in this.sourceCaches)this.sourceCaches[l].used=!1;for(var c=0,u=this._order;c<u.length;c+=1){var h=this._layers[u[c]];h.recalculate(e,this._availableImages),!h.isHidden(e.zoom)&&h.source&&(this.sourceCaches[h.source].used=!0);}this.light.recalculate(e),this.z=e.zoom,i&&this.fire(new t.Event("data",{dataType:"style"}));}},i.prototype._updateTilesForChangedImages=function(){var t=Object.keys(this._changedImages);if(t.length){for(var e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["icons","patterns"],t);this._changedImages={};}},i.prototype._updateWorkerLayers=function(t,e){this.dispatcher.broadcast("updateLayers",{layers:this._serializeLayers(t),removedIds:e});},i.prototype._resetUpdates=function(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={};},i.prototype.setState=function(e){var i=this;if(this._checkLoaded(),Ue(this,t.validateStyle(e)))return !1;(e=t.clone$1(e)).layers=Nt(e.layers);var o=function(e,i){if(!e)return [{command:Zt.setStyle,args:[i]}];var o=[];try{if(!t.deepEqual(e.version,i.version))return [{command:Zt.setStyle,args:[i]}];t.deepEqual(e.center,i.center)||o.push({command:Zt.setCenter,args:[i.center]}),t.deepEqual(e.zoom,i.zoom)||o.push({command:Zt.setZoom,args:[i.zoom]}),t.deepEqual(e.bearing,i.bearing)||o.push({command:Zt.setBearing,args:[i.bearing]}),t.deepEqual(e.pitch,i.pitch)||o.push({command:Zt.setPitch,args:[i.pitch]}),t.deepEqual(e.sprite,i.sprite)||o.push({command:Zt.setSprite,args:[i.sprite]}),t.deepEqual(e.glyphs,i.glyphs)||o.push({command:Zt.setGlyphs,args:[i.glyphs]}),t.deepEqual(e.transition,i.transition)||o.push({command:Zt.setTransition,args:[i.transition]}),t.deepEqual(e.light,i.light)||o.push({command:Zt.setLight,args:[i.light]});var r={},a=[];!function(e,i,o,r){var a;for(a in i=i||{},e=e||{})e.hasOwnProperty(a)&&(i.hasOwnProperty(a)||qt(a,o,r));for(a in i)i.hasOwnProperty(a)&&(e.hasOwnProperty(a)?t.deepEqual(e[a],i[a])||("geojson"===e[a].type&&"geojson"===i[a].type&&Gt(e,i,a)?o.push({command:Zt.setGeoJSONSourceData,args:[a,i[a].data]}):Vt(a,i,o,r)):jt(a,i,o));}(e.sources,i.sources,a,r);var n=[];e.layers&&e.layers.forEach((function(t){r[t.source]?o.push({command:Zt.removeLayer,args:[t.id]}):n.push(t);})),o=o.concat(a),function(e,i,o){i=i||[];var r,a,n,s,l,c,u,h=(e=e||[]).map(Xt),p=i.map(Xt),d=e.reduce(Ht,{}),_=i.reduce(Ht,{}),f=h.slice(),m=Object.create(null);for(r=0,a=0;r<h.length;r++)_.hasOwnProperty(n=h[r])?a++:(o.push({command:Zt.removeLayer,args:[n]}),f.splice(f.indexOf(n,a),1));for(r=0,a=0;r<p.length;r++)f[f.length-1-r]!==(n=p[p.length-1-r])&&(d.hasOwnProperty(n)?(o.push({command:Zt.removeLayer,args:[n]}),f.splice(f.lastIndexOf(n,f.length-a),1)):a++,o.push({command:Zt.addLayer,args:[_[n],c=f[f.length-r]]}),f.splice(f.length-r,0,n),m[n]=!0);for(r=0;r<p.length;r++)if(s=d[n=p[r]],l=_[n],!m[n]&&!t.deepEqual(s,l))if(t.deepEqual(s.source,l.source)&&t.deepEqual(s["source-layer"],l["source-layer"])&&t.deepEqual(s.type,l.type)){for(u in Wt(s.layout,l.layout,o,n,null,Zt.setLayoutProperty),Wt(s.paint,l.paint,o,n,null,Zt.setPaintProperty),t.deepEqual(s.filter,l.filter)||o.push({command:Zt.setFilter,args:[n,l.filter]}),t.deepEqual(s.minzoom,l.minzoom)&&t.deepEqual(s.maxzoom,l.maxzoom)||o.push({command:Zt.setLayerZoomRange,args:[n,l.minzoom,l.maxzoom]}),s)s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?Wt(s[u],l[u],o,n,u.slice(6),Zt.setPaintProperty):t.deepEqual(s[u],l[u])||o.push({command:Zt.setLayerProperty,args:[n,u,l[u]]}));for(u in l)l.hasOwnProperty(u)&&!s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?Wt(s[u],l[u],o,n,u.slice(6),Zt.setPaintProperty):t.deepEqual(s[u],l[u])||o.push({command:Zt.setLayerProperty,args:[n,u,l[u]]}));}else o.push({command:Zt.removeLayer,args:[n]}),c=f[f.lastIndexOf(n)+1],o.push({command:Zt.addLayer,args:[l,c]});}(n,i.layers,o);}catch(t){console.warn("Unable to compute style diff:",t),o=[{command:Zt.setStyle,args:[i]}];}return o}(this.serialize(),e).filter((function(t){return !(t.command in Ze)}));if(0===o.length)return !1;var r=o.filter((function(t){return !(t.command in Ne)}));if(r.length>0)throw new Error("Unimplemented: "+r.map((function(t){return t.command})).join(", ")+".");return o.forEach((function(t){"setTransition"!==t.command&&i[t.command].apply(i,t.args);})),this.stylesheet=e,!0},i.prototype.addImage=function(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,i),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.updateImage=function(t,e){this.imageManager.updateImage(t,e);},i.prototype.getImage=function(t){return this.imageManager.getImage(t)},i.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.listImages=function(){return this._checkLoaded(),this.imageManager.listImages()},i.prototype.addSource=function(e,i,o){var r=this;if(void 0===o&&(o={}),this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!i.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(i).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.validateStyle.source,"sources."+e,i,null,o))){this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);var a=this.sourceCaches[e]=new Dt(e,i,this.dispatcher);a.style=this,a.setEventedParent(this,(function(){return {isSourceLoaded:r.loaded(),source:a.serialize(),sourceId:e}})),a.onAdd(this.map),this._changed=!0;}},i.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+i+'" is using it.')));var o=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],o.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),o.setEventedParent(null),o.clearTiles(),o.onRemove&&o.onRemove(this.map),this._changed=!0;},i.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0;},i.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},i.prototype.addLayer=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=e.id;if(this.getLayer(r))this.fire(new t.ErrorEvent(new Error('Layer with id "'+r+'" already exists on this map')));else {var a;if("custom"===e.type){if(Ue(this,t.validateCustomStyleLayer(e)))return;a=t.createStyleLayer(e);}else {if("object"==typeof e.source&&(this.addSource(r,e.source),e=t.clone$1(e),e=t.extend(e,{source:r})),this._validate(t.validateStyle.layer,"layers."+r,e,{arrayIndex:-1},o))return;a=t.createStyleLayer(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}}),this._serializedLayers[a.id]=a.serialize();}var n=i?this._order.indexOf(i):this._order.length;if(i&&-1===n)this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.')));else {if(this._order.splice(n,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){var s=this._removedLayers[r];delete this._removedLayers[r],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}},i.prototype.moveLayer=function(e,i){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==i){var o=this._order.indexOf(e);this._order.splice(o,1);var r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.'))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")));},i.prototype.removeLayer=function(e){this._checkLoaded();var i=this._layers[e];if(i){i.setEventedParent(null);var o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")));},i.prototype.getLayer=function(t){return this._layers[t]},i.prototype.hasLayer=function(t){return t in this._layers},i.prototype.setLayerZoomRange=function(e,i,o){this._checkLoaded();var r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")));},i.prototype.setFilter=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=this.getLayer(e);if(r){if(!t.deepEqual(r.filter,i))return null==i?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(t.validateStyle.filter,"layers."+r.id+".filter",i,null,o)||(r.filter=t.clone$1(i),this._updateLayer(r)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")));},i.prototype.getFilter=function(e){return t.clone$1(this.getLayer(e).filter)},i.prototype.setLayoutProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getLayoutProperty=function(e,i){var o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style.")));},i.prototype.setPaintProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getPaintProperty(i),o)||(a.setPaintProperty(i,o,r)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},i.prototype.setFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0!==a){var n=a.getSource().type;"geojson"===n&&r?this.fire(new t.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==n||r?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.removeFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=this.sourceCaches[o];if(void 0!==r){var a=r.getSource().type,n="vector"===a?e.sourceLayer:void 0;"vector"!==a||n?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.ErrorEvent(new Error("A feature id is requred to remove its specific state property."))):r.removeFeatureState(n,e.id,i):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.getFeatureState=function(e){this._checkLoaded();var i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r){if("vector"!==r.getSource().type||o)return void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id);this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+i+"' does not exist in the map's style.")));},i.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},i.prototype.serialize=function(){return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,(function(t){return t.serialize()})),layers:this._serializeLayers(this._order)},(function(t){return void 0!==t}))},i.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&"raster"!==this.sourceCaches[t.source].getSource().type&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0;},i.prototype._flattenAndSortRenderedFeatures=function(t){for(var e=this,i=function(t){return "fill-extrusion"===e._layers[t].type},o={},r=[],a=this._order.length-1;a>=0;a--){var n=this._order[a];if(i(n)){o[n]=a;for(var s=0,l=t;s<l.length;s+=1){var c=l[s][n];if(c)for(var u=0,h=c;u<h.length;u+=1)r.push(h[u]);}}}r.sort((function(t,e){return e.intersectionZ-t.intersectionZ}));for(var p=[],d=this._order.length-1;d>=0;d--){var _=this._order[d];if(i(_))for(var f=r.length-1;f>=0;f--){var m=r[f].feature;if(o[m.layer.id]<d)break;p.push(m),r.pop();}else for(var g=0,v=t;g<v.length;g+=1){var y=v[g][_];if(y)for(var x=0,b=y;x<b.length;x+=1)p.push(b[x].feature);}}return p},i.prototype.queryRenderedFeatures=function(e,i,o){i&&i.filter&&this._validate(t.validateStyle.filter,"queryRenderedFeatures.filter",i.filter,null,i);var r={};if(i&&i.layers){if(!Array.isArray(i.layers))return this.fire(new t.ErrorEvent(new Error("parameters.layers must be an Array."))),[];for(var a=0,n=i.layers;a<n.length;a+=1){var s=n[a],l=this._layers[s];if(!l)return this.fire(new t.ErrorEvent(new Error("The layer '"+s+"' does not exist in the map's style and cannot be queried for features."))),[];r[l.source]=!0;}}var c=[];for(var u in i.availableImages=this._availableImages,this.sourceCaches)i.layers&&!r[u]||c.push(O(this.sourceCaches[u],this._layers,this._serializedLayers,e,i,o));return this.placement&&c.push(function(t,e,i,o,r,a,n){for(var s={},l=a.queryRenderedSymbols(o),c=[],u=0,h=Object.keys(l).map(Number);u<h.length;u+=1)c.push(n[h[u]]);c.sort(F);for(var p=function(){var i=_[d],o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],e,i.bucketIndex,i.sourceLayerIndex,r.filter,r.layers,r.availableImages,t);for(var a in o){var n=s[a]=s[a]||[],c=o[a];c.sort((function(t,e){var o=i.featureSortOrder;if(o){var r=o.indexOf(t.featureIndex);return o.indexOf(e.featureIndex)-r}return e.featureIndex-t.featureIndex}));for(var u=0,h=c;u<h.length;u+=1)n.push(h[u]);}},d=0,_=c;d<_.length;d+=1)p();var f=function(e){s[e].forEach((function(o){var r=o.feature,a=i[t[e].source].getFeatureState(r.layer["source-layer"],r.id);r.source=r.layer.source,r.layer["source-layer"]&&(r.sourceLayer=r.layer["source-layer"]),r.state=a;}));};for(var m in s)f(m);return s}(this._layers,this._serializedLayers,this.sourceCaches,e,i,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(c)},i.prototype.querySourceFeatures=function(e,i){i&&i.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",i.filter,null,i);var o=this.sourceCaches[e];return o?function(t,e){for(var i=t.getRenderableIds().map((function(e){return t.getTileByID(e)})),o=[],r={},a=0;a<i.length;a++){var n=i[a],s=n.tileID.canonical.key;r[s]||(r[s]=!0,n.querySourceFeatures(o,e));}return o}(o,i):[]},i.prototype.addSourceType=function(t,e,o){return i.getSourceType(t)?o(new Error('A source type called "'+t+'" already exists.')):(i.setSourceType(t,e),e.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:t,url:e.workerSourceURL},o):o(null,null))},i.prototype.getLight=function(){return this.light.getLight()},i.prototype.setLight=function(e,i){void 0===i&&(i={}),this._checkLoaded();var o=this.light.getLight(),r=!1;for(var a in e)if(!t.deepEqual(e[a],o[a])){r=!0;break}if(r){var n={now:t.browser.now(),transition:t.extend({duration:300,delay:0},this.stylesheet.transition)};this.light.setLight(e,i),this.light.updateTransitions(n);}},i.prototype._validate=function(e,i,o,r,a){return void 0===a&&(a={}),(!a||!1!==a.validate)&&Ue(this,e.call(t.validateStyle,t.extend({key:i,style:this.serialize(),value:o,styleSpec:t.styleSpec},r)))},i.prototype._remove=function(){for(var e in this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),t.evented.off("pluginStateChange",this._rtlTextPluginCallback),this._layers)this._layers[e].setEventedParent(null);for(var i in this.sourceCaches)this.sourceCaches[i].clearTiles(),this.sourceCaches[i].setEventedParent(null);this.imageManager.setEventedParent(null),this.setEventedParent(null),this.dispatcher.remove();},i.prototype._clearSource=function(t){this.sourceCaches[t].clearTiles();},i.prototype._reloadSource=function(t){this.sourceCaches[t].resume(),this.sourceCaches[t].reload();},i.prototype._updateSources=function(t){for(var e in this.sourceCaches)this.sourceCaches[e].update(t);},i.prototype._generateCollisionBoxes=function(){for(var t in this.sourceCaches)this._reloadSource(t);},i.prototype._updatePlacement=function(e,i,o,r,a){void 0===a&&(a=!1);for(var n=!1,s=!1,l={},c=0,u=this._order;c<u.length;c+=1){var h=this._layers[u[c]];if("symbol"===h.type){if(!l[h.source]){var p=this.sourceCaches[h.source];l[h.source]=p.getRenderableIds(!0).map((function(t){return p.getTileByID(t)})).sort((function(t,e){return e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)}));}var d=this.crossTileSymbolIndex.addLayer(h,l[h.source],e.center.lng);n=n||d;}}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((a=a||this._layerOrderChanged||0===o)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(t.browser.now(),e.zoom))&&(this.pauseablePlacement=new Ae(e,this._order,a,i,o,r,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(t.browser.now()),s=!0),n&&this.pauseablePlacement.placement.setStale()),s||n)for(var _=0,f=this._order;_<f.length;_+=1){var m=this._layers[f[_]];"symbol"===m.type&&this.placement.updateLayerOpacities(m,l[m.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(t.browser.now())},i.prototype._releaseSymbolFadeTiles=function(){for(var t in this.sourceCaches)this.sourceCaches[t].releaseSymbolFadeTiles();},i.prototype.getImages=function(t,e,i){this.imageManager.getImages(e.icons,i),this._updateTilesForChangedImages();var o=this.sourceCaches[e.source];o&&o.setDependencies(e.tileID.key,e.type,e.icons);},i.prototype.getGlyphs=function(t,e,i){this.glyphManager.getGlyphs(e.stacks,i);},i.prototype.getResource=function(e,i,o){return t.makeRequest(i,o)},i}(t.Evented);qe.getSourceType=function(t){return k[t]},qe.setSourceType=function(t,e){k[t]=e;},qe.registerForPluginStateChange=t.registerForPluginStateChange;var Ve=t.createLayout([{name:"a_pos",type:"Int16",components:2}]),Ge=gi("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}"),We=gi("uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),Xe=gi("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),He=gi("varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,0,1);} else {gl_Position=u_matrix*vec4(circle_center,0,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),Ke=gi("void main() {gl_FragColor=vec4(1.0);}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),Ye=gi("uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,0,1);gl_Position=u_matrix*pos;}"),Je=gi("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),Qe=gi("varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}","attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,0.0,1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}"),$e=gi("varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),ti=gi("uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}","attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,0,1);}"),ei=gi("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"),ii=gi("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),oi=gi("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),ri=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),ai=gi("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),ni=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),si=gi("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform float u_maxzoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggeration=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/ pow(2.0,(u_zoom-u_maxzoom)*exaggeration+19.2562-u_zoom);gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),li=gi("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"),ci=gi("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),ui=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,vec2(v_lineprogress,0.5));gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define MAX_LINE_DISTANCE 32767.0\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_lineprogress=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0/MAX_LINE_DISTANCE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),hi=gi("uniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),pi=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),di=gi("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),_i=gi("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),0.0,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;v_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));}"),fi=gi("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),mi=gi("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}");function gi(t,e){var i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=e.match(/attribute ([\w]+) ([\w]+)/g),r=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),n=a?a.concat(r):r,s={};return {fragmentSource:t=t.replace(i,(function(t,e,i,o,r){return s[r]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nvarying "+i+" "+o+" "+r+";\n#else\nuniform "+i+" "+o+" u_"+r+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+r+"\n "+i+" "+o+" "+r+" = u_"+r+";\n#endif\n"})),vertexSource:e=e.replace(i,(function(t,e,i,o,r){var a="float"===o?"vec2":"vec4",n=r.match(/color/)?"color":a;return s[r]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nuniform lowp float u_"+r+"_t;\nattribute "+i+" "+a+" a_"+r+";\nvarying "+i+" "+o+" "+r+";\n#else\nuniform "+i+" "+o+" u_"+r+";\n#endif\n":"vec4"===n?"\n#ifndef HAS_UNIFORM_u_"+r+"\n "+r+" = a_"+r+";\n#else\n "+i+" "+o+" "+r+" = u_"+r+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+r+"\n "+r+" = unpack_mix_"+n+"(a_"+r+", u_"+r+"_t);\n#else\n "+i+" "+o+" "+r+" = u_"+r+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+r+"\nuniform lowp float u_"+r+"_t;\nattribute "+i+" "+a+" a_"+r+";\n#else\nuniform "+i+" "+o+" u_"+r+";\n#endif\n":"vec4"===n?"\n#ifndef HAS_UNIFORM_u_"+r+"\n "+i+" "+o+" "+r+" = a_"+r+";\n#else\n "+i+" "+o+" "+r+" = u_"+r+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+r+"\n "+i+" "+o+" "+r+" = unpack_mix_"+n+"(a_"+r+", u_"+r+"_t);\n#else\n "+i+" "+o+" "+r+" = u_"+r+";\n#endif\n"})),staticAttributes:o,staticUniforms:n}}var vi=Object.freeze({__proto__:null,prelude:Ge,background:We,backgroundPattern:Xe,circle:He,clippingMask:Ke,heatmap:Ye,heatmapTexture:Je,collisionBox:Qe,collisionCircle:$e,debug:ti,fill:ei,fillOutline:ii,fillOutlinePattern:oi,fillPattern:ri,fillExtrusion:ai,fillExtrusionPattern:ni,hillshadePrepare:si,hillshade:li,line:ci,lineGradient:ui,linePattern:hi,lineSDF:pi,raster:di,symbolIcon:_i,symbolSDF:fi,symbolTextAndIcon:mi}),yi=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;};function xi(t){for(var e=[],i=0;i<t.length;i++)if(null!==t[i]){var o=t[i].split(" ");e.push(o.pop());}return e}yi.prototype.bind=function(t,e,i,o,r,a,n,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==o.length,c=0;!l&&c<o.length;c++)this.boundPaintVertexBuffers[c]!==o[c]&&(l=!0);t.extVertexArrayObject&&this.vao&&this.boundProgram===e&&this.boundLayoutVertexBuffer===i&&!l&&this.boundIndexBuffer===r&&this.boundVertexOffset===a&&this.boundDynamicVertexBuffer===n&&this.boundDynamicVertexBuffer2===s?(t.bindVertexArrayOES.set(this.vao),n&&n.bind(),r&&r.dynamicDraw&&r.bind(),s&&s.bind()):this.freshBind(e,i,o,r,a,n,s);},yi.prototype.freshBind=function(t,e,i,o,r,a,n){var s,l=t.numAttributes,c=this.context,u=c.gl;if(c.extVertexArrayObject)this.vao&&this.destroy(),this.vao=c.extVertexArrayObject.createVertexArrayOES(),c.bindVertexArrayOES.set(this.vao),s=0,this.boundProgram=t,this.boundLayoutVertexBuffer=e,this.boundPaintVertexBuffers=i,this.boundIndexBuffer=o,this.boundVertexOffset=r,this.boundDynamicVertexBuffer=a,this.boundDynamicVertexBuffer2=n;else {s=c.currentNumAttributes||0;for(var h=l;h<s;h++)u.disableVertexAttribArray(h);}e.enableAttributes(u,t);for(var p=0,d=i;p<d.length;p+=1)d[p].enableAttributes(u,t);a&&a.enableAttributes(u,t),n&&n.enableAttributes(u,t),e.bind(),e.setVertexAttribPointers(u,t,r);for(var _=0,f=i;_<f.length;_+=1){var m=f[_];m.bind(),m.setVertexAttribPointers(u,t,r);}a&&(a.bind(),a.setVertexAttribPointers(u,t,r)),o&&o.bind(),n&&(n.bind(),n.setVertexAttribPointers(u,t,r)),c.currentNumAttributes=l;},yi.prototype.destroy=function(){this.vao&&(this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao),this.vao=null);};var bi=function(t,e,i,o,r,a){var n=t.gl;this.program=n.createProgram();for(var s=xi(i.staticAttributes),l=o?o.getBinderAttributes():[],c=s.concat(l),u=i.staticUniforms?xi(i.staticUniforms):[],h=o?o.getBinderUniforms():[],p=[],d=0,_=u.concat(h);d<_.length;d+=1){var f=_[d];p.indexOf(f)<0&&p.push(f);}var m=o?o.defines():[];a&&m.push("#define OVERDRAW_INSPECTOR;");var g=m.concat(Ge.fragmentSource,i.fragmentSource).join("\n"),v=m.concat(Ge.vertexSource,i.vertexSource).join("\n"),y=n.createShader(n.FRAGMENT_SHADER);if(n.isContextLost())this.failedToCreate=!0;else {n.shaderSource(y,g),n.compileShader(y),n.attachShader(this.program,y);var x=n.createShader(n.VERTEX_SHADER);if(n.isContextLost())this.failedToCreate=!0;else {n.shaderSource(x,v),n.compileShader(x),n.attachShader(this.program,x),this.attributes={};var b={};this.numAttributes=c.length;for(var w=0;w<this.numAttributes;w++)c[w]&&(n.bindAttribLocation(this.program,w,c[w]),this.attributes[c[w]]=w);n.linkProgram(this.program),n.deleteShader(x),n.deleteShader(y);for(var T=0;T<p.length;T++){var E=p[T];if(E&&!b[E]){var I=n.getUniformLocation(this.program,E);I&&(b[E]=I);}}this.fixedUniforms=r(t,b),this.binderUniforms=o?o.getUniforms(t,b):[];}}};function wi(t,e,i){var o=1/pe(i,1,e.transform.tileZoom),r=Math.pow(2,i.tileID.overscaledZ),a=i.tileSize*Math.pow(2,e.transform.tileZoom)/r,n=a*(i.tileID.canonical.x+i.tileID.wrap*r),s=a*i.tileID.canonical.y;return {u_image:0,u_texsize:i.imageAtlasTexture.size,u_scale:[o,t.fromScale,t.toScale],u_fade:t.t,u_pixel_coord_upper:[n>>16,s>>16],u_pixel_coord_lower:[65535&n,65535&s]}}bi.prototype.draw=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_,f){var m,g=t.gl;if(!this.failedToCreate){for(var v in t.program.set(this.program),t.setDepthMode(i),t.setStencilMode(o),t.setColorMode(r),t.setCullFace(a),this.fixedUniforms)this.fixedUniforms[v].set(n[v]);d&&d.setUniforms(t,this.binderUniforms,h,{zoom:p});for(var y=(m={},m[g.LINES]=2,m[g.TRIANGLES]=3,m[g.LINE_STRIP]=1,m)[e],x=0,b=u.get();x<b.length;x+=1){var w=b[x],T=w.vaos||(w.vaos={});(T[s]||(T[s]=new yi)).bind(t,this,l,d?d.getPaintVertexBuffers():[],c,w.vertexOffset,_,f),g.drawElements(e,w.primitiveLength*y,g.UNSIGNED_SHORT,w.primitiveOffset*y*2);}}};var Ti=function(e,i,o,r){var a=i.style.light,n=a.properties.get("position"),s=[n.x,n.y,n.z],l=t.create$1();"viewport"===a.properties.get("anchor")&&t.fromRotation(l,-i.transform.angle),t.transformMat3(s,s,l);var c=a.properties.get("color");return {u_matrix:e,u_lightpos:s,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[c.r,c.g,c.b],u_vertical_gradient:+o,u_opacity:r}},Ei=function(e,i,o,r,a,n,s){return t.extend(Ti(e,i,o,r),wi(n,i,s),{u_height_factor:-Math.pow(2,a.overscaledZ)/s.tileSize/8})},Ii=function(t){return {u_matrix:t}},Pi=function(e,i,o,r){return t.extend(Ii(e),wi(o,i,r))},Si=function(t,e){return {u_matrix:t,u_world:e}},Ci=function(e,i,o,r,a){return t.extend(Pi(e,i,o,r),{u_world:a})},zi=function(e,i,o,r){var a,n,s=e.transform;if("map"===r.paint.get("circle-pitch-alignment")){var l=pe(o,1,s.zoom);a=!0,n=[l,l];}else a=!1,n=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_matrix:e.translatePosMatrix(i.posMatrix,o,r.paint.get("circle-translate"),r.paint.get("circle-translate-anchor")),u_pitch_with_map:+a,u_device_pixel_ratio:t.browser.devicePixelRatio,u_extrude_scale:n}},Di=function(t,e,i){var o=pe(i,1,e.zoom),r=Math.pow(2,e.zoom-i.tileID.overscaledZ),a=i.tileID.overscaleFactor();return {u_matrix:t,u_camera_to_center_distance:e.cameraToCenterDistance,u_pixels_to_tile_units:o,u_extrude_scale:[e.pixelsToGLUnits[0]/(o*r),e.pixelsToGLUnits[1]/(o*r)],u_overscale_factor:a}},Mi=function(t,e,i){return {u_matrix:t,u_inv_matrix:e,u_camera_to_center_distance:i.cameraToCenterDistance,u_viewport_size:[i.width,i.height]}},Li=function(t,e,i){return void 0===i&&(i=1),{u_matrix:t,u_color:e,u_overlay:0,u_overlay_scale:i}},Ai=function(t){return {u_matrix:t}},Ri=function(t,e,i,o){return {u_matrix:t,u_extrude_scale:pe(e,1,i),u_intensity:o}},ki=function(e,i,o){var r=e.transform;return {u_matrix:Ni(e,i,o),u_ratio:1/pe(i,1,r.zoom),u_device_pixel_ratio:t.browser.devicePixelRatio,u_units_to_pixels:[1/r.pixelsToGLUnits[0],1/r.pixelsToGLUnits[1]]}},Bi=function(e,i,o){return t.extend(ki(e,i,o),{u_image:0})},Oi=function(e,i,o,r){var a=e.transform,n=Ui(i,a);return {u_matrix:Ni(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:1/pe(i,1,a.zoom),u_device_pixel_ratio:t.browser.devicePixelRatio,u_image:0,u_scale:[n,r.fromScale,r.toScale],u_fade:r.t,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},Fi=function(e,i,o,r,a){var n=e.lineAtlas,s=Ui(i,e.transform),l="round"===o.layout.get("line-cap"),c=n.getDash(r.from,l),u=n.getDash(r.to,l),h=c.width*a.fromScale,p=u.width*a.toScale;return t.extend(ki(e,i,o),{u_patternscale_a:[s/h,-c.height/2],u_patternscale_b:[s/p,-u.height/2],u_sdfgamma:n.width/(256*Math.min(h,p)*t.browser.devicePixelRatio)/2,u_image:0,u_tex_y_a:c.y,u_tex_y_b:u.y,u_mix:a.t})};function Ui(t,e){return 1/pe(t,1,e.tileZoom)}function Ni(t,e,i){return t.translatePosMatrix(e.tileID.posMatrix,e,i.paint.get("line-translate"),i.paint.get("line-translate-anchor"))}var Zi=function(t,e,i,o,r){return {u_matrix:t,u_tl_parent:e,u_scale_parent:i,u_buffer_scale:1,u_fade_t:o.mix,u_opacity:o.opacity*r.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:r.paint.get("raster-brightness-min"),u_brightness_high:r.paint.get("raster-brightness-max"),u_saturation_factor:(n=r.paint.get("raster-saturation"),n>0?1-1/(1.001-n):-n),u_contrast_factor:(a=r.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:ji(r.paint.get("raster-hue-rotate"))};var a,n;};function ji(t){t*=Math.PI/180;var e=Math.sin(t),i=Math.cos(t);return [(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}var qi,Vi=function(t,e,i,o,r,a,n,s,l,c){var u=r.transform;return {u_is_size_zoom_constant:+("constant"===t||"source"===t),u_is_size_feature_constant:+("constant"===t||"camera"===t),u_size_t:e?e.uSizeT:0,u_size:e?e.uSize:0,u_camera_to_center_distance:u.cameraToCenterDistance,u_pitch:u.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:u.width/u.height,u_fade_change:r.options.fadeDuration?r.symbolFadeChange:1,u_matrix:a,u_label_plane_matrix:n,u_coord_matrix:s,u_is_text:+l,u_pitch_with_map:+o,u_texsize:c,u_texture:0}},Gi=function(e,i,o,r,a,n,s,l,c,u,h){var p=a.transform;return t.extend(Vi(e,i,o,r,a,n,s,l,c,u),{u_gamma_scale:r?Math.cos(p._pitch)*p.cameraToCenterDistance:1,u_device_pixel_ratio:t.browser.devicePixelRatio,u_is_halo:+h})},Wi=function(e,i,o,r,a,n,s,l,c,u){return t.extend(Gi(e,i,o,r,a,n,s,l,!0,c,!0),{u_texsize_icon:u,u_texture_icon:1})},Xi=function(t,e,i){return {u_matrix:t,u_opacity:e,u_color:i}},Hi=function(e,i,o,r,a,n){return t.extend(function(t,e,i,o){var r=i.imageManager.getPattern(t.from.toString()),a=i.imageManager.getPattern(t.to.toString()),n=i.imageManager.getPixelSize(),s=n.width,l=n.height,c=Math.pow(2,o.tileID.overscaledZ),u=o.tileSize*Math.pow(2,i.transform.tileZoom)/c,h=u*(o.tileID.canonical.x+o.tileID.wrap*c),p=u*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:r.tl,u_pattern_br_a:r.br,u_pattern_tl_b:a.tl,u_pattern_br_b:a.br,u_texsize:[s,l],u_mix:e.t,u_pattern_size_a:r.displaySize,u_pattern_size_b:a.displaySize,u_scale_a:e.fromScale,u_scale_b:e.toScale,u_tile_units_to_pixels:1/pe(o,1,i.transform.tileZoom),u_pixel_coord_upper:[h>>16,p>>16],u_pixel_coord_lower:[65535&h,65535&p]}}(r,n,o,a),{u_matrix:e,u_opacity:i})},Ki={fillExtrusion:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fillExtrusionPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_height_factor:new t.Uniform1f(e,i.u_height_factor),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fill:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},fillPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},fillOutline:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world)}},fillOutlinePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},circle:function(e,i){return {u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_scale_with_map:new t.Uniform1i(e,i.u_scale_with_map),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},collisionBox:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pixels_to_tile_units:new t.Uniform1f(e,i.u_pixels_to_tile_units),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_overscale_factor:new t.Uniform1f(e,i.u_overscale_factor)}},collisionCircle:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_inv_matrix:new t.UniformMatrix4f(e,i.u_inv_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_viewport_size:new t.Uniform2f(e,i.u_viewport_size)}},debug:function(e,i){return {u_color:new t.UniformColor(e,i.u_color),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_overlay:new t.Uniform1i(e,i.u_overlay),u_overlay_scale:new t.Uniform1f(e,i.u_overlay_scale)}},clippingMask:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmap:function(e,i){return {u_extrude_scale:new t.Uniform1f(e,i.u_extrude_scale),u_intensity:new t.Uniform1f(e,i.u_intensity),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmapTexture:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_color_ramp:new t.Uniform1i(e,i.u_color_ramp),u_opacity:new t.Uniform1f(e,i.u_opacity)}},hillshade:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_latrange:new t.Uniform2f(e,i.u_latrange),u_light:new t.Uniform2f(e,i.u_light),u_shadow:new t.UniformColor(e,i.u_shadow),u_highlight:new t.UniformColor(e,i.u_highlight),u_accent:new t.UniformColor(e,i.u_accent)}},hillshadePrepare:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_dimension:new t.Uniform2f(e,i.u_dimension),u_zoom:new t.Uniform1f(e,i.u_zoom),u_maxzoom:new t.Uniform1f(e,i.u_maxzoom),u_unpack:new t.Uniform4f(e,i.u_unpack)}},line:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels)}},lineGradient:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_image:new t.Uniform1i(e,i.u_image)}},linePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_texsize:new t.Uniform2f(e,i.u_texsize),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_image:new t.Uniform1i(e,i.u_image),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},lineSDF:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_patternscale_a:new t.Uniform2f(e,i.u_patternscale_a),u_patternscale_b:new t.Uniform2f(e,i.u_patternscale_b),u_sdfgamma:new t.Uniform1f(e,i.u_sdfgamma),u_image:new t.Uniform1i(e,i.u_image),u_tex_y_a:new t.Uniform1f(e,i.u_tex_y_a),u_tex_y_b:new t.Uniform1f(e,i.u_tex_y_b),u_mix:new t.Uniform1f(e,i.u_mix)}},raster:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_tl_parent:new t.Uniform2f(e,i.u_tl_parent),u_scale_parent:new t.Uniform1f(e,i.u_scale_parent),u_buffer_scale:new t.Uniform1f(e,i.u_buffer_scale),u_fade_t:new t.Uniform1f(e,i.u_fade_t),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image0:new t.Uniform1i(e,i.u_image0),u_image1:new t.Uniform1i(e,i.u_image1),u_brightness_low:new t.Uniform1f(e,i.u_brightness_low),u_brightness_high:new t.Uniform1f(e,i.u_brightness_high),u_saturation_factor:new t.Uniform1f(e,i.u_saturation_factor),u_contrast_factor:new t.Uniform1f(e,i.u_contrast_factor),u_spin_weights:new t.Uniform3f(e,i.u_spin_weights)}},symbolIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture)}},symbolSDF:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},symbolTextAndIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texsize_icon:new t.Uniform2f(e,i.u_texsize_icon),u_texture:new t.Uniform1i(e,i.u_texture),u_texture_icon:new t.Uniform1i(e,i.u_texture_icon),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},background:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_color:new t.UniformColor(e,i.u_color)}},backgroundPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image:new t.Uniform1i(e,i.u_image),u_pattern_tl_a:new t.Uniform2f(e,i.u_pattern_tl_a),u_pattern_br_a:new t.Uniform2f(e,i.u_pattern_br_a),u_pattern_tl_b:new t.Uniform2f(e,i.u_pattern_tl_b),u_pattern_br_b:new t.Uniform2f(e,i.u_pattern_br_b),u_texsize:new t.Uniform2f(e,i.u_texsize),u_mix:new t.Uniform1f(e,i.u_mix),u_pattern_size_a:new t.Uniform2f(e,i.u_pattern_size_a),u_pattern_size_b:new t.Uniform2f(e,i.u_pattern_size_b),u_scale_a:new t.Uniform1f(e,i.u_scale_a),u_scale_b:new t.Uniform1f(e,i.u_scale_b),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.Uniform1f(e,i.u_tile_units_to_pixels)}}};function Yi(e,i,o,r,a,n,s){for(var l=e.context,c=l.gl,u=e.useProgram("collisionBox"),h=[],p=0,d=0,_=0;_<r.length;_++){var f=r[_],m=i.getTile(f),g=m.getBucket(o);if(g){var v=f.posMatrix;0===a[0]&&0===a[1]||(v=e.translatePosMatrix(f.posMatrix,m,a,n));var y=s?g.textCollisionBox:g.iconCollisionBox,x=g.collisionCircleArray;if(x.length>0){var b=t.create(),w=v;t.mul(b,g.placementInvProjMatrix,e.transform.glCoordMatrix),t.mul(b,b,g.placementViewportMatrix),h.push({circleArray:x,circleOffset:d,transform:w,invTransform:b}),d=p+=x.length/4;}y&&u.draw(l,c.LINES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,Di(v,e.transform,m),o.id,y.layoutVertexBuffer,y.indexBuffer,y.segments,null,e.transform.zoom,null,null,y.collisionVertexBuffer);}}if(s&&h.length){var T=e.useProgram("collisionCircle"),E=new t.StructArrayLayout2f1f2i16;E.resize(4*p),E._trim();for(var I=0,P=0,S=h;P<S.length;P+=1)for(var C=S[P],z=0;z<C.circleArray.length/4;z++){var D=4*z,M=C.circleArray[D+0],L=C.circleArray[D+1],A=C.circleArray[D+2],R=C.circleArray[D+3];E.emplace(I++,M,L,A,R,0),E.emplace(I++,M,L,A,R,1),E.emplace(I++,M,L,A,R,2),E.emplace(I++,M,L,A,R,3);}(!qi||qi.length<2*p)&&(qi=function(e){var i=2*e,o=new t.StructArrayLayout3ui6;o.resize(i),o._trim();for(var r=0;r<i;r++){var a=6*r;o.uint16[a+0]=4*r+0,o.uint16[a+1]=4*r+1,o.uint16[a+2]=4*r+2,o.uint16[a+3]=4*r+2,o.uint16[a+4]=4*r+3,o.uint16[a+5]=4*r+0;}return o}(p));for(var k=l.createIndexBuffer(qi,!0),B=l.createVertexBuffer(E,t.collisionCircleLayout.members,!0),O=0,F=h;O<F.length;O+=1){var U=F[O],N=Mi(U.transform,U.invTransform,e.transform);T.draw(l,c.TRIANGLES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,N,o.id,B,k,t.SegmentVector.simpleSegment(0,2*U.circleOffset,U.circleArray.length,U.circleArray.length/2),null,e.transform.zoom,null,null,null);}B.destroy(),k.destroy();}}var Ji=t.identity(new Float32Array(16));function Qi(e,i,o,r,a,n){var s=t.getAnchorAlignment(e),l=-(s.horizontalAlign-.5)*i,c=-(s.verticalAlign-.5)*o,u=t.evaluateVariableOffset(e,r);return new t.Point((l/a+u[0])*n,(c/a+u[1])*n)}function $i(e,i,o,r,a,n,s,l,c,u,h){var p=e.text.placedSymbolArray,d=e.text.dynamicLayoutVertexArray,_=e.icon.dynamicLayoutVertexArray,f={};d.clear();for(var m=0;m<p.length;m++){var g=p.get(m),v=g.hidden||!g.crossTileID||e.allowVerticalPlacement&&!g.placedOrientation?null:r[g.crossTileID];if(v){var y=new t.Point(g.anchorX,g.anchorY),x=$t(y,o?l:s),b=te(n.cameraToCenterDistance,x.signedDistanceFromCamera),w=a.evaluateSizeForFeature(e.textSizeData,u,g)*b/t.ONE_EM;o&&(w*=e.tilePixelRatio/c);for(var T=Qi(v.anchor,v.width,v.height,v.textOffset,v.textBoxScale,w),E=o?$t(y.add(T),s).point:x.point.add(i?T.rotate(-n.angle):T),I=e.allowVerticalPlacement&&g.placedOrientation===t.WritingMode.vertical?Math.PI/2:0,P=0;P<g.numGlyphs;P++)t.addDynamicAttributes(d,E,I);h&&g.associatedIconIndex>=0&&(f[g.associatedIconIndex]={shiftedAnchor:E,angle:I});}else ce(g.numGlyphs,d);}if(h){_.clear();for(var S=e.icon.placedSymbolArray,C=0;C<S.length;C++){var z=S.get(C);if(z.hidden)ce(z.numGlyphs,_);else {var D=f[C];if(D)for(var M=0;M<z.numGlyphs;M++)t.addDynamicAttributes(_,D.shiftedAnchor,D.angle);else ce(z.numGlyphs,_);}}e.icon.dynamicLayoutVertexBuffer.updateData(_);}e.text.dynamicLayoutVertexBuffer.updateData(d);}function to(t,e,i){return i.iconsInText&&e?"symbolTextAndIcon":t?"symbolSDF":"symbolIcon"}function eo(e,i,o,r,a,n,s,l,c,u,h,p){for(var d=e.context,_=d.gl,f=e.transform,m="map"===l,g="map"===c,v=m&&"point"!==o.layout.get("symbol-placement"),y=m&&!g&&!v,x=void 0!==o.layout.get("symbol-sort-key").constantOr(1),b=e.depthModeForSublayer(0,It.ReadOnly),w=o.layout.get("text-variable-anchor"),T=[],E=0,I=r;E<I.length;E+=1){var P=I[E],S=i.getTile(P),C=S.getBucket(o);if(C){var z=a?C.text:C.icon;if(z&&z.segments.get().length){var D=z.programConfigurations.get(o.id),M=a||C.sdfIcons,L=a?C.textSizeData:C.iconSizeData,A=g||0!==f.pitch,R=e.useProgram(to(M,a,C),D),k=t.evaluateSizeForZoom(L,f.zoom),B=void 0,O=[0,0],F=void 0,U=void 0,N=null,Z=void 0;if(a)F=S.glyphAtlasTexture,U=_.LINEAR,B=S.glyphAtlasTexture.size,C.iconsInText&&(O=S.imageAtlasTexture.size,N=S.imageAtlasTexture,Z=A||e.options.rotating||e.options.zooming||"composite"===L.kind||"camera"===L.kind?_.LINEAR:_.NEAREST);else {var j=1!==o.layout.get("icon-size").constantOr(0)||C.iconsNeedLinear;F=S.imageAtlasTexture,U=M||e.options.rotating||e.options.zooming||j||A?_.LINEAR:_.NEAREST,B=S.imageAtlasTexture.size;}var q=pe(S,1,e.transform.zoom),V=Jt(P.posMatrix,g,m,e.transform,q),G=Qt(P.posMatrix,g,m,e.transform,q),W=w&&C.hasTextData(),X="none"!==o.layout.get("icon-text-fit")&&W&&C.hasIconData();v&&ie(C,P.posMatrix,e,a,V,G,g,u);var H=e.translatePosMatrix(P.posMatrix,S,n,s),K=v||a&&w||X?Ji:V,Y=e.translatePosMatrix(G,S,n,s,!0),J=M&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1),Q={program:R,buffers:z,uniformValues:M?C.iconsInText?Wi(L.kind,k,y,g,e,H,K,Y,B,O):Gi(L.kind,k,y,g,e,H,K,Y,a,B,!0):Vi(L.kind,k,y,g,e,H,K,Y,a,B),atlasTexture:F,atlasTextureIcon:N,atlasInterpolation:U,atlasInterpolationIcon:Z,isSDF:M,hasHalo:J};if(x)for(var $=0,tt=z.segments.get();$<tt.length;$+=1){var et=tt[$];T.push({segments:new t.SegmentVector([et]),sortKey:et.sortKey,state:Q});}else T.push({segments:z.segments,sortKey:0,state:Q});}}}x&&T.sort((function(t,e){return t.sortKey-e.sortKey}));for(var it=0,ot=T;it<ot.length;it+=1){var rt=ot[it],at=rt.state;if(d.activeTexture.set(_.TEXTURE0),at.atlasTexture.bind(at.atlasInterpolation,_.CLAMP_TO_EDGE),at.atlasTextureIcon&&(d.activeTexture.set(_.TEXTURE1),at.atlasTextureIcon&&at.atlasTextureIcon.bind(at.atlasInterpolationIcon,_.CLAMP_TO_EDGE)),at.isSDF){var nt=at.uniformValues;at.hasHalo&&(nt.u_is_halo=1,io(at.buffers,rt.segments,o,e,at.program,b,h,p,nt)),nt.u_is_halo=0;}io(at.buffers,rt.segments,o,e,at.program,b,h,p,at.uniformValues);}}function io(t,e,i,o,r,a,n,s,l){var c=o.context;r.draw(c,c.gl.TRIANGLES,a,n,s,Ct.disabled,l,i.id,t.layoutVertexBuffer,t.indexBuffer,e,i.paint,o.transform.zoom,t.programConfigurations.get(i.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer);}function oo(t,e,i,o,r,a,n){var s,l,c,u,h,p=t.context.gl,d=i.paint.get("fill-pattern"),_=d&&d.constantOr(1),f=i.getCrossfadeParameters();n?(l=_&&!i.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",s=p.LINES):(l=_?"fillPattern":"fill",s=p.TRIANGLES);for(var m=0,g=o;m<g.length;m+=1){var v=g[m],y=e.getTile(v);if(!_||y.patternsLoaded()){var x=y.getBucket(i);if(x){var b=x.programConfigurations.get(i.id),w=t.useProgram(l,b);_&&(t.context.activeTexture.set(p.TEXTURE0),y.imageAtlasTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE),b.updatePaintBuffers(f));var T=d.constantOr(null);if(T&&y.imageAtlas){var E=y.imageAtlas,I=E.patternPositions[T.to.toString()],P=E.patternPositions[T.from.toString()];I&&P&&b.setConstantPatternPositions(I,P);}var S=t.translatePosMatrix(v.posMatrix,y,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor"));if(n){u=x.indexBuffer2,h=x.segments2;var C=[p.drawingBufferWidth,p.drawingBufferHeight];c="fillOutlinePattern"===l&&_?Ci(S,t,f,y,C):Si(S,C);}else u=x.indexBuffer,h=x.segments,c=_?Pi(S,t,f,y):Ii(S);w.draw(t.context,s,r,t.stencilModeForClipping(v),a,Ct.disabled,c,i.id,x.layoutVertexBuffer,u,h,i.paint,t.transform.zoom,b);}}}}function ro(t,e,i,o,r,a,n){for(var s=t.context,l=s.gl,c=i.paint.get("fill-extrusion-pattern"),u=c.constantOr(1),h=i.getCrossfadeParameters(),p=i.paint.get("fill-extrusion-opacity"),d=0,_=o;d<_.length;d+=1){var f=_[d],m=e.getTile(f),g=m.getBucket(i);if(g){var v=g.programConfigurations.get(i.id),y=t.useProgram(u?"fillExtrusionPattern":"fillExtrusion",v);u&&(t.context.activeTexture.set(l.TEXTURE0),m.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),v.updatePaintBuffers(h));var x=c.constantOr(null);if(x&&m.imageAtlas){var b=m.imageAtlas,w=b.patternPositions[x.to.toString()],T=b.patternPositions[x.from.toString()];w&&T&&v.setConstantPatternPositions(w,T);}var E=t.translatePosMatrix(f.posMatrix,m,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),I=i.paint.get("fill-extrusion-vertical-gradient"),P=u?Ei(E,t,I,p,f,h,m):Ti(E,t,I,p);y.draw(s,s.gl.TRIANGLES,r,a,n,Ct.backCCW,P,i.id,g.layoutVertexBuffer,g.indexBuffer,g.segments,i.paint,t.transform.zoom,v);}}}function ao(e,i,o,r,a,n){var s=e.context,l=s.gl,c=i.fbo;if(c){var u=e.useProgram("hillshade");s.activeTexture.set(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,c.colorAttachment.get());var h=function(e,i,o){var r=o.paint.get("hillshade-shadow-color"),a=o.paint.get("hillshade-highlight-color"),n=o.paint.get("hillshade-accent-color"),s=o.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===o.paint.get("hillshade-illumination-anchor")&&(s-=e.transform.angle);var l,c,u,h=!e.options.moving;return {u_matrix:e.transform.calculatePosMatrix(i.tileID.toUnwrapped(),h),u_image:0,u_latrange:(l=i.tileID,c=Math.pow(2,l.canonical.z),u=l.canonical.y,[new t.MercatorCoordinate(0,u/c).toLngLat().lat,new t.MercatorCoordinate(0,(u+1)/c).toLngLat().lat]),u_light:[o.paint.get("hillshade-exaggeration"),s],u_shadow:r,u_highlight:a,u_accent:n}}(e,i,o);u.draw(s,l.TRIANGLES,r,a,n,Ct.disabled,h,o.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments);}}function no(e,i,o,r,a,n,s){var l=e.context,c=l.gl,u=i.dem;if(u&&u.data){var h=u.dim,p=u.stride,d=u.getPixels();if(l.activeTexture.set(c.TEXTURE1),l.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture=i.demTexture||e.getTileTexture(p),i.demTexture){var _=i.demTexture;_.update(d,{premultiply:!1}),_.bind(c.NEAREST,c.CLAMP_TO_EDGE);}else i.demTexture=new t.Texture(l,d,c.RGBA,{premultiply:!1}),i.demTexture.bind(c.NEAREST,c.CLAMP_TO_EDGE);l.activeTexture.set(c.TEXTURE0);var f=i.fbo;if(!f){var m=new t.Texture(l,{width:h,height:h,data:null},c.RGBA);m.bind(c.LINEAR,c.CLAMP_TO_EDGE),(f=i.fbo=l.createFramebuffer(h,h,!0)).colorAttachment.set(m.texture);}l.bindFramebuffer.set(f.framebuffer),l.viewport.set([0,0,h,h]),e.useProgram("hillshadePrepare").draw(l,c.TRIANGLES,a,n,s,Ct.disabled,function(e,i,o){var r=i.stride,a=t.create();return t.ortho(a,0,t.EXTENT,-t.EXTENT,0,0,1),t.translate(a,a,[0,-t.EXTENT,0]),{u_matrix:a,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_maxzoom:o,u_unpack:i.getUnpackVector()}}(i.tileID,u,r),o.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments),i.needsHillshadePrepare=!1;}}function so(e,i,o,r,a){var n=r.paint.get("raster-fade-duration");if(n>0){var s=t.browser.now(),l=(s-e.timeAdded)/n,c=i?(s-i.timeAdded)/n:-1,u=o.getSource(),h=a.coveringZoomLevel({tileSize:u.tileSize,roundZoom:u.roundZoom}),p=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(e.tileID.overscaledZ-h),d=p&&e.refreshedUponExpiration?1:t.clamp(p?l:1-c,0,1);return e.refreshedUponExpiration&&l>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}var lo=new t.Color(1,0,0,1),co=new t.Color(0,1,0,1),uo=new t.Color(0,0,1,1),ho=new t.Color(1,0,1,1),po=new t.Color(0,1,1,1);function _o(t,e,i,o){mo(t,0,e+i/2,t.transform.width,i,o);}function fo(t,e,i,o){mo(t,e-i/2,0,i,t.transform.height,o);}function mo(e,i,o,r,a,n){var s=e.context,l=s.gl;l.enable(l.SCISSOR_TEST),l.scissor(i*t.browser.devicePixelRatio,o*t.browser.devicePixelRatio,r*t.browser.devicePixelRatio,a*t.browser.devicePixelRatio),s.clear({color:n}),l.disable(l.SCISSOR_TEST);}function go(e,i,o){var r=e.context,a=r.gl,n=o.posMatrix,s=e.useProgram("debug"),l=It.disabled,c=Pt.disabled,u=e.colorModeForRenderPass();r.activeTexture.set(a.TEXTURE0),e.emptyTexture.bind(a.LINEAR,a.CLAMP_TO_EDGE),s.draw(r,a.LINE_STRIP,l,c,u,Ct.disabled,Li(n,t.Color.red),"$debug",e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);var h=i.getTileByID(o.key).latestRawTileData,p=Math.floor((h&&h.byteLength||0)/1024),d=i.getTile(o).tileSize,_=512/Math.min(d,512)*(o.overscaledZ/e.transform.zoom)*.5,f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=" => "+o.overscaledZ),function(t,e){t.initDebugOverlayCanvas();var i=t.debugOverlayCanvas,o=t.context.gl,r=t.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(e,5,5),r.strokeText(e,5,5),t.debugOverlayTexture.update(i),t.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,f+" "+p+"kb"),s.draw(r,a.TRIANGLES,l,c,St.alphaBlended,Ct.disabled,Li(n,t.Color.transparent,_),"$debug",e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments);}var vo={symbol:function(e,i,o,r,a){if("translucent"===e.renderPass){var n=Pt.disabled,s=e.colorModeForRenderPass();o.layout.get("text-variable-anchor")&&function(e,i,o,r,a,n,s){for(var l=i.transform,c="map"===a,u="map"===n,h=0,p=e;h<p.length;h+=1){var d=p[h],_=r.getTile(d),f=_.getBucket(o);if(f&&f.text&&f.text.segments.get().length){var m=t.evaluateSizeForZoom(f.textSizeData,l.zoom),g=pe(_,1,i.transform.zoom),v=Jt(d.posMatrix,u,c,i.transform,g),y="none"!==o.layout.get("icon-text-fit")&&f.hasIconData();if(m){var x=Math.pow(2,l.zoom-_.tileID.overscaledZ);$i(f,c,u,s,t.symbolSize,l,v,d.posMatrix,x,m,y);}}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&eo(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),n,s),0!==o.paint.get("text-opacity").constantOr(1)&&eo(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),n,s),i.map.showCollisionBoxes&&(Yi(e,i,o,r,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),!0),Yi(e,i,o,r,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),!1));}},circle:function(e,i,o,r){if("translucent"===e.renderPass){var a=o.paint.get("circle-opacity"),n=o.paint.get("circle-stroke-width"),s=o.paint.get("circle-stroke-opacity"),l=void 0!==o.layout.get("circle-sort-key").constantOr(1);if(0!==a.constantOr(1)||0!==n.constantOr(1)&&0!==s.constantOr(1)){for(var c=e.context,u=c.gl,h=e.depthModeForSublayer(0,It.ReadOnly),p=Pt.disabled,d=e.colorModeForRenderPass(),_=[],f=0;f<r.length;f++){var m=r[f],g=i.getTile(m),v=g.getBucket(o);if(v){var y=v.programConfigurations.get(o.id),x={programConfiguration:y,program:e.useProgram("circle",y),layoutVertexBuffer:v.layoutVertexBuffer,indexBuffer:v.indexBuffer,uniformValues:zi(e,m,g,o)};if(l)for(var b=0,w=v.segments.get();b<w.length;b+=1){var T=w[b];_.push({segments:new t.SegmentVector([T]),sortKey:T.sortKey,state:x});}else _.push({segments:v.segments,sortKey:0,state:x});}}l&&_.sort((function(t,e){return t.sortKey-e.sortKey}));for(var E=0,I=_;E<I.length;E+=1){var P=I[E],S=P.state;S.program.draw(c,u.TRIANGLES,h,p,d,Ct.disabled,S.uniformValues,o.id,S.layoutVertexBuffer,S.indexBuffer,P.segments,o.paint,e.transform.zoom,S.programConfiguration);}}}},heatmap:function(e,i,o,r){if(0!==o.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){var a=e.context,n=a.gl,s=Pt.disabled,l=new St([n.ONE,n.ONE],t.Color.transparent,[!0,!0,!0,!0]);!function(t,e,i){var o=t.gl;t.activeTexture.set(o.TEXTURE1),t.viewport.set([0,0,e.width/4,e.height/4]);var r=i.heatmapFbo;if(r)o.bindTexture(o.TEXTURE_2D,r.colorAttachment.get()),t.bindFramebuffer.set(r.framebuffer);else {var a=o.createTexture();o.bindTexture(o.TEXTURE_2D,a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),r=i.heatmapFbo=t.createFramebuffer(e.width/4,e.height/4,!1),function(t,e,i,o){var r=t.gl;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e.width/4,e.height/4,0,r.RGBA,t.extRenderToTextureHalfFloat?t.extTextureHalfFloat.HALF_FLOAT_OES:r.UNSIGNED_BYTE,null),o.colorAttachment.set(i);}(t,e,a,r);}}(a,e,o),a.clear({color:t.Color.transparent});for(var c=0;c<r.length;c++){var u=r[c];if(!i.hasRenderableParent(u)){var h=i.getTile(u),p=h.getBucket(o);if(p){var d=p.programConfigurations.get(o.id);e.useProgram("heatmap",d).draw(a,n.TRIANGLES,It.disabled,s,l,Ct.disabled,Ri(u.posMatrix,h,e.transform.zoom,o.paint.get("heatmap-intensity")),o.id,p.layoutVertexBuffer,p.indexBuffer,p.segments,o.paint,e.transform.zoom,d);}}}a.viewport.set([0,0,e.width,e.height]);}else "translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,i){var o=e.context,r=o.gl,a=i.heatmapFbo;if(a){o.activeTexture.set(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),o.activeTexture.set(r.TEXTURE1);var n=i.colorRampTexture;n||(n=i.colorRampTexture=new t.Texture(o,i.colorRamp,r.RGBA)),n.bind(r.LINEAR,r.CLAMP_TO_EDGE),e.useProgram("heatmapTexture").draw(o,r.TRIANGLES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,function(e,i,o,r){var a=t.create();t.ortho(a,0,e.width,e.height,0,0,1);var n=e.context.gl;return {u_matrix:a,u_world:[n.drawingBufferWidth,n.drawingBufferHeight],u_image:0,u_color_ramp:1,u_opacity:i.paint.get("heatmap-opacity")}}(e,i),i.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,i.paint,e.transform.zoom);}}(e,o));},line:function(e,i,o,r){if("translucent"===e.renderPass){var a=o.paint.get("line-opacity"),n=o.paint.get("line-width");if(0!==a.constantOr(1)&&0!==n.constantOr(1)){var s=e.depthModeForSublayer(0,It.ReadOnly),l=e.colorModeForRenderPass(),c=o.paint.get("line-dasharray"),u=o.paint.get("line-pattern"),h=u.constantOr(1),p=o.paint.get("line-gradient"),d=o.getCrossfadeParameters(),_=h?"linePattern":c?"lineSDF":p?"lineGradient":"line",f=e.context,m=f.gl,g=!0;if(p){f.activeTexture.set(m.TEXTURE0);var v=o.gradientTexture;if(!o.gradient)return;v||(v=o.gradientTexture=new t.Texture(f,o.gradient,m.RGBA)),v.bind(m.LINEAR,m.CLAMP_TO_EDGE);}for(var y=0,x=r;y<x.length;y+=1){var b=x[y],w=i.getTile(b);if(!h||w.patternsLoaded()){var T=w.getBucket(o);if(T){var E=T.programConfigurations.get(o.id),I=e.context.program.get(),P=e.useProgram(_,E),S=g||P.program!==I,C=u.constantOr(null);if(C&&w.imageAtlas){var z=w.imageAtlas,D=z.patternPositions[C.to.toString()],M=z.patternPositions[C.from.toString()];D&&M&&E.setConstantPatternPositions(D,M);}var L=h?Oi(e,w,o,d):c?Fi(e,w,o,c,d):p?Bi(e,w,o):ki(e,w,o);h?(f.activeTexture.set(m.TEXTURE0),w.imageAtlasTexture.bind(m.LINEAR,m.CLAMP_TO_EDGE),E.updatePaintBuffers(d)):c&&(S||e.lineAtlas.dirty)&&(f.activeTexture.set(m.TEXTURE0),e.lineAtlas.bind(f)),P.draw(f,m.TRIANGLES,s,e.stencilModeForClipping(b),l,Ct.disabled,L,o.id,T.layoutVertexBuffer,T.indexBuffer,T.segments,o.paint,e.transform.zoom,E),g=!1;}}}}}},fill:function(e,i,o,r){var a=o.paint.get("fill-color"),n=o.paint.get("fill-opacity");if(0!==n.constantOr(1)){var s=e.colorModeForRenderPass(),l=o.paint.get("fill-pattern"),c=e.opaquePassEnabledForLayer()&&!l.constantOr(1)&&1===a.constantOr(t.Color.transparent).a&&1===n.constantOr(0)?"opaque":"translucent";if(e.renderPass===c){var u=e.depthModeForSublayer(1,"opaque"===e.renderPass?It.ReadWrite:It.ReadOnly);oo(e,i,o,r,u,s,!1);}if("translucent"===e.renderPass&&o.paint.get("fill-antialias")){var h=e.depthModeForSublayer(o.getPaintProperty("fill-outline-color")?2:0,It.ReadOnly);oo(e,i,o,r,h,s,!0);}}},"fill-extrusion":function(t,e,i,o){var r=i.paint.get("fill-extrusion-opacity");if(0!==r&&"translucent"===t.renderPass){var a=new It(t.context.gl.LEQUAL,It.ReadWrite,t.depthRangeFor3D);if(1!==r||i.paint.get("fill-extrusion-pattern").constantOr(1))ro(t,e,i,o,a,Pt.disabled,St.disabled),ro(t,e,i,o,a,t.stencilModeFor3D(),t.colorModeForRenderPass());else {var n=t.colorModeForRenderPass();ro(t,e,i,o,a,Pt.disabled,n);}}},hillshade:function(t,e,i,o){if("offscreen"===t.renderPass||"translucent"===t.renderPass){for(var r=t.context,a=e.getSource().maxzoom,n=t.depthModeForSublayer(0,It.ReadOnly),s=t.colorModeForRenderPass(),l="translucent"===t.renderPass?t.stencilConfigForOverlap(o):[{},o],c=l[0],u=0,h=l[1];u<h.length;u+=1){var p=h[u],d=e.getTile(p);d.needsHillshadePrepare&&"offscreen"===t.renderPass?no(t,d,i,a,n,Pt.disabled,s):"translucent"===t.renderPass&&ao(t,d,i,n,c[p.overscaledZ],s);}r.viewport.set([0,0,t.width,t.height]);}},raster:function(t,e,i,o){if("translucent"===t.renderPass&&0!==i.paint.get("raster-opacity")&&o.length)for(var r=t.context,a=r.gl,n=e.getSource(),s=t.useProgram("raster"),l=t.colorModeForRenderPass(),c=n instanceof L?[{},o]:t.stencilConfigForOverlap(o),u=c[0],h=c[1],p=h[h.length-1].overscaledZ,d=!t.options.moving,_=0,f=h;_<f.length;_+=1){var m=f[_],g=t.depthModeForSublayer(m.overscaledZ-p,1===i.paint.get("raster-opacity")?It.ReadWrite:It.ReadOnly,a.LESS),v=e.getTile(m),y=t.transform.calculatePosMatrix(m.toUnwrapped(),d);v.registerFadeDuration(i.paint.get("raster-fade-duration"));var x=e.findLoadedParent(m,0),b=so(v,x,e,i,t.transform),w=void 0,T=void 0,E="nearest"===i.paint.get("raster-resampling")?a.NEAREST:a.LINEAR;r.activeTexture.set(a.TEXTURE0),v.texture.bind(E,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),r.activeTexture.set(a.TEXTURE1),x?(x.texture.bind(E,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),w=Math.pow(2,x.tileID.overscaledZ-v.tileID.overscaledZ),T=[v.tileID.canonical.x*w%1,v.tileID.canonical.y*w%1]):v.texture.bind(E,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST);var I=Zi(y,T||[0,0],w||1,b,i);n instanceof L?s.draw(r,a.TRIANGLES,g,Pt.disabled,l,Ct.disabled,I,i.id,n.boundsBuffer,t.quadTriangleIndexBuffer,n.boundsSegments):s.draw(r,a.TRIANGLES,g,u[m.overscaledZ],l,Ct.disabled,I,i.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments);}},background:function(t,e,i){var o=i.paint.get("background-color"),r=i.paint.get("background-opacity");if(0!==r){var a=t.context,n=a.gl,s=t.transform,l=s.tileSize,c=i.paint.get("background-pattern");if(!t.isPatternMissing(c)){var u=!c&&1===o.a&&1===r&&t.opaquePassEnabledForLayer()?"opaque":"translucent";if(t.renderPass===u){var h=Pt.disabled,p=t.depthModeForSublayer(0,"opaque"===u?It.ReadWrite:It.ReadOnly),d=t.colorModeForRenderPass(),_=t.useProgram(c?"backgroundPattern":"background"),f=s.coveringTiles({tileSize:l});c&&(a.activeTexture.set(n.TEXTURE0),t.imageManager.bind(t.context));for(var m=i.getCrossfadeParameters(),g=0,v=f;g<v.length;g+=1){var y=v[g],x=t.transform.calculatePosMatrix(y.toUnwrapped()),b=c?Hi(x,r,t,c,{tileID:y,tileSize:l},m):Xi(x,r,o);_.draw(a,n.TRIANGLES,p,h,d,Ct.disabled,b,i.id,t.tileExtentBuffer,t.quadTriangleIndexBuffer,t.tileExtentSegments);}}}}},debug:function(t,e,i){for(var o=0;o<i.length;o++)go(t,e,i[o]);},custom:function(t,e,i){var o=t.context,r=i.implementation;if("offscreen"===t.renderPass){var a=r.prerender;a&&(t.setCustomLayerDefaults(),o.setColorMode(t.colorModeForRenderPass()),a.call(r,o.gl,t.transform.customLayerMatrix()),o.setDirty(),t.setBaseState());}else if("translucent"===t.renderPass){t.setCustomLayerDefaults(),o.setColorMode(t.colorModeForRenderPass()),o.setStencilMode(Pt.disabled);var n="3d"===r.renderingMode?new It(t.context.gl.LEQUAL,It.ReadWrite,t.depthRangeFor3D):t.depthModeForSublayer(0,It.ReadOnly);o.setDepthMode(n),r.render(o.gl,t.transform.customLayerMatrix()),o.setDirty(),t.setBaseState(),o.bindFramebuffer.set(null);}}},yo=function(t,e){this.context=new zt(t),this.transform=e,this._tileTextures={},this.setup(),this.numSublayers=Dt.maxUnderzooming+Dt.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new Fe,this.gpuTimers={};};yo.prototype.resize=function(e,i){if(this.width=e*t.browser.devicePixelRatio,this.height=i*t.browser.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(var o=0,r=this.style._order;o<r.length;o+=1)this.style._layers[r[o]].resize();},yo.prototype.setup=function(){var e=this.context,i=new t.StructArrayLayout2i4;i.emplaceBack(0,0),i.emplaceBack(t.EXTENT,0),i.emplaceBack(0,t.EXTENT),i.emplaceBack(t.EXTENT,t.EXTENT),this.tileExtentBuffer=e.createVertexBuffer(i,Ve.members),this.tileExtentSegments=t.SegmentVector.simpleSegment(0,0,4,2);var o=new t.StructArrayLayout2i4;o.emplaceBack(0,0),o.emplaceBack(t.EXTENT,0),o.emplaceBack(0,t.EXTENT),o.emplaceBack(t.EXTENT,t.EXTENT),this.debugBuffer=e.createVertexBuffer(o,Ve.members),this.debugSegments=t.SegmentVector.simpleSegment(0,0,4,5);var r=new t.StructArrayLayout4i8;r.emplaceBack(0,0,0,0),r.emplaceBack(t.EXTENT,0,t.EXTENT,0),r.emplaceBack(0,t.EXTENT,0,t.EXTENT),r.emplaceBack(t.EXTENT,t.EXTENT,t.EXTENT,t.EXTENT),this.rasterBoundsBuffer=e.createVertexBuffer(r,M.members),this.rasterBoundsSegments=t.SegmentVector.simpleSegment(0,0,4,2);var a=new t.StructArrayLayout2i4;a.emplaceBack(0,0),a.emplaceBack(1,0),a.emplaceBack(0,1),a.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(a,Ve.members),this.viewportSegments=t.SegmentVector.simpleSegment(0,0,4,2);var n=new t.StructArrayLayout1ui2;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);var s=new t.StructArrayLayout3ui6;s.emplaceBack(0,1,2),s.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(s),this.emptyTexture=new t.Texture(e,{width:1,height:1,data:new Uint8Array([0,0,0,0])},e.gl.RGBA);var l=this.context.gl;this.stencilClearMode=new Pt({func:l.ALWAYS,mask:0},0,255,l.ZERO,l.ZERO,l.ZERO);},yo.prototype.clearStencil=function(){var e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;var o=t.create();t.ortho(o,0,this.width,this.height,0,0,1),t.scale(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]),this.useProgram("clippingMask").draw(e,i.TRIANGLES,It.disabled,this.stencilClearMode,St.disabled,Ct.disabled,Ai(o),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);},yo.prototype._renderTileClippingMasks=function(t,e){if(this.currentStencilSource!==t.source&&t.isTileClipped()&&e&&e.length){this.currentStencilSource=t.source;var i=this.context,o=i.gl;this.nextStencilID+e.length>256&&this.clearStencil(),i.setColorMode(St.disabled),i.setDepthMode(It.disabled);var r=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(var a=0,n=e;a<n.length;a+=1){var s=n[a],l=this._tileClippingMaskIDs[s.key]=this.nextStencilID++;r.draw(i,o.TRIANGLES,It.disabled,new Pt({func:o.ALWAYS,mask:0},l,255,o.KEEP,o.KEEP,o.REPLACE),St.disabled,Ct.disabled,Ai(s.posMatrix),"$clipping",this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}}},yo.prototype.stencilModeFor3D=function(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();var t=this.nextStencilID++,e=this.context.gl;return new Pt({func:e.NOTEQUAL,mask:255},t,255,e.KEEP,e.KEEP,e.REPLACE)},yo.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Pt({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},yo.prototype.stencilConfigForOverlap=function(t){var e,i=this.context.gl,o=t.sort((function(t,e){return e.overscaledZ-t.overscaledZ})),r=o[o.length-1].overscaledZ,a=o[0].overscaledZ-r+1;if(a>1){this.currentStencilSource=void 0,this.nextStencilID+a>256&&this.clearStencil();for(var n={},s=0;s<a;s++)n[s+r]=new Pt({func:i.GEQUAL,mask:255},s+this.nextStencilID,255,i.KEEP,i.KEEP,i.REPLACE);return this.nextStencilID+=a,[n,o]}return [(e={},e[r]=Pt.disabled,e),o]},yo.prototype.colorModeForRenderPass=function(){var e=this.context.gl;return this._showOverdrawInspector?new St([e.CONSTANT_COLOR,e.ONE],new t.Color(1/8,1/8,1/8,0),[!0,!0,!0,!0]):"opaque"===this.renderPass?St.unblended:St.alphaBlended},yo.prototype.depthModeForSublayer=function(t,e,i){if(!this.opaquePassEnabledForLayer())return It.disabled;var o=1-((1+this.currentLayer)*this.numSublayers+t)*this.depthEpsilon;return new It(i||this.context.gl.LEQUAL,e,[o,o])},yo.prototype.opaquePassEnabledForLayer=function(){return this.currentLayer<this.opaquePassCutoff},yo.prototype.render=function(e,i){var o=this;this.style=e,this.options=i,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(t.browser.now()),this.imageManager.beginFrame();var r=this.style._order,a=this.style.sourceCaches;for(var n in a){var s=a[n];s.used&&s.prepare(this.context);}var l,c,u={},h={},p={};for(var d in a){var _=a[d];u[d]=_.getVisibleCoordinates(),h[d]=u[d].slice().reverse(),p[d]=_.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(var f=0;f<r.length;f++)if(this.style._layers[r[f]].is3D()){this.opaquePassCutoff=f;break}this.renderPass="offscreen";for(var m=0,g=r;m<g.length;m+=1){var v=this.style._layers[g[m]];if(v.hasOffscreenPass()&&!v.isHidden(this.transform.zoom)){var y=h[v.source];("custom"===v.type||y.length)&&this.renderLayer(this,a[v.source],v,y);}}for(this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.Color.black:t.Color.transparent,depth:1}),this.clearStencil(),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],this.renderPass="opaque",this.currentLayer=r.length-1;this.currentLayer>=0;this.currentLayer--){var x=this.style._layers[r[this.currentLayer]],b=a[x.source],w=u[x.source];this._renderTileClippingMasks(x,w),this.renderLayer(this,b,x,w);}for(this.renderPass="translucent",this.currentLayer=0;this.currentLayer<r.length;this.currentLayer++){var T=this.style._layers[r[this.currentLayer]],E=a[T.source],I=("symbol"===T.type?p:h)[T.source];this._renderTileClippingMasks(T,u[T.source]),this.renderLayer(this,E,T,I);}this.options.showTileBoundaries&&(t.values(this.style._layers).forEach((function(t){t.source&&!t.isHidden(o.transform.zoom)&&(t.source!==(c&&c.id)&&(c=o.style.sourceCaches[t.source]),(!l||l.getSource().maxzoom<c.getSource().maxzoom)&&(l=c));})),l&&vo.debug(this,l,l.getVisibleCoordinates())),this.options.showPadding&&function(t){var e=t.transform.padding;_o(t,t.transform.height-(e.top||0),3,lo),_o(t,e.bottom||0,3,co),fo(t,e.left||0,3,uo),fo(t,t.transform.width-(e.right||0),3,ho);var i=t.transform.centerPoint;!function(t,e,i,o){mo(t,e-1,i-10,2,20,o),mo(t,e-10,i-1,20,2,o);}(t,i.x,t.transform.height-i.y,po);}(this),this.context.setDefault();},yo.prototype.renderLayer=function(t,e,i,o){i.isHidden(this.transform.zoom)||("background"===i.type||"custom"===i.type||o.length)&&(this.id=i.id,this.gpuTimingStart(i),vo[i.type](t,e,i,o,this.style.placement.variableOffsets),this.gpuTimingEnd());},yo.prototype.gpuTimingStart=function(t){if(this.options.gpuTiming){var e=this.context.extTimerQuery,i=this.gpuTimers[t.id];i||(i=this.gpuTimers[t.id]={calls:0,cpuTime:0,query:e.createQueryEXT()}),i.calls++,e.beginQueryEXT(e.TIME_ELAPSED_EXT,i.query);}},yo.prototype.gpuTimingEnd=function(){if(this.options.gpuTiming){var t=this.context.extTimerQuery;t.endQueryEXT(t.TIME_ELAPSED_EXT);}},yo.prototype.collectGpuTimers=function(){var t=this.gpuTimers;return this.gpuTimers={},t},yo.prototype.queryGpuTimers=function(t){var e={};for(var i in t){var o=t[i],r=this.context.extTimerQuery,a=r.getQueryObjectEXT(o.query,r.QUERY_RESULT_EXT)/1e6;r.deleteQueryEXT(o.query),e[i]=a;}return e},yo.prototype.translatePosMatrix=function(e,i,o,r,a){if(!o[0]&&!o[1])return e;var n=a?"map"===r?this.transform.angle:0:"viewport"===r?-this.transform.angle:0;if(n){var s=Math.sin(n),l=Math.cos(n);o=[o[0]*l-o[1]*s,o[0]*s+o[1]*l];}var c=[a?o[0]:pe(i,o[0],this.transform.zoom),a?o[1]:pe(i,o[1],this.transform.zoom),0],u=new Float32Array(16);return t.translate(u,e,c),u},yo.prototype.saveTileTexture=function(t){var e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t];},yo.prototype.getTileTexture=function(t){var e=this._tileTextures[t];return e&&e.length>0?e.pop():null},yo.prototype.isPatternMissing=function(t){if(!t)return !1;if(!t.from||!t.to)return !0;var e=this.imageManager.getPattern(t.from.toString()),i=this.imageManager.getPattern(t.to.toString());return !e||!i},yo.prototype.useProgram=function(t,e){this.cache=this.cache||{};var i=""+t+(e?e.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[i]||(this.cache[i]=new bi(this.context,t,vi[t],e,Ki[t],this._showOverdrawInspector)),this.cache[i]},yo.prototype.setCustomLayerDefaults=function(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();},yo.prototype.setBaseState=function(){var t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD);},yo.prototype.initDebugOverlayCanvas=function(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=t.window.document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.Texture(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));},yo.prototype.destroy=function(){this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy();};var xo=function(t,e){this.points=t,this.planes=e;};xo.fromInvProjectionMatrix=function(e,i,o){var r=Math.pow(2,o),a=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((function(i){return t.transformMat4([],i,e)})).map((function(e){return t.scale$1([],e,1/e[3]/i*r)})),n=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((function(e){var i=t.sub([],a[e[0]],a[e[1]]),o=t.sub([],a[e[2]],a[e[1]]),r=t.normalize([],t.cross([],i,o)),n=-t.dot(r,a[e[1]]);return r.concat(n)}));return new xo(a,n)};var bo=function(e,i){this.min=e,this.max=i,this.center=t.scale$2([],t.add([],this.min,this.max),.5);};bo.prototype.quadrant=function(e){for(var i=[e%2==0,e<2],o=t.clone$2(this.min),r=t.clone$2(this.max),a=0;a<i.length;a++)o[a]=i[a]?this.min[a]:this.center[a],r[a]=i[a]?this.center[a]:this.max[a];return r[2]=this.max[2],new bo(o,r)},bo.prototype.distanceX=function(t){return Math.max(Math.min(this.max[0],t[0]),this.min[0])-t[0]},bo.prototype.distanceY=function(t){return Math.max(Math.min(this.max[1],t[1]),this.min[1])-t[1]},bo.prototype.intersects=function(e){for(var i=[[this.min[0],this.min[1],0,1],[this.max[0],this.min[1],0,1],[this.max[0],this.max[1],0,1],[this.min[0],this.max[1],0,1]],o=!0,r=0;r<e.planes.length;r++){for(var a=e.planes[r],n=0,s=0;s<i.length;s++)n+=t.dot$1(a,i[s])>=0;if(0===n)return 0;n!==i.length&&(o=!1);}if(o)return 2;for(var l=0;l<3;l++){for(var c=Number.MAX_VALUE,u=-Number.MAX_VALUE,h=0;h<e.points.length;h++){var p=e.points[h][l]-this.min[l];c=Math.min(c,p),u=Math.max(u,p);}if(u<0||c>this.max[l]-this.min[l])return 0}return 1};var wo=function(t,e,i,o){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===o&&(o=0),isNaN(t)||t<0||isNaN(e)||e<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=t,this.bottom=e,this.left=i,this.right=o;};wo.prototype.interpolate=function(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.number(e.right,i.right,o)),this},wo.prototype.getCenter=function(e,i){var o=t.clamp((this.left+e-this.right)/2,0,e),r=t.clamp((this.top+i-this.bottom)/2,0,i);return new t.Point(o,r)},wo.prototype.equals=function(t){return this.top===t.top&&this.bottom===t.bottom&&this.left===t.left&&this.right===t.right},wo.prototype.clone=function(){return new wo(this.top,this.bottom,this.left,this.right)},wo.prototype.toJSON=function(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}};var To=function(e,i,o,r,a){this.tileSize=512,this.maxValidLatitude=85.051129,this._renderWorldCopies=void 0===a||a,this._minZoom=e||0,this._maxZoom=i||22,this._minPitch=null==o?0:o,this._maxPitch=null==r?60:r,this.setMaxBounds(),this.width=0,this.height=0,this._center=new t.LngLat(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._edgeInsets=new wo,this._posMatrixCache={},this._alignedPosMatrixCache={};},Eo={minZoom:{configurable:!0},maxZoom:{configurable:!0},minPitch:{configurable:!0},maxPitch:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerOffset:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},padding:{configurable:!0},centerPoint:{configurable:!0},unmodified:{configurable:!0},point:{configurable:!0}};To.prototype.clone=function(){var t=new To(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._edgeInsets=this._edgeInsets.clone(),t._calcMatrices(),t},Eo.minZoom.get=function(){return this._minZoom},Eo.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));},Eo.maxZoom.get=function(){return this._maxZoom},Eo.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));},Eo.minPitch.get=function(){return this._minPitch},Eo.minPitch.set=function(t){this._minPitch!==t&&(this._minPitch=t,this.pitch=Math.max(this.pitch,t));},Eo.maxPitch.get=function(){return this._maxPitch},Eo.maxPitch.set=function(t){this._maxPitch!==t&&(this._maxPitch=t,this.pitch=Math.min(this.pitch,t));},Eo.renderWorldCopies.get=function(){return this._renderWorldCopies},Eo.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;},Eo.worldSize.get=function(){return this.tileSize*this.scale},Eo.centerOffset.get=function(){return this.centerPoint._sub(this.size._div(2))},Eo.size.get=function(){return new t.Point(this.width,this.height)},Eo.bearing.get=function(){return -this.angle/Math.PI*180},Eo.bearing.set=function(e){var i=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=t.create$2(),t.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));},Eo.pitch.get=function(){return this._pitch/Math.PI*180},Eo.pitch.set=function(e){var i=t.clamp(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());},Eo.fov.get=function(){return this._fov/Math.PI*180},Eo.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());},Eo.zoom.get=function(){return this._zoom},Eo.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices());},Eo.center.get=function(){return this._center},Eo.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());},Eo.padding.get=function(){return this._edgeInsets.toJSON()},Eo.padding.set=function(t){this._edgeInsets.equals(t)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,t,1),this._calcMatrices());},Eo.centerPoint.get=function(){return this._edgeInsets.getCenter(this.width,this.height)},To.prototype.isPaddingEqual=function(t){return this._edgeInsets.equals(t)},To.prototype.interpolatePadding=function(t,e,i){this._unmodified=!1,this._edgeInsets.interpolate(t,e,i),this._constrain(),this._calcMatrices();},To.prototype.coveringZoomLevel=function(t){var e=(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize));return Math.max(0,e)},To.prototype.getVisibleUnwrappedCoordinates=function(e){var i=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var o=this.pointCoordinate(new t.Point(0,0)),r=this.pointCoordinate(new t.Point(this.width,0)),a=this.pointCoordinate(new t.Point(this.width,this.height)),n=this.pointCoordinate(new t.Point(0,this.height)),s=Math.floor(Math.min(o.x,r.x,a.x,n.x)),l=Math.floor(Math.max(o.x,r.x,a.x,n.x)),c=s-1;c<=l+1;c++)0!==c&&i.push(new t.UnwrappedTileID(c,e));return i},To.prototype.coveringTiles=function(e){var i=this.coveringZoomLevel(e),o=i;if(void 0!==e.minzoom&&i<e.minzoom)return [];void 0!==e.maxzoom&&i>e.maxzoom&&(i=e.maxzoom);var r=t.MercatorCoordinate.fromLngLat(this.center),a=Math.pow(2,i),n=[a*r.x,a*r.y,0],s=xo.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,i),l=e.minzoom||0;this.pitch<=60&&this._edgeInsets.top<.1&&(l=i);var c=function(t){return {aabb:new bo([t*a,0,0],[(t+1)*a,a,0]),zoom:0,x:0,y:0,wrap:t,fullyVisible:!1}},u=[],h=[],p=i,d=e.reparseOverscaled?o:i;if(this._renderWorldCopies)for(var _=1;_<=3;_++)u.push(c(-_)),u.push(c(_));for(u.push(c(0));u.length>0;){var f=u.pop(),m=f.x,g=f.y,v=f.fullyVisible;if(!v){var y=f.aabb.intersects(s);if(0===y)continue;v=2===y;}var x=f.aabb.distanceX(n),b=f.aabb.distanceY(n),w=Math.max(Math.abs(x),Math.abs(b));if(f.zoom===p||w>3+(1<<p-f.zoom)-2&&f.zoom>=l)h.push({tileID:new t.OverscaledTileID(f.zoom===p?d:f.zoom,f.wrap,f.zoom,m,g),distanceSq:t.sqrLen([n[0]-.5-m,n[1]-.5-g])});else for(var T=0;T<4;T++){var E=(m<<1)+T%2,I=(g<<1)+(T>>1);u.push({aabb:f.aabb.quadrant(T),zoom:f.zoom+1,x:E,y:I,wrap:f.wrap,fullyVisible:v});}}return h.sort((function(t,e){return t.distanceSq-e.distanceSq})).map((function(t){return t.tileID}))},To.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();},Eo.unmodified.get=function(){return this._unmodified},To.prototype.zoomScale=function(t){return Math.pow(2,t)},To.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},To.prototype.project=function(e){var i=t.clamp(e.lat,-this.maxValidLatitude,this.maxValidLatitude);return new t.Point(t.mercatorXfromLng(e.lng)*this.worldSize,t.mercatorYfromLat(i)*this.worldSize)},To.prototype.unproject=function(e){return new t.MercatorCoordinate(e.x/this.worldSize,e.y/this.worldSize).toLngLat()},Eo.point.get=function(){return this.project(this.center)},To.prototype.setLocationAtPoint=function(e,i){var o=this.pointCoordinate(i),r=this.pointCoordinate(this.centerPoint),a=this.locationCoordinate(e),n=new t.MercatorCoordinate(a.x-(o.x-r.x),a.y-(o.y-r.y));this.center=this.coordinateLocation(n),this._renderWorldCopies&&(this.center=this.center.wrap());},To.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},To.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},To.prototype.locationCoordinate=function(e){return t.MercatorCoordinate.fromLngLat(e)},To.prototype.coordinateLocation=function(t){return t.toLngLat()},To.prototype.pointCoordinate=function(e){var i=[e.x,e.y,0,1],o=[e.x,e.y,1,1];t.transformMat4(i,i,this.pixelMatrixInverse),t.transformMat4(o,o,this.pixelMatrixInverse);var r=i[3],a=o[3],n=i[1]/r,s=o[1]/a,l=i[2]/r,c=o[2]/a,u=l===c?0:(0-l)/(c-l);return new t.MercatorCoordinate(t.number(i[0]/r,o[0]/a,u)/this.worldSize,t.number(n,s,u)/this.worldSize)},To.prototype.coordinatePoint=function(e){var i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix),new t.Point(i[0]/i[3],i[1]/i[3])},To.prototype.getBounds=function(){return (new t.LngLatBounds).extend(this.pointLocation(new t.Point(0,0))).extend(this.pointLocation(new t.Point(this.width,0))).extend(this.pointLocation(new t.Point(this.width,this.height))).extend(this.pointLocation(new t.Point(0,this.height)))},To.prototype.getMaxBounds=function(){return this.latRange&&2===this.latRange.length&&this.lngRange&&2===this.lngRange.length?new t.LngLatBounds([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]]):null},To.prototype.setMaxBounds=function(t){t?(this.lngRange=[t.getWest(),t.getEast()],this.latRange=[t.getSouth(),t.getNorth()],this._constrain()):(this.lngRange=null,this.latRange=[-this.maxValidLatitude,this.maxValidLatitude]);},To.prototype.calculatePosMatrix=function(e,i){void 0===i&&(i=!1);var o=e.key,r=i?this._alignedPosMatrixCache:this._posMatrixCache;if(r[o])return r[o];var a=e.canonical,n=this.worldSize/this.zoomScale(a.z),s=a.x+Math.pow(2,a.z)*e.wrap,l=t.identity(new Float64Array(16));return t.translate(l,l,[s*n,a.y*n,0]),t.scale(l,l,[n/t.EXTENT,n/t.EXTENT,1]),t.multiply(l,i?this.alignedProjMatrix:this.projMatrix,l),r[o]=new Float32Array(l),r[o]},To.prototype.customLayerMatrix=function(){return this.mercatorMatrix.slice()},To.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,i,o,r,a=-90,n=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;a=t.mercatorYfromLat(h[1])*this.worldSize,e=(n=t.mercatorYfromLat(h[0])*this.worldSize)-a<c.y?c.y/(n-a):0;}if(this.lngRange){var p=this.lngRange;s=t.mercatorXfromLng(p[0])*this.worldSize,i=(l=t.mercatorXfromLng(p[1])*this.worldSize)-s<c.x?c.x/(l-s):0;}var d=this.point,_=Math.max(i||0,e||0);if(_)return this.center=this.unproject(new t.Point(i?(l+s)/2:d.x,e?(n+a)/2:d.y)),this.zoom+=this.scaleZoom(_),this._unmodified=u,void(this._constraining=!1);if(this.latRange){var f=d.y,m=c.y/2;f-m<a&&(r=a+m),f+m>n&&(r=n-m);}if(this.lngRange){var g=d.x,v=c.x/2;g-v<s&&(o=s+v),g+v>l&&(o=l-v);}void 0===o&&void 0===r||(this.center=this.unproject(new t.Point(void 0!==o?o:d.x,void 0!==r?r:d.y))),this._unmodified=u,this._constraining=!1;}},To.prototype._calcMatrices=function(){if(this.height){var e=this.centerOffset;this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var i=Math.PI/2+this._pitch,o=this._fov*(.5+e.y/this.height),r=Math.sin(o)*this.cameraToCenterDistance/Math.sin(t.clamp(Math.PI-i-o,.01,Math.PI-.01)),a=this.point,n=a.x,s=a.y,l=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),c=this.height/50,u=new Float64Array(16);t.perspective(u,this._fov,this.width/this.height,c,l),u[8]=2*-e.x/this.width,u[9]=2*e.y/this.height,t.scale(u,u,[1,-1,1]),t.translate(u,u,[0,0,-this.cameraToCenterDistance]),t.rotateX(u,u,this._pitch),t.rotateZ(u,u,this.angle),t.translate(u,u,[-n,-s,0]),this.mercatorMatrix=t.scale([],u,[this.worldSize,this.worldSize,this.worldSize]),t.scale(u,u,[1,1,t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize,1]),this.projMatrix=u,this.invProjMatrix=t.invert([],this.projMatrix);var h=this.width%2/2,p=this.height%2/2,d=Math.cos(this.angle),_=Math.sin(this.angle),f=n-Math.round(n)+d*h+_*p,m=s-Math.round(s)+d*p+_*h,g=new Float64Array(u);if(t.translate(g,g,[f>.5?f-1:f,m>.5?m-1:m,0]),this.alignedProjMatrix=g,u=t.create(),t.scale(u,u,[this.width/2,-this.height/2,1]),t.translate(u,u,[1,-1,0]),this.labelPlaneMatrix=u,u=t.create(),t.scale(u,u,[1,-1,1]),t.translate(u,u,[-1,-1,0]),t.scale(u,u,[2/this.width,2/this.height,1]),this.glCoordMatrix=u,this.pixelMatrix=t.multiply(new Float64Array(16),this.labelPlaneMatrix,this.projMatrix),!(u=t.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=u,this._posMatrixCache={},this._alignedPosMatrixCache={};}},To.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.Point(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance},To.prototype.getCameraPoint=function(){var e=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.Point(0,e))},To.prototype.getCameraQueryGeometry=function(e){var i=this.getCameraPoint();if(1===e.length)return [e[0],i];for(var o=i.x,r=i.y,a=i.x,n=i.y,s=0,l=e;s<l.length;s+=1){var c=l[s];o=Math.min(o,c.x),r=Math.min(r,c.y),a=Math.max(a,c.x),n=Math.max(n,c.y);}return [new t.Point(o,r),new t.Point(a,r),new t.Point(a,n),new t.Point(o,n),new t.Point(o,r)]},Object.defineProperties(To.prototype,Eo);var Io=function(e){var i,o,r,a;this._hashName=e&&encodeURIComponent(e),t.bindAll(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=(i=this._updateHashUnthrottled.bind(this),o=!1,r=null,a=function(){r=null,o&&(i(),r=setTimeout(a,300),o=!1);},function(){return o=!0,r||a(),r});};Io.prototype.addTo=function(e){return this._map=e,t.window.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},Io.prototype.remove=function(){return t.window.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),delete this._map,this},Io.prototype.getHashString=function(e){var i=this._map.getCenter(),o=Math.round(100*this._map.getZoom())/100,r=Math.ceil((o*Math.LN2+Math.log(512/360/.5))/Math.LN10),a=Math.pow(10,r),n=Math.round(i.lng*a)/a,s=Math.round(i.lat*a)/a,l=this._map.getBearing(),c=this._map.getPitch(),u="";if(u+=e?"/"+n+"/"+s+"/"+o:o+"/"+s+"/"+n,(l||c)&&(u+="/"+Math.round(10*l)/10),c&&(u+="/"+Math.round(c)),this._hashName){var h=this._hashName,p=!1,d=t.window.location.hash.slice(1).split("&").map((function(t){var e=t.split("=")[0];return e===h?(p=!0,e+"="+u):t})).filter((function(t){return t}));return p||d.push(h+"="+u),"#"+d.join("&")}return "#"+u},Io.prototype._getCurrentHash=function(){var e,i=this,o=t.window.location.hash.replace("#","");return this._hashName?(o.split("&").map((function(t){return t.split("=")})).forEach((function(t){t[0]===i._hashName&&(e=t);})),(e&&e[1]||"").split("/")):o.split("/")},Io.prototype._onHashChange=function(){var t=this._getCurrentHash();if(t.length>=3&&!t.some((function(t){return isNaN(t)}))){var e=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(t[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:e,pitch:+(t[4]||0)}),!0}return !1},Io.prototype._updateHashUnthrottled=function(){var e=this.getHashString();try{t.window.history.replaceState(t.window.history.state,"",e);}catch(t){}};var Po={linearity:.3,easing:t.bezier(0,0,.3,1)},So=t.extend({deceleration:2500,maxSpeed:1400},Po),Co=t.extend({deceleration:20,maxSpeed:1400},Po),zo=t.extend({deceleration:1e3,maxSpeed:360},Po),Do=t.extend({deceleration:1e3,maxSpeed:90},Po),Mo=function(t){this._map=t,this.clear();};function Lo(t,e){(!t.duration||t.duration<e.duration)&&(t.duration=e.duration,t.easing=e.easing);}function Ao(e,i,o){var r=o.maxSpeed,a=o.linearity,n=o.deceleration,s=t.clamp(e*a/(i/1e3),-r,r),l=Math.abs(s)/(n*a);return {easing:o.easing,duration:1e3*l,amount:s*(l/2)}}Mo.prototype.clear=function(){this._inertiaBuffer=[];},Mo.prototype.record=function(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:t.browser.now(),settings:e});},Mo.prototype._drainInertiaBuffer=function(){for(var e=this._inertiaBuffer,i=t.browser.now();e.length>0&&i-e[0].time>160;)e.shift();},Mo.prototype._onMoveEnd=function(e){if(this._drainInertiaBuffer(),!(this._inertiaBuffer.length<2)){for(var i={zoom:0,bearing:0,pitch:0,pan:new t.Point(0,0),pinchAround:void 0,around:void 0},o=0,r=this._inertiaBuffer;o<r.length;o+=1){var a=r[o].settings;i.zoom+=a.zoomDelta||0,i.bearing+=a.bearingDelta||0,i.pitch+=a.pitchDelta||0,a.panDelta&&i.pan._add(a.panDelta),a.around&&(i.around=a.around),a.pinchAround&&(i.pinchAround=a.pinchAround);}var n=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,s={};if(i.pan.mag()){var l=Ao(i.pan.mag(),n,t.extend({},So,e||{}));s.offset=i.pan.mult(l.amount/i.pan.mag()),s.center=this._map.transform.center,Lo(s,l);}if(i.zoom){var c=Ao(i.zoom,n,Co);s.zoom=this._map.transform.zoom+c.amount,Lo(s,c);}if(i.bearing){var u=Ao(i.bearing,n,zo);s.bearing=this._map.transform.bearing+t.clamp(u.amount,-179,179),Lo(s,u);}if(i.pitch){var h=Ao(i.pitch,n,Do);s.pitch=this._map.transform.pitch+h.amount,Lo(s,h);}if(s.zoom||s.bearing){var p=void 0===i.pinchAround?i.around:i.pinchAround;s.around=p?this._map.unproject(p):this._map.getCenter();}return this.clear(),t.extend(s,{noMoveStart:!0})}};var Ro=function(e){function o(o,r,a,n){void 0===n&&(n={});var s=i.mousePos(r.getCanvasContainer(),a),l=r.unproject(s);e.call(this,o,t.extend({point:s,lngLat:l,originalEvent:a},n)),this._defaultPrevented=!1,this.target=r;}e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o;var r={defaultPrevented:{configurable:!0}};return o.prototype.preventDefault=function(){this._defaultPrevented=!0;},r.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(o.prototype,r),o}(t.Event),ko=function(e){function o(o,r,a){var n="touchend"===o?a.changedTouches:a.touches,s=i.touchPos(r.getCanvasContainer(),n),l=s.map((function(t){return r.unproject(t)})),c=s.reduce((function(t,e,i,o){return t.add(e.div(o.length))}),new t.Point(0,0)),u=r.unproject(c);e.call(this,o,{points:s,point:c,lngLats:l,lngLat:u,originalEvent:a}),this._defaultPrevented=!1;}e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o;var r={defaultPrevented:{configurable:!0}};return o.prototype.preventDefault=function(){this._defaultPrevented=!0;},r.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(o.prototype,r),o}(t.Event),Bo=function(t){function e(e,i,o){t.call(this,e,{originalEvent:o}),this._defaultPrevented=!1;}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var i={defaultPrevented:{configurable:!0}};return e.prototype.preventDefault=function(){this._defaultPrevented=!0;},i.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(e.prototype,i),e}(t.Event),Oo=function(t,e){this._map=t,this._clickTolerance=e.clickTolerance;};Oo.prototype.reset=function(){delete this._mousedownPos;},Oo.prototype.wheel=function(t){return this._firePreventable(new Bo(t.type,this._map,t))},Oo.prototype.mousedown=function(t,e){return this._mousedownPos=e,this._firePreventable(new Ro(t.type,this._map,t))},Oo.prototype.mouseup=function(t){this._map.fire(new Ro(t.type,this._map,t));},Oo.prototype.click=function(t,e){this._mousedownPos&&this._mousedownPos.dist(e)>=this._clickTolerance||this._map.fire(new Ro(t.type,this._map,t));},Oo.prototype.dblclick=function(t){return this._firePreventable(new Ro(t.type,this._map,t))},Oo.prototype.mouseover=function(t){this._map.fire(new Ro(t.type,this._map,t));},Oo.prototype.mouseout=function(t){this._map.fire(new Ro(t.type,this._map,t));},Oo.prototype.touchstart=function(t){return this._firePreventable(new ko(t.type,this._map,t))},Oo.prototype.touchmove=function(t){this._map.fire(new ko(t.type,this._map,t));},Oo.prototype.touchend=function(t){this._map.fire(new ko(t.type,this._map,t));},Oo.prototype.touchcancel=function(t){this._map.fire(new ko(t.type,this._map,t));},Oo.prototype._firePreventable=function(t){if(this._map.fire(t),t.defaultPrevented)return {}},Oo.prototype.isEnabled=function(){return !0},Oo.prototype.isActive=function(){return !1},Oo.prototype.enable=function(){},Oo.prototype.disable=function(){};var Fo=function(t){this._map=t;};Fo.prototype.reset=function(){this._delayContextMenu=!1,delete this._contextMenuEvent;},Fo.prototype.mousemove=function(t){this._map.fire(new Ro(t.type,this._map,t));},Fo.prototype.mousedown=function(){this._delayContextMenu=!0;},Fo.prototype.mouseup=function(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Ro("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);},Fo.prototype.contextmenu=function(t){this._delayContextMenu?this._contextMenuEvent=t:this._map.fire(new Ro(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault();},Fo.prototype.isEnabled=function(){return !0},Fo.prototype.isActive=function(){return !1},Fo.prototype.enable=function(){},Fo.prototype.disable=function(){};var Uo=function(t,e){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=e.clickTolerance||1;};function No(t,e){for(var i={},o=0;o<t.length;o++)i[t[o].identifier]=e[o];return i}Uo.prototype.isEnabled=function(){return !!this._enabled},Uo.prototype.isActive=function(){return !!this._active},Uo.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},Uo.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},Uo.prototype.mousedown=function(t,e){this.isEnabled()&&t.shiftKey&&0===t.button&&(i.disableDrag(),this._startPos=this._lastPos=e,this._active=!0);},Uo.prototype.mousemoveWindow=function(t,e){if(this._active){var o=e;if(!(this._lastPos.equals(o)||!this._box&&o.dist(this._startPos)<this._clickTolerance)){var r=this._startPos;this._lastPos=o,this._box||(this._box=i.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var a=Math.min(r.x,o.x),n=Math.max(r.x,o.x),s=Math.min(r.y,o.y),l=Math.max(r.y,o.y);i.setTransform(this._box,"translate("+a+"px,"+s+"px)"),this._box.style.width=n-a+"px",this._box.style.height=l-s+"px";}}},Uo.prototype.mouseupWindow=function(e,o){var r=this;if(this._active&&0===e.button){var a=this._startPos,n=o;if(this.reset(),i.suppressClick(),a.x!==n.x||a.y!==n.y)return this._map.fire(new t.Event("boxzoomend",{originalEvent:e})),{cameraAnimation:function(t){return t.fitScreenCoordinates(a,n,r._map.getBearing(),{linear:!0})}};this._fireEvent("boxzoomcancel",e);}},Uo.prototype.keydown=function(t){this._active&&27===t.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",t));},Uo.prototype.reset=function(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(i.remove(this._box),this._box=null),i.enableDrag(),delete this._startPos,delete this._lastPos;},Uo.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,{originalEvent:i}))};var Zo=function(t){this.reset(),this.numTouches=t.numTouches;};Zo.prototype.reset=function(){delete this.centroid,delete this.startTime,delete this.touches,this.aborted=!1;},Zo.prototype.touchstart=function(e,i,o){(this.centroid||o.length>this.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){for(var i=new t.Point(0,0),o=0,r=e;o<r.length;o+=1)i._add(r[o]);return i.div(e.length)}(i),this.touches=No(o,i)));},Zo.prototype.touchmove=function(t,e,i){if(!this.aborted&&this.centroid){var o=No(i,e);for(var r in this.touches){var a=o[r];(!a||a.dist(this.touches[r])>30)&&(this.aborted=!0);}}},Zo.prototype.touchend=function(t,e,i){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){var o=!this.aborted&&this.centroid;if(this.reset(),o)return o}};var jo=function(t){this.singleTap=new Zo(t),this.numTaps=t.numTaps,this.reset();};jo.prototype.reset=function(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();},jo.prototype.touchstart=function(t,e,i){this.singleTap.touchstart(t,e,i);},jo.prototype.touchmove=function(t,e,i){this.singleTap.touchmove(t,e,i);},jo.prototype.touchend=function(t,e,i){var o=this.singleTap.touchend(t,e,i);if(o){var r=t.timeStamp-this.lastTime<500,a=!this.lastTap||this.lastTap.dist(o)<30;if(r&&a||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}};var qo=function(){this._zoomIn=new jo({numTouches:1,numTaps:2}),this._zoomOut=new jo({numTouches:2,numTaps:1}),this.reset();};qo.prototype.reset=function(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();},qo.prototype.touchstart=function(t,e,i){this._zoomIn.touchstart(t,e,i),this._zoomOut.touchstart(t,e,i);},qo.prototype.touchmove=function(t,e,i){this._zoomIn.touchmove(t,e,i),this._zoomOut.touchmove(t,e,i);},qo.prototype.touchend=function(t,e,i){var o=this,r=this._zoomIn.touchend(t,e,i),a=this._zoomOut.touchend(t,e,i);return r?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()+1,around:e.unproject(r)},{originalEvent:t})}}):a?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()-1,around:e.unproject(a)},{originalEvent:t})}}):void 0},qo.prototype.touchcancel=function(){this.reset();},qo.prototype.enable=function(){this._enabled=!0;},qo.prototype.disable=function(){this._enabled=!1,this.reset();},qo.prototype.isEnabled=function(){return this._enabled},qo.prototype.isActive=function(){return this._active};var Vo={0:1,2:2},Go=function(t){this.reset(),this._clickTolerance=t.clickTolerance||1;};Go.prototype.reset=function(){this._active=!1,this._moved=!1,delete this._lastPoint,delete this._eventButton;},Go.prototype._correctButton=function(t,e){return !1},Go.prototype._move=function(t,e){return {}},Go.prototype.mousedown=function(t,e){if(!this._lastPoint){var o=i.mouseButton(t);this._correctButton(t,o)&&(this._lastPoint=e,this._eventButton=o);}},Go.prototype.mousemoveWindow=function(t,e){var i=this._lastPoint;if(i)if(t.preventDefault(),function(t,e){var i=Vo[e];return void 0===t.buttons||(t.buttons&i)!==i}(t,this._eventButton))this.reset();else if(this._moved||!(e.dist(i)<this._clickTolerance))return this._moved=!0,this._lastPoint=e,this._move(i,e)},Go.prototype.mouseupWindow=function(t){this._lastPoint&&i.mouseButton(t)===this._eventButton&&(this._moved&&i.suppressClick(),this.reset());},Go.prototype.enable=function(){this._enabled=!0;},Go.prototype.disable=function(){this._enabled=!1,this.reset();},Go.prototype.isEnabled=function(){return this._enabled},Go.prototype.isActive=function(){return this._active};var Wo=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.mousedown=function(e,i){t.prototype.mousedown.call(this,e,i),this._lastPoint&&(this._active=!0);},e.prototype._correctButton=function(t,e){return 0===e&&!t.ctrlKey},e.prototype._move=function(t,e){return {around:e,panDelta:e.sub(t)}},e}(Go),Xo=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._correctButton=function(t,e){return 0===e&&t.ctrlKey||2===e},e.prototype._move=function(t,e){var i=.8*(e.x-t.x);if(i)return this._active=!0,{bearingDelta:i}},e.prototype.contextmenu=function(t){t.preventDefault();},e}(Go),Ho=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._correctButton=function(t,e){return 0===e&&t.ctrlKey||2===e},e.prototype._move=function(t,e){var i=-.5*(e.y-t.y);if(i)return this._active=!0,{pitchDelta:i}},e.prototype.contextmenu=function(t){t.preventDefault();},e}(Go),Ko=function(t){this._minTouches=1,this._clickTolerance=t.clickTolerance||1,this.reset();};Ko.prototype.reset=function(){this._active=!1,this._touches={},this._sum=new t.Point(0,0);},Ko.prototype.touchstart=function(t,e,i){return this._calculateTransform(t,e,i)},Ko.prototype.touchmove=function(t,e,i){if(this._active)return t.preventDefault(),this._calculateTransform(t,e,i)},Ko.prototype.touchend=function(t,e,i){this._calculateTransform(t,e,i),this._active&&i.length<this._minTouches&&this.reset();},Ko.prototype.touchcancel=function(){this.reset();},Ko.prototype._calculateTransform=function(e,i,o){o.length>0&&(this._active=!0);var r=No(o,i),a=new t.Point(0,0),n=new t.Point(0,0),s=0;for(var l in r){var c=r[l],u=this._touches[l];u&&(a._add(c),n._add(c.sub(u)),s++,r[l]=c);}if(this._touches=r,!(s<this._minTouches)&&n.mag()){var h=n.div(s);if(this._sum._add(h),!(this._sum.mag()<this._clickTolerance))return {around:a.div(s),panDelta:h}}},Ko.prototype.enable=function(){this._enabled=!0;},Ko.prototype.disable=function(){this._enabled=!1,this.reset();},Ko.prototype.isEnabled=function(){return this._enabled},Ko.prototype.isActive=function(){return this._active};var Yo=function(){this.reset();};function Jo(t,e,i){for(var o=0;o<t.length;o++)if(t[o].identifier===i)return e[o]}function Qo(t,e){return Math.log(t/e)/Math.LN2}Yo.prototype.reset=function(){this._active=!1,delete this._firstTwoTouches;},Yo.prototype._start=function(t){},Yo.prototype._move=function(t,e,i){return {}},Yo.prototype.touchstart=function(t,e,i){this._firstTwoTouches||i.length<2||(this._firstTwoTouches=[i[0].identifier,i[1].identifier],this._start([e[0],e[1]]));},Yo.prototype.touchmove=function(t,e,i){if(this._firstTwoTouches){t.preventDefault();var o=this._firstTwoTouches,r=o[1],a=Jo(i,e,o[0]),n=Jo(i,e,r);if(a&&n){var s=this._aroundCenter?null:a.add(n).div(2);return this._move([a,n],s,t)}}},Yo.prototype.touchend=function(t,e,o){if(this._firstTwoTouches){var r=this._firstTwoTouches,a=r[1],n=Jo(o,e,r[0]),s=Jo(o,e,a);n&&s||(this._active&&i.suppressClick(),this.reset());}},Yo.prototype.touchcancel=function(){this.reset();},Yo.prototype.enable=function(t){this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around;},Yo.prototype.disable=function(){this._enabled=!1,this.reset();},Yo.prototype.isEnabled=function(){return this._enabled},Yo.prototype.isActive=function(){return this._active};var $o=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),delete this._distance,delete this._startDistance;},e.prototype._start=function(t){this._startDistance=this._distance=t[0].dist(t[1]);},e.prototype._move=function(t,e){var i=this._distance;if(this._distance=t[0].dist(t[1]),this._active||!(Math.abs(Qo(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:Qo(this._distance,i),pinchAround:e}},e}(Yo);function tr(t,e){return 180*t.angleWith(e)/Math.PI}var er=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),delete this._minDiameter,delete this._startVector,delete this._vector;},e.prototype._start=function(t){this._startVector=this._vector=t[0].sub(t[1]),this._minDiameter=t[0].dist(t[1]);},e.prototype._move=function(t,e){var i=this._vector;if(this._vector=t[0].sub(t[1]),this._active||!this._isBelowThreshold(this._vector))return this._active=!0,{bearingDelta:tr(this._vector,i),pinchAround:e}},e.prototype._isBelowThreshold=function(t){this._minDiameter=Math.min(this._minDiameter,t.mag());var e=25/(Math.PI*this._minDiameter)*360,i=tr(t,this._startVector);return Math.abs(i)<e},e}(Yo);function ir(t){return Math.abs(t.y)>Math.abs(t.x)}var or=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),this._valid=void 0,delete this._firstMove,delete this._lastPoints;},e.prototype._start=function(t){this._lastPoints=t,ir(t[0].sub(t[1]))&&(this._valid=!1);},e.prototype._move=function(t,e,i){var o=t[0].sub(this._lastPoints[0]),r=t[1].sub(this._lastPoints[1]);if(this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid)return this._lastPoints=t,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}},e.prototype.gestureBeginsVertically=function(t,e,i){if(void 0!==this._valid)return this._valid;var o=t.mag()>=2,r=e.mag()>=2;if(o||r){if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;var a=t.y>0==e.y>0;return ir(t)&&ir(e)&&a}},e}(Yo),rr={panStep:100,bearingStep:15,pitchStep:10},ar=function(){var t=rr;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep;};function nr(t){return t*(2-t)}ar.prototype.reset=function(){this._active=!1;},ar.prototype.keydown=function(t){var e=this;if(!(t.altKey||t.ctrlKey||t.metaKey)){var i=0,o=0,r=0,a=0,n=0;switch(t.keyCode){case 61:case 107:case 171:case 187:i=1;break;case 189:case 109:case 173:i=-1;break;case 37:t.shiftKey?o=-1:(t.preventDefault(),a=-1);break;case 39:t.shiftKey?o=1:(t.preventDefault(),a=1);break;case 38:t.shiftKey?r=1:(t.preventDefault(),n=-1);break;case 40:t.shiftKey?r=-1:(t.preventDefault(),n=1);break;default:return}return {cameraAnimation:function(s){var l=s.getZoom();s.easeTo({duration:300,easeId:"keyboardHandler",easing:nr,zoom:i?Math.round(l)+i*(t.shiftKey?2:1):l,bearing:s.getBearing()+o*e._bearingStep,pitch:s.getPitch()+r*e._pitchStep,offset:[-a*e._panStep,-n*e._panStep],center:s.getCenter()},{originalEvent:t});}}}},ar.prototype.enable=function(){this._enabled=!0;},ar.prototype.disable=function(){this._enabled=!1,this.reset();},ar.prototype.isEnabled=function(){return this._enabled},ar.prototype.isActive=function(){return this._active};var sr=function(e,i){this._map=e,this._el=e.getCanvasContainer(),this._handler=i,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=1/450,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this);};sr.prototype.setZoomRate=function(t){this._defaultZoomRate=t;},sr.prototype.setWheelZoomRate=function(t){this._wheelZoomRate=t;},sr.prototype.isEnabled=function(){return !!this._enabled},sr.prototype.isActive=function(){return !!this._active||void 0!==this._finishTimeout},sr.prototype.isZooming=function(){return !!this._zooming},sr.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around);},sr.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},sr.prototype.wheel=function(e){if(this.isEnabled()){var i=e.deltaMode===t.window.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,o=t.browser.now(),r=o-(this._lastWheelEventTime||0);this._lastWheelEventTime=o,0!==i&&i%4.000244140625==0?this._type="wheel":0!==i&&Math.abs(i)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*i)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),e.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=e,this._delta-=i,this._active||this._start(e)),e.preventDefault();}},sr.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(t);},sr.prototype._start=function(e){if(this._delta){this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);var o=i.mousePos(this._el,e);this._around=t.LngLat.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(o)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame());}},sr.prototype.renderFrame=function(){return this._onScrollFrame()},sr.prototype._onScrollFrame=function(){var e=this;if(this._frameId&&(this._frameId=null,this.isActive())){var i=this._map.transform;if(0!==this._delta){var o="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?this._wheelZoomRate:this._defaultZoomRate,r=2/(1+Math.exp(-Math.abs(this._delta*o)));this._delta<0&&0!==r&&(r=1/r);var a="number"==typeof this._targetZoom?i.zoomScale(this._targetZoom):i.scale;this._targetZoom=Math.min(i.maxZoom,Math.max(i.minZoom,i.scaleZoom(a*r))),"wheel"===this._type&&(this._startZoom=i.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}var n,s="number"==typeof this._targetZoom?this._targetZoom:i.zoom,l=this._startZoom,c=this._easing,u=!1;if("wheel"===this._type&&l&&c){var h=Math.min((t.browser.now()-this._lastWheelEventTime)/200,1),p=c(h);n=t.number(l,s,p),h<1?this._frameId||(this._frameId=!0):u=!0;}else n=s,u=!0;return this._active=!0,u&&(this._active=!1,this._finishTimeout=setTimeout((function(){e._zooming=!1,e._handler._triggerRenderFrame(),delete e._targetZoom,delete e._finishTimeout;}),200)),{noInertia:!0,needsRenderFrame:!u,zoomDelta:n-i.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}},sr.prototype._smoothOutEasing=function(e){var i=t.ease;if(this._prevEase){var o=this._prevEase,r=(t.browser.now()-o.start)/o.duration,a=o.easing(r+.01)-o.easing(r),n=.27/Math.sqrt(a*a+1e-4)*.01,s=Math.sqrt(.0729-n*n);i=t.bezier(n,s,.25,1);}return this._prevEase={start:t.browser.now(),duration:e,easing:i},i},sr.prototype.reset=function(){this._active=!1;};var lr=function(t,e){this._clickZoom=t,this._tapZoom=e;};lr.prototype.enable=function(){this._clickZoom.enable(),this._tapZoom.enable();},lr.prototype.disable=function(){this._clickZoom.disable(),this._tapZoom.disable();},lr.prototype.isEnabled=function(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()},lr.prototype.isActive=function(){return this._clickZoom.isActive()||this._tapZoom.isActive()};var cr=function(){this.reset();};cr.prototype.reset=function(){this._active=!1;},cr.prototype.dblclick=function(t,e){return t.preventDefault(),{cameraAnimation:function(i){i.easeTo({duration:300,zoom:i.getZoom()+(t.shiftKey?-1:1),around:i.unproject(e)},{originalEvent:t});}}},cr.prototype.enable=function(){this._enabled=!0;},cr.prototype.disable=function(){this._enabled=!1,this.reset();},cr.prototype.isEnabled=function(){return this._enabled},cr.prototype.isActive=function(){return this._active};var ur=function(){this._tap=new jo({numTouches:1,numTaps:1}),this.reset();};ur.prototype.reset=function(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,this._tap.reset();},ur.prototype.touchstart=function(t,e,i){this._swipePoint||(this._tapTime&&t.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?i.length>0&&(this._swipePoint=e[0],this._swipeTouch=i[0].identifier):this._tap.touchstart(t,e,i));},ur.prototype.touchmove=function(t,e,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;var o=e[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,t.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(t,e,i);},ur.prototype.touchend=function(t,e,i){this._tapTime?this._swipePoint&&0===i.length&&this.reset():this._tap.touchend(t,e,i)&&(this._tapTime=t.timeStamp);},ur.prototype.touchcancel=function(){this.reset();},ur.prototype.enable=function(){this._enabled=!0;},ur.prototype.disable=function(){this._enabled=!1,this.reset();},ur.prototype.isEnabled=function(){return this._enabled},ur.prototype.isActive=function(){return this._active};var hr=function(t,e,i){this._el=t,this._mousePan=e,this._touchPan=i;};hr.prototype.enable=function(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan");},hr.prototype.disable=function(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan");},hr.prototype.isEnabled=function(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()},hr.prototype.isActive=function(){return this._mousePan.isActive()||this._touchPan.isActive()};var pr=function(t,e,i){this._pitchWithRotate=t.pitchWithRotate,this._mouseRotate=e,this._mousePitch=i;};pr.prototype.enable=function(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable();},pr.prototype.disable=function(){this._mouseRotate.disable(),this._mousePitch.disable();},pr.prototype.isEnabled=function(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())},pr.prototype.isActive=function(){return this._mouseRotate.isActive()||this._mousePitch.isActive()};var dr=function(t,e,i,o){this._el=t,this._touchZoom=e,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;};dr.prototype.enable=function(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate");},dr.prototype.disable=function(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate");},dr.prototype.isEnabled=function(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()},dr.prototype.isActive=function(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()},dr.prototype.disableRotation=function(){this._rotationDisabled=!0,this._touchRotate.disable();},dr.prototype.enableRotation=function(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();};var _r=function(t){return t.zoom||t.drag||t.pitch||t.rotate},fr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(t.Event);function mr(t){return t.panDelta&&t.panDelta.mag()||t.zoomDelta||t.bearingDelta||t.pitchDelta}var gr=function(e,o){this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Mo(e),this._bearingSnap=o.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(o),t.bindAll(["handleEvent","handleWindowEvent"],this);var r=this._el;this._listeners=[[r,"touchstart",{passive:!0}],[r,"touchmove",{passive:!1}],[r,"touchend",void 0],[r,"touchcancel",void 0],[r,"mousedown",void 0],[r,"mousemove",void 0],[r,"mouseup",void 0],[t.window.document,"mousemove",{capture:!0}],[t.window.document,"mouseup",void 0],[r,"mouseover",void 0],[r,"mouseout",void 0],[r,"dblclick",void 0],[r,"click",void 0],[r,"keydown",{capture:!1}],[r,"keyup",void 0],[r,"wheel",{passive:!1}],[r,"contextmenu",void 0],[t.window,"blur",void 0]];for(var a=0,n=this._listeners;a<n.length;a+=1){var s=n[a],l=s[0];i.addEventListener(l,s[1],l===t.window.document?this.handleWindowEvent:this.handleEvent,s[2]);}};gr.prototype.destroy=function(){for(var e=0,o=this._listeners;e<o.length;e+=1){var r=o[e],a=r[0];i.removeEventListener(a,r[1],a===t.window.document?this.handleWindowEvent:this.handleEvent,r[2]);}},gr.prototype._addDefaultHandlers=function(t){var e=this._map,i=e.getCanvasContainer();this._add("mapEvent",new Oo(e,t));var o=e.boxZoom=new Uo(e,t);this._add("boxZoom",o);var r=new qo,a=new cr;e.doubleClickZoom=new lr(a,r),this._add("tapZoom",r),this._add("clickZoom",a);var n=new ur;this._add("tapDragZoom",n);var s=e.touchPitch=new or;this._add("touchPitch",s);var l=new Xo(t),c=new Ho(t);e.dragRotate=new pr(t,l,c),this._add("mouseRotate",l,["mousePitch"]),this._add("mousePitch",c,["mouseRotate"]);var u=new Wo(t),h=new Ko(t);e.dragPan=new hr(i,u,h),this._add("mousePan",u),this._add("touchPan",h,["touchZoom","touchRotate"]);var p=new er,d=new $o;e.touchZoomRotate=new dr(i,d,p,n),this._add("touchRotate",p,["touchPan","touchZoom"]),this._add("touchZoom",d,["touchPan","touchRotate"]);var _=e.scrollZoom=new sr(e,this);this._add("scrollZoom",_,["mousePan"]);var f=e.keyboard=new ar;this._add("keyboard",f),this._add("blockableMapEvent",new Fo(e));for(var m=0,g=["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"];m<g.length;m+=1){var v=g[m];t.interactive&&t[v]&&e[v].enable(t[v]);}},gr.prototype._add=function(t,e,i){this._handlers.push({handlerName:t,handler:e,allowed:i}),this._handlersById[t]=e;},gr.prototype.stop=function(){if(!this._updatingCamera){for(var t=0,e=this._handlers;t<e.length;t+=1)e[t].handler.reset();this._inertia.clear(),this._fireEvents({},{}),this._changes=[];}},gr.prototype.isActive=function(){for(var t=0,e=this._handlers;t<e.length;t+=1)if(e[t].handler.isActive())return !0;return !1},gr.prototype.isZooming=function(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()},gr.prototype.isRotating=function(){return !!this._eventsInProgress.rotate},gr.prototype.isMoving=function(){return Boolean(_r(this._eventsInProgress))||this.isZooming()},gr.prototype._blockedByActive=function(t,e,i){for(var o in t)if(o!==i&&(!e||e.indexOf(o)<0))return !0;return !1},gr.prototype.handleWindowEvent=function(t){this.handleEvent(t,t.type+"Window");},gr.prototype._getMapTouches=function(t){for(var e=[],i=0,o=t;i<o.length;i+=1){var r=o[i];this._el.contains(r.target)&&e.push(r);}return e},gr.prototype.handleEvent=function(t,e){if("blur"!==t.type){this._updatingCamera=!0;for(var o="renderFrame"===t.type?void 0:t,r={needsRenderFrame:!1},a={},n={},s=t.touches?this._getMapTouches(t.touches):void 0,l=s?i.touchPos(this._el,s):i.mousePos(this._el,t),c=0,u=this._handlers;c<u.length;c+=1){var h=u[c],p=h.handlerName,d=h.handler,_=h.allowed;if(d.isEnabled()){var f=void 0;this._blockedByActive(n,_,p)?d.reset():d[e||t.type]&&(f=d[e||t.type](t,l,s),this.mergeHandlerResult(r,a,f,p,o),f&&f.needsRenderFrame&&this._triggerRenderFrame()),(f||d.isActive())&&(n[p]=d);}}var m={};for(var g in this._previousActiveHandlers)n[g]||(m[g]=o);this._previousActiveHandlers=n,(Object.keys(m).length||mr(r))&&(this._changes.push([r,a,m]),this._triggerRenderFrame()),(Object.keys(n).length||mr(r))&&this._map._stop(!0),this._updatingCamera=!1;var v=r.cameraAnimation;v&&(this._inertia.clear(),this._fireEvents({},{}),this._changes=[],v(this._map));}else this.stop();},gr.prototype.mergeHandlerResult=function(e,i,o,r,a){if(o){t.extend(e,o);var n={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=n),void 0!==o.panDelta&&(i.drag=n),void 0!==o.pitchDelta&&(i.pitch=n),void 0!==o.bearingDelta&&(i.rotate=n);}},gr.prototype._applyChanges=function(){for(var e={},i={},o={},r=0,a=this._changes;r<a.length;r+=1){var n=a[r],s=n[0],l=n[1],c=n[2];s.panDelta&&(e.panDelta=(e.panDelta||new t.Point(0,0))._add(s.panDelta)),s.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+s.zoomDelta),s.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+s.bearingDelta),s.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+s.pitchDelta),void 0!==s.around&&(e.around=s.around),void 0!==s.pinchAround&&(e.pinchAround=s.pinchAround),s.noInertia&&(e.noInertia=s.noInertia),t.extend(i,l),t.extend(o,c);}this._updateMapTransform(e,i,o),this._changes=[];},gr.prototype._updateMapTransform=function(t,e,i){var o=this._map,r=o.transform;if(!mr(t))return this._fireEvents(e,i);var a=t.panDelta,n=t.zoomDelta,s=t.bearingDelta,l=t.pitchDelta,c=t.around,u=t.pinchAround;void 0!==u&&(c=u),o._stop(!0),c=c||o.transform.centerPoint;var h=r.pointLocation(a?c.sub(a):c);s&&(r.bearing+=s),l&&(r.pitch+=l),n&&(r.zoom+=n),r.setLocationAtPoint(h,c),this._map._update(),t.noInertia||this._inertia.record(t),this._fireEvents(e,i);},gr.prototype._fireEvents=function(e,i){var o=this,r=_r(this._eventsInProgress),a=_r(e),n={};for(var s in e)this._eventsInProgress[s]||(n[s+"start"]=e[s].originalEvent),this._eventsInProgress[s]=e[s];for(var l in !r&&a&&this._fireEvent("movestart",a.originalEvent),n)this._fireEvent(l,n[l]);for(var c in e.rotate&&(this._bearingChanged=!0),a&&this._fireEvent("move",a.originalEvent),e)this._fireEvent(c,e[c].originalEvent);var u,h={};for(var p in this._eventsInProgress){var d=this._eventsInProgress[p],_=d.handlerName,f=d.originalEvent;this._handlersById[_].isActive()||(delete this._eventsInProgress[p],h[p+"end"]=u=i[_]||f);}for(var m in h)this._fireEvent(m,h[m]);var g=_r(this._eventsInProgress);if((r||a)&&!g){this._updatingCamera=!0;var v=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),y=function(t){return 0!==t&&-o._bearingSnap<t&&t<o._bearingSnap};v?(y(v.bearing||this._map.getBearing())&&(v.bearing=0),this._map.easeTo(v,{originalEvent:u})):(this._map.fire(new t.Event("moveend",{originalEvent:u})),y(this._map.getBearing())&&this._map.resetNorth()),this._bearingChanged=!1,this._updatingCamera=!1;}},gr.prototype._fireEvent=function(e,i){this._map.fire(new t.Event(e,i?{originalEvent:i}:{}));},gr.prototype._triggerRenderFrame=function(){var t=this;void 0===this._frameId&&(this._frameId=this._map._requestRenderFrame((function(e){delete t._frameId,t.handleEvent(new fr("renderFrame",{timeStamp:e})),t._applyChanges();})));};var vr=function(e){function i(i,o){e.call(this),this._moving=!1,this._zooming=!1,this.transform=i,this._bearingSnap=o.bearingSnap,t.bindAll(["_renderFrameCallback"],this);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getCenter=function(){return new t.LngLat(this.transform.center.lng,this.transform.center.lat)},i.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},i.prototype.panBy=function(e,i,o){return e=t.Point.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},i),o)},i.prototype.panTo=function(e,i,o){return this.easeTo(t.extend({center:e},i),o)},i.prototype.getZoom=function(){return this.transform.zoom},i.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},i.prototype.zoomTo=function(e,i,o){return this.easeTo(t.extend({zoom:e},i),o)},i.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},i.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},i.prototype.getBearing=function(){return this.transform.bearing},i.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},i.prototype.getPadding=function(){return this.transform.padding},i.prototype.setPadding=function(t,e){return this.jumpTo({padding:t},e),this},i.prototype.rotateTo=function(e,i,o){return this.easeTo(t.extend({bearing:e},i),o)},i.prototype.resetNorth=function(e,i){return this.rotateTo(0,t.extend({duration:1e3},e),i),this},i.prototype.resetNorthPitch=function(e,i){return this.easeTo(t.extend({bearing:0,pitch:0,duration:1e3},e),i),this},i.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(t,e):this},i.prototype.getPitch=function(){return this.transform.pitch},i.prototype.setPitch=function(t,e){return this.jumpTo({pitch:t},e),this},i.prototype.cameraForBounds=function(e,i){return e=t.LngLatBounds.convert(e),this._cameraForBoxAndBearing(e.getNorthWest(),e.getSouthEast(),0,i)},i.prototype._cameraForBoxAndBearing=function(e,i,o,r){var a={top:0,bottom:0,right:0,left:0};if("number"==typeof(r=t.extend({padding:a,offset:[0,0],maxZoom:this.transform.maxZoom},r)).padding){var n=r.padding;r.padding={top:n,bottom:n,right:n,left:n};}r.padding=t.extend(a,r.padding);var s=this.transform,l=s.padding,c=s.project(t.LngLat.convert(e)),u=s.project(t.LngLat.convert(i)),h=c.rotate(-o*Math.PI/180),p=u.rotate(-o*Math.PI/180),d=new t.Point(Math.max(h.x,p.x),Math.max(h.y,p.y)),_=new t.Point(Math.min(h.x,p.x),Math.min(h.y,p.y)),f=d.sub(_),m=(s.width-(l.left+l.right+r.padding.left+r.padding.right))/f.x,g=(s.height-(l.top+l.bottom+r.padding.top+r.padding.bottom))/f.y;if(!(g<0||m<0)){var v=Math.min(s.scaleZoom(s.scale*Math.min(m,g)),r.maxZoom),y=t.Point.convert(r.offset),x=new t.Point(y.x+(r.padding.left-r.padding.right)/2,y.y+(r.padding.top-r.padding.bottom)/2).mult(s.scale/s.zoomScale(v));return {center:s.unproject(c.add(u).div(2).sub(x)),zoom:v,bearing:o}}t.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset.");},i.prototype.fitBounds=function(t,e,i){return this._fitInternal(this.cameraForBounds(t,e),e,i)},i.prototype.fitScreenCoordinates=function(e,i,o,r,a){return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(t.Point.convert(e)),this.transform.pointLocation(t.Point.convert(i)),o,r),r,a)},i.prototype._fitInternal=function(e,i,o){return e?(delete(i=t.extend(e,i)).padding,i.linear?this.easeTo(i,o):this.flyTo(i,o)):this},i.prototype.jumpTo=function(e,i){this.stop();var o=this.transform,r=!1,a=!1,n=!1;return "zoom"in e&&o.zoom!==+e.zoom&&(r=!0,o.zoom=+e.zoom),void 0!==e.center&&(o.center=t.LngLat.convert(e.center)),"bearing"in e&&o.bearing!==+e.bearing&&(a=!0,o.bearing=+e.bearing),"pitch"in e&&o.pitch!==+e.pitch&&(n=!0,o.pitch=+e.pitch),null==e.padding||o.isPaddingEqual(e.padding)||(o.padding=e.padding),this.fire(new t.Event("movestart",i)).fire(new t.Event("move",i)),r&&this.fire(new t.Event("zoomstart",i)).fire(new t.Event("zoom",i)).fire(new t.Event("zoomend",i)),a&&this.fire(new t.Event("rotatestart",i)).fire(new t.Event("rotate",i)).fire(new t.Event("rotateend",i)),n&&this.fire(new t.Event("pitchstart",i)).fire(new t.Event("pitch",i)).fire(new t.Event("pitchend",i)),this.fire(new t.Event("moveend",i))},i.prototype.easeTo=function(e,i){var o=this;this._stop(!1,e.easeId),(!1===(e=t.extend({offset:[0,0],duration:500,easing:t.ease},e)).animate||!e.essential&&t.browser.prefersReducedMotion)&&(e.duration=0);var r=this.transform,a=this.getZoom(),n=this.getBearing(),s=this.getPitch(),l=this.getPadding(),c="zoom"in e?+e.zoom:a,u="bearing"in e?this._normalizeBearing(e.bearing,n):n,h="pitch"in e?+e.pitch:s,p="padding"in e?e.padding:r.padding,d=t.Point.convert(e.offset),_=r.centerPoint.add(d),f=r.pointLocation(_),m=t.LngLat.convert(e.center||f);this._normalizeCenter(m);var g,v,y=r.project(f),x=r.project(m).sub(y),b=r.zoomScale(c-a);e.around&&(g=t.LngLat.convert(e.around),v=r.locationPoint(g));var w={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=this._zooming||c!==a,this._rotating=this._rotating||n!==u,this._pitching=this._pitching||h!==s,this._padding=!r.isPaddingEqual(p),this._easeId=e.easeId,this._prepareEase(i,e.noMoveStart,w),clearTimeout(this._easeEndTimeoutID),this._ease((function(e){if(o._zooming&&(r.zoom=t.number(a,c,e)),o._rotating&&(r.bearing=t.number(n,u,e)),o._pitching&&(r.pitch=t.number(s,h,e)),o._padding&&(r.interpolatePadding(l,p,e),_=r.centerPoint.add(d)),g)r.setLocationAtPoint(g,v);else {var f=r.zoomScale(r.zoom-a),m=c>a?Math.min(2,b):Math.max(.5,b),w=Math.pow(m,1-e),T=r.unproject(y.add(x.mult(e*w)).mult(f));r.setLocationAtPoint(r.renderWorldCopies?T.wrap():T,_);}o._fireMoveEvents(i);}),(function(t){o._afterEase(i,t);}),e),this},i.prototype._prepareEase=function(e,i,o){void 0===o&&(o={}),this._moving=!0,i||o.moving||this.fire(new t.Event("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.Event("pitchstart",e));},i.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e));},i.prototype._afterEase=function(e,i){if(!this._easeId||!i||this._easeId!==i){delete this._easeId;var o=this._zooming,r=this._rotating,a=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,o&&this.fire(new t.Event("zoomend",e)),r&&this.fire(new t.Event("rotateend",e)),a&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e));}},i.prototype.flyTo=function(e,i){var o=this;if(!e.essential&&t.browser.prefersReducedMotion){var r=t.pick(e,["center","zoom","bearing","pitch","around"]);return this.jumpTo(r,i)}this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var a=this.transform,n=this.getZoom(),s=this.getBearing(),l=this.getPitch(),c=this.getPadding(),u="zoom"in e?t.clamp(+e.zoom,a.minZoom,a.maxZoom):n,h="bearing"in e?this._normalizeBearing(e.bearing,s):s,p="pitch"in e?+e.pitch:l,d="padding"in e?e.padding:a.padding,_=a.zoomScale(u-n),f=t.Point.convert(e.offset),m=a.centerPoint.add(f),g=a.pointLocation(m),v=t.LngLat.convert(e.center||g);this._normalizeCenter(v);var y=a.project(g),x=a.project(v).sub(y),b=e.curve,w=Math.max(a.width,a.height),T=w/_,E=x.mag();if("minZoom"in e){var I=t.clamp(Math.min(e.minZoom,n,u),a.minZoom,a.maxZoom),P=w/a.zoomScale(I-n);b=Math.sqrt(P/E*2);}var S=b*b;function C(t){var e=(T*T-w*w+(t?-1:1)*S*S*E*E)/(2*(t?T:w)*S*E);return Math.log(Math.sqrt(e*e+1)-e)}function z(t){return (Math.exp(t)-Math.exp(-t))/2}function D(t){return (Math.exp(t)+Math.exp(-t))/2}var M=C(0),L=function(t){return D(M)/D(M+b*t)},A=function(t){return w*((D(M)*(z(e=M+b*t)/D(e))-z(M))/S)/E;var e;},R=(C(1)-M)/b;if(Math.abs(E)<1e-6||!isFinite(R)){if(Math.abs(w-T)<1e-6)return this.easeTo(e,i);var k=T<w?-1:1;R=Math.abs(Math.log(T/w))/b,A=function(){return 0},L=function(t){return Math.exp(k*b*t)};}return e.duration="duration"in e?+e.duration:1e3*R/("screenSpeed"in e?+e.screenSpeed/b:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=s!==h,this._pitching=p!==l,this._padding=!a.isPaddingEqual(d),this._prepareEase(i,!1),this._ease((function(e){var r=e*R,_=1/L(r);a.zoom=1===e?u:n+a.scaleZoom(_),o._rotating&&(a.bearing=t.number(s,h,e)),o._pitching&&(a.pitch=t.number(l,p,e)),o._padding&&(a.interpolatePadding(c,d,e),m=a.centerPoint.add(f));var g=1===e?v:a.unproject(y.add(x.mult(A(r))).mult(_));a.setLocationAtPoint(a.renderWorldCopies?g.wrap():g,m),o._fireMoveEvents(i);}),(function(){return o._afterEase(i)}),e),this},i.prototype.isEasing=function(){return !!this._easeFrameId},i.prototype.stop=function(){return this._stop()},i.prototype._stop=function(t,e){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var i=this._onEaseEnd;delete this._onEaseEnd,i.call(this,e);}if(!t){var o=this.handlers;o&&o.stop();}return this},i.prototype._ease=function(e,i,o){!1===o.animate||0===o.duration?(e(1),i()):(this._easeStart=t.browser.now(),this._easeOptions=o,this._onEaseFrame=e,this._onEaseEnd=i,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));},i.prototype._renderFrameCallback=function(){var e=Math.min((t.browser.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},i.prototype._normalizeBearing=function(e,i){e=t.wrap(e,-180,180);var o=Math.abs(e-i);return Math.abs(e-360-i)<o&&(e-=360),Math.abs(e+360-i)<o&&(e+=360),e},i.prototype._normalizeCenter=function(t){var e=this.transform;if(e.renderWorldCopies&&!e.lngRange){var i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}},i}(t.Evented),yr=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this);};yr.prototype.getDefaultPosition=function(){return "bottom-right"},yr.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._innerContainer=i.create("div","mapboxgl-ctrl-attrib-inner",this._container),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},yr.prototype.onRemove=function(){i.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0;},yr.prototype._updateEditLink=function(){var e=this._editLink;e||(e=this._editLink=this._container.querySelector(".mapbox-improve-map"));var i=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||t.config.ACCESS_TOKEN}];if(e){var o=i.reduce((function(t,e,o){return e.value&&(t+=e.key+"="+e.value+(o<i.length-1?"&":"")),t}),"?");e.href=t.config.FEEDBACK_URL+"/"+o+(this._map._hash?this._map._hash.getHashString(!0):""),e.rel="noopener nofollow";}},yr.prototype._updateData=function(t){!t||"metadata"!==t.sourceDataType&&"style"!==t.dataType||(this._updateAttributions(),this._updateEditLink());},yr.prototype._updateAttributions=function(){if(this._map.style){var t=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?t=t.concat(this.options.customAttribution.map((function(t){return "string"!=typeof t?"":t}))):"string"==typeof this.options.customAttribution&&t.push(this.options.customAttribution)),this._map.style.stylesheet){var e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}var i=this._map.style.sourceCaches;for(var o in i){var r=i[o];if(r.used){var a=r.getSource();a.attribution&&t.indexOf(a.attribution)<0&&t.push(a.attribution);}}t.sort((function(t,e){return t.length-e.length}));var n=(t=t.filter((function(e,i){for(var o=i+1;o<t.length;o++)if(t[o].indexOf(e)>=0)return !1;return !0}))).join(" | ");n!==this._attribHTML&&(this._attribHTML=n,t.length?(this._innerContainer.innerHTML=n,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null);}},yr.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact");};var xr=function(){t.bindAll(["_updateLogo"],this),t.bindAll(["_updateCompact"],this);};xr.prototype.onAdd=function(t){this._map=t,this._container=i.create("div","mapboxgl-ctrl");var e=i.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.rel="noopener nofollow",e.href="https://www.mapbox.com/",e.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),e.setAttribute("rel","noopener nofollow"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container},xr.prototype.onRemove=function(){i.remove(this._container),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact);},xr.prototype.getDefaultPosition=function(){return "bottom-left"},xr.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none");},xr.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return !0;return !1}},xr.prototype._updateCompact=function(){var t=this._container.children;if(t.length){var e=t[0];this._map.getCanvasContainer().offsetWidth<250?e.classList.add("mapboxgl-compact"):e.classList.remove("mapboxgl-compact");}};var br=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;};br.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},br.prototype.remove=function(t){for(var e=this._currentlyRunning,i=0,o=e?this._queue.concat(e):this._queue;i<o.length;i+=1){var r=o[i];if(r.id===t)return void(r.cancelled=!0)}},br.prototype.run=function(t){void 0===t&&(t=0);var e=this._currentlyRunning=this._queue;this._queue=[];for(var i=0,o=e;i<o.length;i+=1){var r=o[i];if(!r.cancelled&&(r.callback(t),this._cleared))break}this._cleared=!1,this._currentlyRunning=!1;},br.prototype.clear=function(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];};var wr={"FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox logo","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScaleControl.Feet":"ft","ScaleControl.Meters":"m","ScaleControl.Kilometers":"km","ScaleControl.Miles":"mi","ScaleControl.NauticalMiles":"nm"},Tr=t.window.HTMLImageElement,Er=t.window.HTMLElement,Ir=t.window.ImageBitmap,Pr={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:60,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",transformRequest:null,accessToken:null,fadeDuration:300,crossSourceCollisions:!0},Sr=function(o){function r(e){var i=this;if(null!=(e=t.extend({},Pr,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=e.maxPitch&&e.maxPitch>60)throw new Error("maxPitch must be less than or equal to 60");var r=new To(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies);if(o.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._antialias=e.antialias,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossSourceCollisions=e.crossSourceCollisions,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new br,this._controls=[],this._mapId=t.uniqueId(),this._locale=t.extend({},wr,e.locale),this._requestManager=new t.RequestManager(e.transformRequest,e.accessToken),"string"==typeof e.container){if(this._container=t.window.document.getElementById(e.container),!this._container)throw new Error("Container '"+e.container+"' not found.")}else {if(!(e.container instanceof Er))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container;}if(e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),void 0===this.painter)throw new Error("Failed to initialize WebGL.");this.on("move",(function(){return i._update(!1)})),this.on("moveend",(function(){return i._update(!1)})),this.on("zoom",(function(){return i._update(!0)})),void 0!==t.window&&(t.window.addEventListener("online",this._onWindowOnline,!1),t.window.addEventListener("resize",this._onWindowResize,!1)),this.handlers=new gr(this,e),this._hash=e.hash&&new Io("string"==typeof e.hash&&e.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),e.bounds&&(this.resize(),this.fitBounds(e.bounds,t.extend({},e.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=e.localIdeographFontFamily,e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new yr({customAttribution:e.customAttribution})),this.addControl(new xr,e.logoPosition),this.on("style.load",(function(){i.transform.unmodified&&i.jumpTo(i.style.stylesheet);})),this.on("data",(function(e){i._update("style"===e.dataType),i.fire(new t.Event(e.dataType+"data",e));})),this.on("dataloading",(function(e){i.fire(new t.Event(e.dataType+"dataloading",e));}));}o&&(r.__proto__=o),(r.prototype=Object.create(o&&o.prototype)).constructor=r;var a={showTileBoundaries:{configurable:!0},showPadding:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0},version:{configurable:!0}};return r.prototype._getMapId=function(){return this._mapId},r.prototype.addControl=function(e,i){if(void 0===i&&e.getDefaultPosition&&(i=e.getDefaultPosition()),void 0===i&&(i="top-right"),!e||!e.onAdd)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));var o=e.onAdd(this);this._controls.push(e);var r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this},r.prototype.removeControl=function(e){if(!e||!e.onRemove)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));var i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this},r.prototype.resize=function(e){var i=this._containerDimensions(),o=i[0],r=i[1];this._resizeCanvas(o,r),this.transform.resize(o,r),this.painter.resize(o,r);var a=!this._moving;return a&&(this.stop(),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e))),this.fire(new t.Event("resize",e)),a&&this.fire(new t.Event("moveend",e)),this},r.prototype.getBounds=function(){return this.transform.getBounds()},r.prototype.getMaxBounds=function(){return this.transform.getMaxBounds()},r.prototype.setMaxBounds=function(e){return this.transform.setMaxBounds(t.LngLatBounds.convert(e)),this._update()},r.prototype.setMinZoom=function(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()<t&&this.setZoom(t),this;throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")},r.prototype.getMinZoom=function(){return this.transform.minZoom},r.prototype.setMaxZoom=function(t){if((t=null==t?22:t)>=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},r.prototype.getMaxZoom=function(){return this.transform.maxZoom},r.prototype.setMinPitch=function(t){if((t=null==t?0:t)<0)throw new Error("minPitch must be greater than or equal to 0");if(t>=0&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()<t&&this.setPitch(t),this;throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")},r.prototype.getMinPitch=function(){return this.transform.minPitch},r.prototype.setMaxPitch=function(t){if((t=null==t?60:t)>60)throw new Error("maxPitch must be less than or equal to 60");if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t&&this.setPitch(t),this;throw new Error("maxPitch must be greater than the current minPitch")},r.prototype.getMaxPitch=function(){return this.transform.maxPitch},r.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},r.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update()},r.prototype.project=function(e){return this.transform.locationPoint(t.LngLat.convert(e))},r.prototype.unproject=function(e){return this.transform.pointLocation(t.Point.convert(e))},r.prototype.isMoving=function(){return this._moving||this.handlers.isMoving()},r.prototype.isZooming=function(){return this._zooming||this.handlers.isZooming()},r.prototype.isRotating=function(){return this._rotating||this.handlers.isRotating()},r.prototype._createDelegatedListener=function(t,e,i){var o,r=this;if("mouseenter"===t||"mouseover"===t){var a=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){var n=r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[];n.length?a||(a=!0,i.call(r,new Ro(t,r,o.originalEvent,{features:n}))):a=!1;},mouseout:function(){a=!1;}}}}if("mouseleave"===t||"mouseout"===t){var n=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){(r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[]).length?n=!0:n&&(n=!1,i.call(r,new Ro(t,r,o.originalEvent)));},mouseout:function(e){n&&(n=!1,i.call(r,new Ro(t,r,e.originalEvent)));}}}}return {layer:e,listener:i,delegates:(o={},o[t]=function(t){var o=r.getLayer(e)?r.queryRenderedFeatures(t.point,{layers:[e]}):[];o.length&&(t.features=o,i.call(r,t),delete t.features);},o)}},r.prototype.on=function(t,e,i){if(void 0===i)return o.prototype.on.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(r),r.delegates)this.on(a,r.delegates[a]);return this},r.prototype.once=function(t,e,i){if(void 0===i)return o.prototype.once.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in r.delegates)this.once(a,r.delegates[a]);return this},r.prototype.off=function(t,e,i){var r=this;return void 0===i?o.prototype.off.call(this,t,e):(this._delegatedListeners&&this._delegatedListeners[t]&&function(o){for(var a=o[t],n=0;n<a.length;n++){var s=a[n];if(s.layer===e&&s.listener===i){for(var l in s.delegates)r.off(l,s.delegates[l]);return a.splice(n,1),r}}}(this._delegatedListeners),this)},r.prototype.queryRenderedFeatures=function(e,i){if(!this.style)return [];var o;if(void 0!==i||void 0===e||e instanceof t.Point||Array.isArray(e)||(i=e,e=void 0),i=i||{},(e=e||[[0,0],[this.transform.width,this.transform.height]])instanceof t.Point||"number"==typeof e[0])o=[t.Point.convert(e)];else {var r=t.Point.convert(e[0]),a=t.Point.convert(e[1]);o=[r,new t.Point(a.x,r.y),a,new t.Point(r.x,a.y),r];}return this.style.queryRenderedFeatures(o,i,this.transform)},r.prototype.querySourceFeatures=function(t,e){return this.style.querySourceFeatures(t,e)},r.prototype.setStyle=function(e,i){return !1!==(i=t.extend({},{localIdeographFontFamily:this._localIdeographFontFamily},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))},r.prototype._getUIString=function(t){var e=this._locale[t];if(null==e)throw new Error("Missing UI string '"+t+"'");return e},r.prototype._updateStyle=function(t,e){return this.style&&(this.style.setEventedParent(null),this.style._remove()),t?(this.style=new qe(this,e||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof t?this.style.loadURL(t):this.style.loadJSON(t),this):(delete this.style,this)},r.prototype._lazyInitEmptyStyle=function(){this.style||(this.style=new qe(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());},r.prototype._diffStyle=function(e,i){var o=this;if("string"==typeof e){var r=this._requestManager.normalizeStyleURL(e),a=this._requestManager.transformRequest(r,t.ResourceType.Style);t.getJSON(a,(function(e,r){e?o.fire(new t.ErrorEvent(e)):r&&o._updateDiff(r,i);}));}else "object"==typeof e&&this._updateDiff(e,i);},r.prototype._updateDiff=function(e,i){try{this.style.setState(e)&&this._update(!0);}catch(o){t.warnOnce("Unable to perform style diff: "+(o.message||o.error||o)+". Rebuilding the style from scratch."),this._updateStyle(e,i);}},r.prototype.getStyle=function(){if(this.style)return this.style.serialize()},r.prototype.isStyleLoaded=function(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")},r.prototype.addSource=function(t,e){return this._lazyInitEmptyStyle(),this.style.addSource(t,e),this._update(!0)},r.prototype.isSourceLoaded=function(e){var i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.ErrorEvent(new Error("There is no source with ID '"+e+"'")));},r.prototype.areTilesLoaded=function(){var t=this.style&&this.style.sourceCaches;for(var e in t){var i=t[e]._tiles;for(var o in i){var r=i[o];if("loaded"!==r.state&&"errored"!==r.state)return !1}}return !0},r.prototype.addSourceType=function(t,e,i){return this._lazyInitEmptyStyle(),this.style.addSourceType(t,e,i)},r.prototype.removeSource=function(t){return this.style.removeSource(t),this._update(!0)},r.prototype.getSource=function(t){return this.style.getSource(t)},r.prototype.addImage=function(e,i,o){void 0===o&&(o={});var r=o.pixelRatio;void 0===r&&(r=1);var a=o.sdf;void 0===a&&(a=!1);var n=o.stretchX,s=o.stretchY,l=o.content;if(this._lazyInitEmptyStyle(),i instanceof Tr||Ir&&i instanceof Ir){var c=t.browser.getImageData(i);this.style.addImage(e,{data:new t.RGBAImage({width:c.width,height:c.height},c.data),pixelRatio:r,stretchX:n,stretchY:s,content:l,sdf:a,version:0});}else {if(void 0===i.width||void 0===i.height)return this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));var u=i;this.style.addImage(e,{data:new t.RGBAImage({width:i.width,height:i.height},new Uint8Array(i.data)),pixelRatio:r,stretchX:n,stretchY:s,content:l,sdf:a,version:0,userImage:u}),u.onAdd&&u.onAdd(this,e);}},r.prototype.updateImage=function(e,i){var o=this.style.getImage(e);if(!o)return this.fire(new t.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));var r=i instanceof Tr||Ir&&i instanceof Ir?t.browser.getImageData(i):i,a=r.width,n=r.height,s=r.data;return void 0===a||void 0===n?this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`"))):a!==o.data.width||n!==o.data.height?this.fire(new t.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image"))):(o.data.replace(s,!(i instanceof Tr||Ir&&i instanceof Ir)),void this.style.updateImage(e,o))},r.prototype.hasImage=function(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)},r.prototype.removeImage=function(t){this.style.removeImage(t);},r.prototype.loadImage=function(e,i){t.getImage(this._requestManager.transformRequest(e,t.ResourceType.Image),i);},r.prototype.listImages=function(){return this.style.listImages()},r.prototype.addLayer=function(t,e){return this._lazyInitEmptyStyle(),this.style.addLayer(t,e),this._update(!0)},r.prototype.moveLayer=function(t,e){return this.style.moveLayer(t,e),this._update(!0)},r.prototype.removeLayer=function(t){return this.style.removeLayer(t),this._update(!0)},r.prototype.getLayer=function(t){return this.style.getLayer(t)},r.prototype.setLayerZoomRange=function(t,e,i){return this.style.setLayerZoomRange(t,e,i),this._update(!0)},r.prototype.setFilter=function(t,e,i){return void 0===i&&(i={}),this.style.setFilter(t,e,i),this._update(!0)},r.prototype.getFilter=function(t){return this.style.getFilter(t)},r.prototype.setPaintProperty=function(t,e,i,o){return void 0===o&&(o={}),this.style.setPaintProperty(t,e,i,o),this._update(!0)},r.prototype.getPaintProperty=function(t,e){return this.style.getPaintProperty(t,e)},r.prototype.setLayoutProperty=function(t,e,i,o){return void 0===o&&(o={}),this.style.setLayoutProperty(t,e,i,o),this._update(!0)},r.prototype.getLayoutProperty=function(t,e){return this.style.getLayoutProperty(t,e)},r.prototype.setLight=function(t,e){return void 0===e&&(e={}),this._lazyInitEmptyStyle(),this.style.setLight(t,e),this._update(!0)},r.prototype.getLight=function(){return this.style.getLight()},r.prototype.setFeatureState=function(t,e){return this.style.setFeatureState(t,e),this._update()},r.prototype.removeFeatureState=function(t,e){return this.style.removeFeatureState(t,e),this._update()},r.prototype.getFeatureState=function(t){return this.style.getFeatureState(t)},r.prototype.getContainer=function(){return this._container},r.prototype.getCanvasContainer=function(){return this._canvasContainer},r.prototype.getCanvas=function(){return this._canvas},r.prototype._containerDimensions=function(){var t=0,e=0;return this._container&&(t=this._container.clientWidth||400,e=this._container.clientHeight||300),[t,e]},r.prototype._detectMissingCSS=function(){"rgb(250, 128, 114)"!==t.window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")&&t.warnOnce("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.");},r.prototype._setupContainer=function(){var t=this._container;t.classList.add("mapboxgl-map"),(this._missingCSSCanary=i.create("div","mapboxgl-canary",t)).style.visibility="hidden",this._detectMissingCSS();var e=this._canvasContainer=i.create("div","mapboxgl-canvas-container",t);this._interactive&&e.classList.add("mapboxgl-interactive"),this._canvas=i.create("canvas","mapboxgl-canvas",e),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("aria-label","Map");var o=this._containerDimensions();this._resizeCanvas(o[0],o[1]);var r=this._controlContainer=i.create("div","mapboxgl-control-container",t),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((function(t){a[t]=i.create("div","mapboxgl-ctrl-"+t,r);}));},r.prototype._resizeCanvas=function(e,i){var o=t.browser.devicePixelRatio||1;this._canvas.width=o*e,this._canvas.height=o*i,this._canvas.style.width=e+"px",this._canvas.style.height=i+"px";},r.prototype._setupPainter=function(){var i=t.extend({},e.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),o=this._canvas.getContext("webgl",i)||this._canvas.getContext("experimental-webgl",i);o?(this.painter=new yo(o,this.transform),t.webpSupported.testSupport(o)):this.fire(new t.ErrorEvent(new Error("Failed to initialize WebGL")));},r.prototype._contextLost=function(e){e.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}));},r.prototype._contextRestored=function(e){this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}));},r.prototype.loaded=function(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()},r.prototype._update=function(t){return this.style?(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this.triggerRepaint(),this):this},r.prototype._requestRenderFrame=function(t){return this._update(),this._renderTaskQueue.add(t)},r.prototype._cancelRenderFrame=function(t){this._renderTaskQueue.remove(t);},r.prototype._render=function(e){var i,o=this,r=0,a=this.painter.context.extTimerQuery;if(this.listens("gpu-timing-frame")&&(i=a.createQueryEXT(),a.beginQueryEXT(a.TIME_ELAPSED_EXT,i),r=t.browser.now()),this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),!this._removed){var n=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;var s=this.transform.zoom,l=t.browser.now();this.style.zoomHistory.update(s,l);var c=new t.EvaluationParameters(s,{now:l,fadeDuration:this._fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),u=c.crossFadingFactor();1===u&&u===this._crossFadingFactor||(n=!0,this._crossFadingFactor=u),this.style.update(c);}if(this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,this._fadeDuration,this._crossSourceCollisions),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:this._fadeDuration,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer")}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||n)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),this.listens("gpu-timing-frame")){var h=t.browser.now()-r;a.endQueryEXT(a.TIME_ELAPSED_EXT,i),setTimeout((function(){var e=a.getQueryObjectEXT(i,a.QUERY_RESULT_EXT)/1e6;a.deleteQueryEXT(i),o.fire(new t.Event("gpu-timing-frame",{cpuTime:h,gpuTime:e}));}),50);}if(this.listens("gpu-timing-layer")){var p=this.painter.collectGpuTimers();setTimeout((function(){var e=o.painter.queryGpuTimers(p);o.fire(new t.Event("gpu-timing-layer",{layerTimes:e}));}),50);}var d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.Event("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0),this}},r.prototype.remove=function(){this._hash&&this._hash.remove();for(var e=0,i=this._controls;e<i.length;e+=1)i[e].onRemove(this);this._controls=[],this._frame&&(this._frame.cancel(),this._frame=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),void 0!==t.window&&(t.window.removeEventListener("resize",this._onWindowResize,!1),t.window.removeEventListener("online",this._onWindowOnline,!1));var o=this.painter.context.gl.getExtension("WEBGL_lose_context");o&&o.loseContext(),Cr(this._canvasContainer),Cr(this._controlContainer),Cr(this._missingCSSCanary),this._container.classList.remove("mapboxgl-map"),this._removed=!0,this.fire(new t.Event("remove"));},r.prototype.triggerRepaint=function(){var e=this;this.style&&!this._frame&&(this._frame=t.browser.frame((function(t){e._frame=null,e._render(t);})));},r.prototype._onWindowOnline=function(){this._update();},r.prototype._onWindowResize=function(t){this._trackResize&&this.resize({originalEvent:t})._update();},a.showTileBoundaries.get=function(){return !!this._showTileBoundaries},a.showTileBoundaries.set=function(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update());},a.showPadding.get=function(){return !!this._showPadding},a.showPadding.set=function(t){this._showPadding!==t&&(this._showPadding=t,this._update());},a.showCollisionBoxes.get=function(){return !!this._showCollisionBoxes},a.showCollisionBoxes.set=function(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update());},a.showOverdrawInspector.get=function(){return !!this._showOverdrawInspector},a.showOverdrawInspector.set=function(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update());},a.repaint.get=function(){return !!this._repaint},a.repaint.set=function(t){this._repaint!==t&&(this._repaint=t,this.triggerRepaint());},a.vertices.get=function(){return !!this._vertices},a.vertices.set=function(t){this._vertices=t,this._update();},r.prototype._setCacheLimits=function(e,i){t.setCacheLimits(e,i);},a.version.get=function(){return t.version},Object.defineProperties(r.prototype,a),r}(vr);function Cr(t){t.parentNode&&t.parentNode.removeChild(t);}var zr={showCompass:!0,showZoom:!0,visualizePitch:!1},Dr=function(e){var o=this;this.options=t.extend({},zr,e),this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this.options.showZoom&&(t.bindAll(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",(function(t){return o._map.zoomIn({},{originalEvent:t})})),i.create("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden",!0),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",(function(t){return o._map.zoomOut({},{originalEvent:t})})),i.create("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden",!0)),this.options.showCompass&&(t.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",(function(t){o.options.visualizePitch?o._map.resetNorthPitch({},{originalEvent:t}):o._map.resetNorth({},{originalEvent:t});})),this._compassIcon=i.create("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden",!0));};Dr.prototype._updateZoomButtons=function(){var t=this._map.getZoom();this._zoomInButton.disabled=t===this._map.getMaxZoom(),this._zoomOutButton.disabled=t===this._map.getMinZoom();},Dr.prototype._rotateCompassArrow=function(){var t=this.options.visualizePitch?"scale("+1/Math.pow(Math.cos(this._map.transform.pitch*(Math.PI/180)),.5)+") rotateX("+this._map.transform.pitch+"deg) rotateZ("+this._map.transform.angle*(180/Math.PI)+"deg)":"rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassIcon.style.transform=t;},Dr.prototype.onAdd=function(t){return this._map=t,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Mr(this._map,this._compass,this.options.visualizePitch)),this._container},Dr.prototype.onRemove=function(){i.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;},Dr.prototype._createButton=function(t,e){var o=i.create("button",t,this._container);return o.type="button",o.addEventListener("click",e),o},Dr.prototype._setButtonTitle=function(t,e){var i=this._map._getUIString("NavigationControl."+e);t.title=i,t.setAttribute("aria-label",i);};var Mr=function(e,o,r){void 0===r&&(r=!1),this._clickTolerance=10,this.element=o,this.mouseRotate=new Xo({clickTolerance:e.dragRotate._mouseRotate._clickTolerance}),this.map=e,r&&(this.mousePitch=new Ho({clickTolerance:e.dragRotate._mousePitch._clickTolerance})),t.bindAll(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),i.addEventListener(o,"mousedown",this.mousedown),i.addEventListener(o,"touchstart",this.touchstart,{passive:!1}),i.addEventListener(o,"touchmove",this.touchmove),i.addEventListener(o,"touchend",this.touchend),i.addEventListener(o,"touchcancel",this.reset);};function Lr(e,i,o){if(e=new t.LngLat(e.lng,e.lat),i){var r=new t.LngLat(e.lng-360,e.lat),a=new t.LngLat(e.lng+360,e.lat),n=o.locationPoint(e).distSqr(i);o.locationPoint(r).distSqr(i)<n?e=r:o.locationPoint(a).distSqr(i)<n&&(e=a);}for(;Math.abs(e.lng-o.center.lng)>180;){var s=o.locationPoint(e);if(s.x>=0&&s.y>=0&&s.x<=o.width&&s.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e}Mr.prototype.down=function(t,e){this.mouseRotate.mousedown(t,e),this.mousePitch&&this.mousePitch.mousedown(t,e),i.disableDrag();},Mr.prototype.move=function(t,e){var i=this.map,o=this.mouseRotate.mousemoveWindow(t,e);if(o&&o.bearingDelta&&i.setBearing(i.getBearing()+o.bearingDelta),this.mousePitch){var r=this.mousePitch.mousemoveWindow(t,e);r&&r.pitchDelta&&i.setPitch(i.getPitch()+r.pitchDelta);}},Mr.prototype.off=function(){var t=this.element;i.removeEventListener(t,"mousedown",this.mousedown),i.removeEventListener(t,"touchstart",this.touchstart,{passive:!1}),i.removeEventListener(t,"touchmove",this.touchmove),i.removeEventListener(t,"touchend",this.touchend),i.removeEventListener(t,"touchcancel",this.reset),this.offTemp();},Mr.prototype.offTemp=function(){i.enableDrag(),i.removeEventListener(t.window,"mousemove",this.mousemove),i.removeEventListener(t.window,"mouseup",this.mouseup);},Mr.prototype.mousedown=function(e){this.down(t.extend({},e,{ctrlKey:!0,preventDefault:function(){return e.preventDefault()}}),i.mousePos(this.element,e)),i.addEventListener(t.window,"mousemove",this.mousemove),i.addEventListener(t.window,"mouseup",this.mouseup);},Mr.prototype.mousemove=function(t){this.move(t,i.mousePos(this.element,t));},Mr.prototype.mouseup=function(t){this.mouseRotate.mouseupWindow(t),this.mousePitch&&this.mousePitch.mouseupWindow(t),this.offTemp();},Mr.prototype.touchstart=function(t){1!==t.targetTouches.length?this.reset():(this._startPos=this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:function(){return t.preventDefault()}},this._startPos));},Mr.prototype.touchmove=function(t){1!==t.targetTouches.length?this.reset():(this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.move({preventDefault:function(){return t.preventDefault()}},this._lastPos));},Mr.prototype.touchend=function(t){0===t.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)<this._clickTolerance&&this.element.click(),this.reset();},Mr.prototype.reset=function(){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp();};var Ar={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Rr(t,e,i){var o=t.classList;for(var r in Ar)o.remove("mapboxgl-"+i+"-anchor-"+r);o.add("mapboxgl-"+i+"-anchor-"+e);}var kr,Br=function(e){function o(o,r){var a=this;if(e.call(this),(o instanceof t.window.HTMLElement||r)&&(o=t.extend({element:o},r)),t.bindAll(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress"],this),this._anchor=o&&o.anchor||"center",this._color=o&&o.color||"#3FB1CE",this._scale=o&&o.scale||1,this._draggable=o&&o.draggable||!1,this._state="inactive",this._rotation=o&&o.rotation||0,this._rotationAlignment=o&&o.rotationAlignment||"auto",this._pitchAlignment=o&&o.pitchAlignment&&"auto"!==o.pitchAlignment?o.pitchAlignment:this._rotationAlignment,o&&o.element)this._element=o.element,this._offset=t.Point.convert(o&&o.offset||[0,0]);else {this._defaultMarker=!0,this._element=i.create("div"),this._element.setAttribute("aria-label","Map marker");var n=i.createNS("http://www.w3.org/2000/svg","svg");n.setAttributeNS(null,"display","block"),n.setAttributeNS(null,"height","41px"),n.setAttributeNS(null,"width","27px"),n.setAttributeNS(null,"viewBox","0 0 27 41");var s=i.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"stroke","none"),s.setAttributeNS(null,"stroke-width","1"),s.setAttributeNS(null,"fill","none"),s.setAttributeNS(null,"fill-rule","evenodd");var l=i.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"fill-rule","nonzero");var c=i.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"transform","translate(3.0, 29.0)"),c.setAttributeNS(null,"fill","#000000");for(var u=0,h=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];u<h.length;u+=1){var p=h[u],d=i.createNS("http://www.w3.org/2000/svg","ellipse");d.setAttributeNS(null,"opacity","0.04"),d.setAttributeNS(null,"cx","10.5"),d.setAttributeNS(null,"cy","5.80029008"),d.setAttributeNS(null,"rx",p.rx),d.setAttributeNS(null,"ry",p.ry),c.appendChild(d);}var _=i.createNS("http://www.w3.org/2000/svg","g");_.setAttributeNS(null,"fill",this._color);var f=i.createNS("http://www.w3.org/2000/svg","path");f.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),_.appendChild(f);var m=i.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"opacity","0.25"),m.setAttributeNS(null,"fill","#000000");var g=i.createNS("http://www.w3.org/2000/svg","path");g.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),m.appendChild(g);var v=i.createNS("http://www.w3.org/2000/svg","g");v.setAttributeNS(null,"transform","translate(6.0, 7.0)"),v.setAttributeNS(null,"fill","#FFFFFF");var y=i.createNS("http://www.w3.org/2000/svg","g");y.setAttributeNS(null,"transform","translate(8.0, 8.0)");var x=i.createNS("http://www.w3.org/2000/svg","circle");x.setAttributeNS(null,"fill","#000000"),x.setAttributeNS(null,"opacity","0.25"),x.setAttributeNS(null,"cx","5.5"),x.setAttributeNS(null,"cy","5.5"),x.setAttributeNS(null,"r","5.4999962");var b=i.createNS("http://www.w3.org/2000/svg","circle");b.setAttributeNS(null,"fill","#FFFFFF"),b.setAttributeNS(null,"cx","5.5"),b.setAttributeNS(null,"cy","5.5"),b.setAttributeNS(null,"r","5.4999962"),y.appendChild(x),y.appendChild(b),l.appendChild(c),l.appendChild(_),l.appendChild(m),l.appendChild(v),l.appendChild(y),n.appendChild(l),n.setAttributeNS(null,"height",41*this._scale+"px"),n.setAttributeNS(null,"width",27*this._scale+"px"),this._element.appendChild(n),this._offset=t.Point.convert(o&&o.offset||[0,-14]);}this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",(function(t){t.preventDefault();})),this._element.addEventListener("mousedown",(function(t){t.preventDefault();})),this._element.addEventListener("focus",(function(){var t=a._map.getContainer();t.scrollTop=0,t.scrollLeft=0;})),Rr(this._element,this._anchor,"marker"),this._popup=null;}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.addTo=function(t){return this.remove(),this._map=t,t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this},o.prototype.remove=function(){return this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),i.remove(this._element),this._popup&&this._popup.remove(),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this},o.prototype.getElement=function(){return this._element},o.prototype.setPopup=function(t){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),t){if(!("offset"in t.options)){var e=Math.sqrt(Math.pow(13.5,2)/2);t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[e,-1*(24.6+e)],"bottom-right":[-e,-1*(24.6+e)],left:[13.5,-24.6],right:[-13.5,-24.6]}:this._offset;}this._popup=t,this._lngLat&&this._popup.setLngLat(this._lngLat),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this},o.prototype._onKeyPress=function(t){var e=t.code,i=t.charCode||t.keyCode;"Space"!==e&&"Enter"!==e&&32!==i&&13!==i||this.togglePopup();},o.prototype._onMapClick=function(t){var e=t.originalEvent.target,i=this._element;this._popup&&(e===i||i.contains(e))&&this.togglePopup();},o.prototype.getPopup=function(){return this._popup},o.prototype.togglePopup=function(){var t=this._popup;return t?(t.isOpen()?t.remove():t.addTo(this._map),this):this},o.prototype._update=function(t){if(this._map){this._map.transform.renderWorldCopies&&(this._lngLat=Lr(this._lngLat,this._pos,this._map.transform)),this._pos=this._map.project(this._lngLat)._add(this._offset);var e="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?e="rotateZ("+this._rotation+"deg)":"map"===this._rotationAlignment&&(e="rotateZ("+(this._rotation-this._map.getBearing())+"deg)");var o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o="rotateX("+this._map.getPitch()+"deg)"),t&&"moveend"!==t.type||(this._pos=this._pos.round()),i.setTransform(this._element,Ar[this._anchor]+" translate("+this._pos.x+"px, "+this._pos.y+"px) "+o+" "+e);}},o.prototype.getOffset=function(){return this._offset},o.prototype.setOffset=function(e){return this._offset=t.Point.convert(e),this._update(),this},o.prototype._onMove=function(e){this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.Event("dragstart"))),this.fire(new t.Event("drag"));},o.prototype._onUp=function(){this._element.style.pointerEvents="auto",this._positionDelta=null,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.Event("dragend")),this._state="inactive";},o.prototype._addDragHandler=function(t){this._element.contains(t.originalEvent.target)&&(t.preventDefault(),this._positionDelta=t.point.sub(this._pos).add(this._offset),this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},o.prototype.setDraggable=function(t){return this._draggable=!!t,this._map&&(t?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this},o.prototype.isDraggable=function(){return this._draggable},o.prototype.setRotation=function(t){return this._rotation=t||0,this._update(),this},o.prototype.getRotation=function(){return this._rotation},o.prototype.setRotationAlignment=function(t){return this._rotationAlignment=t||"auto",this._update(),this},o.prototype.getRotationAlignment=function(){return this._rotationAlignment},o.prototype.setPitchAlignment=function(t){return this._pitchAlignment=t&&"auto"!==t?t:this._rotationAlignment,this._update(),this},o.prototype.getPitchAlignment=function(){return this._pitchAlignment},o}(t.Evented),Or={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0},Fr=0,Ur=!1,Nr=function(e){function o(i){e.call(this),this.options=t.extend({},Or,i),t.bindAll(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker"],this);}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.onAdd=function(e){var o;return this._map=e,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),o=this._setupUI,void 0!==kr?o(kr):void 0!==t.window.navigator.permissions?t.window.navigator.permissions.query({name:"geolocation"}).then((function(t){o(kr="denied"!==t.state);})):o(kr=!!t.window.navigator.geolocation),this._container},o.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),i.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,Fr=0,Ur=!1;},o.prototype._isOutOfMapMaxBounds=function(t){var e=this._map.getMaxBounds(),i=t.coords;return e&&(i.longitude<e.getWest()||i.longitude>e.getEast()||i.latitude<e.getSouth()||i.latitude>e.getNorth())},o.prototype._setErrorState=function(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");}},o.prototype._onSuccess=function(e){if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.Event("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();}},o.prototype._updateCamera=function(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.extend({bearing:r},this.options.fitBoundsOptions);this._map.fitBounds(i.toBounds(o),a,{geolocateSource:!0});},o.prototype._updateMarker=function(e){if(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},o.prototype._updateCircleRadius=function(){var t=this._map._container.clientHeight/2,e=this._map.unproject([0,t]),i=this._map.unproject([1,t]),o=e.distanceTo(i),r=Math.ceil(2*this._accuracy/o);this._circleElement.style.width=r+"px",this._circleElement.style.height=r+"px";},o.prototype._onZoom=function(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},o.prototype._onError=function(e){if(this._map){if(this.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;var i=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=i,this._geolocateButton.setAttribute("aria-label",i),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ur)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();}},o.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},o.prototype._setupUI=function(e){var o=this;if(this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this._geolocateButton=i.create("button","mapboxgl-ctrl-geolocate",this._container),i.create("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden",!0),this._geolocateButton.type="button",!1===e){t.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");var r=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=r,this._geolocateButton.setAttribute("aria-label",r);}else {var a=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.title=a,this._geolocateButton.setAttribute("aria-label",a);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=i.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new Br(this._dotElement),this._circleElement=i.create("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Br({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(function(e){e.geolocateSource||"ACTIVE_LOCK"!==o._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(o._watchState="BACKGROUND",o._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),o._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),o.fire(new t.Event("trackuserlocationend")));}));},o.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":Fr--,Ur=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"));}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){var e;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),++Fr>1?(e={maximumAge:6e5,timeout:0},Ur=!0):(e=this.options.positionOptions,Ur=!1),this._geolocationWatchID=t.window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else t.window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0},o.prototype._clearWatch=function(){t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);},o}(t.Evented),Zr={maxWidth:100,unit:"metric"},jr=function(e){this.options=t.extend({},Zr,e),t.bindAll(["_onMove","setUnit"],this);};function qr(t,e,i){var o=i&&i.maxWidth||100,r=t._container.clientHeight/2,a=t.unproject([0,r]),n=t.unproject([o,r]),s=a.distanceTo(n);if(i&&"imperial"===i.unit){var l=3.2808*s;l>5280?Vr(e,o,l/5280,t._getUIString("ScaleControl.Miles")):Vr(e,o,l,t._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?Vr(e,o,s/1852,t._getUIString("ScaleControl.NauticalMiles")):s>=1e3?Vr(e,o,s/1e3,t._getUIString("ScaleControl.Kilometers")):Vr(e,o,s,t._getUIString("ScaleControl.Meters"));}function Vr(t,e,i,o){var r,a,n,s=(r=i,(a=Math.pow(10,(""+Math.floor(r)).length-1))*(n=(n=r/a)>=10?10:n>=5?5:n>=3?3:n>=2?2:n>=1?1:function(t){var e=Math.pow(10,Math.ceil(-Math.log(t)/Math.LN10));return Math.round(t*e)/e}(n)));t.style.width=e*(s/i)+"px",t.innerHTML=s+"&nbsp;"+o;}jr.prototype.getDefaultPosition=function(){return "bottom-left"},jr.prototype._onMove=function(){qr(this._map,this._container,this.options);},jr.prototype.onAdd=function(t){return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},jr.prototype.onRemove=function(){i.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;},jr.prototype.setUnit=function(t){this.options.unit=t,qr(this._map,this._container,this.options);};var Gr=function(e){this._fullscreen=!1,e&&e.container&&(e.container instanceof t.window.HTMLElement?this._container=e.container:t.warnOnce("Full screen control 'container' must be a DOM element.")),t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.window.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.window.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.window.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.window.document&&(this._fullscreenchange="MSFullscreenChange");};Gr.prototype.onAdd=function(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._controlContainer},Gr.prototype.onRemove=function(){i.remove(this._controlContainer),this._map=null,t.window.document.removeEventListener(this._fullscreenchange,this._changeIcon);},Gr.prototype._checkFullscreenSupport=function(){return !!(t.window.document.fullscreenEnabled||t.window.document.mozFullScreenEnabled||t.window.document.msFullscreenEnabled||t.window.document.webkitFullscreenEnabled)},Gr.prototype._setupUI=function(){var e=this._fullscreenButton=i.create("button","mapboxgl-ctrl-fullscreen",this._controlContainer);i.create("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden",!0),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.window.document.addEventListener(this._fullscreenchange,this._changeIcon);},Gr.prototype._updateTitle=function(){var t=this._getTitle();this._fullscreenButton.setAttribute("aria-label",t),this._fullscreenButton.title=t;},Gr.prototype._getTitle=function(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")},Gr.prototype._isFullscreen=function(){return this._fullscreen},Gr.prototype._changeIcon=function(){(t.window.document.fullscreenElement||t.window.document.mozFullScreenElement||t.window.document.webkitFullscreenElement||t.window.document.msFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle());},Gr.prototype._onClickFullscreen=function(){this._isFullscreen()?t.window.document.exitFullscreen?t.window.document.exitFullscreen():t.window.document.mozCancelFullScreen?t.window.document.mozCancelFullScreen():t.window.document.msExitFullscreen?t.window.document.msExitFullscreen():t.window.document.webkitCancelFullScreen&&t.window.document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen();};var Wr={closeButton:!0,closeOnClick:!0,className:"",maxWidth:"240px"},Xr=function(e){function o(i){e.call(this),this.options=t.extend(Object.create(Wr),i),t.bindAll(["_update","_onClose","remove","_onMouseMove","_onMouseUp","_onDrag"],this);}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.addTo=function(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")):this._map.on("move",this._update),this.fire(new t.Event("open")),this},o.prototype.isOpen=function(){return !!this._map},o.prototype.remove=function(){return this._content&&i.remove(this._content),this._container&&(i.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),delete this._map),this.fire(new t.Event("close")),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.remove("mapboxgl-track-pointer")),this},o.prototype.trackPointer=function(){return this._trackPointer=!0,this._pos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")),this},o.prototype.getElement=function(){return this._container},o.prototype.setText=function(e){return this.setDOMContent(t.window.document.createTextNode(e))},o.prototype.setHTML=function(e){var i,o=t.window.document.createDocumentFragment(),r=t.window.document.createElement("body");for(r.innerHTML=e;i=r.firstChild;)o.appendChild(i);return this.setDOMContent(o)},o.prototype.getMaxWidth=function(){return this._container&&this._container.style.maxWidth},o.prototype.setMaxWidth=function(t){return this.options.maxWidth=t,this._update(),this},o.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},o.prototype.addClassName=function(t){this._container&&this._container.classList.add(t);},o.prototype.removeClassName=function(t){this._container&&this._container.classList.remove(t);},o.prototype.toggleClassName=function(t){if(this._container)return this._container.classList.toggle(t)},o.prototype._createContent=function(){this._content&&i.remove(this._content),this._content=i.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=i.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="&#215;",this._closeButton.addEventListener("click",this._onClose));},o.prototype._onMouseUp=function(t){this._update(t.point);},o.prototype._onMouseMove=function(t){this._update(t.point);},o.prototype._onDrag=function(t){this._update(t.point);},o.prototype._update=function(e){var o=this;if(this._map&&(this._lngLat||this._trackPointer)&&this._content&&(this._container||(this._container=i.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=i.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className&&this.options.className.split(" ").forEach((function(t){return o._container.classList.add(t)})),this._trackPointer&&this._container.classList.add("mapboxgl-popup-track-pointer")),this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._map.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=Lr(this._lngLat,this._pos,this._map.transform)),!this._trackPointer||e)){var r=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat),a=this.options.anchor,n=function e(i){if(i){if("number"==typeof i){var o=Math.round(Math.sqrt(.5*Math.pow(i,2)));return {center:new t.Point(0,0),top:new t.Point(0,i),"top-left":new t.Point(o,o),"top-right":new t.Point(-o,o),bottom:new t.Point(0,-i),"bottom-left":new t.Point(o,-o),"bottom-right":new t.Point(-o,-o),left:new t.Point(i,0),right:new t.Point(-i,0)}}if(i instanceof t.Point||Array.isArray(i)){var r=t.Point.convert(i);return {center:r,top:r,"top-left":r,"top-right":r,bottom:r,"bottom-left":r,"bottom-right":r,left:r,right:r}}return {center:t.Point.convert(i.center||[0,0]),top:t.Point.convert(i.top||[0,0]),"top-left":t.Point.convert(i["top-left"]||[0,0]),"top-right":t.Point.convert(i["top-right"]||[0,0]),bottom:t.Point.convert(i.bottom||[0,0]),"bottom-left":t.Point.convert(i["bottom-left"]||[0,0]),"bottom-right":t.Point.convert(i["bottom-right"]||[0,0]),left:t.Point.convert(i.left||[0,0]),right:t.Point.convert(i.right||[0,0])}}return e(new t.Point(0,0))}(this.options.offset);if(!a){var s,l=this._container.offsetWidth,c=this._container.offsetHeight;s=r.y+n.bottom.y<c?["top"]:r.y>this._map.transform.height-c?["bottom"]:[],r.x<l/2?s.push("left"):r.x>this._map.transform.width-l/2&&s.push("right"),a=0===s.length?"bottom":s.join("-");}var u=r.add(n[a]).round();i.setTransform(this._container,Ar[a]+" translate("+u.x+"px,"+u.y+"px)"),Rr(this._container,a,"popup");}},o.prototype._onClose=function(){this.remove();},o}(t.Evented),Hr={version:t.version,supported:e,setRTLTextPlugin:t.setRTLTextPlugin,getRTLTextPluginStatus:t.getRTLTextPluginStatus,Map:Sr,NavigationControl:Dr,GeolocateControl:Nr,AttributionControl:yr,ScaleControl:jr,FullscreenControl:Gr,Popup:Xr,Marker:Br,Style:qe,LngLat:t.LngLat,LngLatBounds:t.LngLatBounds,Point:t.Point,MercatorCoordinate:t.MercatorCoordinate,Evented:t.Evented,config:t.config,prewarm:function(){Ft().acquire(Rt);},clearPrewarmedResources:function(){var t=Bt;t&&(t.isPreloaded()&&1===t.numActive()?(t.release(Rt),Bt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},get accessToken(){return t.config.ACCESS_TOKEN},set accessToken(e){t.config.ACCESS_TOKEN=e;},get baseApiUrl(){return t.config.API_URL},set baseApiUrl(e){t.config.API_URL=e;},get workerCount(){return kt.workerCount},set workerCount(t){kt.workerCount=t;},get maxParallelImageRequests(){return t.config.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(e){t.config.MAX_PARALLEL_IMAGE_REQUESTS=e;},clearStorage:function(e){t.clearTileCache(e);},workerUrl:""};return Hr}));
//
return mapboxgl;
})));
//# sourceMappingURL=mapbox-gl.js.map
/***/ }),
/* 67 */
/***/ (function(module, exports) {
module.exports = function escape(url) {
if (typeof url !== 'string') {
return url
}
// If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
url = url.slice(1, -1);
}
// Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url)) {
return '"' + url.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"'
}
return url
}
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
var exportRecord = function exportRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
var initialize = function initialize() {
$container = (0, _jquery2.default)('body');
$container.on('click', '.record-export-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var key = '';
var kind = $el.data('kind');
var idContent = $el.data('id');
switch (kind) {
case 'basket':
key = 'ssel';
break;
case 'record':
key = 'lst';
break;
default:
}
doExport(key + '=' + idContent);
});
};
var openModal = function openModal(datas) {
return doExport(datas);
};
function doExport(datas) {
var $dialog = _dialog2.default.create(services, {
size: 'Medium',
title: localeService.t('export')
});
_jquery2.default.ajax({
method: 'POST',
url: url + 'prod/export/multi-export/',
data: datas,
success: function success(data) {
$dialog.setContent(data);
if (window.exportConfig.isGuest) {
_dialog2.default.get(1).close();
var guestModal = _dialog2.default.create({
size: '500x100',
closeOnEscape: true,
closeButton: false,
title: window.exportConfig.msg.modalTile
}, 2);
guestModal.setContent(window.exportConfig.msg.modalContent);
} else {
_onExportReady($dialog, window.exportConfig);
}
}
});
return true;
}
var _onExportReady = function _onExportReady($dialog, dataConfig) {
(0, _jquery2.default)('.tabs', $dialog.getDomElement()).tabs();
(0, _jquery2.default)('.close_button', $dialog.getDomElement()).bind('click', function () {
$dialog.close();
});
var tabs = (0, _jquery2.default)('.tabs', $dialog.getDomElement());
if (dataConfig.haveFtp === true) {
(0, _jquery2.default)('#ftp_form_selector').bind('change', function () {
(0, _jquery2.default)('#ftp .ftp_form').hide();
(0, _jquery2.default)('#ftp .ftp_form_' + (0, _jquery2.default)(this).val()).show();
(0, _jquery2.default)('.ftp_folder_check', _dialog2.default.get(1).getDomElement()).unbind('change').bind('change', function () {
if ((0, _jquery2.default)(this).prop('checked')) {
(0, _jquery2.default)(this).next().prop('disabled', false);
} else {
(0, _jquery2.default)(this).next().prop('disabled', true);
}
});
}).trigger('change');
}
(0, _jquery2.default)('a.TOUview').bind('click', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var options = {
size: 'Medium',
closeButton: true,
title: dataConfig.msg.termOfUseTitle
};
var termOfuseDialog = _dialog2.default.create(services, options, 2);
_jquery2.default.get($el.attr('href'), function (content) {
termOfuseDialog.setContent(content);
});
});
(0, _jquery2.default)('.close_button').bind('click', function () {
$dialog.close();
});
(0, _jquery2.default)('#download .download_button').bind('click', function () {
if (!check_subdefs((0, _jquery2.default)('#download'), dataConfig)) {
return false;
}
if (!check_TOU((0, _jquery2.default)('#download'), dataConfig)) {
return false;
}
var total = 0;
var count = 0;
(0, _jquery2.default)('input[name="obj[]"]', (0, _jquery2.default)('#download')).each(function () {
var total_el = (0, _jquery2.default)('#download input[name=download_' + (0, _jquery2.default)(this).val() + ']');
var count_el = (0, _jquery2.default)('#download input[name=count_' + (0, _jquery2.default)(this).val() + ']');
if ((0, _jquery2.default)(this).prop('checked')) {
total += parseInt((0, _jquery2.default)(total_el).val(), 10);
count += parseInt((0, _jquery2.default)(count_el).val(), 10);
}
});
if (count > 1 && total / 1024 / 1024 > dataConfig.maxDownload) {
if (confirm(dataConfig.msg.fileTooLarge + ' \n ' + dataConfig.msg.fileTooLargeAlt)) {
(0, _jquery2.default)('input[name="obj[]"]:checked', (0, _jquery2.default)('#download')).each(function (i, n) {
(0, _jquery2.default)('input[name="obj[]"][value="' + (0, _jquery2.default)(n).val() + '"]', (0, _jquery2.default)('#sendmail')).prop('checked', true);
});
(0, _jquery2.default)(document).find('input[name="taglistdestmail"]').tagsinput('add', dataConfig.user.email);
var tabs = (0, _jquery2.default)('.tabs', $dialog.getDomElement());
tabs.tabs('option', 'active', 1);
}
return false;
}
(0, _jquery2.default)('#download form').submit();
$dialog.close();
});
(0, _jquery2.default)('#order .order_button').bind('click', function () {
var title = '';
if (!check_TOU((0, _jquery2.default)('#order'), dataConfig)) {
return false;
}
(0, _jquery2.default)('#order .order_button_loader').css('visibility', 'visible');
var options = (0, _jquery2.default)('#order form').serialize();
var $this = (0, _jquery2.default)(this);
$this.prop('disabled', true).addClass('disabled');
_jquery2.default.post(url + 'prod/order/', options, function (data) {
$this.prop('disabled', false).removeClass('disabled');
(0, _jquery2.default)('#order .order_button_loader').css('visibility', 'hidden');
if (!data.error) {
title = dataConfig.msg.success;
} else {
title = dataConfig.msg.warning;
}
var options = {
size: 'Alert',
closeButton: true,
title: title
};
_dialog2.default.create(services, options, 2).setContent(data.msg);
if (!data.error) {
humane.info(data.msg);
$dialog.close();
} else {
humane.error(data.msg);
}
return;
}, 'json');
});
(0, _jquery2.default)('#ftp .ftp_button').bind('click', function () {
if (!check_subdefs((0, _jquery2.default)('#ftp'), dataConfig)) {
return false;
}
if (!check_TOU((0, _jquery2.default)('#ftp'), dataConfig)) {
return false;
}
(0, _jquery2.default)('#ftp .ftp_button_loader').show();
(0, _jquery2.default)('#ftp .ftp_form:hidden').remove();
var $this = (0, _jquery2.default)(this);
var options_addr = (0, _jquery2.default)('#ftp_form_stock form:visible').serialize();
var options_join = (0, _jquery2.default)('#ftp_joined').serialize();
$this.prop('disabled', true);
_jquery2.default.post(url + 'prod/export/ftp/', options_addr + '&' + options_join, function (data) {
$this.prop('disabled', false);
(0, _jquery2.default)('#ftp .ftp_button_loader').hide();
if (data.success) {
humane.info(data.message);
$dialog.close();
} else {
var alert = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true,
title: dataConfig.msg.warning
}, 2);
alert.setContent(data.message);
}
return;
}, 'json');
});
(0, _jquery2.default)('#ftp .tryftp_button').bind('click', function () {
(0, _jquery2.default)('#ftp .tryftp_button_loader').css('visibility', 'visible');
var $this = (0, _jquery2.default)(this);
$this.prop('disabled', true);
var options_addr = (0, _jquery2.default)('#ftp_form_stock form:visible').serialize();
_jquery2.default.post(url + 'prod/export/ftp/test/',
// no need to include 'ftp_joined' checkboxes to test ftp
options_addr, function (data) {
(0, _jquery2.default)('#ftp .tryftp_button_loader').css('visibility', 'hidden');
var options = {
size: 'Alert',
closeButton: true,
title: data.success ? dataConfig.msg.success : dataConfig.msg.warning
};
_dialog2.default.create(services, options, 3).setContent(data.message);
$this.prop('disabled', false);
return;
});
});
(0, _jquery2.default)('#sendmail .sendmail_button').bind('click', function () {
if (!validEmail((0, _jquery2.default)('input[name="taglistdestmail"]', (0, _jquery2.default)('#sendmail')).val(), dataConfig)) {
return false;
}
if (!check_subdefs((0, _jquery2.default)('#sendmail'), dataConfig)) {
return false;
}
if (!check_TOU((0, _jquery2.default)('#sendmail'), dataConfig)) {
return false;
}
if ((0, _jquery2.default)('iframe[name=""]').length === 0) {
(0, _jquery2.default)('body').append('<iframe style="display:none;" name="sendmail_target"></iframe>');
}
(0, _jquery2.default)('#sendmail form').submit();
humane.infoLarge((0, _jquery2.default)('#export-send-mail-notif').val());
$dialog.close();
});
(0, _jquery2.default)('.datepicker', $dialog.getDomElement()).datepicker({
changeYear: true,
changeMonth: true,
dateFormat: 'yy-mm-dd'
});
(0, _jquery2.default)('a.undisposable_link', $dialog.getDomElement()).bind('click', function () {
(0, _jquery2.default)(this).parent().parent().find('.undisposable').slideToggle();
return false;
});
(0, _jquery2.default)('input[name="obj[]"]', (0, _jquery2.default)('#download, #sendmail, #ftp')).bind('change', function () {
var $form = (0, _jquery2.default)(this).closest('form');
if ((0, _jquery2.default)('input.caption[name="obj[]"]:checked', $form).length > 0) {
(0, _jquery2.default)('div.businessfields', $form).show();
} else {
(0, _jquery2.default)('div.businessfields', $form).hide();
}
});
};
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validEmail(emailList, dataConfig) {
//split emailList by ; , or whitespace and filter empty element
var emails = emailList.split(/[ ,;]+/).filter(Boolean);
var alert = void 0;
for (var i = 0; i < emails.length; i++) {
if (!validateEmail(emails[i])) {
alert = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true,
title: dataConfig.msg.warning
}, 2);
alert.setContent(dataConfig.msg.invalidEmail);
return false;
}
}
return true;
}
function check_TOU(container, dataConfig) {
var checkbox = (0, _jquery2.default)('input[name="TOU_accept"]', (0, _jquery2.default)(container));
var go = checkbox.length === 0 || checkbox.prop('checked');
var alert = void 0;
if (!go) {
alert = _dialog2.default.create(services, {
size: 'Small',
closeOnEscape: true,
closeButton: true,
title: dataConfig.msg.warning
}, 2);
alert.setContent(dataConfig.msg.termOfUseAgree);
return false;
}
return true;
}
function check_subdefs(container, dataConfig) {
var go = false;
var required = false;
var alert = void 0;
(0, _jquery2.default)('input[name="obj[]"]', (0, _jquery2.default)(container)).each(function () {
if ((0, _jquery2.default)(this).prop('checked')) {
go = true;
}
});
(0, _jquery2.default)('input.required, textarea.required', container).each(function (i, n) {
if (_jquery2.default.trim((0, _jquery2.default)(n).val()) === '') {
required = true;
(0, _jquery2.default)(n).addClass('error');
} else {
(0, _jquery2.default)(n).removeClass('error');
}
});
if (required) {
alert = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true,
title: dataConfig.msg.warning
}, 2);
alert.setContent(dataConfig.msg.requiredFields);
return false;
}
if (!go) {
alert = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true,
title: dataConfig.msg.warning
}, 2);
alert.setContent(dataConfig.msg.missingSubdef);
return false;
}
return true;
}
return { initialize: initialize, openModal: openModal };
};
exports.default = exportRecord;
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _feedback = __webpack_require__(171);
var _feedback2 = _interopRequireDefault(_feedback);
var _listManager = __webpack_require__(172);
var _listManager2 = _interopRequireDefault(_listManager);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pushRecord = function pushRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var feedbackInstance = null;
var listManagerInstance = null;
var initialize = function initialize(options) {
var feedback = options.feedback,
listManager = options.listManager;
if ((0, _jquery2.default)('#PushBox').length > 0) {
feedbackInstance = new _feedback2.default(services, feedback);
listManagerInstance = new _listManager2.default(services, listManager);
} else {
(0, _jquery2.default)('.close-dialog-action').on('click', function () {
return _dialog2.default.close('1');
});
}
};
function reloadBridge(url) {
var options = (0, _jquery2.default)('#dialog_publicator form[name="current_datas"]').serializeArray();
var dialog = dialog.get(1);
dialog.load(url, 'POST', options);
}
function createList(listOptions) {
listManagerInstance.createList(listOptions);
}
function addUser(userOptions) {
feedbackInstance.addUser(userOptions);
}
function setActiveList() {}
function removeList(listObj) {
var makeDialog = function makeDialog(box) {
var buttons = {};
buttons[localeService.t('valider')] = function () {
var callbackOK = function callbackOK() {
(0, _jquery2.default)('.list-container ul.list').children().each(function () {
if ((0, _jquery2.default)(this).data('list-id') == listObj.list_id) {
(0, _jquery2.default)(this).remove();
}
});
_dialog2.default.get(2).close();
};
listManagerInstance.removeList(listObj.list_id, callbackOK);
};
var options = {
title: localeService.t('Delete the list'),
cancelButton: true,
buttons: buttons,
size: 'Alert'
};
var $dialog = _dialog2.default.create(services, options, 2);
if (listObj.container === '#ListManager') {
$dialog.getDomElement().closest('.ui-dialog').addClass('dialog_delete_list_listmanager');
}
$dialog.getDomElement().closest('.ui-dialog').addClass('dialog_container dialog_delete_list').find('.ui-dialog-buttonset button').each(function () {
var self = (0, _jquery2.default)(this).children();
if (self.text() === 'Validate') self.text('Yes');else self.text('No');
});
$dialog.setContent(box);
};
var html = _.template((0, _jquery2.default)('#list_editor_dialog_delete_tpl').html());
makeDialog(html);
}
appEvents.listenAll({
// 'push.doInitialize': initialize,
'push.addUser': addUser,
'push.setActiveList': setActiveList,
'push.createList': createList,
'push.reload': reloadBridge,
'push.removeList': removeList
});
return {
initialize: initialize,
// Feedback: Feedback,
// ListManager: ListManager,
reloadBridge: reloadBridge
};
};
exports.default = pushRecord;
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.List = exports.Lists = undefined;
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
var Lists = function Lists() {};
var List = function List(id) {
if (parseInt(id, 10) <= 0) {
throw 'Invalid list id';
}
this.id = id;
};
Lists.prototype = {
create: function create(name, callback) {
_jquery2.default.ajax({
type: 'POST',
// @TODO - load baseUrl from configService
url: '/prod/lists/list/',
dataType: 'json',
data: { name: name },
success: function success(data) {
if (data.success) {
humane.info(data.message);
if (typeof callback === 'function') {
var list = new List(data.list_id);
callback(list);
}
} else {
humane.error(data.message);
}
}
});
},
get: function get(callback, type, selectedList) {
type = typeof type === 'undefined' ? 'json' : type;
_jquery2.default.ajax({
type: 'GET',
// @TODO - load baseUrl from configService
url: '/prod/lists/all/',
dataType: type,
data: {},
success: function success(data) {
if (type === 'json') {
if (data.success) {
humane.info(data.message);
if (typeof callback === 'function') {
callback(data.result);
}
} else {
humane.error(data.message);
}
} else {
if (typeof callback === 'function') {
callback(data, selectedList);
}
}
}
});
}
};
List.prototype = {
addUsers: function addUsers(arrayUsers, callback) {
if (!arrayUsers instanceof Array) {
throw 'addUsers takes array as argument';
}
var $this = this;
var data = { usr_ids: (0, _jquery2.default)(arrayUsers).toArray() };
_jquery2.default.ajax({
type: 'POST',
// @TODO - load baseUrl from configService
url: '/prod/lists/list/' + $this.id + '/add/',
dataType: 'json',
data: data,
success: function success(data) {
if (data.success) {
humane.info(data.message);
if (typeof callback === 'function') {
callback($this, data);
}
} else {
humane.error(data.message);
}
}
});
},
addUser: function addUser(usr_id, callback) {
this.addUsers([usr_id], callback);
},
remove: function remove(callback) {
var $this = this;
_jquery2.default.ajax({
type: 'POST',
// @TODO - load baseUrl from configService
url: '/prod/lists/list/' + this.id + '/delete/',
dataType: 'json',
data: {},
success: function success(data) {
if (data.success) {
humane.info(data.message);
if (typeof callback === 'function') {
callback($this);
}
} else {
humane.error(data.message);
}
}
});
},
update: function update(name, callback) {
var $this = this;
_jquery2.default.ajax({
type: 'POST',
// @TODO - load baseUrl from configService
url: '/prod/lists/list/' + this.id + '/update/',
dataType: 'json',
data: { name: name },
success: function success(data) {
if (data.success) {
humane.info(data.message);
if (typeof callback === 'function') {
callback($this);
}
} else {
humane.error(data.message);
}
}
});
},
removeUser: function removeUser(usr_id, callback) {
var $this = this;
_jquery2.default.ajax({
type: 'POST',
// @TODO - load baseUrl from configService
url: '/prod/lists/list/' + this.id + '/remove/' + usr_id + '/',
dataType: 'json',
data: {},
success: function success(data) {
if (data.success) {
humane.info(data.message);
if (typeof callback === 'function') {
callback($this, data);
}
} else {
humane.error(data.message);
}
}
});
},
get: function get(callback) {
var $this = this;
_jquery2.default.ajax({
type: 'GET',
// @TODO - load baseUrl from configService
url: '/prod/lists/list/' + this.id + '/',
dataType: 'json',
data: {},
success: function success(data) {
if (data.success) {
humane.info(data.message);
if (typeof callback === 'function') {
callback($this, data);
}
} else {
humane.error(data.message);
}
}
});
}
};
exports.Lists = Lists;
exports.List = List;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* triggered via workzone > Basket > context menu
*/
__webpack_require__(38);
var pushAddUser = function pushAddUser(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var searchSelectionSerialized = '';
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelectionSerialized = selection.serialized;
}
});
var initialize = function initialize(options) {
var $container = options.$container;
$container.on('click', '.push-add-user', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.html;
}
if ($el.hasClass('validation')) {
dialogOptions.isValidation = true;
}
if ($el.hasClass('listmanager-add-user')) {
dialogOptions.isListManager = true;
}
openModal(dialogOptions);
});
};
var openModal = function openModal() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var url = configService.get('baseUrl');
var dialogOptions = (0, _lodash2.default)({
size: '558x305',
loading: false,
title: localeService.t('create new user')
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions, 2);
$dialog.getDomElement().closest('.ui-dialog').addClass('dialog_container');
if (dialogOptions.isValidation) {
$dialog.getDomElement().closest('.ui-dialog').addClass('validation');
}
if (dialogOptions.isListManager) {
$dialog.getDomElement().closest('.ui-dialog').addClass('push-add-user-listmanager');
}
return _jquery2.default.get(url + 'prod/push/add-user/', function (data) {
$dialog.setContent(data);
_onDialogReady(window.addUserConfig);
return;
});
};
var _onDialogReady = function _onDialogReady(config) {
var $addUserForm = (0, _jquery2.default)('#quickAddUser');
var $addUserFormMessages = $addUserForm.find('.messages');
var closeModal = function closeModal() {
var $dialog = $addUserForm.closest('.ui-dialog-content');
if ($dialog.data('ui-dialog')) {
$dialog.dialog('destroy').remove();
}
};
var submitAddUser = function submitAddUser() {
$addUserFormMessages.empty();
var method = $addUserForm.attr('method');
method = _jquery2.default.inArray(method.toLowerCase(), ['post', 'get']) ? method : 'POST';
_jquery2.default.ajax({
type: method,
url: $addUserForm.attr('action'),
data: $addUserForm.serializeArray(),
beforeSend: function beforeSend() {
$addUserForm.addClass('loading');
},
success: function success(datas) {
if (datas.success === true) {
appEvents.emit('push.addUser', {
$userForm: $addUserForm,
callback: closeModal()
});
//p4.Feedback.addUser($addUserForm, closeModal);
} else {
if (datas.message !== undefined) {
$addUserFormMessages.empty().append('<div class="alert alert-error">' + datas.message + '</div>');
}
}
$addUserForm.removeClass('loading');
},
error: function error() {
$addUserForm.removeClass('loading');
},
timeout: function timeout() {
$addUserForm.removeClass('loading');
}
});
};
if (config.geonameServerUrl.length > 0) {
$addUserForm.find('.geoname_field').geocompleter({
server: config.geonameServerUrl,
limit: 40
});
}
$addUserForm.on('submit', function (event) {
event.preventDefault();
submitAddUser();
});
$addUserForm.on('click', '.valid', function (event) {
event.preventDefault();
submitAddUser();
});
$addUserForm.on('click', '.cancel', function (event) {
event.preventDefault();
closeModal();
return false;
});
};
return { initialize: initialize };
};
exports.default = pushAddUser;
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var printRecord = function printRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
appEvents.listenAll({
'record.doPrint': doPrint
});
var initialize = function initialize() {
$container = (0, _jquery2.default)('body');
$container.on('click', '.record-print-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var key = '';
var kind = $el.data('kind');
var idContent = $el.data('id');
switch (kind) {
case 'basket':
key = 'ssel';
break;
case 'record':
key = 'lst';
break;
default:
}
doPrint(key + '=' + idContent);
});
};
var openModal = function openModal(datas) {
return doPrint(_jquery2.default.param(datas));
};
function doPrint(value) {
if ((0, _jquery2.default)('#DIALOG').data('ui-dialog')) {
(0, _jquery2.default)('#DIALOG').dialog('destroy');
}
(0, _jquery2.default)('#DIALOG').attr('title', localeService.t('print')).empty().addClass('loading').dialog({
resizable: false,
closeOnEscape: true,
modal: true,
width: '800',
height: '500',
open: function open(event, ui) {
(0, _jquery2.default)(this).dialog('widget').css('z-index', '1999');
},
close: function close(event, ui) {
(0, _jquery2.default)(this).dialog('widget').css('z-index', 'auto');
}
}).dialog('open');
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/printer/?' + value,
dataType: 'html',
beforeSend: function beforeSend() {},
success: function success(data) {
(0, _jquery2.default)('#DIALOG').removeClass('loading').empty().append(data);
return;
}
});
}
return { initialize: initialize, openModal: openModal };
};
exports.default = printRecord;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _videoScreenCapture = __webpack_require__(181);
var _videoScreenCapture2 = _interopRequireDefault(_videoScreenCapture);
var _videoRangeCapture = __webpack_require__(184);
var _videoRangeCapture2 = _interopRequireDefault(_videoRangeCapture);
var _videoSubtitleCapture = __webpack_require__(185);
var _videoSubtitleCapture2 = _interopRequireDefault(_videoSubtitleCapture);
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(186);
var humane = __webpack_require__(8);
var recordVideoEditorModal = function recordVideoEditorModal(services, datas) {
var activeTab = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $dialog = null;
var toolsStream = new Rx.Subject();
var initialize = function initialize() {
(0, _jquery2.default)(document).on('click', '.video-tools-record-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var idLst = $el.data("idlst");
var datas = {};
var key = "lst";
datas[key] = idLst;
openModal(datas, activeTab);
});
};
initialize();
toolsStream.subscribe(function (params) {
switch (params.action) {
case 'refresh':
openModal.apply(null, params.options);
break;
default:
}
});
var openModal = function openModal(datas, activeTab) {
$dialog = _dialog2.default.create(services, {
size: 'Custom',
customWidth: 1100,
customHeight: 700,
title: localeService.t('videoEditor'),
loading: true
});
return _jquery2.default.get(url + 'prod/tools/videoEditor', datas, function (data) {
$dialog.setContent(data);
$dialog.setOption('contextArgs', datas);
$dialog.getDomElement().closest('.ui-dialog').addClass('videoEditor_dialog');
_onModalReady(data, window.toolsConfig, activeTab);
return;
});
};
var _onModalReady = function _onModalReady(template, data, activeTab) {
var $scope = (0, _jquery2.default)('#prod-tool-box');
var tabs = (0, _jquery2.default)('#tool-tabs', $scope).tabs();
if (activeTab !== false) {
tabs.tabs('option', 'active', activeTab);
}
// available if only 1 record is selected:
if (data.isVideo === "true") {
(0, _videoScreenCapture2.default)(services).initialize({ $container: $scope, data: data });
(0, _videoRangeCapture2.default)(services).initialize({ $container: (0, _jquery2.default)('.video-range-editor-container'), data: data, services: services });
(0, _videoSubtitleCapture2.default)(services).initialize({ $container: (0, _jquery2.default)('.video-subtitle-editor-container'), data: data, services: services });
} else {
var confirmationDialog = _dialog2.default.create(services, {
size: 'Alert',
title: localeService.t('warning'),
closeOnEscape: true
}, 3);
var content = (0, _jquery2.default)('<div />').css({
'text-align': 'center',
width: '100%',
'font-size': '14px'
}).append(localeService.t('error video editor'));
confirmationDialog.setContent(content);
$dialog.close();
}
};
return { openModal: openModal };
};
exports.default = recordVideoEditorModal;
/***/ }),
/* 74 */,
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _orderItem = __webpack_require__(195);
var _orderItem2 = _interopRequireDefault(_orderItem);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var order = function order(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var $container = options.$container;
$container.on('click', '.order-open-action', function (event) {
event.preventDefault();
orderModal(event);
});
$container.on('click', '.order-notif', function (event) {
event.preventDefault();
(0, _jquery2.default)('#notification_box').hide();
orderModal(event, this);
});
};
var orderModal = function orderModal(event, id) {
var $dialog = _dialog2.default.create(services, {
size: 'Full',
title: (0, _jquery2.default)(event).attr('title')
});
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/order/',
success: function success(data) {
$dialog.setContent(data);
_onOrderReady($dialog);
if ((0, _jquery2.default)(id).length) {
(0, _jquery2.default)('#order_manager').css('opacity', 0).hide(function () {
console.log((0, _jquery2.default)(id).data("id"));
(0, _jquery2.default)('#order_' + (0, _jquery2.default)(id).data("id")).trigger('click');
});
}
}
});
return true;
};
var _onOrderReady = function _onOrderReady($dialog) {
var filterDateSelected = false;
var perPage = window.orderData.perPage;
var date = window.orderData.date;
var dateSelection = window.orderData.dateSelection;
var dateSelectionText = window.orderData.dateSelectionText;
var info = window.orderData.info;
var tabSelection = window.orderData.tabSelection;
var FilterTodo = {
TODO: 'pending',
PROCESSED: 'processed'
};
var FilterDate = {
NO_FILTER: 'no_filter',
CURRENT_WEEK: 'current_week',
PAST_WEEK: 'past_week',
PAST_MONTH: 'past_month',
BEFORE: 'before',
AFTER: 'after'
};
/******** functions *********/
var setDateInPicker = function setDateInPicker(date) {
if (date !== '') {
(0, _jquery2.default)('#datepicker').val(date);
}
};
var setDateSelection = function setDateSelection(element) {
var selection = (0, _jquery2.default)(element).attr('name');
dateSelection = FilterDate[selection];
setSelectionText(dateSelection);
clearAll();
(0, _jquery2.default)(element).addClass('active');
};
var setSelectionText = function setSelectionText(dateSelection) {
if (dateSelection === undefined) {
return;
}
(0, _jquery2.default)('.reset-btn').hide();
if (dateSelection !== FilterDate.NO_FILTER) {
if (dateSelection === FilterDate.BEFORE || dateSelection === FilterDate.AFTER) {
dateSelectionText = (0, _jquery2.default)('#filter_box tbody tr td button[name=' + dateSelection.toUpperCase() + ']').html() + ' ' + (0, _jquery2.default)('#datepicker').val();
var obj = {};
obj.date = (0, _jquery2.default)('#datepicker').val();
obj.type = dateSelection;
info.limit = obj;
} else {
dateSelectionText = (0, _jquery2.default)('#filter_box tbody tr td button[name=' + dateSelection.toUpperCase() + ']').html();
info.limit = null;
}
(0, _jquery2.default)('#filter-text').text(dateSelectionText);
(0, _jquery2.default)('.reset-btn').show();
} else {
(0, _jquery2.default)('#filter-text').text(window.orderData.noFilterText);
info.limit = null;
}
info.todo = tabSelection;
info.start = dateSelection;
};
var clearAll = function clearAll() {
(0, _jquery2.default)('#filter_box tbody tr td').children('button').each(function () {
(0, _jquery2.default)(this).removeClass('active');
});
};
var performRequest = function performRequest() {
_jquery2.default.ajax({
type: 'GET',
url: '../prod/order/',
data: info,
success: function success(data) {
$dialog.setContent(data);
_onOrderReady($dialog);
}
});
};
var toggleFilterDate = function toggleFilterDate() {
if (!filterDateSelected) {
filterDateSelected = true;
(0, _jquery2.default)('#filter-date').addClass('active');
(0, _jquery2.default)('#filter_box').css('display', 'block');
} else {
filterDateSelected = false;
(0, _jquery2.default)('#filter-date').removeClass('active');
(0, _jquery2.default)('#filter_box').css('display', 'none');
}
};
(0, _jquery2.default)('#datepicker').datepicker({
beforeShow: function beforeShow() {
setTimeout(function () {
(0, _jquery2.default)('.ui-datepicker').css('z-index', 999999);
}, 0);
},
changeYear: true,
changeMonth: true,
dateFormat: 'yy/mm/dd',
onSelect: function onSelect(value) {
date = value;
setSelectionText(dateSelection);
}
});
(0, _jquery2.default)('.reset-btn', $dialog.getDomElement()).bind('click', function (e) {
info.start = FilterDate.NO_FILTER;
setSelectionText(FilterDate.NO_FILTER);
(0, _jquery2.default)('#date-form').trigger('submit');
});
(0, _jquery2.default)('#ORDERPREVIEW').tabs({
activate: function activate(event, ui) {
if (ui.newPanel.selector === '#PROCESSED-ORDER') {
(0, _jquery2.default)('.pager-processed').show();
(0, _jquery2.default)('.pager-todo').hide();
tabSelection = FilterTodo.PROCESSED;
} else {
(0, _jquery2.default)('.pager-processed').hide();
(0, _jquery2.default)('.pager-todo').show();
tabSelection = FilterTodo.TODO;
}
}
});
(0, _jquery2.default)('#ORDERPREVIEW').tabs('option', 'active', tabSelection === FilterTodo.PROCESSED ? 1 : 0);
(0, _jquery2.default)('.pager-processed').hide();
(0, _jquery2.default)('a.self-ajax', $dialog.getDomElement()).bind('click', function (e) {
e.preventDefault();
var url = (0, _jquery2.default)(this).attr('href');
_dialog2.default.load(url);
});
(0, _jquery2.default)('#date-form .toggle-button-text', $dialog.getDomElement()).bind('click', function (e) {
setDateSelection(this);
//trigger request immediately for this week, past week, past month
if ((0, _jquery2.default)(this).attr('name') !== 'BEFORE' && (0, _jquery2.default)(this).attr('name') !== 'AFTER') {
(0, _jquery2.default)('#date-form').trigger('submit');
}
});
(0, _jquery2.default)('.pager li', $dialog.getDomElement()).bind('click', function (e) {
info.todo = tabSelection;
info.start = dateSelection;
info['per-page'] = perPage;
info.page = (0, _jquery2.default)(this).find('a').attr('data-page');
performRequest();
});
(0, _jquery2.default)('tr.order_row', $dialog.getDomElement()).bind('click', function (event) {
event.preventDefault();
var orderId = (0, _jquery2.default)(this).attr('id').split('_').pop();
(0, _orderItem2.default)(services).openModal(orderId);
}).addClass('clickable');
(0, _jquery2.default)('#filter-date a').click(function () {
toggleFilterDate();
});
(0, _jquery2.default)('#date-form').submit(function (e) {
e.preventDefault();
performRequest();
toggleFilterDate();
});
setDateInPicker(date);
setSelectionText(dateSelection);
if (dateSelection !== FilterDate.NO_FILTER) {
var element = (0, _jquery2.default)('#filter_box tbody tr td button[name=\'' + dateSelection.toUpperCase() + ']');
setDateSelection(element);
}
};
return {
initialize: initialize,
orderModal: orderModal
};
};
exports.default = order;
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var resultInfos = function resultInfos(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var searchSelectionSerialized = '0';
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
updateSelectionCounter(selection.asArray.length);
}
});
var initialize = function initialize(options) {
var $container = options.$container;
updateSelectionCounter(0);
$container.on('click', '.search-display-info', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.html;
}
var dialogContent = $el.data('infos');
openModal(dialogOptions, dialogContent);
});
};
var render = function render(template, selectionCount) {
(0, _jquery2.default)('#tool_results').empty().append(template);
updateSelectionCounter(selectionCount);
};
function number_format(number, decimals, dec_point, thousands_sep) {
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep,
dec = typeof dec_point === 'undefined' ? '.' : dec_point,
s = '',
toFixedFix = function toFixedFix(n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
var updateSelectionCounter = function updateSelectionCounter(selectionLength) {
(0, _jquery2.default)('#nbrecsel').empty().append(number_format(selectionLength, null, null, " "));
};
var openModal = function openModal() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var content = arguments[1];
var url = configService.get('baseUrl');
var dialogOptions = (0, _lodash2.default)({
size: '600x600',
loading: false
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions, 1);
$dialog.setContent(content);
};
return { initialize: initialize, render: render };
}; /**
* triggered via workzone > Basket > context menu
*/
exports.default = resultInfos;
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function contains(item, list) {
if (!list || !list.length) return false;
for (var i = 0; i < list.length; i++) {
if (list[i] === item) return true;
}
return false;
}
module.exports = {
idUrl: function(_, t) {
if (_.indexOf('/') === -1) t.loadID(_);
else t.loadURL(_);
},
log: function(_) {
if (typeof console === 'object' &&
typeof console.error === 'function') {
console.error(_);
}
},
strict: function(_, type) {
if (typeof _ !== type) {
throw new Error('Invalid argument: ' + type + ' expected');
}
},
strict_instance: function(_, klass, name) {
if (!(_ instanceof klass)) {
throw new Error('Invalid argument: ' + name + ' expected');
}
},
strict_oneof: function(_, values) {
if (!contains(_, values)) {
throw new Error('Invalid argument: ' + _ + ' given, valid values are ' +
values.join(', '));
}
},
strip_tags: function(_) {
return _.replace(/<[^<]+>/g, '');
},
lbounds: function(_) {
// leaflet-compatible bounds, since leaflet does not do geojson
return new L.LatLngBounds([[_[1], _[0]], [_[3], _[2]]]);
}
};
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var html_sanitize = __webpack_require__(164);
module.exports = function(_) {
if (!_) return '';
return html_sanitize(_, cleanUrl, cleanId);
};
// https://bugzilla.mozilla.org/show_bug.cgi?id=255107
function cleanUrl(url) {
'use strict';
if (/^https?/.test(url.getScheme())) return url.toString();
if (/^mailto?/.test(url.getScheme())) return url.toString();
if ('data' == url.getScheme() && /^image/.test(url.getPath())) {
return url.toString();
}
}
function cleanId(id) { return id; }
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var config = __webpack_require__(81),
version = __webpack_require__(82).version;
module.exports = function(path, accessToken) {
accessToken = accessToken || L.mapbox.accessToken;
if (!accessToken && config.REQUIRE_ACCESS_TOKEN) {
throw new Error('An API access token is required to use Mapbox.js. ' +
'See https://www.mapbox.com/mapbox.js/api/v' + version + '/api-access-tokens/');
}
var url = (document.location.protocol === 'https:' || config.FORCE_HTTPS) ? config.HTTPS_URL : config.HTTP_URL;
url = url.replace(/\/v4$/, '');
url += path;
if (config.REQUIRE_ACCESS_TOKEN) {
if (accessToken[0] === 's') {
throw new Error('Use a public access token (pk.*) with Mapbox.js, not a secret access token (sk.*). ' +
'See https://www.mapbox.com/mapbox.js/api/v' + version + '/api-access-tokens/');
}
url += url.indexOf('?') !== -1 ? '&access_token=' : '?access_token=';
url += accessToken;
}
return url;
};
module.exports.tileJSON = function(urlOrMapID, accessToken) {
if (urlOrMapID.indexOf('mapbox://styles') === 0) {
throw new Error('Styles created with Mapbox Studio need to be used with ' +
'L.mapbox.styleLayer, not L.mapbox.tileLayer');
}
if (urlOrMapID.indexOf('/') !== -1)
return urlOrMapID;
var url = module.exports('/v4/' + urlOrMapID + '.json', accessToken);
// TileJSON requests need a secure flag appended to their URLs so
// that the server knows to send SSL-ified resource references.
if (url.indexOf('https') === 0)
url += '&secure';
return url;
};
module.exports.style = function(styleURL, accessToken) {
if (styleURL.indexOf('mapbox://styles/') === -1) throw new Error('Incorrectly formatted Mapbox style at ' + styleURL);
var ownerIDStyle = styleURL.split('mapbox://styles/')[1];
var url = module.exports('/styles/v1/' + ownerIDStyle, accessToken)
.replace('http://', 'https://');
return url;
};
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var format_url = __webpack_require__(79),
util = __webpack_require__(77),
sanitize = __webpack_require__(78);
// mapbox-related markers functionality
// provide an icon from mapbox's simple-style spec and hosted markers
// service
function icon(fp, options) {
fp = fp || {};
var sizes = {
small: [20, 50],
medium: [30, 70],
large: [35, 90]
},
size = fp['marker-size'] || 'medium',
symbol = ('marker-symbol' in fp && fp['marker-symbol'] !== '') ? '-' + fp['marker-symbol'] : '',
color = (fp['marker-color'] || '7e7e7e').replace('#', '');
return L.icon({
iconUrl: format_url('/v4/marker/' +
'pin-' + size.charAt(0) + symbol + '+' + color +
// detect and use retina markers, which are x2 resolution
(L.Browser.retina ? '@2x' : '') + '.png', options && options.accessToken),
iconSize: sizes[size],
iconAnchor: [sizes[size][0] / 2, sizes[size][1] / 2],
popupAnchor: [0, -sizes[size][1] / 2]
});
}
// a factory that provides markers for Leaflet from Mapbox's
// [simple-style specification](https://github.com/mapbox/simplestyle-spec)
// and [Markers API](http://mapbox.com/developers/api/#markers).
function style(f, latlon, options) {
return L.marker(latlon, {
icon: icon(f.properties, options),
title: util.strip_tags(
sanitize((f.properties && f.properties.title) || ''))
});
}
// Sanitize and format properties of a GeoJSON Feature object in order
// to form the HTML string used as the argument for `L.createPopup`
function createPopup(f, sanitizer) {
if (!f || !f.properties) return '';
var popup = '';
if (f.properties.title) {
popup += '<div class="marker-title">' + f.properties.title + '</div>';
}
if (f.properties.description) {
popup += '<div class="marker-description">' + f.properties.description + '</div>';
}
return (sanitizer || sanitize)(popup);
}
module.exports = {
icon: icon,
style: style,
createPopup: createPopup
};
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = {
HTTP_URL: 'http://a.tiles.mapbox.com/v4',
HTTPS_URL: 'https://a.tiles.mapbox.com/v4',
FORCE_HTTPS: false,
REQUIRE_ACCESS_TOKEN: true
};
/***/ }),
/* 82 */
/***/ (function(module, exports) {
module.exports = {"_args":[["mapbox.js@2.4.0","/home/esokia-6/work/work41/Phraseanet/Phraseanet-production-client"]],"_from":"mapbox.js@2.4.0","_id":"mapbox.js@2.4.0","_inBundle":false,"_integrity":"sha1-xDsISl3XEzTIPuHfKPpnRD1zwpw=","_location":"/mapbox.js","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"mapbox.js@2.4.0","name":"mapbox.js","escapedName":"mapbox.js","rawSpec":"2.4.0","saveSpec":null,"fetchSpec":"2.4.0"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/mapbox.js/-/mapbox.js-2.4.0.tgz","_spec":"2.4.0","_where":"/home/esokia-6/work/work41/Phraseanet/Phraseanet-production-client","author":{"name":"Mapbox"},"bugs":{"url":"https://github.com/mapbox/mapbox.js/issues"},"dependencies":{"corslite":"0.0.6","isarray":"0.0.1","leaflet":"0.7.7","mustache":"2.2.1","sanitize-caja":"0.1.3"},"description":"mapbox javascript api","devDependencies":{"browserify":"^13.0.0","clean-css":"~2.0.7","eslint":"^0.23.0","expect.js":"0.3.1","happen":"0.1.3","leaflet-fullscreen":"0.0.4","leaflet-hash":"0.2.1","marked":"~0.3.0","minifyify":"^6.1.0","minimist":"0.0.5","mocha":"2.4.5","mocha-phantomjs":"4.0.2","sinon":"1.10.2"},"engines":{"node":"*"},"homepage":"http://mapbox.com/","license":"BSD-3-Clause","main":"src/index.js","name":"mapbox.js","optionalDependencies":{},"repository":{"type":"git","url":"git://github.com/mapbox/mapbox.js.git"},"scripts":{"test":"eslint --no-eslintrc -c .eslintrc src && mocha-phantomjs test/index.html"},"version":"2.4.0"}
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = __webpack_require__(119);
var doccy;
if (typeof document !== 'undefined') {
doccy = document;
} else {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
}
module.exports = doccy;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6)))
/***/ }),
/* 84 */
/***/ (function(module, exports) {
function clean (s) {
return s.replace(/\n\r?\s*/g, '')
}
module.exports = function tsml (sa) {
var s = ''
, i = 0
for (; i < arguments.length; i++)
s += clean(sa[i]) + (arguments[i + 1] || '')
return s
}
/***/ }),
/* 85 */
/***/ (function(module, exports) {
module.exports = SafeParseTuple
function SafeParseTuple(obj, reviver) {
var json
var error = null
try {
json = JSON.parse(obj, reviver)
} catch (err) {
error = err
}
return [error, json]
}
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var window = __webpack_require__(43)
var isFunction = __webpack_require__(120)
var parseHeaders = __webpack_require__(121)
var xtend = __webpack_require__(137)
module.exports = createXHR
createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
options = initParams(uri, options, callback)
options.method = method.toUpperCase()
return _createXHR(options)
}
})
function forEachArray(array, iterator) {
for (var i = 0; i < array.length; i++) {
iterator(array[i])
}
}
function isEmpty(obj){
for(var i in obj){
if(obj.hasOwnProperty(i)) return false
}
return true
}
function initParams(uri, options, callback) {
var params = uri
if (isFunction(options)) {
callback = options
if (typeof uri === "string") {
params = {uri:uri}
}
} else {
params = xtend(options, {uri: uri})
}
params.callback = callback
return params
}
function createXHR(uri, options, callback) {
options = initParams(uri, options, callback)
return _createXHR(options)
}
function _createXHR(options) {
if(typeof options.callback === "undefined"){
throw new Error("callback argument missing")
}
var called = false
var callback = function cbOnce(err, response, body){
if(!called){
called = true
options.callback(err, response, body)
}
}
function readystatechange() {
if (xhr.readyState === 4) {
setTimeout(loadFunc, 0)
}
}
function getBody() {
// Chrome with requestType=blob throws errors arround when even testing access to responseText
var body = undefined
if (xhr.response) {
body = xhr.response
} else {
body = xhr.responseText || getXml(xhr)
}
if (isJson) {
try {
body = JSON.parse(body)
} catch (e) {}
}
return body
}
function errorFunc(evt) {
clearTimeout(timeoutTimer)
if(!(evt instanceof Error)){
evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
}
evt.statusCode = 0
return callback(evt, failureResponse)
}
// will load the data & process the response in a special response object
function loadFunc() {
if (aborted) return
var status
clearTimeout(timeoutTimer)
if(options.useXDR && xhr.status===undefined) {
//IE8 CORS GET successful response doesn't have a status field, but body is fine
status = 200
} else {
status = (xhr.status === 1223 ? 204 : xhr.status)
}
var response = failureResponse
var err = null
if (status !== 0){
response = {
body: getBody(),
statusCode: status,
method: method,
headers: {},
url: uri,
rawRequest: xhr
}
if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
response.headers = parseHeaders(xhr.getAllResponseHeaders())
}
} else {
err = new Error("Internal XMLHttpRequest Error")
}
return callback(err, response, response.body)
}
var xhr = options.xhr || null
if (!xhr) {
if (options.cors || options.useXDR) {
xhr = new createXHR.XDomainRequest()
}else{
xhr = new createXHR.XMLHttpRequest()
}
}
var key
var aborted
var uri = xhr.url = options.uri || options.url
var method = xhr.method = options.method || "GET"
var body = options.body || options.data
var headers = xhr.headers = options.headers || {}
var sync = !!options.sync
var isJson = false
var timeoutTimer
var failureResponse = {
body: undefined,
headers: {},
statusCode: 0,
method: method,
url: uri,
rawRequest: xhr
}
if ("json" in options && options.json !== false) {
isJson = true
headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
if (method !== "GET" && method !== "HEAD") {
headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
body = JSON.stringify(options.json === true ? body : options.json)
}
}
xhr.onreadystatechange = readystatechange
xhr.onload = loadFunc
xhr.onerror = errorFunc
// IE9 must have onprogress be set to a unique function.
xhr.onprogress = function () {
// IE must die
}
xhr.onabort = function(){
aborted = true;
}
xhr.ontimeout = errorFunc
xhr.open(method, uri, !sync, options.username, options.password)
//has to be after open
if(!sync) {
xhr.withCredentials = !!options.withCredentials
}
// Cannot set timeout with sync request
// not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
// both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
if (!sync && options.timeout > 0 ) {
timeoutTimer = setTimeout(function(){
if (aborted) return
aborted = true//IE9 may still call readystatechange
xhr.abort("timeout")
var e = new Error("XMLHttpRequest timeout")
e.code = "ETIMEDOUT"
errorFunc(e)
}, options.timeout )
}
if (xhr.setRequestHeader) {
for(key in headers){
if(headers.hasOwnProperty(key)){
xhr.setRequestHeader(key, headers[key])
}
}
} else if (options.headers && !isEmpty(options.headers)) {
throw new Error("Headers cannot be set on an XDomainRequest object")
}
if ("responseType" in options) {
xhr.responseType = options.responseType
}
if ("beforeSend" in options &&
typeof options.beforeSend === "function"
) {
options.beforeSend(xhr)
}
// Microsoft Edge browser sends "undefined" when send is called with undefined value.
// XMLHttpRequest spec says to pass null as body to indicate no body
// See https://github.com/naugtur/xhr/issues/100.
xhr.send(body || null)
return xhr
}
function getXml(xhr) {
if (xhr.responseType === "document") {
return xhr.responseXML
}
var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
if (xhr.responseType === "" && !firefoxBugTakenEffect) {
return xhr.responseXML
}
return null
}
function noop() {}
/***/ }),
/* 87 */,
/* 88 */,
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _utils = __webpack_require__(39);
var utils = _interopRequireWildcard(_utils);
var _bootstrap = __webpack_require__(92);
var _bootstrap2 = _interopRequireDefault(_bootstrap);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(209);
__webpack_require__(210);
__webpack_require__(211);
__webpack_require__(212);
__webpack_require__(213);
__webpack_require__(214);
__webpack_require__(215);
_jquery2.default.widget.bridge('uitooltip', _jquery2.default.fn.tooltip);
//window.btn = $.fn.button.noConflict(); // reverts $.fn.button to jqueryui btn
//$.fn.btn = window.btn; // assigns bootstrap button functionality to $.fn.btn
var ProductionApplication = {
bootstrap: _bootstrap2.default, utils: utils
};
if (typeof window !== 'undefined') {
window.ProductionApplication = ProductionApplication;
}
module.exports = ProductionApplication;
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// @TODO enable lints
/* eslint-disable max-len*/
/* eslint-disable object-shorthand*/
/* eslint-disable dot-notation*/
/* eslint-disable vars-on-top*/
/* eslint-disable prefer-template*/
/* eslint-disable prefer-const*/
/* eslint-disable spaced-comment*/
/* eslint-disable curly*/
/* eslint-disable object-curly-spacing*/
/* eslint-disable spaced-comment*/
/* eslint-disable prefer-arrow-callback*/
/* eslint-disable one-var*/
/* eslint-disable space-in-parens*/
/* eslint-disable camelcase*/
/* eslint-disable no-undef*/
/* eslint-disable quote-props*/
/* eslint-disable no-shadow*/
/* eslint-disable no-param-reassign*/
/* eslint-disable no-unused-expressions*/
/* eslint-disable no-shadow*/
/* eslint-disable no-implied-eval*/
/* eslint-disable brace-style*/
/* eslint-disable no-unused-vars*/
/* eslint-disable brace-style*/
/* eslint-disable no-lonely-if*/
/* eslint-disable no-inline-comments*/
/* eslint-disable default-case*/
/* eslint-disable one-var*/
/* eslint-disable semi*/
/* eslint-disable no-throw-literal*/
/* eslint-disable no-sequences*/
/* eslint-disable consistent-this*/
/* eslint-disable no-dupe-keys*/
/* eslint-disable semi*/
/* eslint-disable no-loop-func*/
var cookie = __webpack_require__(91);
var initialize = function initialize() {
// $(document).ready(function () {
var locale = cookie.get('i18next');
if (locale === undefined) {
locale = 'en-GB';
}
var cache = (0, _jquery2.default)('#mainMenu .helpcontextmenu');
(0, _jquery2.default)('.context-menu-item', cache).hover(function () {
(0, _jquery2.default)(this).addClass('context-menu-item-hover');
}, function () {
(0, _jquery2.default)(this).removeClass('context-menu-item-hover');
});
};
// @deprecated
function manageSession(data, showMessages) {
if (typeof showMessages === 'undefined') showMessages = false;
if (data.status === 'disconnected' || data.status === 'session') {
disconnected();
return false;
}
if (showMessages) {
var box = (0, _jquery2.default)('#notification_box');
box.empty().append(data.notifications);
if (box.is(':visible')) fix_notification_height();
if ((0, _jquery2.default)('.notification.unread', box).length > 0) {
var trigger = (0, _jquery2.default)('#notification_trigger');
(0, _jquery2.default)('.counter', trigger).empty().append((0, _jquery2.default)('.notification.unread', box).length);
(0, _jquery2.default)('.counter', trigger).css('visibility', 'visible');
} else (0, _jquery2.default)('#notification_trigger .counter').css('visibility', 'hidden').empty();
if (data.changed.length > 0) {
var current_open = (0, _jquery2.default)('.SSTT.ui-state-active');
var current_sstt = current_open.length > 0 ? current_open.attr('id').split('_').pop() : false;
var main_open = false;
for (var i = 0; i !== data.changed.length; i++) {
var sstt = (0, _jquery2.default)('#SSTT_' + data.changed[i]);
if (sstt.size() === 0) {
if (main_open === false) {
(0, _jquery2.default)('#baskets .bloc').animate({ 'top': 30 }, function () {
(0, _jquery2.default)('#baskets .alert_datas_changed:first').show();
});
main_open = true;
}
} else {
if (!sstt.hasClass('active')) sstt.addClass('unread');else {
(0, _jquery2.default)('.alert_datas_changed', (0, _jquery2.default)('#SSTT_content_' + data.changed[i])).show();
}
}
}
}
if (_jquery2.default.trim(data.message) !== '') {
if ((0, _jquery2.default)('#MESSAGE').length === 0) (0, _jquery2.default)('body').append('<div id="#MESSAGE"></div>');
(0, _jquery2.default)('#MESSAGE').empty().append('<div style="margin:30px 10px;"><h4><b>' + data.message + '</b></h4></div><div style="margin:20px 0px 10px;"><label class="checkbox"><input type="checkbox" class="dialog_remove" />' + language.hideMessage + '</label></div>').attr('title', 'Global Message').dialog({
autoOpen: false,
closeOnEscape: true,
resizable: false,
draggable: false,
modal: true,
close: function close() {
if ((0, _jquery2.default)('.dialog_remove:checked', (0, _jquery2.default)(this)).length > 0) {
// setTemporaryPref
_jquery2.default.ajax({
type: 'POST',
url: '/user/preferences/temporary/',
data: {
prop: 'message',
value: 0
},
success: function success(data) {
return;
}
});
}
}
}).dialog('open');
}
}
return true;
}
exports.default = {
initialize: initialize,
manageSession: manageSession
};
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* JavaScript Cookie v2.2.1
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader;
if (true) {
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
registeredInModuleLoader = true;
}
if (true) {
module.exports = factory();
registeredInModuleLoader = true;
}
if (!registeredInModuleLoader) {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
}(function () {
function extend () {
var i = 0;
var result = {};
for (; i < arguments.length; i++) {
var attributes = arguments[ i ];
for (var key in attributes) {
result[key] = attributes[key];
}
}
return result;
}
function decode (s) {
return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
}
function init (converter) {
function api() {}
function set (key, value, attributes) {
if (typeof document === 'undefined') {
return;
}
attributes = extend({
path: '/'
}, api.defaults, attributes);
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
}
// We're using "expires" because "max-age" is not supported by IE
attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
try {
var result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
value = converter.write ?
converter.write(value, key) :
encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
key = encodeURIComponent(String(key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape);
var stringifiedAttributes = '';
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += '; ' + attributeName;
if (attributes[attributeName] === true) {
continue;
}
// Considers RFC 6265 section 5.2:
// ...
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
// Consume the characters of the unparsed-attributes up to,
// not including, the first %x3B (";") character.
// ...
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
}
return (document.cookie = key + '=' + value + stringifiedAttributes);
}
function get (key, json) {
if (typeof document === 'undefined') {
return;
}
var jar = {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all.
var cookies = document.cookie ? document.cookie.split('; ') : [];
var i = 0;
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var cookie = parts.slice(1).join('=');
if (!json && cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1);
}
try {
var name = decode(parts[0]);
cookie = (converter.read || converter)(cookie, name) ||
decode(cookie);
if (json) {
try {
cookie = JSON.parse(cookie);
} catch (e) {}
}
jar[name] = cookie;
if (key === name) {
break;
}
} catch (e) {}
}
return key ? jar[key] : jar;
}
api.set = set;
api.get = function (key) {
return get(key, false /* read as raw */);
};
api.getJSON = function (key) {
return get(key, true /* read as json */);
};
api.remove = function (key, attributes) {
set(key, '', extend(attributes, {
expires: -1
}));
};
api.defaults = {};
api.withConverter = init;
return api;
}
return init(function () {});
}));
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _phraseanetCommon = __webpack_require__(11);
var AppCommons = _interopRequireWildcard(_phraseanetCommon);
var _publication = __webpack_require__(57);
var _publication2 = _interopRequireDefault(_publication);
var _workzone = __webpack_require__(93);
var _workzone2 = _interopRequireDefault(_workzone);
var _index = __webpack_require__(46);
var _index2 = _interopRequireDefault(_index);
var _locale = __webpack_require__(20);
var _locale2 = _interopRequireDefault(_locale);
var _ui = __webpack_require__(47);
var _ui2 = _interopRequireDefault(_ui);
var _configService = __webpack_require__(16);
var _configService2 = _interopRequireDefault(_configService);
var _i18next = __webpack_require__(21);
var _i18next2 = _interopRequireDefault(_i18next);
var _config = __webpack_require__(201);
var _config2 = _interopRequireDefault(_config);
var _emitter = __webpack_require__(15);
var _emitter2 = _interopRequireDefault(_emitter);
var _user = __webpack_require__(202);
var _user2 = _interopRequireDefault(_user);
var _basket = __webpack_require__(203);
var _basket2 = _interopRequireDefault(_basket);
var _search = __webpack_require__(204);
var _search2 = _interopRequireDefault(_search);
var _utils = __webpack_require__(39);
var _utils2 = _interopRequireDefault(_utils);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var humane = __webpack_require__(8);
__webpack_require__(208);
var Bootstrap = function () {
function Bootstrap(userConfig) {
var _this = this;
_classCallCheck(this, Bootstrap);
this.ready = _jquery2.default.Deferred();
var configuration = (0, _lodash2.default)({}, _config2.default, userConfig);
this.appEvents = new _emitter2.default();
// this.appEvents.listenAll(user().subscribeToEvents);
this.appEvents.listenAll((0, _basket2.default)().subscribeToEvents);
// @TODO add locale/translations in streams
this.configService = new _configService2.default(configuration);
this.localeService = new _locale2.default({
configService: this.configService
});
this.localeService.fetchTranslations().then(function () {
_this.onConfigReady();
});
this.utils = _utils2.default;
return this;
}
_createClass(Bootstrap, [{
key: 'getServices',
value: function getServices() {
return this.ready;
}
}, {
key: 'onConfigReady',
value: function onConfigReady() {
var _this2 = this;
this.appServices = {
configService: this.configService,
localeService: this.localeService,
appEvents: this.appEvents
};
// export translation for backward compatibility:
window.language = this.localeService.getTranslations();
var userSession = (0, _user2.default)(this.appServices);
var appProdNotification = {
url: this.configService.get('notify.url'),
moduleId: this.configService.get('notify.moduleId'),
userId: this.configService.get('notify.userId')
};
/**
* Initialize notifier
* @type {{bindEvents, createNotifier, isValid, poll}}
*/
var notifier = (0, _index2.default)(this.appServices);
notifier.initialize();
// create a new notification poll:
appProdNotification = notifier.createNotifier(appProdNotification);
if (notifier.isValid(appProdNotification)) {
notifier.poll(appProdNotification);
} else {
throw new Error('implementation error: failed to configure new notifier');
}
// @TODO remove global variables
// register some global variables,
window.bodySize = {
x: 0,
y: 0
};
window.baskAjax = null;
window.baskAjaxrunning = false;
window.answAjax = null;
window.answAjaxrunning = false;
window.searchAjax = null;
window.searchAjaxRunning = false;
/**
* add components
*/
this.appUi = (0, _ui2.default)(this.appServices);
this.appSearch = (0, _search2.default)(this.appServices);
this.appPublication = (0, _publication2.default)(this.appServices);
this.appWorkzone = (0, _workzone2.default)(this.appServices);
(0, _jquery2.default)(document).ready(function () {
// @TODO to be removed
var $body = (0, _jquery2.default)('body');
// trigger default route
_this2.initJqueryPlugins();
_this2.initDom();
_this2.appWorkzone.initialize();
_this2.appPublication.initialize();
_this2.ready.resolve({
search: _this2.appSearch,
workzone: _this2.appWorkzone
});
// proxy selection
_this2.appSearch.getResultSelectionStream().subscribe(function (data) {
_this2.appEvents.emit('broadcast.searchResultSelection', data);
});
// on navigation object changes
_this2.appSearch.getResultNavigationStream().subscribe(function (data) {
_this2.appEvents.emit('broadcast.searchResultNavigation', data);
});
_this2.appWorkzone.getResultSelectionStream().subscribe(function (data) {
_this2.appEvents.emit('broadcast.workzoneResultSelection', data);
});
// should be loaded after dom ready:
_this2.initState();
_this2.appUi.initialize({ $container: $body });
});
}
}, {
key: 'initState',
value: function initState() {
var initialState = this.configService.get('initialState');
switch (initialState) {
case 'publication':
this.appEvents.emit('publication.fetch');
// window.publicationModule.fetchPublications();
break;
default:
// trigger a search on loading
this.appEvents.emit('search.playFirstQuery');
//$('#searchForm').trigger('submit');
// $('form[name="phrasea_query"]').addClass('triggerAfterInit');
// trigger last search
}
}
}, {
key: 'initJqueryPlugins',
value: function initJqueryPlugins() {
AppCommons.commonModule.initialize();
_jquery2.default.datepicker.setDefaults({ showMonthAfterYear: false });
_jquery2.default.datepicker.setDefaults(_jquery2.default.datepicker.regional[this.localeService.getLocale()]);
}
}, {
key: 'initDom',
value: function initDom() {
var _this3 = this;
document.getElementById('loader_bar').style.width = '30%';
humane.infoLarge = humane.spawn({ addnCls: 'humane-libnotify-info humane-large', timeout: 5000 });
humane.info = humane.spawn({ addnCls: 'humane-libnotify-info', timeout: 1000 });
humane.error = humane.spawn({ addnCls: 'humane-libnotify-error', timeout: 1000 });
humane.forceNew = true;
// cguModule.activateCgus();
// @TODO to be removed
// catch main menu links
(0, _jquery2.default)('body').on('click', 'a.dialog', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(event.currentTarget);
var size = 'Medium';
if ($this.hasClass('small-dialog')) {
size = 'Small';
} else if ($this.hasClass('full-dialog')) {
size = 'Full';
}
var options = {
size: size,
loading: true,
title: $this.attr('title'),
closeOnEscape: true
};
var $dialog = _dialog2.default.create(_this3.appServices, options);
_jquery2.default.ajax({
type: 'GET',
url: $this.attr('href'),
dataType: 'html',
success: function success(data) {
$dialog.setContent(data);
return;
}
});
});
(0, _jquery2.default)(document).bind('contextmenu', function (event) {
var targ = void 0;
if (event.target) {
targ = event.target;
} else if (event.srcElement) {
targ = event.srcElement;
}
// safari bug
if (targ.nodeType === 3) {
targ = targ.parentNode;
}
var gogo = true;
var targ_name = targ.nodeName ? targ.nodeName.toLowerCase() : false;
if (targ_name !== 'input' && targ_name.toLowerCase() !== 'textarea') {
gogo = false;
}
if (targ_name === 'input') {
if ((0, _jquery2.default)(targ).is(':checkbox')) {
gogo = false;
}
}
return gogo;
});
(0, _jquery2.default)('#loader_bar').stop().animate({
width: '70%'
}, 450);
//startThesaurus();
this.appEvents.emit('searchAdvancedForm.checkFilters');
this.appUi.activeZoning();
this.appEvents.emit('ui.resizeAll');
(0, _jquery2.default)(window).bind('resize', function () {
_this3.appEvents.emit('ui.resizeAll');
});
(0, _jquery2.default)('body').append('<iframe id="MODALDL" class="modalbox" src="about:blank;" name="download" style="display:none;border:none;" frameborder="0"></iframe>');
(0, _jquery2.default)('body').append('<iframe id="idHFrameZ" src="about:blank" style="display:none;" name="HFrameZ"></iframe>');
(0, _jquery2.default)('.datepicker').datepicker({
changeYear: true,
changeMonth: true,
dateFormat: 'yy/mm/dd'
});
this.appSearch.initialize();
(0, _jquery2.default)('input.input_select_copy').on('focus', function () {
(0, _jquery2.default)(this).select();
});
(0, _jquery2.default)('input.input_select_copy').on('blur', function () {
(0, _jquery2.default)(this).deselect();
});
(0, _jquery2.default)('input.input_select_copy').on('click', function () {
(0, _jquery2.default)(this).select();
});
(0, _jquery2.default)('#loader_bar').stop().animate({
width: '100%'
}, 450, function () {
(0, _jquery2.default)('#loader').parent().fadeOut('slow', function () {
(0, _jquery2.default)(this).remove();
});
});
}
}]);
return Bootstrap;
}();
var bootstrap = function bootstrap(userConfig) {
return new Bootstrap(userConfig);
};
exports.default = bootstrap;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
var _index = __webpack_require__(94);
var _index2 = _interopRequireDefault(_index);
var _index3 = __webpack_require__(60);
var _index4 = _interopRequireDefault(_index3);
var _index5 = __webpack_require__(99);
var _index6 = _interopRequireDefault(_index5);
var _selectable = __webpack_require__(23);
var _selectable2 = _interopRequireDefault(_selectable);
var _alert = __webpack_require__(44);
var _alert2 = _interopRequireDefault(_alert);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
__webpack_require__(14);
__webpack_require__(19);
var workzone = function workzone(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var workzoneOptions = {};
var searchSelection = { asArray: [], serialized: '' };
(0, _index4.default)(services);
(0, _index6.default)(services).initialize();
(0, _index2.default)(services).initialize();
var nextBasketScroll = false;
var warnOnRemove = true;
var $container = void 0;
var dragBloc = (0, _jquery2.default)('#basket-tab').val();
function checkActiveBloc(destBloc) {
if (document.getElementById('expose_tab') && document.getElementById('expose_tab').getAttribute('aria-expanded') == 'true') {
(0, _jquery2.default)('#basket-tab').val('#expose_tab');
}
if (document.getElementById('baskets') && document.getElementById('baskets').getAttribute('aria-expanded') == 'true') {
(0, _jquery2.default)('#basket-tab').val('#baskets');
}
var destBloc = (0, _jquery2.default)('#basket-tab').val();
console.log(destBloc);
return destBloc;
}
checkActiveBloc(dragBloc);
var initialize = function initialize() {
$container = (0, _jquery2.default)('#idFrameC');
checkActiveBloc(dragBloc);
$container.resizable({
handles: 'e',
resize: function resize() {
appEvents.emit('ui.answerSizer');
appEvents.emit('ui.linearizeUi');
},
stop: function stop() {
var el = (0, _jquery2.default)('.SSTT.active').next();
var w = el.find('div.chim-wrapper:first').outerWidth();
var iw = el.innerWidth();
var diff = $container.width() - el.outerWidth();
var n = Math.floor(iw / w);
$container.height('auto');
var nwidth = n * w + diff + n + 10;
if (isNaN(nwidth)) {
appEvents.emit('ui.saveWindow');
return;
}
if (nwidth < 247) {
nwidth = 247;
}
if (el.find('div.chim-wrapper:first').hasClass('valid') && nwidth < 410) {
nwidth = 410;
}
$container.stop().animate({
width: nwidth
}, 300, 'linear', function () {
appEvents.emit('ui.answerSizer');
appEvents.emit('ui.linearizeUi');
appEvents.emit('ui.saveWindow');
});
}
});
(0, _jquery2.default)('#idFrameC .expose_li').on('click', function (event) {
checkActiveBloc(dragBloc);
});
(0, _jquery2.default)('.add_publication').on('click', function (event) {
openExposePublicationAdd();
});
(0, _jquery2.default)('.refresh-list').on('click', function (event) {
var exposeName = (0, _jquery2.default)('#expose_list').val();
(0, _jquery2.default)('.publication-list').empty().html('<img src="/assets/common/images/icons/main-loader.gif" alt="loading"/>');
updatePublicationList(exposeName);
});
(0, _jquery2.default)('.display-list').on('click', function (event) {
var exposeName = (0, _jquery2.default)('#expose_list').val();
(0, _jquery2.default)('.publication-list').empty().html('<img src="/assets/common/images/icons/main-loader.gif" alt="loading"/>');
updatePublicationList(exposeName);
});
(0, _jquery2.default)('#expose_list').on('change', function () {
(0, _jquery2.default)('.publication-list').empty().html('<img src="/assets/common/images/icons/main-loader.gif" alt="loading"/>');
updatePublicationList(this.value);
});
(0, _jquery2.default)('.publication-list').on('click', '.top-block', function (event) {
(0, _jquery2.default)(this).parent().find('.expose_item_deployed').toggleClass('open');
(0, _jquery2.default)(this).toggleClass('open');
});
(0, _jquery2.default)('#idFrameC .ui-tabs-nav li').on('click', function (event) {
if ($container.attr('data-status') === 'closed') {
(0, _jquery2.default)('#retractableButton').find('i').removeClass('fa-angle-double-right').addClass('fa-angle-double-left');
$container.width(360);
(0, _jquery2.default)('#rightFrame').css('left', 360);
(0, _jquery2.default)('#rightFrame').width((0, _jquery2.default)(window).width() - 360);
(0, _jquery2.default)('#baskets, #expose_tab, #proposals, #thesaurus_tab').hide();
(0, _jquery2.default)('.ui-resizable-handle, #basket_menu_trigger').show();
var IDname = (0, _jquery2.default)(this).attr('aria-controls');
(0, _jquery2.default)('#' + IDname).show();
}
$container.attr('data-status', 'open');
(0, _jquery2.default)('.WZbasketTab').css('background-position', '9px 21px');
$container.removeClass('closed');
});
var previousTab = '';
(0, _jquery2.default)('#idFrameC #retractableButton').bind('click', function (event) {
if ($container.attr('data-status') !== 'closed') {
(0, _jquery2.default)(this).find('i').removeClass('fa-angle-double-left').addClass('fa-angle-double-right');
$container.width(80);
(0, _jquery2.default)('#rightFrame').css('left', 80);
(0, _jquery2.default)('#rightFrame').width((0, _jquery2.default)(window).width() - 80);
$container.attr('data-status', 'closed');
(0, _jquery2.default)('#baskets, #expose_tab, #proposals, #thesaurus_tab, .ui-resizable-handle, #basket_menu_trigger').hide();
(0, _jquery2.default)('#idFrameC .ui-tabs-nav li').removeClass('ui-state-active');
(0, _jquery2.default)('.WZbasketTab').css('background-position', '15px 16px');
$container.addClass('closed');
previousTab = (0, _jquery2.default)('#idFrameC .prod-icon-menu').find('li.ui-tabs-active');
} else {
(0, _jquery2.default)(this).find('i').removeClass('fa-angle-double-right').addClass('fa-angle-double-left');
$container.width(360);
(0, _jquery2.default)('#rightFrame').css('left', 360);
(0, _jquery2.default)('#rightFrame').width((0, _jquery2.default)(window).width() - 360);
$container.attr('data-status', 'open');
(0, _jquery2.default)('.ui-resizable-handle, #basket_menu_trigger').show();
(0, _jquery2.default)('.WZbasketTab').css('background-position', '9px 16px');
$container.removeClass('closed');
(0, _jquery2.default)('#idFrameC .prod-icon-menu li').last().find('a').trigger('click');
(0, _jquery2.default)('#idFrameC .prod-icon-menu li').first().find('a').trigger('click');
(0, _jquery2.default)(previousTab).find('a').trigger('click');
}
event.stopImmediatePropagation();
// workzoneOptions.close();
return false;
});
(0, _jquery2.default)('#basket_menu_trigger').contextMenu('#basket_menu', {
openEvt: 'click',
dropDown: true,
theme: 'vista',
showTransition: 'slideDown',
hideTransition: 'hide',
shadow: false
});
(0, _jquery2.default)('#basket_menu_trigger').trigger('click');
(0, _jquery2.default)('#basket_menu_trigger').trigger('click');
(0, _jquery2.default)('.basketTips').tooltip({
delay: 200,
extraClass: 'tooltip_flat'
});
(0, _jquery2.default)('.basket_title').tooltip({
extraClass: 'tooltip_flat'
});
(0, _jquery2.default)('#idFrameC .tabs').tabs({
activate: function activate(event, ui) {
if (ui.newTab.context.hash === '#thesaurus_tab') {
appEvents.emit('thesaurus.show');
}
workzoneOptions.open();
}
});
(0, _jquery2.default)('.basket_refresher').on('click', function () {
return workzoneOptions.refresh('current');
});
activeBaskets();
(0, _jquery2.default)('body').on('click', 'a.story_unfix', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
unfix($el.attr('href'));
return false;
});
workzoneOptions = {
selection: new _selectable2.default(services, (0, _jquery2.default)('#baskets'), { selector: '.CHIM' }),
refresh: refreshBaskets,
addElementToBasket: function addElementToBasket(options) {
var sbas_id = options.sbas_id,
record_id = options.record_id,
event = options.event,
singleSelection = options.singleSelection;
singleSelection = !!singleSelection || false;
if ((0, _jquery2.default)('#baskets .SSTT.active').length === 1) {
return dropOnBask(event, (0, _jquery2.default)('#IMGT_' + sbas_id + '_' + record_id), (0, _jquery2.default)('#baskets .SSTT.active'), singleSelection);
} else {
humane.info(localeService.t('noActiveBasket'));
}
},
removeElementFromBasket: WorkZoneElementRemover,
reloadCurrent: function reloadCurrent() {
var sstt = (0, _jquery2.default)('#baskets .content:visible');
if (sstt.length > 0) {
getContent(sstt.prev());
}
},
close: function close() {
var frame = $container;
var that = this;
if (!frame.hasClass('closed')) {
// hide tabs content
(0, _jquery2.default)('#idFrameC .tabs > .ui-tabs-panel').hide();
frame.data('openwidth', frame.width());
frame.animate({ width: 100 }, 300, 'linear', function () {
appEvents.emit('ui.answerSizer');
appEvents.emit('ui.linearizeUi');
(0, _jquery2.default)('#answers').trigger('resize');
});
frame.addClass('closed');
(0, _jquery2.default)('.escamote', frame).hide();
frame.unbind('click.escamote').bind('click.escamote', function () {
that.open();
});
}
},
open: function open() {
var frame = $container;
if (frame.hasClass('closed')) {
var width = frame.data('openwidth') ? frame.data('openwidth') : 300;
frame.css({ width: width });
appEvents.emit('ui.answerSizer');
appEvents.emit('ui.linearizeUi');
frame.removeClass('closed');
(0, _jquery2.default)('.escamote', frame).show();
frame.unbind('click.escamote');
// show tabs content
var activeTabIdx = (0, _jquery2.default)('#idFrameC .tabs').tabs('option', 'active');
(0, _jquery2.default)('#idFrameC .tabs > div:eq(' + activeTabIdx + ')').show();
}
}
};
filterBaskets();
(0, _jquery2.default)('#expose_tabs').tabs();
};
var getResultSelectionStream = function getResultSelectionStream() {
return workzoneOptions.selection.stream;
};
/*left filter basket*/
function filterBaskets() {
(0, _jquery2.default)('#feedback-list input').click(function () {
(0, _jquery2.default)('.feedbacks-block').toggleClass('hidden');
});
(0, _jquery2.default)('#push-list input').click(function () {
(0, _jquery2.default)('.pushes-block').toggleClass('hidden');
});
(0, _jquery2.default)('#basket-list input').click(function () {
(0, _jquery2.default)('.baskets-block').toggleClass('hidden');
});
(0, _jquery2.default)('#story-list input').click(function () {
(0, _jquery2.default)('.stories-block').toggleClass('hidden');
});
}
function refreshBaskets(options) {
var _ref = options || {},
_ref$basketId = _ref.basketId,
basketId = _ref$basketId === undefined ? false : _ref$basketId,
sort = _ref.sort,
scrolltobottom = _ref.scrolltobottom,
type = _ref.type;
type = typeof type === 'undefined' ? 'basket' : type;
var active = (0, _jquery2.default)('#baskets .SSTT.ui-state-active');
if (basketId === 'current' && active.length > 0) {
basketId = active.attr('id').split('_').slice(1, 2).pop();
}
sort = _jquery2.default.inArray(sort, ['date', 'name']) >= 0 ? sort : '';
scrolltobottom = typeof scrolltobottom === 'undefined' ? false : scrolltobottom;
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/WorkZone/',
data: {
id: basketId,
sort: sort,
type: type
},
beforeSend: function beforeSend() {
(0, _jquery2.default)('#basketcontextwrap').remove();
},
success: function success(data) {
var cache = (0, _jquery2.default)('#idFrameC #baskets');
if ((0, _jquery2.default)('.SSTT', cache).data('ui-droppable')) {
(0, _jquery2.default)('.SSTT', cache).droppable('destroy');
}
if ((0, _jquery2.default)('.bloc', cache).data('ui-droppable')) {
(0, _jquery2.default)('.bloc', cache).droppable('destroy');
}
if (cache.data('ui-accordion')) {
cache.accordion('destroy').empty().append(data);
}
activeBaskets();
filterBaskets();
(0, _jquery2.default)('.basketTips').tooltip({
delay: 200
});
cache.disableSelection();
if (!scrolltobottom) {
return;
}
nextBasketScroll = true;
return;
}
});
}
function setTemporaryPref(name, value) {
_jquery2.default.ajax({
type: 'POST',
url: '/user/preferences/temporary/',
data: {
prop: name,
value: value
},
success: function success(data) {
return;
}
});
}
(0, _jquery2.default)('#baskets div.content select[name=valid_ord]').on('change', function () {
var active = (0, _jquery2.default)('#baskets .SSTT.ui-state-active');
if (active.length === 0) {
return;
}
var order = (0, _jquery2.default)(this).val();
getContent(active, order);
});
function WorkZoneElementRemover(el, confirm) {
var context = el.data('context');
if (confirm !== true && (0, _jquery2.default)(el).hasClass('groupings') && warnOnRemove) {
var buttons = {};
buttons[localeService.t('valider')] = function () {
(0, _jquery2.default)('#DIALOG-baskets').dialog('close').remove();
WorkZoneElementRemover(el, true);
};
buttons[localeService.t('annuler')] = function () {
(0, _jquery2.default)('#DIALOG-baskets').dialog('close').remove();
};
var texte = '<p>' + localeService.t('confirmRemoveReg') + '</p><div><input type="checkbox" onchange="prodApp.appEvents.emit(\'workzone.doRemoveWarning\', this);"/>' + localeService.t('hideMessage') + '</div>';
(0, _jquery2.default)('body').append('<div id="DIALOG-baskets"></div>');
(0, _jquery2.default)('#DIALOG-baskets').attr('title', localeService.t('removeTitle')).empty().append(texte).dialog({
autoOpen: false,
closeOnEscape: true,
resizable: false,
draggable: false,
modal: true,
buttons: buttons,
overlay: {
backgroundColor: '#000',
opacity: 0.7
}
}).dialog('open');
return false;
} else {
var id = (0, _jquery2.default)(el).attr('id').split('_').slice(2, 4).join('_');
return _jquery2.default.ajax({
type: 'POST',
url: (0, _jquery2.default)(el).attr('href'),
dataType: 'json',
beforeSend: function beforeSend() {
(0, _jquery2.default)('.wrapCHIM_' + id).find('.CHIM').fadeOut();
},
success: function success(data) {
if (data.success) {
humane.info(data.message);
workzoneOptions.selection.remove(id);
if ((0, _jquery2.default)('.wrapCHIM_' + id).find('.CHIM').data('ui-draggable')) {
(0, _jquery2.default)('.wrapCHIM_' + id).find('.CHIM').draggable('destroy');
}
(0, _jquery2.default)('.wrapCHIM_' + id).remove();
if (context === 'reg_train_basket') {
var carousel = (0, _jquery2.default)('#PREVIEWCURRENTCONT');
var carouselItemLength = (0, _jquery2.default)('li', carousel).length;
var selectedItem = (0, _jquery2.default)('li.prevTrainCurrent.selected', carousel);
var selectedItemIndex = (0, _jquery2.default)('li', carousel).index(selectedItem);
// item is first and list has at least 2 items
if (selectedItemIndex === 0 && carouselItemLength > 1) {
// click next item
selectedItem.next().find('img').trigger('click');
// item is last item and list has at least 2 items
} else if (carouselItemLength > 1 && selectedItemIndex === carouselItemLength - 1) {
// click previous item
selectedItem.prev().find('img').trigger('click');
// Basket is empty
} else if (carouselItemLength > 1) {
// click next item
selectedItem.next().find('img').trigger('click');
} else {
appEvents.emit('preview.close');
}
selectedItem.remove();
} else {
return workzoneOptions.reloadCurrent();
}
} else {
humane.error(data.message);
(0, _jquery2.default)('.wrapCHIM_' + id).find('.CHIM').fadeIn();
}
}
});
}
}
function activeBaskets() {
var cache = (0, _jquery2.default)('#idFrameC #baskets');
cache.accordion({
active: 'active',
heightStyle: 'content',
collapsible: true,
header: 'div.header',
activate: function activate(event, ui) {
var b_active = (0, _jquery2.default)('#baskets .SSTT.active');
if (nextBasketScroll) {
nextBasketScroll = false;
if (!b_active.next().is(':visible')) {
return;
}
var t = (0, _jquery2.default)('#baskets .SSTT.active').position().top + b_active.next().height() - 200;
t = t < 0 ? 0 : t;
(0, _jquery2.default)('#baskets .bloc').stop().animate({
scrollTop: t
});
}
var uiactive = (0, _jquery2.default)(this).find('.ui-state-active');
b_active.not('.ui-state-active').removeClass('active');
if (uiactive.length === 0) {
return;
/* everything is closed */
}
uiactive.addClass('ui-state-focus active');
workzoneOptions.selection.empty();
getContent(uiactive);
},
beforeActivate: function beforeActivate(event, ui) {
ui.newHeader.addClass('active');
(0, _jquery2.default)('#basketcontextwrap .basketcontextmenu').hide();
}
});
(0, _jquery2.default)('.bloc', cache).droppable({
accept: function accept(elem) {
if ((0, _jquery2.default)(elem).hasClass('grouping') && !(0, _jquery2.default)(elem).hasClass('SSTT')) {
return true;
}
return false;
},
scope: 'objects',
hoverClass: 'groupDrop',
tolerance: 'pointer',
drop: function drop() {
fix();
}
});
if ((0, _jquery2.default)('.SSTT.active', cache).length > 0) {
var el = (0, _jquery2.default)('.SSTT.active', cache)[0];
(0, _jquery2.default)(el).trigger('click');
}
(0, _jquery2.default)('.SSTT, .content', cache).droppable({
scope: 'objects',
hoverClass: 'baskDrop',
tolerance: 'pointer',
accept: function accept(elem) {
if ((0, _jquery2.default)(elem).hasClass('CHIM')) {
if ((0, _jquery2.default)(elem).closest('.content').prev()[0] === (0, _jquery2.default)(this)[0]) {
return false;
}
}
if ((0, _jquery2.default)(elem).hasClass('grouping') || (0, _jquery2.default)(elem).parent()[0] === (0, _jquery2.default)(this)[0]) {
return false;
}
return true;
},
drop: function drop(event, ui) {
dropOnBask(event, ui.draggable, (0, _jquery2.default)(this));
}
});
if ((0, _jquery2.default)('#basketcontextwrap').length === 0) {
(0, _jquery2.default)('body').append('<div id="basketcontextwrap"></div>');
}
(0, _jquery2.default)('.context-menu-item', cache).hover(function () {
(0, _jquery2.default)(this).addClass('context-menu-item-hover');
}, function () {
(0, _jquery2.default)(this).removeClass('context-menu-item-hover');
});
_jquery2.default.each((0, _jquery2.default)('.SSTT', cache), function () {
var el = (0, _jquery2.default)(this);
(0, _jquery2.default)(this).find('.contextMenuTrigger').contextMenu('#' + (0, _jquery2.default)(this).attr('id') + ' .contextMenu', {
appendTo: '#basketcontextwrap',
openEvt: 'click',
theme: 'vista',
dropDown: true,
showTransition: 'slideDown',
hideTransition: 'hide',
shadow: false
});
});
}
function activeExpose() {
var idFrameC = (0, _jquery2.default)('#idFrameC');
// drop on publication
idFrameC.find('.publication-droppable').droppable({
scope: 'objects',
hoverClass: 'baskDrop',
tolerance: 'pointer',
accept: function accept(elem) {
if ((0, _jquery2.default)(elem).hasClass('CHIM')) {
if ((0, _jquery2.default)(elem).closest('.content').prev()[0] === (0, _jquery2.default)(this)[0]) {
return false;
}
}
if ((0, _jquery2.default)(elem).hasClass('grouping') || (0, _jquery2.default)(elem).parent()[0] === (0, _jquery2.default)(this)[0]) {
return false;
}
return true;
},
drop: function drop(event, ui) {
dropOnBask(event, ui.draggable, (0, _jquery2.default)(this));
}
});
// delete an asset from publication
idFrameC.find('.publication-droppable').on('click', '.removeAsset', function () {
var publicationId = (0, _jquery2.default)(this).attr('data-publication-id');
var assetId = (0, _jquery2.default)(this).attr('data-asset-id');
var exposeName = (0, _jquery2.default)('#expose_list').val();
var assetsContainer = (0, _jquery2.default)(this).parents('.expose_item_deployed');
var buttons = {};
var $dialog = _dialog2.default.create(services, {
size: '480x160',
title: localeService.t('warning')
});
buttons[localeService.t('valider')] = function () {
$dialog.setContent('<img src="/assets/common/images/icons/main-loader.gif" alt="loading"/>');
_jquery2.default.ajax({
type: 'POST',
url: '/prod/expose/publication/delete-asset/' + publicationId + '/' + assetId + '/?exposeName=' + exposeName,
beforeSend: function beforeSend() {
assetsContainer.addClass('loading');
},
success: function success(data) {
if (data.success === true) {
$dialog.close();
getPublicationAssetsList(publicationId, exposeName, assetsContainer, 1);
} else {
$dialog.setContent(data.message);
console.log(data);
}
}
});
};
buttons[localeService.t('annuler')] = function () {
$dialog.close();
};
var texte = '<p>' + localeService.t('removeAssetPublication') + '</p>';
$dialog.setOption('buttons', buttons);
$dialog.setContent(texte);
});
idFrameC.find('.publication-droppable').on('click', '.edit_expose', function (event) {
openExposePublicationEdit((0, _jquery2.default)(this));
});
// delete a publication
idFrameC.find('.publication-droppable').on('click', '.delete-publication', function () {
var publicationId = (0, _jquery2.default)(this).attr('data-publication-id');
var exposeName = (0, _jquery2.default)('#expose_list').val();
var buttons = {};
var $dialog = _dialog2.default.create(services, {
size: '480x160',
title: localeService.t('warning')
});
buttons[localeService.t('valider')] = function () {
$dialog.setContent('<img src="/assets/common/images/icons/main-loader.gif" alt="loading"/>');
_jquery2.default.ajax({
type: 'POST',
url: '/prod/expose/delete-publication/' + publicationId + '/?exposeName=' + exposeName,
success: function success(data) {
if (data.success === true) {
$dialog.close();
updatePublicationList(exposeName);
} else {
$dialog.setContent(data.message);
console.log(data);
}
}
});
};
buttons[localeService.t('annuler')] = function () {
$dialog.close();
};
var texte = '<p>' + localeService.t('removeExposePublication') + '</p>';
$dialog.setOption('buttons', buttons);
$dialog.setContent(texte);
});
// refresh publication content
idFrameC.find('.publication-droppable').on('click', '.refresh-publication', function () {
var publicationId = (0, _jquery2.default)(this).attr('data-publication-id');
var exposeName = (0, _jquery2.default)('#expose_list').val();
var assetsContainer = (0, _jquery2.default)(this).parents('.expose_item_deployed');
assetsContainer.empty().addClass('loading');
getPublicationAssetsList(publicationId, exposeName, assetsContainer, 1);
});
// set publication cover
idFrameC.find('.publication-droppable').on('click', '.set-cover', function () {
var publicationId = (0, _jquery2.default)(this).attr('data-publication-id');
var assetId = (0, _jquery2.default)(this).attr('data-asset-id');
var exposeName = (0, _jquery2.default)('#expose_list').val();
var publicationData = JSON.stringify({ "cover": '/assets/' + assetId }, undefined, 4);
_jquery2.default.ajax({
type: "PUT",
url: '/prod/expose/update-publication/' + publicationId,
dataType: 'json',
data: {
exposeName: '' + exposeName,
publicationData: publicationData
},
success: function success(data) {
if (data.success) {
updatePublicationList(exposeName);
} else {
console.log(data.message);
}
}
});
});
// load more asset and append it at the end
idFrameC.find('.publication-droppable').on('click', '.load_more_asset', function () {
var publicationId = (0, _jquery2.default)(this).attr('data-publication-id');
var exposeName = (0, _jquery2.default)('#expose_list').val();
var assetsContainer = (0, _jquery2.default)(this).parents('.expose_item_bottom').find('.expose_drag_drop');
var page = assetsContainer.find('#list_assets_page').val();
(0, _jquery2.default)(this).find('.loading_more').removeClass('hidden');
getPublicationAssetsList(publicationId, exposeName, assetsContainer, parseInt(page) + 1);
});
}
function updatePublicationList(exposeName) {
_jquery2.default.ajax({
type: 'GET',
url: '/prod/expose/list-publication/?exposeName=' + exposeName,
success: function success(data) {
(0, _jquery2.default)('.publication-list').empty().html(data);
(0, _jquery2.default)('.expose_basket_item .top_block').on('click', function (event) {
(0, _jquery2.default)(this).parent().find('.expose_item_deployed').toggleClass('open');
(0, _jquery2.default)(this).toggleClass('open');
if ((0, _jquery2.default)(this).hasClass('open')) {
var publicationId = (0, _jquery2.default)(this).attr('data-publication-id');
var _exposeName = (0, _jquery2.default)('#expose_list').val();
var assetsContainer = (0, _jquery2.default)(this).parents('.expose_basket_item').find('.expose_item_deployed');
assetsContainer.addClass('loading');
getPublicationAssetsList(publicationId, _exposeName, assetsContainer, 1);
}
});
activeExpose();
}
});
}
function getPublicationAssetsList(publicationId, exposeName, assetsContainer) {
var page = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
_jquery2.default.ajax({
type: 'GET',
url: '/prod/expose/get-publication/' + publicationId + '/assets?exposeName=' + exposeName + '&page=' + page,
success: function success(data) {
if (typeof data.success === 'undefined') {
if (page === 1) {
assetsContainer.removeClass('loading');
assetsContainer.empty().html(data);
} else {
assetsContainer.append(data);
assetsContainer.parents('.expose_item_bottom').find('.loading_more').addClass('hidden');
assetsContainer.find('#list_assets_page').val(page);
}
} else {
console.log(data);
}
}
});
}
function getContent(header, order) {
if (window.console) {
console.log('Reload content for ', header);
}
var url = (0, _jquery2.default)('a', header).attr('href');
if (typeof order !== 'undefined') {
url += '?order=' + order;
}
_jquery2.default.ajax({
type: 'GET',
url: url,
dataType: 'html',
beforeSend: function beforeSend() {
(0, _jquery2.default)('#tooltip').hide();
header.next().addClass('loading');
},
success: function success(data) {
header.removeClass('unread');
var dest = header.next();
if (dest.data('ui-droppable')) {
dest.droppable('destroy');
}
dest.empty().removeClass('loading');
dest.append(data);
(0, _jquery2.default)('a.WorkZoneElementRemover', dest).bind('mousedown', function (event) {
return false;
}).bind('click', function (event) {
return WorkZoneElementRemover((0, _jquery2.default)(this), false);
});
(0, _jquery2.default)("#baskets div.content select[name=valid_ord]").on('change', function () {
var active = (0, _jquery2.default)('#baskets .SSTT.ui-state-active');
if (active.length === 0) {
return;
}
var order = (0, _jquery2.default)(this).val();
getContent(active, order);
});
dest.droppable({
accept: function accept(elem) {
if ((0, _jquery2.default)(elem).hasClass('CHIM')) {
if ((0, _jquery2.default)(elem).closest('.content')[0] === (0, _jquery2.default)(this)[0]) {
return false;
}
}
if ((0, _jquery2.default)(elem).hasClass('grouping') || (0, _jquery2.default)(elem).parent()[0] === (0, _jquery2.default)(this)[0]) {
return false;
}
return true;
},
hoverClass: 'baskDrop',
scope: 'objects',
drop: function drop(event, ui) {
dropOnBask(event, ui.draggable, (0, _jquery2.default)(this).prev());
},
tolerance: 'pointer'
});
(0, _jquery2.default)('.noteTips, .captionRolloverTips', dest).tooltip({
extraClass: 'tooltip_flat'
});
dest.find('.CHIM').draggable({
helper: function helper() {
(0, _jquery2.default)('body').append('<div id="dragDropCursor" ' + 'style="position:absolute;z-index:9999;background:red;' + '-moz-border-radius:8px;-webkit-border-radius:8px;">' + '<div style="padding:2px 5px;font-weight:bold;">' + workzoneOptions.selection.length() + '</div></div>');
return (0, _jquery2.default)('#dragDropCursor');
},
scope: 'objects',
distance: 20,
scroll: false,
refreshPositions: true,
cursorAt: {
top: 10,
left: -20
},
start: function start(event, ui) {
var baskets = (0, _jquery2.default)('#baskets');
baskets.append('<div class="top-scroller"></div>' + '<div class="bottom-scroller"></div>');
(0, _jquery2.default)('.bottom-scroller', baskets).bind('mousemove', function () {
(0, _jquery2.default)('#baskets .bloc').scrollTop((0, _jquery2.default)('#baskets .bloc').scrollTop() + 30);
});
(0, _jquery2.default)('.top-scroller', baskets).bind('mousemove', function () {
(0, _jquery2.default)('#baskets .bloc').scrollTop((0, _jquery2.default)('#baskets .bloc').scrollTop() - 30);
});
},
stop: function stop() {
(0, _jquery2.default)('#baskets').find('.top-scroller, .bottom-scroller').unbind().remove();
},
drag: function drag(event, ui) {
if (appCommons.utilsModule.is_ctrl_key(event) || (0, _jquery2.default)(this).closest('.content').hasClass('grouping')) {
(0, _jquery2.default)('#dragDropCursor div').empty().append('+ ' + workzoneOptions.selection.length());
} else {
(0, _jquery2.default)('#dragDropCursor div').empty().append(workzoneOptions.selection.length());
}
}
});
window.workzoneOptions = workzoneOptions;
appEvents.emit('ui.answerSizer');
return;
}
});
}
function openExposePublicationAdd() {
(0, _jquery2.default)('#DIALOG-expose-add').attr('title', localeService.t('Edit expose title')).dialog({
autoOpen: false,
closeOnEscape: true,
resizable: true,
draggable: true,
width: 900,
height: 575,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.7
},
close: function close(e, ui) {}
}).dialog('open');
(0, _jquery2.default)('.ui-dialog').addClass('black-dialog-wrap publish-dialog');
(0, _jquery2.default)('#DIALOG-expose-add').on('click', '.close-expose-modal', function () {
(0, _jquery2.default)('#DIALOG-expose-add').dialog('close');
});
}
function openExposePublicationEdit(edit) {
(0, _jquery2.default)('#DIALOG-expose-edit').empty().html('<img src="/assets/common/images/icons/main-loader.gif" alt="loading"/>');
(0, _jquery2.default)('#DIALOG-expose-edit').attr('title', localeService.t('Edit expose title')).dialog({
autoOpen: false,
closeOnEscape: true,
resizable: true,
draggable: true,
width: 900,
height: 575,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.7
},
close: function close(e, ui) {
(0, _jquery2.default)('#DIALOG-expose-edit').empty();
}
}).dialog('open');
(0, _jquery2.default)('.ui-dialog').addClass('black-dialog-wrap publish-dialog');
(0, _jquery2.default)('#DIALOG-expose-edit').on('click', '.close-expose-modal', function () {
(0, _jquery2.default)('#DIALOG-expose-edit').dialog('close');
});
_jquery2.default.ajax({
type: "GET",
url: '/prod/expose/get-publication/' + edit.data("id") + '?exposeName=' + (0, _jquery2.default)("#expose_list").val(),
success: function success(data) {
(0, _jquery2.default)('#DIALOG-expose-edit').empty().html(data);
}
});
}
function dropOnBask(event, from, destKey, singleSelection) {
checkActiveBloc(dragBloc);
var action = '';
var dest_uri = '';
var lstbr = [];
var sselcont = [];
var act = 'ADD';
from = (0, _jquery2.default)(from);
if (from.hasClass('CHIM')) {
/* Element(s) come from an open object in the workzone */
action = (0, _jquery2.default)(' #baskets .ui-state-active').hasClass('grouping') ? 'REG2' : 'CHU2';
} else {
/* Element(s) come from result */
action = 'IMGT2';
}
action += destKey.hasClass('grouping') ? 'REG' : 'CHU';
if (destKey.hasClass('content')) {
/* I dropped on content */
dest_uri = (0, _jquery2.default)('a', destKey.prev()).attr('href');
} else {
/* I dropped on Title */
dest_uri = (0, _jquery2.default)('a', destKey).attr('href');
}
if (window.console) {
window.console.log('Requested action is ', action, ' and act on ', dest_uri);
}
if (action === 'IMGT2CHU' || action === 'IMGT2REG') {
if ((0, _jquery2.default)(from).hasClass('.baskAdder')) {
lstbr = [(0, _jquery2.default)(from).attr('id').split('_').slice(2, 4).join('_')];
} else if (singleSelection) {
if (from.length === 1) {
lstbr = [(0, _jquery2.default)(from).attr('id').split('_').slice(1, 3).join('_')];
} else {
lstbr = [(0, _jquery2.default)(from).selector.split('_').slice(1, 3).join('_')];
}
} else {
lstbr = searchSelection.asArray;
}
} else {
sselcont = _jquery2.default.map(workzoneOptions.selection.get(), function (n, i) {
return (0, _jquery2.default)('.CHIM_' + n, (0, _jquery2.default)('#baskets .content:visible')).attr('id').split('_').slice(1, 2).pop();
});
lstbr = workzoneOptions.selection.get();
}
switch (action) {
case 'CHU2CHU':
if (!appCommons.utilsModule.is_ctrl_key(event)) act = 'MOV';
break;
case 'IMGT2REG':
case 'CHU2REG':
case 'REG2REG':
var sameSbas = true;
var sbas_reg = destKey.attr('sbas');
for (var i = 0; i < lstbr.length && sameSbas; i++) {
if (lstbr[i].split('_').shift() !== sbas_reg) {
sameSbas = false;
break;
}
}
if (sameSbas === false) {
return (0, _alert2.default)('', localeService.t('reg_wrong_sbas'));
}
break;
default:
}
var url = '';
var data = {};
switch (act + action) {
case 'MOVCHU2CHU':
url = dest_uri + 'stealElements/';
data = {
elements: sselcont
};
break;
case 'ADDCHU2REG':
case 'ADDREG2REG':
case 'ADDIMGT2REG':
case 'ADDCHU2CHU':
case 'ADDREG2CHU':
case 'ADDIMGT2CHU':
url = dest_uri + 'addElements/';
data = {
lst: lstbr.join(';')
};
break;
default:
if (window.console) {
console.log('Should not happen');
}
return false;
}
//save basket after drop elt
if ((0, _jquery2.default)('#basket-tab').val() === '#baskets') {
if (window.console) {
window.console.log('About to execute ajax POST on ', url, ' with datas ', data);
}
_jquery2.default.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
beforeSend: function beforeSend() {},
success: function success(data) {
if (!data.success) {
humane.error(data.message);
} else {
humane.info(data.message);
}
if (act === 'MOV' || (0, _jquery2.default)(destKey).next().is(':visible') === true || (0, _jquery2.default)(destKey).hasClass('content') === true) {
(0, _jquery2.default)('.CHIM.selected:visible').fadeOut();
workzoneOptions.selection.empty();
return workzoneOptions.reloadCurrent();
}
return true;
}
});
} else {
console.log(data.lst);
var publicationId = destKey.attr('data-publication-id');
var exposeName = (0, _jquery2.default)('#expose_list').val();
var assetsContainer = destKey.find('.expose_item_deployed');
assetsContainer.empty().addClass('loading');
_jquery2.default.ajax({
type: 'POST',
url: '/prod/expose/publication/add-assets',
data: {
publicationId: publicationId,
exposeName: exposeName,
lst: data.lst
},
dataType: 'json',
success: function success(data) {
setTimeout(function () {
getPublicationAssetsList(publicationId, exposeName, assetsContainer, 1);
}, 6000);
console.log(data.message);
}
});
}
}
function fix() {
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/WorkZone/attachStories/',
data: { stories: searchSelection.asArray },
dataType: 'json',
success: function success(data) {
humane.info(data.message);
workzoneOptions.refresh();
}
});
}
function unfix(link) {
_jquery2.default.ajax({
type: 'POST',
url: link,
dataType: 'json',
success: function success(data) {
humane.info(data.message);
workzoneOptions.refresh();
}
});
}
function setRemoveWarning(state) {
warnOnRemove = state;
}
// remove record from basket/story preferences
function toggleRemoveWarning(el) {
var state = !el.checked;
appCommons.userModule.setPref('reg_delete', state ? '1' : '0');
warnOnRemove = state;
}
// map events to result selection:
appEvents.listenAll({
'workzone.selection.selectAll': function workzoneSelectionSelectAll() {
return workzoneOptions.selection.selectAll();
},
// 'workzone.selection.unselectAll': () => workzoneOptions.selection.empty(),
// 'workzone.selection.selectByType': (dataType) => workzoneOptions.selection.select(dataType.type),
'workzone.selection.remove': function workzoneSelectionRemove(data) {
return workzoneOptions.selection.remove(data.records);
}
});
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelection = selection;
},
'workzone.refresh': refreshBaskets,
'workzone.doAddToBasket': function workzoneDoAddToBasket(options) {
workzoneOptions.addElementToBasket(options);
},
'workzone.doRemoveFromBasket': function workzoneDoRemoveFromBasket(options) {
WorkZoneElementRemover(options.event, options.confirm);
},
'workzone.doRemoveWarning': setRemoveWarning,
'workzone.doToggleRemoveWarning': toggleRemoveWarning
});
return {
initialize: initialize, workzoneFacets: _index4.default, workzoneBaskets: _index6.default, workzoneThesaurus: _index2.default, setRemoveWarning: setRemoveWarning,
toggleRemoveWarning: toggleRemoveWarning, getResultSelectionStream: getResultSelectionStream
};
};
exports.default = workzone;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _index = __webpack_require__(95);
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(96);
var workzoneThesaurus = function workzoneThesaurus(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $container = null;
var thesaurusService = (0, _index2.default)(services);
var initialize = function initialize() {
$container = (0, _jquery2.default)('#thesaurus_tab');
thesaurusService.initialize({ $container: $container });
(0, _jquery2.default)('#thesaurus_tab .input-medium').on('keyup', function () {
if ((0, _jquery2.default)('#thesaurus_tab .input-medium').val() !== '') {
(0, _jquery2.default)('#thesaurus_tab .th_clear').show();
} else {
(0, _jquery2.default)('#thesaurus_tab .th_clear').hide();
}
});
(0, _jquery2.default)('.th_clear').on('click', function () {
(0, _jquery2.default)('#thesaurus_tab .input-medium').val('');
(0, _jquery2.default)('#thesaurus_tab .gform').submit();
(0, _jquery2.default)('#thesaurus_tab .th_clear').hide();
});
(0, _jquery2.default)('.treeview>li.expandable>.hitarea').on('click', function () {
if ((0, _jquery2.default)(this).css('background-position') === '99% 22px') {
(0, _jquery2.default)(this).css('background-position', '99% -28px');
(0, _jquery2.default)(this).addClass('active');
} else {
(0, _jquery2.default)(this).css('background-position', '99% 22px');
(0, _jquery2.default)(this).removeClass('active');
}
});
};
appEvents.listenAll({
'thesaurus.show': thesaurusService.show
});
return { initialize: initialize };
};
exports.default = workzoneThesaurus;
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
var _sprintfJs = __webpack_require__(59);
var _phraseanetCommon = __webpack_require__(11);
var AppCommons = _interopRequireWildcard(_phraseanetCommon);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(19);
var thesaurusService = function thesaurusService(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var options = {};
var config = {};
var sbas = void 0;
var bas2sbas = void 0;
var trees = void 0; // @TODO remove global
var initialize = function initialize(params) {
var $container = params.$container;
config = configService.get('thesaurusConfig');
// set up thlist:
options.thlist = {};
options.tabs = null;
for (var db in config.availableDatabases) {
if (config.availableDatabases.hasOwnProperty(db)) {
var curDb = config.availableDatabases[db];
options.thlist['s' + curDb.id] = new ThesauThesaurusSeeker(curDb.id);
}
}
startThesaurus();
var cclicks = 0;
var cDelay = 350;
var cTimer = null;
/* unknown usefullness:*/
/*let bclicks = 0, bDelay = 350, bTimer = null;
$('body')
.on('click', '.thesaurus-from-facets-action', (event) => {
event.preventDefault();
bclicks++;
if(bclicks === 1) {
bTimer = setTimeout(function() {
thesau_clickThesaurus(event);
bclicks = 0;
}, bDelay);
} else {
console.log('double click')
clearTimeout(bTimer);
thesau_dblclickThesaurus(event);
bclicks = 0;
}
})*/
$container.on('click', '.thesaurus-branch-action', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
cclicks++;
if (cclicks === 1) {
cTimer = setTimeout(function () {
Xclick(event);
cclicks = 0;
}, cDelay);
} else {
clearTimeout(cTimer);
if ($el.data('context') === 'thesaurus') {
TXdblClick(event);
} else {
CXdblClick(event);
}
cclicks = 0;
}
}).on('dblclick', '.thesaurus-branch-action', function (event) {
// dbl is handled by click event
event.preventDefault();
}).on('click', '.thesaurus-cancel-wizard-action', function (event) {
// dbl is handled by click event
event.preventDefault();
thesauCancelWizard();
}).on('keyup', '.thesaurus-filter-suggest-action', function (event) {
event.preventDefault();
searchValue((0, _jquery2.default)(event.currentTarget).val());
}).on('submit', '.thesaurus-filter-submit-action', function (event) {
event.preventDefault();
T_Gfilter(event.currentTarget);
});
searchValue = _underscore2.default.debounce(searchValue, 300);
};
function show() {
// first show of thesaurus
if (options.currentWizard === '???') {
thesauShowWizard('wiz_0', false);
}
}
function thesauCancelWizard() {
thesauShowWizard('wiz_0', true);
}
function thesauShowWizard(wizard, refreshFilter) {
var offsetTabHeight = (0, _jquery2.default)('#THPD_tabs .ui-tabs-nav')[0].offsetHeight;
if (wizard !== options.currentWizard) {
(0, _jquery2.default)('#THPD_WIZARDS DIV.wizard', options.tabs).hide();
(0, _jquery2.default)('#THPD_WIZARDS .' + wizard, options.tabs).show();
(0, _jquery2.default)('#THPD_T', options.tabs).css('top', (0, _jquery2.default)('#THPD_WIZARDS', options.tabs).height() + offsetTabHeight);
(0, _jquery2.default)('#THPD_C', options.tabs).css('top', (0, _jquery2.default)('#THPD_WIZARDS', options.tabs).height() + offsetTabHeight);
options.currentWizard = wizard;
if (refreshFilter) {
searchValue((0, _jquery2.default)('#THPD_WIZARDS .gform', options.tabs).eq(0).val());
}
// browse
if (wizard === 'wiz_0') {
(0, _jquery2.default)('#THPD_WIZARDS .th_cancel', options.tabs).hide();
} else {
(0, _jquery2.default)('#THPD_WIZARDS .th_cancel', options.tabs).show();
}
// accept
if (wizard === 'wiz_1') {
(0, _jquery2.default)('#THPD_WIZARDS .th_ok', options.tabs).hide();
} else {
(0, _jquery2.default)('#THPD_WIZARDS .th_ok', options.tabs).show();
}
(0, _jquery2.default)('#THPD_WIZARDS FORM :text')[0].focus();
}
}
// here when the 'filter' forms is submited with key <enter> or button <ok>
// force immediate search
function T_Gfilter(o) {
var f;
if (o.nodeName === 'FORM') {
f = (0, _jquery2.default)(o).find('input[name=search_value]').val();
} else if (o.nodeName === 'INPUT') {
f = (0, _jquery2.default)(o).val();
}
searchValue(f);
switch (options.currentWizard) {
case 'wiz_0':
// browse
break;
case 'wiz_1':
// accept
break;
case 'wiz_2':
// replace
T_replaceBy2(f);
break;
default:
break;
}
}
// here when a key is pressed in the 'filter' form
var searchValue = function searchValue(f) {
switch (options.currentWizard) {
case 'wiz_0':
// browse
searchValueByMode(f, 'ALL');
break;
case 'wiz_1':
// accept
searchValueByMode(f, 'CANDIDATE');
break;
case 'wiz_2':
// replace
searchValueByMode(f, 'CANDIDATE');
break;
default:
break;
}
};
function T_replaceBy2(f) {
if (trees.C._selInfos.n !== 1) {
return;
}
var term = trees.C._selInfos.sel.eq(0).find('span span').html();
var cid = trees.C._selInfos.sel[0].getAttribute('id').split('.');
cid.shift();
var sbas = cid.shift();
cid = cid.join('.');
trees.C._toReplace = { sbas: sbas, cid: cid, replaceby: f };
var msg = (0, _sprintfJs.sprintf)(config.replaceMessage, { from: term, to: f });
var confirmBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
cancelButton: true,
buttons: {
Ok: function Ok() {
confirmBox.close();
T_replaceCandidates_OK();
}
}
});
confirmBox.setContent(msg);
}
function searchValueByMode(f, mode) {
if (mode === 'ALL') {
(function () {
var type = void 0;
var id = void 0;
var z = '';
if ((0, _jquery2.default)('.ui-tabs-nav li.ui-state-active a', options.tabs).attr('href') === '#THPD_T') {
//thesaurus
type = 'TH';
id = 'T';
} else {
//candidate
type = 'CT';
id = 'C';
}
// search in every base, everywhere
for (var i in sbas) {
var _zurl = '/xmlhttp/search_term_prod.j.php' + '?sbid=' + sbas[i].sbid + '&typ=' + type + '&id=' + id + '&t=' + encodeURIComponent(f);
(0, _jquery2.default)('#THPD_T_treeBox').addClass('loading');
sbas[i].seeker = _jquery2.default.ajax({
url: _zurl,
type: 'POST',
data: [],
dataType: 'json',
success: function success(j) {
var z = '#TX_P\\.' + j.parm.sbid + '\\.T';
if (type === 'TH') {
z = '#TX_P\\.' + j.parm.sbid + '\\.' + id;
} else {
z = '#CX_P\\.' + j.parm.sbid + '\\.' + id;
}
var o = (0, _jquery2.default)(z);
var isLast = o.hasClass('last');
o.replaceWith(j.html);
if (isLast) {
(0, _jquery2.default)(z).addClass('last');
}
},
complete: function complete() {
(0, _jquery2.default)('#THPD_T_treeBox').removeClass('loading');
}
});
}
})();
} else if (mode === 'CANDIDATE') {
// search only on the good base and the good branch(es)
for (var i in sbas) {
var zurl = '/xmlhttp/search_term_prod.j.php?sbid=' + sbas[i].sbid + '&typ=TH' + '&id=T';
(0, _jquery2.default)('#THPD_T_treeBox').addClass('loading');
if (sbas[i].sbid === trees.C._selInfos.sbas) {
zurl += '&t=' + encodeURIComponent(f) + '&field=' + encodeURIComponent(trees.C._selInfos.field);
}
sbas[i].seeker = _jquery2.default.ajax({
url: zurl,
type: 'POST',
data: [],
dataType: 'json',
success: function success(j) {
var z = '#TX_P\\.' + j.parm.sbid + '\\.T';
var o = (0, _jquery2.default)(z);
var isLast = o.hasClass('last');
o.replaceWith(j.html);
if (isLast) {
(0, _jquery2.default)(z).addClass('last');
}
},
complete: function complete() {
(0, _jquery2.default)('#THPD_T_treeBox').removeClass('loading');
}
});
}
}
}
// ======================================================================================================
function T_replaceCandidates_OK() {
var replacingBox = _dialog2.default.create(services, {
size: 'Alert'
});
replacingBox.setContent(config.replaceInProgressMsg);
var parms = {
url: '/xmlhttp/replacecandidate.j.php',
data: {
'id[]': trees.C._toReplace.sbas + '.' + trees.C._toReplace.cid,
t: trees.C._toReplace.replaceby,
debug: '0'
},
async: false,
cache: false,
dataType: 'json',
timeout: 10 * 60 * 1000, // 10 minutes !
success: function success(result, textStatus) {
trees.C._toReplace = null;
thesauShowWizard('wiz_0', false);
replacingBox.close();
if (result.msg !== '') {
var alert = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true
});
alert.setContent(result.msg);
}
for (var i in result.ctermsDeleted) {
var cid = '#CX_P\\.' + result.ctermsDeleted[i].replace(new RegExp('\\.', 'g'), '\\.'); // escape les '.' pour jquery
(0, _jquery2.default)(cid).remove();
}
},
_ret: null // private alchemy
};
_jquery2.default.ajax(parms);
}
function T_acceptCandidates_OK() {
var same_sbas = true;
var acceptingBox = _dialog2.default.create(services, {
size: 'Alert'
});
acceptingBox.setContent(config.acceptMsg);
var t_ids = [];
var dst = trees.C._toAccept.dst.split('.');
dst.shift();
var sbid = dst.shift();
dst = dst.join('.');
// obviously the candidates and the target already complies (same sbas, good tbranch)
trees.C._selInfos.sel.each(function () {
var x = this.getAttribute('id').split('.');
x.shift();
if (x.shift() !== sbid) {
same_sbas = false;
}
t_ids.push(x.join('.'));
});
if (!same_sbas) {
return;
}
var parms = {
url: '/xmlhttp/acceptcandidates.j.php',
data: {
// "debug": false,
sbid: sbid,
tid: dst,
'cid[]': t_ids,
typ: trees.C._toAccept.type,
piv: trees.C._toAccept.lng
},
async: false,
cache: false,
dataType: 'json',
success: function success(result, textStatus) {
for (var i in result.refresh) {
var zurl = '/xmlhttp/openbranch_prod.j.php' + '?type=' + result.refresh[i].type + '&sbid=' + result.refresh[i].sbid + '&sortsy=1' + '&id=' + encodeURIComponent(result.refresh[i].id);
_jquery2.default.get(zurl, [], function (j) {
var z = '#' + j.parm.type + 'X_P\\.' + j.parm.sbid + '\\.' + j.parm.id.replace(new RegExp('\\.', 'g'), '\\.'); // escape les '.' pour jquery
(0, _jquery2.default)(z).children('ul').eq(0).replaceWith(j.html);
}, 'json');
}
trees.C._toAccept = null;
thesauShowWizard('wiz_0', false);
acceptingBox.close();
},
error: function error() {
acceptingBox.close();
},
timeout: function timeout() {
acceptingBox.close();
},
_ret: null // private alchemy
};
_jquery2.default.ajax(parms);
}
function C_deleteCandidates_OK() {
var deletingBox = _dialog2.default.create(services, {
size: 'Alert'
});
deletingBox.setContent(config.deleteMsg);
var t_ids = [];
var lisel = trees.C.tree.find('LI .selected');
trees.C.tree.find('LI .selected').each(function () {
var x = this.getAttribute('id').split('.');
x.shift();
t_ids.push(x.join('.'));
});
var parms = {
url: '/xmlhttp/replacecandidate.j.php',
data: { 'id[]': t_ids },
async: false,
cache: false,
dataType: 'json',
timeout: 10 * 60 * 1000, // 10 minutes !
success: function success(result, textStatus) {
deletingBox.close();
if (result.msg !== '') {
var alert = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true
});
alert.setContent(result.msg);
}
for (var i in result.ctermsDeleted) {
var cid = '#CX_P\\.' + result.ctermsDeleted[i].replace(new RegExp('\\.', 'g'), '\\.'); // escape les '.' pour jquery
(0, _jquery2.default)(cid).remove();
}
},
_ret: null
};
_jquery2.default.ajax(parms);
}
// menu option T:accept as...
function T_acceptCandidates(menuItem, menu, type) {
var lidst = trees.T.tree.find('LI .selected');
if (lidst.length !== 1) {
return;
}
var lisel = trees.C.tree.find('LI .selected');
if (lisel.length === 0) {
return;
}
var msg;
if (lisel.length === 1) {
var term = lisel.eq(0).find('span span').html();
msg = (0, _sprintfJs.sprintf)(config.candidateUniqueMsg, term);
} else {
msg = (0, _sprintfJs.sprintf)(config.candidateManyMsg, lisel.length);
}
trees.C._toAccept.type = type;
trees.C._toAccept.dst = lidst.eq(0).attr('id');
var confirmBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
cancelButton: true,
buttons: {
Ok: function Ok() {
confirmBox.close();
T_acceptCandidates_OK();
}
}
});
confirmBox.setContent(msg);
}
// menu option T:search
function T_search(menuItem, menu, cmenu, e, label) {
if (!menu._li) {
return;
}
var tcids = menu._li.attr('id').split('.');
tcids.shift();
var sbid = tcids.shift();
var term = menu._li.find('span span').html();
doThesSearch('T', sbid, term, null);
}
function C_MenuOption(menuItem, menu, option, parm) {
// nothing selected in candidates ?
if (!trees.C._selInfos) {
return;
}
trees.C._toAccept = null; // cancel previous 'accept' action anyway
trees.C._toReplace = null; // cancel previous 'replace' action anyway
// display helpful message into the thesaurus box...
var msg = void 0;
var term = void 0;
switch (option) {
case 'ACCEPT':
// glue selection to the tree
trees.C._toAccept = { lng: parm.lng };
if (trees.C._selInfos.n === 1) {
msg = (0, _sprintfJs.sprintf)(config.acceptCandidateUniqueMsg, menu._srcElement.find('span').html());
} else {
msg = (0, _sprintfJs.sprintf)(config.acceptCandidateManyMsg, trees.C._selInfos.n);
}
// set the content of the wizard
(0, _jquery2.default)('#THPD_WIZARDS .wiz_1 .txt').html(msg);
// ... and switch to the thesaurus tab
options.tabs.tabs('option', 'active', 0);
thesauShowWizard('wiz_1', true);
break;
case 'REPLACE':
if (trees.C._selInfos.n === 1) {
term = trees.C._selInfos.sel.eq(0).find('span span').html();
msg = (0, _sprintfJs.sprintf)(config.replaceCandidateUniqueMsg, term);
} else {
msg = (0, _sprintfJs.sprintf)(config.replaceCandidateManyMsg, trees.C._selInfos.n);
}
options.tabs.tabs('option', 'active', 0);
// set the content of the wizard
(0, _jquery2.default)('#THPD_WIZARDS .wiz_2 .txt').html(msg);
// ... and switch to the thesaurus tab
thesauShowWizard('wiz_2', true);
break;
case 'DELETE':
(0, _jquery2.default)('#THPD_WIZARDS DIV', options.tabs).hide();
if (trees.C._selInfos.n === 1) {
term = trees.C._selInfos.sel.eq(0).find('span span').html();
msg = (0, _sprintfJs.sprintf)(config.deleteCandidateUniqueMsg, term);
} else {
msg = (0, _sprintfJs.sprintf)(config.deleteCandidateManyMsg, trees.C._selInfos.n);
}
var confirmBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
cancelButton: true,
buttons: {
Ok: function Ok() {
confirmBox.close();
C_deleteCandidates_OK();
}
}
});
confirmBox.setContent(msg);
break;
default:
}
}
function Xclick(e) {
var x = e.srcElement ? e.srcElement : e.target;
var li = (0, _jquery2.default)(x).closest('li');
var tids = li.attr('id').split('.');
var type = void 0;
switch (x.nodeName) {
case 'DIV':
// +/-
var tid = tids.shift();
var sbid = tids.shift();
type = tid.substr(0, 1);
// TX_P ou CX_P
if ((type === 'T' || type === 'C') && tid.substr(1, 4) === 'X_P') {
var ul = li.children('ul').eq(0);
if (ul.css('display') === 'none' || AppCommons.utilsModule.is_ctrl_key(e)) {
if (AppCommons.utilsModule.is_ctrl_key(e)) {
ul.text(config.loadingMsg);
li.removeAttr('loaded');
}
ul.show();
if (!li.attr('loaded')) {
var zurl = '/xmlhttp/openbranch_prod.j.php?type=' + type + '&sbid=' + sbid + '&id=' + encodeURIComponent(tids.join('.'));
if (li.hasClass('last')) {
zurl += '&last=1';
}
zurl += '&sortsy=1';
_jquery2.default.get(zurl, [], function (j) {
ul.replaceWith(j.html);
li.attr('loaded', '1');
}, 'json');
}
} else {
ul.hide();
}
}
break;
case 'SPAN':
type = tids[0].substr(0, 1);
if (type === 'T' && tids.length > 2 || tids.length === 4) {
tids.pop();
var tid3 = tids.join('.');
if (!AppCommons.utilsModule.is_ctrl_key(e) && !AppCommons.utilsModule.is_shift_key(e)) {
(0, _jquery2.default)('LI', trees[type].tree).removeClass('selected');
options.lastClickedCandidate = null;
} else {
// if($("#THPD_C_treeBox")._lastClicked)
if (options.lastClickedCandidate !== null) {
if (options.lastClickedCandidate.tid3 !== tid3) {
(0, _jquery2.default)('LI', trees[type].tree).removeClass('selected');
options.lastClickedCandidate = null;
} else {
if (e.shiftKey) {
var lip = li.parent().children('li');
var idx0 = lip.index(options.lastClickedCandidate.item);
var idx1 = lip.index(li);
if (idx0 < idx1) {
lip.filter(function (index) {
return index >= idx0 && index < idx1;
}).addClass('selected');
} else {
lip.filter(function (index) {
return index > idx1 && index <= idx0;
}).addClass('selected');
}
}
}
}
}
li.toggleClass('selected');
if (type === 'C') {
options.lastClickedCandidate = { item: li, tid3: tid3 };
}
}
break;
default:
break;
}
}
function TXdblClick(e) {
var x = e.srcElement ? e.srcElement : e.target;
var tid = (0, _jquery2.default)(x).closest('li').attr('id');
var term = void 0;
switch (x.nodeName) {
case 'SPAN':
// term
switch (options.currentWizard) {
case 'wiz_0':
// simply browse
if (tid.substr(0, 5) === 'TX_P.') {
var tids = tid.split('.');
if (tids.length > 3) {
var sbid = tids[1];
term = (0, _jquery2.default)(x).hasClass('separator') ? (0, _jquery2.default)(x).prev().text() : (0, _jquery2.default)(x).text();
doThesSearch('T', sbid, term, null);
}
}
break;
case 'wiz_2':
// replace by
if (tid.substr(0, 5) === 'TX_P.') {
term = (0, _jquery2.default)(x).text();
(0, _jquery2.default)('#THPD_WIZARDS .wiz_2 :text').val(term);
T_replaceBy2(term);
}
break;
default:
}
break;
default:
break;
}
}
function CXdblClick(e) {
var x = e.srcElement ? e.srcElement : e.target;
switch (x.nodeName) {
case 'SPAN':
// term
var li = (0, _jquery2.default)(x).closest('li');
var field = li.closest('[field]').attr('field');
if (typeof field !== 'undefined') {
var tid = li.attr('id');
if (tid.substr(0, 5) === 'CX_P.') {
var sbid = tid.split('.')[1];
var term = (0, _jquery2.default)(x).text();
doThesSearch('C', sbid, term, field);
}
}
break;
default:
break;
}
}
function doThesSearch(type, sbid, term, field) {
appEvents.emit('searchAdvancedForm.activateDatabase', { databases: [sbid] });
var queryString = '';
if (type === 'T') {
queryString = '[' + term + ']';
} else {
queryString = field + '="' + term + '"';
}
appEvents.emit('facets.doResetSelectedFacets');
(0, _jquery2.default)('#EDIT_query').val(queryString);
appEvents.emit('searchAdvancedForm.checkFilters');
appEvents.emit('search.doNewSearch', queryString);
//searchModule.newSearch(v);
}
/* unknown usefullness:
function thesau_clickThesaurus(event) // onclick dans le thesaurus
{
// on cherche ou on a clique
for(var e=event.srcElement ? event.srcElement : event.target; e && ((!e.tagName) || (!e.id)); e=e.parentNode)
;
if(e)
{
switch(e.id.substr(0,4))
{
case "TH_P": // +/- de deploiement de mot
js = "thesau_thesaurus_ow('"+e.id.substr(5)+"')";
self.setTimeout(js, 10);
break;
}
}
return(false);
}
function thesau_dblclickThesaurus(event) // onclick dans le thesaurus
{
var err;
try
{
options.lastTextfocus.focus();
}
catch(err)
{
return;
}
// on cherche ou on a clique
for(var e=event.srcElement; e && ((!e.tagName) || (!e.id)); e=e.parentNode)
;
if(e)
{
switch(e.id.substr(0,4))
{
case "GL_W": // double click sur le mot
var t = e.id.split(".");
t.shift();
var sbid = t.shift();
var thid = t.join(".");
var url = "/xmlhttp/getsy_prod.x.php";
var parms = "bid=" + sbid + "&id=" + thid;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send(parms);
var ret = xmlhttp.responseXML;
result = ret.getElementsByTagName("result");
if(result.length==1)
{
val = result.item(0).getAttribute("t");
replaceEditSel(val);
}
break;
}
}
return(false);
}
function replaceEditSel(value)
{
if(!options.lastTextfocus || !options.lastTextfocus.selectedTerm)
return;
options.lastTextfocus.value = options.lastTextfocus.value.substr(0, options.lastTextfocus.selectedTerm.start) + value + options.lastTextfocus.value.substr(options.lastTextfocus.selectedTerm.end);
if(typeof(document.selection) != 'undefined')
{
// explorer
var range = options.lastTextfocus.createTextRange();
range.move('character', options.lastTextfocus.selectedTerm.start + value.length);
range.select();
}
else if(typeof(options.lastTextfocus.selectionStart) != 'undefined')
{
// gecko (safari)
options.lastTextfocus.selectionStart = options.lastTextfocus.selectionEnd = options.lastTextfocus.selectedTerm.start + value.length;
}
cbEditing2(options.lastTextfocus, "MOUSEUP"); // force le calcul de la nouvelle selection
options.lastTextfocus.focus();
return;
}
function thesau_thesaurus_ow(id) // on ouvre ou ferme une branche de thesaurus
{
var o = document.getElementById("TH_K."+id);
if(o.className=="o")
{
// on ferme
o.className = "c";
document.getElementById("TH_P."+id).innerHTML = "+";
document.getElementById("TH_K."+id).innerHTML = config.loadingMsg;
}
else if(o.className=="c" || o.className=="h")
{
// on ouvre
o.className = "o";
document.getElementById("TH_P."+id).innerHTML = "-";
var t_id = id.split(".");
var sbas_id = t_id[0];
t_id.shift();
var thid = t_id.join(".");
var url = "/xmlhttp/getterm_prod.x.php";
var parms = "bid=" + sbas_id;
parms += "&lng="+p4.lng;
parms += "&sortsy=1";
parms += "&id=" + thid;
parms += "&typ=TH";
options.thlist['s'+sbas_id].openBranch(id, thid);
}
return(false);
}
function cbEditing2(textarea, act)
{
var sbas_id = p4.edit.sbas_id;
tmpCurField = 0;
if(textarea.id=="idZTextArea")
{
tmpCurField = p4.edit.curField ;
}
else
{
if(textarea.id=="idZTextAreaReg")
tmpCurField = p4.edit.curFieldReg;
}
options.lastTextfocus = textarea;
textarea.selectedTerm = null;
var p0 = -1;
var p1 = -1;
if(typeof(document.selection) != 'undefined')
{
// ici si explorer
var range = document.selection.createRange();
var i;
var oldrange = range.duplicate();
for(i=0; i<200; i++, p0++)
{
pe = range.parentElement();
if(pe != textarea)
break;
range.moveStart("character", -1);
}
range = oldrange.duplicate();
for(i=0; i<200; i++, p1++)
{
pe = range.parentElement();
if(pe != textarea)
break;
range.moveEnd("character", -1);
}
}
else if(typeof(textarea.selectionStart) != "undefined")
{
// ici si gecko (safari)
p0 = textarea.selectionStart;
p1 = textarea.selectionEnd;
}
if(p0 != -1 && p1 != -1)
{
var c;
// on etend les positions a tout le keyword (entre ';')
t = textarea.value;
l = t.length;
for( ; p0 > 0; p0--)
{
c = t.charCodeAt(p0-1);
if(c==59 || c==10 || c==13) // 59==";"
break;
}
for( ; p1 < l; p1++)
{
c = t.charCodeAt(p1);
if(c==59 || c==10 || c==13)
break;
}
// on copie le resultat dans le textarea
textarea.selectedTerm = { start:p0, end:p1 };
// on cherche le terme dans le thesaurus
var zText = textarea.value.substr(p0, p1-p0);
if(document.forms["formSearchTH"].formSearchTHck.checked)
{
if(zText && zText.length>2 && document.forms["formSearchTH"].formSearchTHfld.value != zText)
{
document.forms["formSearchTH"].formSearchTHfld.value = zText;
document.getElementById("TH_searching").src = "/assets/common/images/icons/ftp-loader.gif";
options.thlist['s'+sbas_id].search(zText);
}
}
}
return(true);
}
*/
function ThesauThesaurusSeeker(sbas_id) {
this.sbas_id = sbas_id;
this._ctimer = null;
this._xmlhttp = null;
this.tObj = { TH_searching: null, TH_P: null, TH_K: null };
this.search = function (txt) {
var _this = this;
if (this._ctimer) {
clearTimeout(this._ctimer);
}
this._ctimer = setTimeout(function () {
return options.thlist['s' + _this.sbas_id].search_delayed('"' + txt.replace("'", "\\'") + '"');
}, 100);
};
this.search_delayed = function (txt) {
var me = this;
if (this._xmlttp.abort && typeof this._xmlttp.abort === 'function') {
this._xmlhttp.abort();
}
var url = '/xmlhttp/openbranches_prod.x.php';
var parms = {
bid: this.sbas_id,
t: txt,
mod: 'TREE'
};
this._xmlhttp = _jquery2.default.ajax({
url: url,
type: 'POST',
data: parms,
success: function success(ret) {
me.xmlhttpstatechanged(ret);
},
error: function error() {},
timeout: function timeout() {}
});
this._ctimer = null;
};
this.openBranch = function (id, thid) {
var me = this;
if (this._xmlttp.abort && typeof this._xmlttp.abort === 'function') {
this._xmlhttp.abort();
}
var url = '/xmlhttp/getterm_prod.x.php';
var parms = {
bid: this.sbas_id,
sortsy: 1,
id: thid,
typ: 'TH'
};
this._xmlhttp = _jquery2.default.ajax({
url: url,
type: 'POST',
data: parms,
success: function success(ret) {
me.xmlhttpstatechanged(ret, id);
},
error: function error() {},
timeout: function timeout() {}
});
};
this.xmlhttpstatechanged = function (ret, id) {
try {
if (!this.tObj.TH_searching) {
this.tObj.TH_searching = document.getElementById('TH_searching');
}
this.tObj.TH_searching.src = '/assets/common/images/icons/ftp-loader-blank.gif';
// && (typeof(ret.parsed)=="undefined" || ret.parsed))
if (ret) {
var htmlnodes = ret.getElementsByTagName('html');
var htmlnode = htmlnodes.item(0).firstChild;
if (htmlnodes && htmlnodes.length === 1 && htmlnode) {
if (typeof id === 'undefined') {
// called from search or 'auto' : full thesaurus search
if (!this.tObj.TH_P) {
this.tObj.TH_P = document.getElementById('TH_P.' + this.sbas_id + '.T');
}
if (!this.tObj.TH_K) {
this.tObj.TH_K = document.getElementById('TH_K.' + this.sbas_id + '.T');
}
this.tObj.TH_P.innerHTML = '...';
this.tObj.TH_K.className = 'h';
this.tObj.TH_K.innerHTML = htmlnode.nodeValue;
} else {
// called from 'openBranch'
// var js = "document.getElementById('TH_K."+thid+"').innerHTML = \""+htmlnode.nodeValue+"\"";
// self.setTimeout(js, 10);
document.getElementById('TH_K.' + id).innerHTML = htmlnode.nodeValue;
}
}
}
} catch (err) {}
};
}
function startThesaurus() {
options.thlist = config.thlist;
options.currentWizard = '???';
sbas = config.sbas;
bas2sbas = config.bas2sbas;
options.lastTextfocus = null;
options.lastClickedCandidate = null;
options.tabs = (0, _jquery2.default)('#THPD_tabs');
options.tabs.tabs();
trees = {
T: {
tree: (0, _jquery2.default)('#THPD_T_tree', options.tabs)
},
C: {
tree: (0, _jquery2.default)('#THPD_C_tree', options.tabs),
// may contain : {'type', 'dst', 'lng'}
_toAccept: null,
_toReplace: null,
// may contain : {'sel':lisel, 'field':field, 'sbas':sbas, 'n':lisel.length}
_selInfos: null
}
};
trees.T.tree.contextMenu([{
label: config.searchMsg,
onclick: function onclick(menuItem, menu, cmenu, e, label) {
T_search(menuItem, menu, cmenu, e, label);
}
}, {
label: config.acceptSpecificTermMsg,
onclick: function onclick(menuItem, menu) {
T_acceptCandidates(menuItem, menu, 'TS');
}
}, {
label: config.acceptSynonymeMsg,
onclick: function onclick(menuItem, menu) {
T_acceptCandidates(menuItem, menu, 'SY');
}
}], {
className: 'THPD_TMenu',
beforeShow: function beforeShow() {
var menuOptions = (0, _jquery2.default)(this.menu).find('.context-menu-item');
menuOptions.eq(1).addClass('context-menu-item-disabled');
menuOptions.eq(2).addClass('context-menu-item-disabled');
var x = this._showEvent.srcElement ? this._showEvent.srcElement : this._showEvent.target;
var li = (0, _jquery2.default)(x).closest('li');
this._li = null;
var tcids = li.attr('id').split('.');
if (tcids.length > 2 && tcids[0] === 'TX_P' && tcids[2] !== 'T' && x.nodeName !== 'LI') {
this._li = li;
tcids.shift();
var sbas = tcids.shift();
// this._srcElement = li; // private alchemy
if (!li.hasClass('selected')) {
// rclick OUTSIDE the selection : unselect all
trees.T.tree.find('LI').removeClass('selected');
(0, _jquery2.default)('li', trees.T.tree).removeClass('selected');
li.addClass('selected');
}
if (trees.C._selInfos && trees.C._selInfos.sbas === sbas) {
// whe check if the candidates can be validated here
// aka does the tbranch of the field (of candidates) reaches the paste location ?
var parms = {
url: '/xmlhttp/checkcandidatetarget.j.php' + '?sbid=' + sbas + '&acf=' + encodeURIComponent(trees.C._selInfos.field) + '&id=' + encodeURIComponent(tcids.join('.')),
data: [],
async: false,
cache: false,
dataType: 'json',
timeout: 1000,
success: function success(result, textStatus) {
this._ret = result;
if (result.acceptable) {
menuOptions.eq(1).removeClass('context-menu-item-disabled');
menuOptions.eq(2).removeClass('context-menu-item-disabled');
}
},
_ret: null // private alchemy
};
_jquery2.default.ajax(parms);
}
}
return true;
}
});
var contextMenu = [];
for (var i = 0; i < config.langContextMenu.length; i++) {
var langPlist = config.langContextMenu[i];
contextMenu.push({
label: langPlist.label,
onclick: function onclick(menuItem, menu) {
C_MenuOption(menuItem, menu, 'ACCEPT', {
lng: langPlist.lngCode
});
}
});
}
contextMenu.push({
label: config.replaceWithMsg,
// disabled:true,
onclick: function onclick(menuItem, menu) {
C_MenuOption(menuItem, menu, 'REPLACE', null);
}
});
contextMenu.push({
label: config.removeActionMsg,
// disabled:true,
onclick: function onclick(menuItem, menu) {
C_MenuOption(menuItem, menu, 'DELETE', null);
}
});
trees.C.tree.contextMenu(contextMenu, {
beforeShow: function beforeShow() {
var ret = false;
var x = this._showEvent.srcElement ? this._showEvent.srcElement : this._showEvent.target;
var li = (0, _jquery2.default)(x).closest('li');
if (!li.hasClass('selected')) {
// rclick OUTSIDE the selection : unselect all
// lisel.removeClass('selected');
trees.C.tree.find('LI').removeClass('selected');
options.lastClickedCandidate = null;
}
var tcids = li.attr('id').split('.');
if (tcids.length === 4 && tcids[0] === 'CX_P' && x.nodeName !== 'LI') {
// candidate context menu only clicking on final term
if (!li.hasClass('selected')) {
li.addClass('selected');
}
// this._cutInfos = { sbid:tcids[1], field:li.parent().attr('field') }; // private alchemy
this._srcElement = li; // private alchemy
// as selection changes, compute usefull info (field, sbas)
var lisel = trees.C.tree.find('LI .selected');
if (lisel.length > 0) {
// lisel are all from the same candidate field, so check the first li
var li0 = lisel.eq(0);
var field = li0.parent().attr('field');
var sbas = li0.attr('id').split('.')[1];
// glue selection info to the tree
trees.C._selInfos = {
sel: lisel,
field: field,
sbas: sbas,
n: lisel.length
};
if (lisel.length === 1) {
(0, _jquery2.default)(this.menu).find('.context-menu-item').eq(config.languagesCount).removeClass('context-menu-item-disabled');
} else {
(0, _jquery2.default)(this.menu).find('.context-menu-item').eq(config.languagesCount).addClass('context-menu-item-disabled');
}
} else {
trees.C._selInfos = null;
}
ret = true;
}
return ret;
}
});
}
return { initialize: initialize, show: show };
};
exports.default = thesaurusService;
/***/ }),
/* 96 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 97 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/*!
* jquery.fancytree.js
* Dynamic tree view control, with support for lazy loading of branches.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2006-2014, Martin Wendt (http://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version @VERSION
* @date @DATE
*/
/** Core Fancytree module.
*/
// Start of local namespace
;(function($, window, document, undefined) {
"use strict";
// prevent duplicate loading
if ( $.ui && $.ui.fancytree ) {
$.ui.fancytree.warn("Fancytree: ignored duplicate include");
return;
}
/* *****************************************************************************
* Private functions and variables
*/
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);
}
}
}
/*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;
}
/** Return a wrapper that calls sub.methodName() and exposes
* this : tree
* this._local : tree.ext.EXTNAME
* this._super : base.methodName()
*/
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);
};
// Return the wrapper function
return function(){
var prevLocal = tree._local,
prevSuper = tree._super;
try{
tree._local = _local;
tree._super = _super;
return baseFunc.apply(tree, arguments);
}finally{
tree._local = prevLocal;
tree._super = prevSuper;
}
};
})(); // 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();
}else{
return $.Deferred(function(){this.resolveWith(context, argArray);}).promise();
}
}
function _getRejectedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.reject();}).promise();
}else{
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
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;
}
// 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);
};
}
var i,
FT = null, // initialized below
ENTITY_MAP = {"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;", "/": "&#x2F;"},
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: "=",
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: "'"},
//boolean attributes that can be set with equivalent class names in the LI tags
CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),
CLASS_ATTR_MAP = {},
// Top-level Fancytree node attributes, that can be set by dict
NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "),
NODE_ATTR_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++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; }
/* *****************************************************************************
* 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 Addtional CSS classes, added to the node's `&lt;span>`
* @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
* Note: Also non-folders may have children.
* @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'.
* @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 banner
*/
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 occured
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];
}
// 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] && !$.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
this.children = null;
cl = obj.children;
if(cl && cl.length){
this._setChildren(cl);
}
// 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]));
}
},
/**
* 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,
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{
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( !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();
}
return firstNode;
},
/**
* 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);
},
/**
* 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");
},
/**
* 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){
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) 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 >= 2 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.tree.options.debugLevel >= 2 ) {
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();
},
// TODO: expand(flag)
/**Find all nodes that contain `match` in the title.
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
* @see FancytreeNode#findAll
*/
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 contains `match` in the title (not including self).
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @example
* <b>fat</b> text
*/
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;
},
/* Apply selection state (internal use only) */
_changeSelectStatusAttrs: function (state) {
var changed = false;
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() {
var flag = this.isSelected();
// this.debug("fixSelection3AfterClick()");
this.visit(function(node){
node._changeSelectStatusAttrs(flag);
});
this.fixSelection3FromEndNodes();
},
/**
* 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() {
// this.debug("fixSelection3FromEndNodes()");
_assert(this.tree.options.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,
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( s !== false ) {
someSelected = true;
}
if( s !== true ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
}else{
// This is an end-node: simply report the status
// state = ( node.unselectable ) ? undefined : !!node.selected;
state = !!node.selected;
}
node._changeSelectStatusAttrs(state);
return state;
}
_walk(this);
// Update parent's state
this.visitParents(function(node){
var i, l, child, state,
children = node.children,
allSelected = true,
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// When fixing the parents, we trust the sibling status (i.e.
// we don't recurse)
if( child.selected || child.partsel ) {
someSelected = true;
}
if( !child.unselectable && !child.selected ) {
allSelected = false;
}
}
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').
* @returns {string}
*/
getIndexHier: function(separator) {
separator = separator || ".";
var res = [];
$.each(this.getParentList(false, true), function(i, o){
res.push(o.getIndex() + 1);
});
return res.join(separator);
},
/** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32".
* @param {boolean} [excludeSelf=false]
* @returns {string}
*/
getKeyPath: function(excludeSelf) {
var path = [],
sep = this.tree.options.keyPathSeparator;
this.visitParents(function(n){
if(n.parent){
path.unshift(n.key);
}
}, !excludeSelf);
return sep + path.join(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 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 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 keyboard focus.
* @returns {boolean}
*/
hasFocus: function() {
return (this.tree.hasFocus() && this.tree.focusNode === this);
},
/** Write to browser console if debugLevel >= 1 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.tree.options.debugLevel >= 1 ) {
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 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;
}
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 this is the (invisible) system root node.
* @returns {boolean}
*/
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', or 'error' (node.statusNodeType contains the type).
* @returns {boolean}
*/
isStatusNode: function() {
return !!this.statusNodeType;
},
/** Return true if this a top level node, i.e. a direct child of the (invisible) system root node.
* @returns {boolean}
*/
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,
parents = this.getParentList(false, false);
for(i=0, l=parents.length; i<l; i++){
if( ! parents[i].expanded ){ return false; }
}
return true;
},
/** Deprecated.
* @deprecated since 2014-02-16: use load() instead.
*/
lazyLoad: function(discard) {
this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead.");
return this.load(discard);
},
/**
* Load all children of a lazy node if neccessary. The *expanded* state is maintained.
* @param {boolean} [forceReload=false] Pass true to discard any existing nodes before.
* @returns {$.Promise}
*/
load: function(forceReload) {
var res, source,
that = this;
_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( this.expanded ) {
res.always(function(){
that.render();
});
}
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,
that = 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--){
// that.debug("pushexpand" + parents[i]);
deferreds.push(parents[i].setExpanded(true, opts));
}
$.when.apply($, deferreds).done(function(){
// All expands have finished
// that.debug("expand DONE", scroll);
if( scroll ){
that.scrollIntoView(effects).done(function(){
// that.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'.
* '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";
}
var pos,
prevParent = this.parent,
targetParent = (mode === "child") ? targetNode : targetNode.parent;
if(this === targetNode){
return;
}else if( !this.parent ){
throw "Cannot move system root";
}else if( targetParent.isDescendantOf(this) ){
throw "Cannot move a node to its own descendant";
}
// 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);
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);
targetParent.children.splice(pos, 0, this);
break;
case "after":
// Insert this node after target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0);
targetParent.children.splice(pos+1, 0, this);
break;
default:
throw "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);
}
// Handle cross-tree moves
if( this.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 experimantal!");
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);
// }
// 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.
*
* @param {number} where The keyCode that would normally trigger this move,
* e.g. `$.ui.keyCode.LEFT` would collapse the node if it
* is expanded or move to the parent oterwise.
* @param {boolean} [activate=true]
* @returns {$.Promise}
*/
// navigate: function(where, activate) {
// console.time("navigate")
// this._navigate(where, activate)
// console.timeEnd("navigate")
// },
navigate: function(where, activate) {
var i, parents,
handled = true,
KC = $.ui.keyCode,
sib = null;
// Navigate to node
function _goto(n){
if( n ){
try { n.makeVisible(); } catch(e) {} // #272
// Node may still be hidden by a filter
if( ! $(n.span).is(":visible") ) {
n.debug("Navigate: skipping hidden node");
n.navigate(where, activate);
return;
}
return activate === false ? n.setFocus() : n.setActive();
}
}
switch( where ) {
case KC.BACKSPACE:
if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.LEFT:
if( this.expanded ) {
this.setExpanded(false);
_goto(this);
} else if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.RIGHT:
if( !this.expanded && (this.children || this.lazy) ) {
this.setExpanded();
_goto(this);
} else if( this.children && this.children.length ) {
_goto(this.children[0]);
}
break;
case KC.UP:
sib = this.getPrevSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getPrevSibling();
}
while( sib && sib.expanded && sib.children && sib.children.length ) {
sib = sib.children[sib.children.length - 1];
}
if( !sib && this.parent && this.parent.parent ){
sib = this.parent;
}
_goto(sib);
break;
case KC.DOWN:
if( this.expanded && this.children && this.children.length ) {
sib = this.children[0];
} else {
parents = this.getParentList(false, true);
for(i=parents.length-1; i>=0; i--) {
sib = parents[i].getNextSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getNextSibling();
}
if( sib ){ break; }
}
}
_goto(sib);
break;
default:
handled = false;
}
},
/**
* 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);
},
/**
* 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.
* <li>If a node was created/removed, node.render() must be called <i>on the parent</i>.
* </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).
* @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);
},
/**
* 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:
throw "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) ) {
this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead.");
options = {topNode: options};
}
// this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent);
// this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container;
var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop,
opts = $.extend({
effects: (effects === true) ? {duration: 200, queue: false} : effects,
scrollOfs: this.tree.options.scrollOfs,
scrollParent: this.tree.options.scrollParent || this.tree.$container,
topNode: null
}, options),
dfd = new $.Deferred(),
that = this,
nodeHeight = $(this.span).height(),
$container = $(opts.scrollParent),
topOfs = opts.scrollOfs.top || 0,
bottomOfs = opts.scrollOfs.bottom || 0,
containerHeight = $container.height(),// - topOfs - bottomOfs,
scrollTop = $container.scrollTop(),
$animateTarget = $container,
isParentWindow = $container[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( isParentWindow ) {
nodeY = $(this.span).offset().top;
topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0;
$animateTarget = $("html,body");
} else {
_assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body.");
containerOffsetTop = $container.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, ($container.innerHeight() - $container[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.isRoot() || $(topNode.span).is(":visible"), "topNode must be visible");
if( topNodeY < newScrollTop ){
newScrollTop = topNodeY - topOfs;
// this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop);
}
}
}
if(newScrollTop !== null){
// this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop);
if(opts.effects){
opts.effects.complete = function(){
dfd.resolveWith(that);
};
$animateTarget.stop(true).animate({
scrollTop: newScrollTop
}, opts.effects);
}else{
$animateTarget[0].scrollTop = newScrollTop;
dfd.resolveWith(this);
}
}else{
dfd.resolveWith(this);
}
return dfd.promise();
},
/**Activate this node.
* @param {boolean} [flag=true] pass false to deactivate
* @param {object} [opts] additional options. Defaults to {noEvents: false}
* @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
*/
setSelected: function(flag){
return this.tree._callHook("nodeSetSelected", this, flag);
},
/**Mark a lazy node as 'error', 'loading', or 'ok'.
* @param {string} status 'error', '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();
},
/**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();
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();
}
},
/** 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) is called for every node, in order to allow modifications
* @returns {NodeData}
*/
toDict: function(recursive, callback) {
var i, l, node,
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 ){
callback(dict);
}
if( recursive ) {
if(this.hasChildren()){
dict.children = [];
for(i=0, l=this.children.length; i<l; i++ ){
node = this.children[i];
if( !node.isStatusNode() ){
dict.children.push(node.toDict(true, callback));
}
}
}else{
// dict.children = null;
}
}
return dict;
},
/** 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 + ", '" + this.title + "')>";
},
/** Call fn(node) for all child nodes.<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}
*/
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;
},
/** Write warning to browser console (prepending node info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
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 {FancytreeOptions} options
* @property {FancytreeNode} rootNode
* @property {FancytreeNode} activeNode
* @property {FancytreeNode} focusNode
* @property {jQueryObject} $div
* @property {object} widget
* @property {object} ext
* @property {object} data
* @property {object} options
* @property {string} _id
* @property {string} statusClassPropName
* @property {string} ariaPropName
* @property {string} nodeContainerAttrName
* @property {string} $container
* @property {FancytreeNode} lastSelectedNode
*/
function Fancytree(widget) {
this.widget = widget;
this.$div = widget.element;
this.options = widget.options;
if( this.options ) {
if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) {
this.options.lazyLoad = function() {
FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead.");
return widget.options.lazyload.apply(this, arguments);
};
}
if( $.isFunction(this.options.loaderror) ) {
$.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead.");
}
if( this.options.fx !== undefined ) {
FT.warn("The 'fx' options was replaced by 'toggleEffect' since 2014-11-30.");
}
}
this.ext = {}; // Active extension instances
// allow to init tree.data.foo from <div data-foo=''>
this.data = _getElementDataAsDict(this.$div);
this._id = $.ui.fancytree._nextId++;
this._ns = ".fancytree-" + this._id; // append for namespaced events
this.activeNode = null;
this.focusNode = null;
this._hasFocus = null;
this.lastSelectedNode = null;
this.systemFocusElement = null;
this.lastQuicksearchTerm = "";
this.lastQuicksearchTime = 0;
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>", {
"class": "ui-fancytree fancytree-container"
}).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
this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
if(this.options.aria){
this.$container
.attr("role", "tree")
.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 };
}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);
},
/* 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} extension 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) {
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);
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 prevously 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
* @returns {FancytreeNode} activated node (null, if not found)
*/
activateKey: function(key) {
var node = this.getNodeByKey(key);
if(node){
node.setActive();
}else if(this.activeNode){
this.activeNode.setActive(false);
}
return node;
},
/** (experimental)
*
* @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 resovled, 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();
}
},
*/
/** Return the number of nodes.
* @returns {integer}
*/
count: function() {
return this.rootNode.countChildren();
},
/** Write to browser console if debugLevel >= 2 (prepending tree name)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
// TODO: disable()
// TODO: enable()
// TODO: enableUpdate()
/** 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 stopNode = null,
parentChildren = startNode.parent.children,
matchingNode = null,
walkVisible = function(parent, idx, fn) {
var i, grandParent,
parentChildren = parent.children,
siblingCount = parentChildren.length,
node = parentChildren[idx];
// visit node itself
if( node && fn(node) === false ) {
return false;
}
// visit descendants
if( node && node.children && node.expanded ) {
if( walkVisible(node, 0, fn) === false ) {
return false;
}
}
// visit subsequent siblings
for( i = idx + 1; i < siblingCount; i++ ) {
if( walkVisible(parent, i, fn) === false ) {
return false;
}
}
// visit parent's subsequent siblings
grandParent = parent.parent;
if( grandParent ) {
return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn);
} else {
// wrap-around: restart with first node
return walkVisible(parent, 0, fn);
}
};
match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match;
startNode = startNode || this.getFirstChild();
walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){
// Stop iteration if we see the start node a second time
if( node === stopNode ) {
return false;
}
stopNode = stopNode || node;
// Ignore nodes hidden by a filter
if( ! $(node.span).is(":visible") ) {
node.debug("quicksearch: skipping hidden node");
return;
}
// Test if we found a match, but search for a second match if this
// was the currently active node
if( match(node) ) {
// node.debug("quicksearch match " + node.title, startNode);
matchingNode = node;
if( matchingNode !== startNode ) {
return false;
}
}
});
return matchingNode;
},
// TODO: fromDict
/**
* Generate INPUT elements that can be submitted with html forms.
*
* In selectMode 3 only the topmost selected nodes are considered.
*
* @param {boolean | string} [selected=true]
* @param {boolean | string} [active=true]
*/
generateFormElements: function(selected, active) {
// TODO: test case
var nodeList,
selectedName = (selected !== false) ? "ft_" + this._id + "[]" : selected,
activeName = (active !== false) ? "ft_" + this._id + "_active" : active,
id = "fancytree_result_" + this._id,
$result = $("#" + id);
if($result.length){
$result.empty();
}else{
$result = $("<div>", {
id: id
}).hide().insertAfter(this.$container);
}
if(selectedName){
nodeList = this.getSelectedNodes( this.options.selectMode === 3 );
$.each(nodeList, function(idx, node){
$result.append($("<input>", {
type: "checkbox",
name: selectedName,
value: node.key,
checked: true
}));
});
}
if(activeName && this.activeNode){
$result.append($("<input>", {
type: "radio",
name: activeName,
value: this.activeNode.key,
checked: true
}));
}
},
/**
* 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.
* @param {boolean} [ifTreeHasFocus=false] (not yet implemented)
* @returns {FancytreeNode}
*/
getFocusNode: function(ifTreeHasFocus) {
// TODO: implement ifTreeHasFocus
return this.focusNode;
},
/**
* 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).
// $("#...") has problems, if the key contains '.', so we use getElementById()
var el, match;
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
// TODO: optimize with specialized loop
// TODO: consider keyMap?
searchRoot = searchRoot || this.rootNode;
match = null;
searchRoot.visit(function(node){
// window.console.log("getNodeByKey(" + key + "): ", node.key);
if(node.key === key) {
match = node;
return false;
}
}, true);
return match;
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.rootNode;
},
/**
* Return an array of selected nodes.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
var nodeList = [];
this.rootNode.visit(function(node){
if( node.selected ) {
nodeList.push(node);
if( stopOnParents === true ){
return "skip"; // stop processing this branch
}
}
});
return nodeList;
},
/** Return true if the tree control has keyboard focus
* @returns {boolean}
*/
hasFocus: function(){
return !!this._hasFocus;
},
/** Write to browser console if debugLevel >= 1 (prepending tree name)
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/*
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 ment for lazy hierarchies.
* A callback is executed for every node as we go.
* @example
* tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
* if(status === "loaded") {
* console.log("loaded intermiediate 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} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error')
* @returns {$.Promise}
*/
loadKeyPath: function(keyPathList, callback, _rootNode) {
var deferredList, dfd, i, path, key, loadMap, node, root, segList,
sep = this.options.keyPathSeparator,
self = this;
if(!$.isArray(keyPathList)){
keyPathList = [keyPathList];
}
// Pass 1: handle all path segments for nodes that are already loaded
// Collect distinct top-most lazy nodes in a map
loadMap = {};
for(i=0; i<keyPathList.length; i++){
root = _rootNode || this.rootNode;
path = keyPathList[i];
// strip leading slash
if(path.charAt(0) === sep){
path = path.substr(1);
}
// traverse and strip keys, until we hit a lazy, unloaded node
segList = path.split(sep);
while(segList.length){
key = segList.shift();
// node = _findDirectChild(root, key);
node = root._findDirectChild(key);
if(!node){
this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")");
callback.call(this, key, "error");
break;
}else if(segList.length === 0){
callback.call(this, node, "ok");
break;
}else if(!node.lazy || (node.hasChildren() !== undefined )){
callback.call(this, node, "loaded");
root = node;
}else{
callback.call(this, node, "loaded");
// segList.unshift(key);
if(loadMap[key]){
loadMap[key].push(segList.join(sep));
}else{
loadMap[key] = [segList.join(sep)];
}
break;
}
}
}
// alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap));
// Now load all lazy nodes and continue itearation for remaining paths
deferredList = [];
// Avoid jshint warning 'Don't make functions within a loop.':
function __lazyload(key, node, dfd){
callback.call(self, node, "loading");
node.load().done(function(){
self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self));
}).fail(function(errMsg){
self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")");
callback.call(self, node, "error");
dfd.reject();
});
}
for(key in loadMap){
node = root._findDirectChild(key);
// alert("loadKeyPath: lazy node(" + key + ") = " + node);
dfd = new $.Deferred();
deferredList.push(dfd);
__lazyload(key, node, dfd);
}
// Return a promise that is resovled, when ALL paths were loaded
return $.when.apply($, deferredList).promise();
},
/** Re-fire beforeActivate and activate events. */
reactivate: function(setFocus) {
var res,
node = this.activeNode;
if( !node ) {
return _getResolvedPromise();
}
this.activeNode = null; // Force re-activating
res = node.setActive();
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 is parent is collapsed
* @param {boolean} [deep=false]
*/
render: function(force, deep) {
return this.rootNode.render(force, deep);
},
// TODO: selectKey: function(key, select)
// TODO: serializeArray: function(stopOnParents)
/**
* @param {boolean} [flag=true]
*/
setFocus: function(flag) {
return this._callHook("treeSetFocus", this, flag);
},
/**
* 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(node)] Called for every node
* @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 + ")>";
},
/* _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.
*
* @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);
},
/** Write warning to browser console (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
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 <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.)
* @mixin Fancytree_Hooks
*/
$.extend(Fancytree.prototype,
/** @lends Fancytree_Hooks# */
{
/** Default handling for mouse click events.
*
* @param {EventData} ctx
*/
nodeClick: function(ctx) {
// this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which);
var activate, expand,
// event = ctx.originalEvent,
targetType = ctx.targetType,
node = ctx.node;
// TODO: use switch
// TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
if( targetType === "expander" ) {
// 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,
event = ctx.originalEvent,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
which = event.which,
whichChar = String.fromCharCode(which),
clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey),
$target = $(event.target),
handled = true,
activate = !(event.ctrlKey || !opts.autoActivate );
// node.debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
// FT.debug("keyEventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.keyEventToString(event) + '"');
// Set focus to first node, if no other node has the focus yet
if( !node ){
this.getFirstChild().setFocus();
node = ctx.node = this.focusNode;
node.debug("Keydown force focus on first node");
}
if( opts.quicksearch && clean && /\w/.test(whichChar) && !$target.is(":input:enabled") ) {
// Allow to search for longer streaks if typed in quickly
stamp = new Date().getTime();
if( stamp - tree.lastQuicksearchTime > 500 ) {
tree.lastQuicksearchTerm = "";
}
tree.lastQuicksearchTime = stamp;
tree.lastQuicksearchTerm += whichChar;
// tree.debug("quicksearch find", tree.lastQuicksearchTerm);
matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode());
if( matchNode ) {
matchNode.setActive();
}
event.preventDefault();
return;
}
switch( FT.keyEventToString(event) ) {
case "+":
case "=": // 187: '+' @ Chrome, Safari
tree.nodeSetExpanded(ctx, true);
break;
case "-":
tree.nodeSetExpanded(ctx, false);
break;
case "space":
if(opts.checkbox){
tree.nodeToggleSelected(ctx);
}else{
tree.nodeSetActive(ctx, true);
}
break;
case "enter":
tree.nodeSetActive(ctx, true);
break;
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, dfd,
tree = ctx.tree,
node = ctx.node;
if($.isFunction(source)){
source = source();
}
// TOTHINK: move to 'ajax' extension?
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;
if($.isArray(delay)){ // random delay range [min..max]
delay = delay[0] + Math.random() * (delay[1] - delay[0]);
}
node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms");
ajax.debugDelay = false;
dfd = $.Deferred(function (dfd) {
setTimeout(function () {
$.ajax(ajax)
.done(function () { dfd.resolveWith(this, arguments); })
.fail(function () { dfd.rejectWith(this, arguments); });
}, delay);
});
}else{
dfd = $.ajax(ajax);
}
// Defer the deferred: we want to be able to reject, even if ajax
// resolved ok.
source = new $.Deferred();
dfd.done(function (data, textStatus, jqXHR) {
var errorObj, res;
if(typeof data === "string"){
$.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
}
// postProcess is similar to the standard ajax dataFilter hook,
// but it is also called for JSONP
if( ctx.options.postProcess ){
res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, error: null, dataType: this.dataType});
if( res.error ) {
errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error};
errorObj = tree._makeHookContext(node, null, errorObj);
source.rejectWith(this, [errorObj]);
return;
}
data = $.isArray(res) ? res : data;
} else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) {
// Process ASPX WebMethod JSON object inside "d" property
data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d;
}
source.resolveWith(this, [data]);
}).fail(function (jqXHR, textStatus, errorThrown) {
var errorObj = tree._makeHookContext(node, null, {
error: jqXHR,
args: Array.prototype.slice.call(arguments),
message: errorThrown,
details: jqXHR.status + ": " + errorThrown
});
source.rejectWith(this, [errorObj]);
});
}
if($.isFunction(source.promise)){
// `source` is a deferred, i.e. ajax request
_assert(!node.isLoading());
// node._isLoading = true;
tree.nodeSetStatus(ctx, "loading");
source.done(function (children) {
tree.nodeSetStatus(ctx, "ok");
}).fail(function(error){
var ctxErr;
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( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) {
tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details);
}
});
}
// $.when(source) resolves also for non-deferreds
return $.when(source).done(function(children){
var metaData;
if( $.isPlainObject(children) ){
// We got {foo: 'abc', children: [...]}
// Copy extra properties to tree.data.foo
_assert($.isArray(children.children), "source must contain (or be) an array of children");
_assert(node.isRoot(), "source may only be an object for root nodes");
metaData = children;
children = children.children;
delete metaData.children;
$.extend(tree.data, metaData);
}
_assert($.isArray(children), "expected array of children");
node._setChildren(children);
// trigger fancytreeloadchildren
tree._triggerNodeEvent("loadChildren", node);
// }).always(function(){
// node._isLoading = false;
});
},
/** [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]);
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);
// Unlink to support GC
childNode.visit(function(n){
n.parent = null;
}, true);
this._callHook("treeRegisterNode", this, false, childNode);
if ( opts.removeNode ){
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
// 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.isRoot() ) {
$(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.visit(function(n){
n.parent = null;
tree._callHook("treeRegisterNode", tree, false, n);
if ( opts.removeNode ){
subCtx.node = n;
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
});
if( node.lazy ){
// 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
node.children = [];
} else{
node.children = null;
}
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 `&lt;li>&lt;span>..&lt;/span> .. &lt;/li>` tags for this node.
*
* This method takes care that all HTML markup is created that is required
* to display this node in it's 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.
*
* Note: if a node was created/removed, nodeRender() must be called for the
* parent.
* <code>
* <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>
* </code>
*
* @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
* - childern 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;
// FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
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){
// 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 ) {
// node.debug("render... really");
firstTime = true;
node.li = document.createElement("li");
node.li.ftnode = node;
if(aria){
// TODO: why doesn't this work:
// node.li.role = "treeitem";
// $(node.li).attr("role", "treeitem")
// .attr("aria-labelledby", "ftal_" + node.key);
}
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.span).attr("aria-labelledby", "ftal_" + node.key);
}
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);
}
}else{
// this.nodeRenderTitle(ctx);
this.nodeRenderStatus(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 ) {
// node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
node.ul.insertBefore(childNode1.li, childNode2.li);
} else {
childLI = childLI.nextSibling;
}
}
}
}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){
parent.ul.appendChild(node.li);
}
}
},
/** Create HTML for the node's outer <span> (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 id, iconSpanClass, nodeTitle, role, tabindex, tooltip,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
level = node.getLevel(),
ares = [],
iconSrc = node.data.icon;
if(title !== undefined){
node.title = title;
}
if(!node.span){
// 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)
// TODO: optimize this if clause
if( level < opts.minExpandLevel ) {
if( !node.lazy ) {
node.expanded = true;
}
if(level > 1){
if(aria){
ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>");
}else{
ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>");
}
}
// .. else (i.e. for root level) skip expander/connector alltogether
} else {
if(aria){
ares.push("<span role='button' class='fancytree-expander'></span>");
}else{
ares.push("<span class='fancytree-expander'></span>");
}
}
// Checkbox mode
if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) {
if(aria){
ares.push("<span role='checkbox' class='fancytree-checkbox'></span>");
}else{
ares.push("<span class='fancytree-checkbox'></span>");
}
}
// folder or doctype icon
role = aria ? " role='img'" : "";
if( iconSrc === true || (iconSrc !== false && opts.icons !== false) ) {
// opts.icons defines the default behavior, node.icon == true/false can override this
if ( iconSrc && typeof iconSrc === "string" ) {
// node.icon is an image url
iconSrc = (iconSrc.charAt(0) === "/") ? iconSrc : ((opts.imagePath || "") + iconSrc);
ares.push("<img src='" + iconSrc + "' class='fancytree-icon' alt='' />");
} else {
// See if node.iconClass or opts.iconClass() define a class name
iconSpanClass = (opts.iconClass && opts.iconClass.call(tree, node, ctx)) || node.data.iconclass || null;
if( iconSpanClass ) {
ares.push("<span " + role + " class='fancytree-custom-icon " + iconSpanClass + "'></span>");
} else {
ares.push("<span " + role + " class='fancytree-icon'></span>");
}
}
}
// node title
nodeTitle = "";
if ( opts.renderTitle ){
nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || "";
}
if(!nodeTitle){
tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : "";
id = aria ? " id='ftal_" + node.key + "'" : "";
role = aria ? " role='treeitem'" : "";
tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + 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);
},
/** Update element classes according to node state.
* @param {EventData} ctx
*/
nodeRenderStatus: function(ctx) {
// Set classes for current status
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
// nodeContainer = node[tree.nodeContainerAttrName],
hasChildren = node.hasChildren(),
isLastSib = node.isLastSibling(),
aria = opts.aria,
// $ariaElem = aria ? $(node[tree.ariaPropName]) : null,
$ariaElem = $(node.span).find(".fancytree-title"),
cn = opts._classNames,
cnList = [],
statusElem = node[tree.statusClassPropName];
if( !statusElem ){
// if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
return;
}
// 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(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
// TODO: is this the right element for this attribute?
$ariaElem
.attr("aria-activedescendant", true);
// .attr("tabindex", "-1");
}
}else if(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
$ariaElem
.removeAttr("aria-activedescendant");
// .removeAttr("tabindex");
}
if( node.expanded ){
cnList.push(cn.expanded);
if(aria){
$ariaElem.attr("aria-expanded", true);
}
}else if(aria){
$ariaElem.removeAttr("aria-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.partsel ){
cnList.push(cn.partsel);
}
if( node.unselectable ){
cnList.push(cn.unselectable);
}
if( node._isLoading ){
cnList.push(cn.loading);
}
if( node._error ){
cnList.push(cn.error);
}
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){
node.li.className = isLastSib ? cn.lastsib : "";
}
},
/** 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}
* @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),
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){
// tree.nodeMakeVisible(ctx);
node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll
}
tree.activeNode = node;
tree.nodeRenderStatus(ctx);
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);
}
}
},
/** 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 finshed.
*/
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.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(){
if( flag && opts.autoScroll && !noAnimation ) {
// Scroll down to last child, but keep current node visible
node.getLastChild().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 isVisible, isExpanded,
effect = opts.toggleEffect;
node.expanded = flag;
// Create required markup, but make sure the top UL is hidden, so we
// can animate later
tree._callHook("nodeRender", ctx, false, false, true);
// If the currently active node is now hidden, deactivate it
// if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) {
// this.activeNode.deactivate();
// }
// Expanding a lazy node: set 'loading...' and call callback
// if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) {
// this._loadContent();
// return;
// }
// 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 positon: absolute
// duration = opts.fx.duration || 200;
// easing = opts.fx.easing;
// $(node.ul).animate(opts.fx, duration, easing, function(){
// node.debug("nodeSetExpanded: animate start...");
$(node.ul).toggle(effect.effect, effect.options, effect.duration, function(){
// node.debug("nodeSetExpanded: animate done");
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 ot 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;
flag = (flag !== false);
// 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");
// Note: we pass _calledByNodeSetFocus=true
this._callHook("treeSetFocus", ctx, true, true);
}
// this.nodeMakeVisible(ctx);
node.makeVisible({scrollIntoView: false});
tree.focusNode = node;
// node.debug("FOCUS...");
// $(node.span).find(".fancytree-title").focus();
this._triggerNodeEvent("focus", ctx);
// if(ctx.options.autoActivate){
// tree.nodeSetActive(ctx, true);
// }
if(ctx.options.autoScroll){
node.scrollIntoView();
}
this._callHook("nodeRenderStatus", ctx);
}
},
/** (De)Select node, return new status (sync).
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetSelected: function(ctx, flag) {
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options;
// flag defaults to true
flag = (flag !== false);
node.debug("nodeSetSelected(" + flag + ")", ctx);
if( node.unselectable){
return;
}
// TODO: !!node.expanded is nicer, but doesn't pass jshint
// https://github.com/jshint/jshint/issues/455
// if( !!node.expanded === !!flag){
if((node.selected && flag) || (!node.selected && !flag)){
return !!node.selected;
}else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){
return !!node.selected;
}
if(flag && opts.selectMode === 1){
// single selection mode
if(tree.lastSelectedNode){
tree.lastSelectedNode.setSelected(false);
}
}else if(opts.selectMode === 3){
// multi.hier selection mode
node.selected = flag;
// this._fixSelectionState(node);
node.fixSelection3AfterClick();
}
node.selected = flag;
this.nodeRenderStatus(ctx);
tree.lastSelectedNode = flag ? node : null;
tree._triggerNodeEvent("select", ctx);
},
/** Show node status (ok, loading, error) using styles and a dummy child node.
*
* @param {EventData} ctx
* @param status
* @param message
* @param details
*/
nodeSetStatus: function(ctx, status, message, details) {
var node = ctx.node,
tree = ctx.tree;
// cn = ctx.options._classNames;
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();
}
}
}
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);
// tree._callHook("nodeRender", firstChild);
tree._callHook("nodeRenderTitle", firstChild);
} else {
data.key = "_statusNode";
node._setChildren([data]);
node.children[0].statusNodeType = type;
tree.render();
}
return node.children[0];
}
switch( status ){
case "ok":
_clearStatusNode();
// $(node.span).removeClass(cn.loading).removeClass(cn.error);
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
case "loading":
// $(node.span).removeClass(cn.error).addClass(cn.loading);
if( !node.parent ) {
_setStatusNode({
title: tree.options.strings.loading + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-wait"
}, status);
}
node._isLoading = true;
node._error = null;
node.renderStatus();
break;
case "error":
// $(node.span).removeClass(cn.loading).addClass(cn.error);
_setStatusNode({
title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-error"
}, status);
node._isLoading = false;
node._error = { message: message, details: details };
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) {
return this.nodeSetSelected(ctx, !ctx.node.selected);
},
/** 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;
},
/** 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) {
},
/** Widget was (re-)initialized.
* @param {EventData} ctx
*/
treeInit: function(ctx) {
//this.debug("Fancytree.treeInit()");
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 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":
$ul = $container.find(">ul:first");
$ul.addClass("ui-fancytree-source ui-helper-hidden");
source = $.ui.fancytree.parseHtml($ul);
// allow to init tree.data.foo from <ul data-foo=''>
this.data = $.extend(this.data, _getElementDataAsDict($ul));
break;
case "json":
// $().addClass("ui-helper-hidden");
source = $.parseJSON($container.text());
if(source.children){
if(source.title){tree.title = source.title;}
source = source.children;
}
break;
default:
$.error("Invalid data-type: " + type);
}
}else if(typeof source === "string"){
// TODO: source is an element ID
$.error("Not implemented");
}
// $container.addClass("ui-widget ui-widget-content ui-corner-all");
// Trigger fancytreeinit after nodes have been loaded
dfd = this.nodeLoadChildren(rootCtx, source).done(function(){
tree.render();
if( ctx.options.selectMode === 3 ){
tree.rootNode.fixSelection3FromEndNodes();
}
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) {
},
/** Widget got focus.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
treeSetFocus: function(ctx, flag, _calledByNodeSetFocus) {
flag = (flag !== false);
// this.debug("treeSetFocus(" + flag + "), _calledByNodeSetFocus: " + _calledByNodeSetFocus);
// this.debug(" focusNode: " + this.focusNode);
// this.debug(" activeNode: " + this.activeNode);
if( flag !== this.hasFocus() ){
this._hasFocus = flag;
this.$container.toggleClass("fancytree-treefocus", flag);
this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
}
}
});
/* ******************************************************************************
* jQuery UI widget boilerplate
*/
/**
* The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br>
* This constructor is not called directly. Use `$(selector).fancytree({})`
* to initialize the plugin instead.<br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members:
* var tree = $("#tree").fancytree("getTree");
* var node = $("#tree").fancytree("getActiveNode", "1234");
* </pre>
*
* @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: false, // TODO: default to true
autoActivate: true,
autoCollapse: false,
// autoFocus: false,
autoScroll: false,
checkbox: false,
/**defines click behavior*/
clickFolderMode: 4,
debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo)
disabled: false, // TODO: required anymore?
enableAspx: true, // TODO: document
extensions: [],
// fx: { height: "toggle", duration: 200 },
// toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 },
// toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 },
toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 },
generateIds: false,
icons: true,
idPrefix: "ft_",
focusOnSelect: false,
keyboard: true,
keyPathSeparator: "/",
minExpandLevel: 1,
quicksearch: false,
scrollOfs: {top: 0, bottom: 0},
scrollParent: null,
selectMode: 2,
strings: {
loading: "Loading&#8230;",
loadError: "Load error!"
},
tabbable: true,
titlesTabbable: false,
_classNames: {
node: "fancytree-node",
folder: "fancytree-folder",
combinedExpanderPrefix: "fancytree-exp-",
combinedIconPrefix: "fancytree-ico-",
hasChildren: "fancytree-has-children",
active: "fancytree-active",
selected: "fancytree-selected",
expanded: "fancytree-expanded",
lazy: "fancytree-lazy",
focused: "fancytree-focused",
partsel: "fancytree-partsel",
unselectable: "fancytree-unselectable",
lastsib: "fancytree-lastsib",
loading: "fancytree-loading",
error: "fancytree-error"
},
// events
lazyLoad: null,
postProcess: null
},
/* 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,
extensions = this.options.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);
this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
// 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;
}
//
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 ebent binding into hooks altogether
this._bind();
},
/* Use the _setOption method to respond to changes to options */
_setOption: function(key, value) {
var callDefault = true,
rerender = false;
switch( key ) {
case "aria":
case "checkbox":
case "icons":
case "minExpandLevel":
case "tabbable":
// case "nolink":
this.tree._callHook("treeCreate", this.tree);
rerender = true;
break;
case "source":
callDefault = false;
this.tree._callHook("treeLoad", this.tree, value);
break;
}
this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">");
if(callDefault){
// In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.apply(this, arguments);
// TODO: In jQuery UI 1.9 and above, you use the _super method instead
// this._super( "_setOption", key, value );
}
if(rerender){
this.tree.render(true, false); // force, not-deep
}
},
/** 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);
// this.element.removeClass("ui-widget ui-widget-content ui-corner-all");
this.tree.$div.find(">ul.fancytree-container").remove();
this.$source && this.$source.removeClass("ui-helper-hidden");
// 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.unbind(ns);
this.tree.$container.unbind(ns);
$(document).unbind(ns);
},
/* Add mouse and kyboard handlers to the container */
_bind: function() {
var that = 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");
// tree.debug("Tree container got event " + event.type, node, event);
// tree.treeOnFocusInOut.call(tree, event);
if(node){
// For example clicking into an <input> that is part of a node
tree._callHook("nodeSetFocus", node, flag);
}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("click" + ns + " dblclick" + ns, function(event){
if(opts.disabled){
return true;
}
var ctx,
et = FT.getEventTarget(event),
node = et.node,
tree = that.tree,
prevPhase = tree.phase;
if( !node ){
return true; // Allow bubbling of other events
}
ctx = tree._makeHookContext(node, event);
// that.tree.debug("event(" + event.type + "): node: ", node);
try {
tree.phase = "userEvent";
switch(event.type) {
case "click":
ctx.targetType = et.type;
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);
}
// } catch(e) {
// // var _ = null; // DT issue 117 // TODO
// $.error(e);
} finally {
tree.phase = prevPhase;
}
});
},
/** Return the active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.tree.activeNode;
},
/** Return the matching node or null.
* @param {string} key
* @returns {FancytreeNode}
*/
getNodeByKey: function(key) {
return this.tree.getNodeByKey(key);
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.tree.rootNode;
},
/** Return the current tree instance.
* @returns {Fancytree}
*/
getTree: function() {
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.<br>
* <br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access static members:
* var node = $.ui.fancytree.getNode(element);
* alert($.ui.fancytree.version);
* </pre>
*
* @mixin Fancytree_Static
*/
$.extend($.ui.fancytree,
/** @lends Fancytree_Static# */
{
/** @type {string} */
version: "@VERSION", // Set to semver by 'grunt release'
/** @type {string} */
buildType: "development", // Set to 'production' by 'grunt build'
/** @type {int} */
debugLevel: 2, // Set to 1 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 */
_FancytreeClass: Fancytree,
/** Expose class object as $.ui.fancytree._FancytreeNodeClass */
_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);
},
/** 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;
invokeAsap && !timer && fn.apply(ctx, args);
clearTimeout(timer);
timer = setTimeout(function() {
invokeAsap || fn.apply(ctx, args);
timer = null;
}, timeout);
};
},
/** Write message to console if debugLevel >= 2
* @param {string} msg
*/
debug: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments);
},
/** Write error message to console.
* @param {string} msg
*/
error: function(msg){
consoleApply("error", arguments);
},
/** Convert &lt;, &gt;, &amp;, &quot;, &#39;, &#x2F; to the equivalent entitites.
*
* @param {string} s
* @returns {string}
*/
escapeHtml: function(s){
return ("" + s).replace(/[&<>"'\/]/g, function (s) {
return ENTITY_MAP[s];
});
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTargetType: function(event){
return this.getEventTarget(event).type;
},
/** 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 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) ){
res.type = "checkbox";
}else if( /\bfancytree-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 && $(event.target).closest(".fancytree-title").length ) {
// #228: clicking an embedded element inside a title
res.type = "title";
}
return res;
},
/** Return a FancytreeNode instance from element.
*
* @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.selector !== undefined){
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.
* TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem
* @param {Element | jQueryObject | Event} el
* @returns {Fancytree} matching tree or null
* /
getTree: function(el){
if(el instanceof Fancytree){
return el; // el already was a Fancytree
}else if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
...
return null;
},
*/
/** Write message to console if debugLevel >= 1
* @param {string} msg
*/
info: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments);
},
/** Convert a keydown event to a string like 'ctrl+a', 'ctrl+shift+f2'.
* @param {event}
* @returns {string}
*/
keyEventToString: function(event) {
// Poor-man's hotkeys. See here for a complete implementation:
// https://github.com/jeresig/jquery.hotkeys
var which = event.which,
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( !IGNORE_KEYCODES[which] ) {
s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() );
}
return s.join("+");
},
/**
* Parse tree data from HTML <ul> markup
*
* @param {jQueryObject} $ul
* @returns {NodeData[]}
*/
parseHtml: function($ul) {
// TODO: understand this:
/*jshint validthis:true */
var extraClasses, i, l, iPos, tmp, tmp2, classes, className,
$children = $ul.find(">li"),
children = [];
$children.each(function() {
var allData,
$li = $(this),
$liSpan = $li.find(">span:first", this),
$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;
}
// Add <li data-NAME='...'> as node.data.NAME
allData = _getElementDataAsDict($li);
if(allData && !$.isEmptyObject(allData)) {
// #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.
* @param {string} msg
*/
warn: function(msg){
consoleApply("warn", arguments);
}
});
}(jQuery, window, document));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _delete = __webpack_require__(100);
var _delete2 = _interopRequireDefault(_delete);
var _archive = __webpack_require__(101);
var _archive2 = _interopRequireDefault(_archive);
var _create = __webpack_require__(102);
var _create2 = _interopRequireDefault(_create);
var _create3 = __webpack_require__(103);
var _create4 = _interopRequireDefault(_create3);
var _update = __webpack_require__(104);
var _update2 = _interopRequireDefault(_update);
var _browse = __webpack_require__(105);
var _browse2 = _interopRequireDefault(_browse);
var _reorderContent = __webpack_require__(106);
var _reorderContent2 = _interopRequireDefault(_reorderContent);
var _reorderContent3 = __webpack_require__(107);
var _reorderContent4 = _interopRequireDefault(_reorderContent3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var workzoneBaskets = function workzoneBaskets(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var initialize = function initialize() {
(0, _delete2.default)(services).initialize();
(0, _archive2.default)(services).initialize();
(0, _create2.default)(services).initialize();
(0, _create4.default)(services).initialize();
(0, _update2.default)(services).initialize();
(0, _browse2.default)(services).initialize();
(0, _reorderContent2.default)(services).initialize();
(0, _reorderContent4.default)(services).initialize();
(0, _jquery2.default)(window).on("load", function () {
appEvents.emit('workzone.refresh', {
basketId: 'current',
sort: 'date'
});
});
(0, _jquery2.default)('body').on('click', '.basket-filter-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
if ($el.data('sort') !== '') {
appEvents.emit('workzone.refresh', {
basketId: 'current',
sort: $el.data('sort')
});
}
}).on('click', '.basket-preferences-action', function (event) {
event.preventDefault();
openBasketPreferences();
});
};
function openBasketPreferences() {
(0, _jquery2.default)('#basket_preferences').dialog({
closeOnEscape: true,
resizable: false,
width: 450,
height: 500,
modal: true,
draggable: false,
overlay: {
backgroundColor: '#000',
opacity: 0.7
}
}).dialog('open');
}
appEvents.listenAll({
'baskets.doOpenBasketPreferences': openBasketPreferences
});
return {
initialize: initialize,
openBasketPreferences: openBasketPreferences
};
};
exports.default = workzoneBaskets;
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var deleteBasket = function deleteBasket(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
var initialize = function initialize() {
$container = (0, _jquery2.default)('body');
$container.on('click', '.basket-delete-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
deleteConfirmation($el, $el.data('context'));
});
};
var deleteConfirmation = function deleteConfirmation($el, type) {
switch (type) {
/*case 'IMGT':
case 'CHIM':
var lst = '';
if (type === 'IMGT') {
lst = p4.Results.Selection.serialize();
}
if (type === 'CHIM') {
lst = p4.WorkZone.Selection.serialize();
}
_deleteRecords(lst);
break;
*/
case 'SSTT':
var buttons = {};
buttons[localeService.t('valider')] = function (e) {
_deleteBasket($el);
};
(0, _jquery2.default)('#DIALOG').empty().append(localeService.t('confirmDel')).attr('title', localeService.t('attention')).dialog({
autoOpen: false,
resizable: false,
modal: true,
draggable: false
}).dialog('open').dialog('option', 'buttons', buttons);
(0, _jquery2.default)('#tooltip').hide();
break;
/*case 'STORY':
lst = $el.val();
_deleteRecords(lst);
break;*/
default:
}
};
var _deleteBasket = function _deleteBasket(item) {
if ((0, _jquery2.default)('#DIALOG').data('ui-dialog')) {
(0, _jquery2.default)('#DIALOG').dialog('destroy');
}
// id de chutier
var k = (0, _jquery2.default)(item).attr('id').split('_').slice(1, 2).pop();
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/baskets/' + k + '/delete/',
dataType: 'json',
success: function success(data) {
if (data.success) {
var basket = (0, _jquery2.default)('#SSTT_' + k);
var next = basket.next();
if (next.data('ui-droppable')) {
next.droppable('destroy');
}
next.slideUp().remove();
if (basket.data('ui-droppable')) {
basket.droppable('destroy');
}
basket.slideUp().remove();
if ((0, _jquery2.default)('#baskets .SSTT').length === 0) {
appEvents.emit('workzone.refresh');
}
} else {
alert(data.message);
}
return;
}
});
};
/*const _deleteRecords = (lst) => {
if (lst.split(';').length === 0) {
alert(localeService.t('nodocselected'));
return false;
}
let $dialog = dialog.create(services, {
size: 'Small',
title: localeService.t('deleteRecords')
});
$.ajax({
type: 'POST',
url: '../prod/records/delete/what/',
dataType: 'html',
data: {lst: lst},
success: function (data) {
$dialog.setContent(data);
}
});
return false;
};*/
return { initialize: initialize, deleteConfirmation: deleteConfirmation };
};
exports.default = deleteBasket;
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var archiveBasket = function archiveBasket(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
var initialize = function initialize() {
$container = (0, _jquery2.default)('body');
$container.on('click', '.basket-archive-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
doArchive($el.data('basket-id'));
});
};
function doArchive(basketId) {
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/baskets/' + basketId + '/archive/?archive=1',
dataType: 'json',
beforeSend: function beforeSend() {},
success: function success(data) {
if (data.success) {
var basket = (0, _jquery2.default)('#SSTT_' + basketId);
var next = basket.next();
if (next.data('ui-droppable')) {
next.droppable('destroy');
}
next.slideUp().remove();
if (basket.data('ui-droppable')) {
basket.droppable('destroy');
}
basket.slideUp().remove();
if ((0, _jquery2.default)('#baskets .SSTT').length === 0) {
appEvents.emit('workzone.refresh');
}
} else {
alert(data.message);
}
return;
}
});
}
return { initialize: initialize };
};
exports.default = archiveBasket;
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var basketCreate = function basketCreate(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var searchSelectionSerialized = '';
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelectionSerialized = selection.serialized;
}
});
var initialize = function initialize() {
(0, _jquery2.default)('body').on('click', '.basket-create-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.attr('title');
}
openModal(dialogOptions);
});
};
var openModal = function openModal() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var dialogOptions = (0, _lodash2.default)({
size: 'Small',
loading: false
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions);
return _jquery2.default.get(url + 'prod/baskets/create/', function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
};
var _onDialogReady = function _onDialogReady() {
// recordBridge(services).initialize();
var $dialog = _dialog2.default.get(1);
var $dialogBox = $dialog.getDomElement();
(0, _jquery2.default)('input[name="lst"]', $dialogBox).val(searchSelectionSerialized);
var buttons = $dialog.getOption('buttons');
buttons[localeService.t('create')] = function () {
(0, _jquery2.default)('form', $dialogBox).trigger('submit');
};
$dialog.setOption('buttons', buttons);
(0, _jquery2.default)('form', $dialogBox).bind('submit', function (event) {
var $form = (0, _jquery2.default)(this);
var $dialog = $dialogBox.closest('.ui-dialog');
var buttonPanel = $dialog.find('.ui-dialog-buttonpane');
// @TODO should be in a service:
_jquery2.default.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {
(0, _jquery2.default)(":button:contains('" + localeService.t('create') + "')", buttonPanel).attr('disabled', true).addClass('ui-state-disabled');
},
success: function success(data) {
appEvents.emit('workzone.refresh', {
basketId: data.basket.id
});
_dialog2.default.close(1);
return;
},
error: function error() {
(0, _jquery2.default)(":button:contains('" + localeService.t('create ') + "')", buttonPanel).attr('disabled', false).removeClass('ui-state-disabled');
},
timeout: function timeout() {}
});
return false;
});
};
return { initialize: initialize };
}; /**
* triggered via workzone > Basket > context menu
*/
exports.default = basketCreate;
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var storyCreate = function storyCreate(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var searchSelectionSerialized = '';
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelectionSerialized = selection.serialized;
}
});
var initialize = function initialize() {
(0, _jquery2.default)('body').on('click', '.story-create-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.attr('title');
}
openModal(dialogOptions);
});
};
var openModal = function openModal() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var dialogOptions = (0, _lodash2.default)({
size: 'Small',
loading: false
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions);
return _jquery2.default.get(url + 'prod/story/create/', function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
};
var _onDialogReady = function _onDialogReady() {
var $dialog = _dialog2.default.get(1);
var $dialogBox = $dialog.getDomElement();
(0, _jquery2.default)('input[name="lst"]', $dialogBox).val(searchSelectionSerialized);
var buttons = $dialog.getOption('buttons');
buttons[localeService.t('create')] = function () {
(0, _jquery2.default)('form', $dialogBox).trigger('submit');
};
$dialog.setOption('buttons', buttons);
(0, _jquery2.default)('form', $dialogBox).bind('submit', function (event) {
var $form = (0, _jquery2.default)(this);
var $dialog = $dialogBox.closest('.ui-dialog');
var buttonPanel = $dialog.find('.ui-dialog-buttonpane');
_jquery2.default.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {
(0, _jquery2.default)(":button:contains('" + localeService.t('create') + "')", buttonPanel).attr('disabled', true).addClass('ui-state-disabled');
},
success: function success(data) {
appEvents.emit('workzone.refresh', {
basketId: data.WorkZone,
sort: '',
scrolltobottom: true,
type: 'story'
});
_dialog2.default.close(1);
return;
},
error: function error() {
(0, _jquery2.default)(":button:contains('" + localeService.t('create') + "')", buttonPanel).attr('disabled', false).removeClass('ui-state-disabled');
},
timeout: function timeout() {}
});
return false;
});
};
return { initialize: initialize };
}; /**
* triggered via workzone > Basket > context menu
*/
exports.default = storyCreate;
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8); /**
* triggered via workzone > Basket > context menu
*/
var basketUpdate = function basketUpdate(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var basketId = false;
var searchSelectionSerialized = '';
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelectionSerialized = selection.serialized;
}
});
var initialize = function initialize() {
(0, _jquery2.default)('body').on('click', '.basket-update-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.attr('title');
}
basketId = $el.data('basket-id');
openModal(dialogOptions);
});
};
var openModal = function openModal() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var dialogOptions = (0, _lodash2.default)({
size: 'Medium',
loading: false
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions);
return _jquery2.default.get(url + 'prod/baskets/' + basketId + '/update/', function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
};
var _onDialogReady = function _onDialogReady() {
(0, _jquery2.default)('form[name="basket-rename-box"]').on('submit', function (event) {
event.preventDefault();
onSubmitRenameForm(event);
});
(0, _jquery2.default)('#basket-rename-box button').on('click', function (event) {
event.preventDefault();
onSubmitRenameForm(event);
});
var onSubmitRenameForm = function onSubmitRenameForm(event) {
var $form = (0, _jquery2.default)(event.currentTarget).closest('form');
_jquery2.default.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
data: $form.serializeArray(),
beforeSend: function beforeSend() {},
success: function success(data) {
_dialog2.default.get(1).close();
if (data.success) {
humane.info(data.message);
appEvents.emit('workzone.refresh', {
basketId: basketId
});
} else {
humane.error(data.message);
return false;
}
}
});
return false;
};
};
return { initialize: initialize };
};
exports.default = basketUpdate;
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(14);
var humane = __webpack_require__(8);
var basketBrowse = function basketBrowse(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize() {
(0, _jquery2.default)('body').on('click', '.basket-browse-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.attr('title');
dialogOptions.width = 920;
}
openModal(dialogOptions);
});
};
var openModal = function openModal() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var dialogOptions = (0, _lodash2.default)({
size: 'Medium',
loading: false
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions);
return _jquery2.default.get(url + 'prod/WorkZone/Browse/', function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
};
var _onDialogReady = function _onDialogReady() {
var $container = (0, _jquery2.default)('#BasketBrowser');
var results = null;
function loadResults(datas, url) {
var $results = (0, _jquery2.default)('.results', $container);
results = _jquery2.default.ajax({
type: 'GET',
url: url,
dataType: 'html',
data: datas,
beforeSend: function beforeSend() {
if (results && results.abort && typeof results.abort === 'function') {
results.abort();
}
$results.addClass('loading').empty();
},
error: function error() {
$results.removeClass('loading');
},
timeout: function timeout() {
$results.removeClass('loading');
},
success: function success(data) {
$results.removeClass('loading').append(data);
activateLinks($results);
active_archiver($results);
return;
}
});
}
function loadBasket(url) {
results = _jquery2.default.ajax({
type: 'GET',
url: url,
dataType: 'html',
beforeSend: function beforeSend() {
if (results && results.abort && typeof results.abort === 'function') {
results.abort();
}
(0, _jquery2.default)('.Browser', $container).hide();
(0, _jquery2.default)('.Basket', $container).addClass('loading').empty().show();
},
error: function error() {
(0, _jquery2.default)('.Browser', $container).show();
(0, _jquery2.default)('.Basket', $container).removeClass('loading').hide();
},
timeout: function timeout() {
(0, _jquery2.default)('.Browser', $container).show();
(0, _jquery2.default)('.Basket', $container).removeClass('loading').hide();
},
success: function success(data) {
(0, _jquery2.default)('.Basket', $container).removeClass('loading').append(data);
(0, _jquery2.default)('.Basket a.back', $container).bind('click', function () {
(0, _jquery2.default)('.Basket', $container).hide();
(0, _jquery2.default)('.Browser', $container).show();
return false;
});
active_archiver((0, _jquery2.default)('.Basket', $container));
return;
}
});
}
function activateLinks($scope) {
var confirmBox = {};
var buttons = {};
(0, _jquery2.default)('a.result', $scope).bind('click', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
loadResults({}, $this.attr('href'));
return false;
});
(0, _jquery2.default)('.result_page').bind('click', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
loadResults({}, $this.attr('href'));
return false;
});
(0, _jquery2.default)('a.basket_link', $scope).bind('click', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
loadBasket($this.attr('href'));
return false;
});
(0, _jquery2.default)('a.delete-basket', $scope).bind('click', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
var buttons = {};
buttons[localeService.t('valider')] = function () {
_jquery2.default.ajax({
type: 'POST',
dataType: 'json',
url: $this.attr('href'),
data: {},
success: function success(datas) {
if (datas.success) {
confirmBox.close();
(0, _jquery2.default)('form[name="BasketBrowser"]', $container).trigger('submit');
appEvents.emit('workzone.refresh');
} else {
confirmBox.close();
var alertBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true
}, 2);
alertBox.setContent(datas.message);
}
},
error: function error() {
confirmBox.close();
var alertBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true
}, 2);
alertBox.setContent("{{'Something wrong happened, please retry or contact an admin.'|trans|e('js') }}");
}
});
};
confirmBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
cancelButton: true,
buttons: buttons
}, 2);
confirmBox.setContent("{{'You are about to delete this basket. Would you like to continue ?'|trans|e('js') }}");
return false;
});
}
function active_archiver($scope) {
(0, _jquery2.default)('a.UserTips', $scope).bind('click', function () {
return false;
}).tooltip();
(0, _jquery2.default)('.infoTips, .previewTips', $scope).tooltip();
(0, _jquery2.default)('a.archive_toggler', $scope).bind('click', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
var parent = $this.parent();
_jquery2.default.ajax({
type: 'POST',
url: $this.attr('href'),
dataType: 'json',
beforeSend: function beforeSend() {
(0, _jquery2.default)('.loader', parent).show();
(0, _jquery2.default)('.archive_toggler:visible', parent).addClass('last_act').hide();
},
error: function error() {
(0, _jquery2.default)('.loader', parent).hide();
(0, _jquery2.default)('.last_act', parent).removeClass('last_act').show();
},
timeout: function timeout() {
(0, _jquery2.default)('.loader', parent).hide();
(0, _jquery2.default)('.last_act', parent).removeClass('last_act').show();
},
success: function success(data) {
(0, _jquery2.default)('.loader', parent).hide();
(0, _jquery2.default)('.last_act', parent).removeClass('last_act');
if (!data.success) {
humane.error(data.message);
return;
}
if (data.archive === true) {
(0, _jquery2.default)('.unarchiver', parent).show();
(0, _jquery2.default)('.archiver', parent).hide();
(0, _jquery2.default)($this).closest('.result').removeClass('unarchived');
} else {
(0, _jquery2.default)('.unarchiver', parent).hide();
(0, _jquery2.default)('.archiver', parent).show();
(0, _jquery2.default)($this).closest('.result').addClass('unarchived');
}
appEvents.emit('workzone.refresh');
return;
}
});
return false;
});
}
(0, _jquery2.default)('form[name="BasketBrowser"]', $container).bind('submit', function () {
var $this = (0, _jquery2.default)(this);
loadResults($this.serializeArray(), $this.attr('action'));
return false;
}).trigger('submit').find('label').bind('click', function () {
var input = (0, _jquery2.default)(this).prev('input');
var inputs = (0, _jquery2.default)('input[name="' + (0, _jquery2.default)(this).prev('input').attr('name') + '"]', $container);
inputs.prop('checked', false).next('label').removeClass('selected');
input.prop('checked', true).next('label').addClass('selected');
(0, _jquery2.default)('form[name="BasketBrowser"]', $container).trigger('submit');
});
};
return { initialize: initialize };
};
exports.default = basketBrowse;
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _selectable = __webpack_require__(23);
var _selectable2 = _interopRequireDefault(_selectable);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var basketReorderContent = function basketReorderContent(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var searchSelectionSerialized = '';
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelectionSerialized = selection.serialized;
}
});
var initialize = function initialize() {
(0, _jquery2.default)('body').on('click', '.basket-reorder-content-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.attr('title');
}
openModal($el.data('basket-id'), dialogOptions);
});
};
var openModal = function openModal(basketId) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var dialogOptions = (0, _lodash2.default)({
size: 'Medium',
loading: false
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions);
return _jquery2.default.get(url + 'prod/baskets/' + basketId + '/reorder/', function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
};
var _onDialogReady = function _onDialogReady() {
var container = (0, _jquery2.default)('#reorder_box');
(0, _jquery2.default)('button.autoorder', container).bind('click', function () {
autoorder();
return false;
});
(0, _jquery2.default)('button.reverseorder', container).bind('click', function () {
reverse_order();
return false;
});
function autoorder() {
var val = _jquery2.default.trim((0, _jquery2.default)('#auto_order').val());
if (val === '') {
return;
}
var diapos = [];
(0, _jquery2.default)('#reorder_box .diapo form').each(function (i, n) {
diapos.push({
title: (0, _jquery2.default)('input[name=title]', n).val(),
order: parseInt((0, _jquery2.default)('input[name=default]', n).val(), 10),
id: (0, _jquery2.default)('input[name=id]', n).val(),
date_created: new Date((0, _jquery2.default)('input[name=date_created]', n).val()),
date_updated: new Date((0, _jquery2.default)('input[name=date_updated]', n).val())
});
});
var elements = [];
var sorterCallback;
if (val === 'default') {
sorterCallback = function sorterCallback(diapo) {
return diapo.order;
};
elements = sorting(sorterCallback, diapos, false);
} else if (val === 'date_updated' || val === 'date_created') {
sorterCallback = function sorterCallback(diapo) {
if (val === 'date_created') {
return diapo.date_created;
}
return diapo.date_updated;
};
elements = sorting(sorterCallback, diapos, true);
} else {
sorterCallback = function sorterCallback(diapo) {
return diapo.title.toLowerCase();
};
elements = sorting(sorterCallback, diapos, false);
}
(0, _jquery2.default)('#reorder_box .elements').append(elements);
}
function sorting(sorterCallback, diapos, reverse) {
var elements = [];
if (reverse == true) {
_.chain(diapos).sortBy(sorterCallback).reverse().each(function (diapo) {
elements.push((0, _jquery2.default)('#ORDER_' + diapo.id));
});
} else {
_.chain(diapos).sortBy(sorterCallback).each(function (diapo) {
elements.push((0, _jquery2.default)('#ORDER_' + diapo.id));
});
}
return elements;
}
function reverse_order() {
var $container = (0, _jquery2.default)('#reorder_box .elements');
(0, _jquery2.default)('#reorder_box .diapo').each(function () {
(0, _jquery2.default)(this).prependTo($container);
});
}
('.elements div', container).bind('click', function () {
(0, _jquery2.default)(this).addClass("selected").siblings().removeClass("selected");
return false;
});
(0, _jquery2.default)('.elements', container).sortable({
appendTo: container,
placeholder: 'diapo ui-sortable-placeholder',
distance: 20,
cursorAt: {
top: 10,
left: -20
},
items: 'div.diapo',
scroll: true,
scrollSensitivity: 40,
scrollSpeed: 30,
start: function start(event, ui) {
var selected = (0, _jquery2.default)('.selected', container);
selected.each(function (i, n) {
(0, _jquery2.default)(n).attr('position', i);
});
var n = selected.length - 1;
(0, _jquery2.default)('.selected:visible', container).hide();
while (n > 0) {
(0, _jquery2.default)('<div style="height:130px;" class="diapo ui-sortable-placeholderfollow"></div>').after((0, _jquery2.default)('.diapo.ui-sortable-placeholder', container));
n--;
}
},
stop: function stop(event, ui) {
(0, _jquery2.default)('.diapo.ui-sortable-placeholderfollow', container).remove();
var main_id = (0, _jquery2.default)(ui.item[0]).attr('id');
var selected = (0, _jquery2.default)('.selected', container);
var sorter = [];
selected.each(function (i, n) {
var position = parseInt((0, _jquery2.default)(n).attr('position'), 10);
if (position !== '') {
sorter[position] = (0, _jquery2.default)(n);
}
var id = (0, _jquery2.default)(n).attr('id');
if (id === main_id) {
return;
}
});
var before = true;
var last_moved = (0, _jquery2.default)(ui.item[0]);
(0, _jquery2.default)(sorter).each(function (i, n) {
(0, _jquery2.default)(n).show().removeAttr('position');
if ((0, _jquery2.default)(n).attr('id') === main_id) {
before = false;
} else {
if (before) {
(0, _jquery2.default)(n).before((0, _jquery2.default)(ui.item[0]));
} else {
(0, _jquery2.default)(n).after((0, _jquery2.default)(last_moved));
}
}
last_moved = sorter[i];
});
},
change: function change() {
(0, _jquery2.default)('.diapo.ui-sortable-placeholderfollow', container).remove();
var n = OrderSelection.length() - 1;
while (n > 0) {
(0, _jquery2.default)('<div style="height:130px;" class="diapo ui-sortable-placeholderfollow"></div>').after((0, _jquery2.default)('.diapo.ui-sortable-placeholder', container));
n--;
}
}
}).disableSelection();
var OrderSelection = new _selectable2.default(services, (0, _jquery2.default)('.elements', container), {
selector: '.CHIM'
});
(0, _jquery2.default)('form[name="reorder"] .btn').bind('click', function (event) {
//$this.SetLoader(true);
var $form = (0, _jquery2.default)(this).closest('form');
(0, _jquery2.default)('.elements form', container).each(function (i, el) {
var id = (0, _jquery2.default)('input[name="id"]', (0, _jquery2.default)(el)).val();
(0, _jquery2.default)('input[name="element[' + id + ']"]', $form).val(i + 1);
});
_jquery2.default.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {},
success: function success(data) {
if (!data.success) {
alert(data.message);
}
appEvents.emit('workzone.refresh', {
basketId: 'current'
});
_dialog2.default.get(1).close();
return;
}
});
return false;
});
};
return { initialize: initialize };
}; /**
* triggered via workzone > Basket > context menu
*/
exports.default = basketReorderContent;
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _selectable = __webpack_require__(23);
var _selectable2 = _interopRequireDefault(_selectable);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var storyReorderContent = function storyReorderContent(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize() {
(0, _jquery2.default)('body').on('click', '.story-reorder-content-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dialogOptions = {};
if ($el.attr('title') !== undefined) {
dialogOptions.title = $el.attr('title');
}
openModal($el.data('db-id'), $el.data('record-id'), dialogOptions);
});
};
var openModal = function openModal(dbId, recordId) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var dialogOptions = (0, _lodash2.default)({
size: 'Medium',
loading: false
}, options);
var $dialog = _dialog2.default.create(services, dialogOptions);
// /prod/story/1/62/reorder/
return _jquery2.default.get(url + 'prod/story/' + dbId + '/' + recordId + '/reorder/', function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
};
var _onDialogReady = function _onDialogReady() {
var optionsContainer = (0, _jquery2.default)('#reorder_options');
var container = (0, _jquery2.default)('#reorder_box');
(0, _jquery2.default)('button.autoorder', optionsContainer).bind('click', function () {
autoorder();
return false;
});
(0, _jquery2.default)('button.reverseorder', optionsContainer).bind('click', function () {
reverse_order();
return false;
});
function autoorder() {
var val = _jquery2.default.trim((0, _jquery2.default)('#auto_order').val());
if (val === '') {
return;
}
var diapos = [];
(0, _jquery2.default)('#reorder_box .diapo form').each(function (i, n) {
diapos.push({
title: (0, _jquery2.default)('input[name=title]', n).val(),
order: parseInt((0, _jquery2.default)('input[name=default]', n).val(), 10),
id: (0, _jquery2.default)('input[name=id]', n).val(),
date_created: new Date((0, _jquery2.default)('input[name=date_created]', n).val()),
date_updated: new Date((0, _jquery2.default)('input[name=date_updated]', n).val())
});
});
var elements = [];
var sorterCallback;
if (val === 'default') {
sorterCallback = function sorterCallback(diapo) {
return diapo.order;
};
elements = sorting(sorterCallback, diapos, false);
} else if (val === 'date_updated' || val === 'date_created') {
sorterCallback = function sorterCallback(diapo) {
if (val === 'date_created') {
return diapo.date_created;
}
return diapo.date_updated;
};
elements = sorting(sorterCallback, diapos, true);
} else {
sorterCallback = function sorterCallback(diapo) {
return diapo.title.toLowerCase();
};
elements = sorting(sorterCallback, diapos, false);
}
(0, _jquery2.default)('#reorder_box .elements').append(elements);
}
function sorting(sorterCallback, diapos, reverse) {
var elements = [];
if (reverse == true) {
_.chain(diapos).sortBy(sorterCallback).reverse().each(function (diapo) {
elements.push((0, _jquery2.default)('#ORDER_' + diapo.id));
});
} else {
_.chain(diapos).sortBy(sorterCallback).each(function (diapo) {
elements.push((0, _jquery2.default)('#ORDER_' + diapo.id));
});
}
return elements;
}
function reverse_order() {
var $container = (0, _jquery2.default)('#reorder_box .elements');
(0, _jquery2.default)('#reorder_box .diapo').each(function () {
(0, _jquery2.default)(this).prependTo($container);
});
}
('.elements div', container).bind('click', function () {
(0, _jquery2.default)(this).addClass("selected").siblings().removeClass("selected");
return false;
});
(0, _jquery2.default)('.elements', container).sortable({
appendTo: container,
placeholder: 'diapo ui-sortable-placeholder',
distance: 20,
cursorAt: {
top: 10,
left: -20
},
items: 'div.diapo',
scroll: true,
scrollSensitivity: 40,
scrollSpeed: 30,
start: function start(event, ui) {
var selected = (0, _jquery2.default)('.selected', container);
selected.each(function (i, n) {
(0, _jquery2.default)(n).attr('position', i);
});
var n = selected.length - 1;
(0, _jquery2.default)('.selected:visible', container).hide();
while (n > 0) {
(0, _jquery2.default)('<div style="height:130px;" class="diapo ui-sortable-placeholderfollow"></div>').after((0, _jquery2.default)('.diapo.ui-sortable-placeholder', container));
n--;
}
},
stop: function stop(event, ui) {
(0, _jquery2.default)('.diapo.ui-sortable-placeholderfollow', container).remove();
var main_id = (0, _jquery2.default)(ui.item[0]).attr('id');
var selected = (0, _jquery2.default)('.selected', container);
var sorter = [];
selected.each(function (i, n) {
var position = parseInt((0, _jquery2.default)(n).attr('position'), 10);
if (position !== '') {
sorter[position] = (0, _jquery2.default)(n);
}
var id = (0, _jquery2.default)(n).attr('id');
if (id === main_id) {
return;
}
});
var before = true;
var last_moved = (0, _jquery2.default)(ui.item[0]);
(0, _jquery2.default)(sorter).each(function (i, n) {
(0, _jquery2.default)(n).show().removeAttr('position');
if ((0, _jquery2.default)(n).attr('id') === main_id) {
before = false;
} else {
if (before) {
(0, _jquery2.default)(n).before((0, _jquery2.default)(ui.item[0]));
} else {
(0, _jquery2.default)(n).after((0, _jquery2.default)(last_moved));
}
}
last_moved = sorter[i];
});
},
change: function change() {
(0, _jquery2.default)('.diapo.ui-sortable-placeholderfollow', container).remove();
var n = OrderSelection.length() - 1;
while (n > 0) {
(0, _jquery2.default)('<div style="height:130px;" class="diapo ui-sortable-placeholderfollow"></div>').after((0, _jquery2.default)('.diapo.ui-sortable-placeholder', container));
n--;
}
}
}).disableSelection();
var OrderSelection = new _selectable2.default(services, (0, _jquery2.default)('.elements', container), {
selector: '.CHIM'
});
(0, _jquery2.default)('form[name="reorder"] .btn').bind('click', function (event) {
var $form = (0, _jquery2.default)(this).closest('form');
(0, _jquery2.default)('.elements form', container).each(function (i, el) {
var id = (0, _jquery2.default)('input[name="id"]', (0, _jquery2.default)(el)).val();
(0, _jquery2.default)('input[name="element[' + id + ']"]', $form).val(i + 1);
});
_jquery2.default.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {},
success: function success(data) {
if (!data.success) {
alert(data.message);
}
appEvents.emit('workzone.refresh', {
basketId: 'current',
sort: null,
scrolltobottom: false,
type: 'story'
});
_dialog2.default.get(1).close();
return;
},
error: function error() {},
timeout: function timeout() {}
});
return false;
});
};
return { initialize: initialize };
}; /**
* triggered via workzone > Basket > context menu
*/
exports.default = storyReorderContent;
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// import user from '../user/index.js';
var notifyLayout = function notifyLayout(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $notificationBoxContainer = (0, _jquery2.default)('#notification_box');
var $notificationTrigger = (0, _jquery2.default)('.notification_trigger');
var $notificationDialog = (0, _jquery2.default)('#notifications-dialog');
var initialize = function initialize() {
$notificationTrigger.on('mousedown', function (event) {
event.stopPropagation();
var $target = (0, _jquery2.default)(event.currentTarget);
if ($target.hasClass('open')) {
$notificationBoxContainer.hide();
$target.removeClass('open');
clear_notifications();
} else {
$notificationBoxContainer.show();
setBoxHeight();
$target.addClass('open');
read_notifications();
}
});
(0, _jquery2.default)(document).on('mousedown', function () {
if ($notificationTrigger.hasClass('open')) {
$notificationTrigger.trigger('click');
}
if ($notificationTrigger.hasClass('open')) {
$notificationBoxContainer.hide();
$notificationTrigger.removeClass('open');
clear_notifications();
}
});
$notificationBoxContainer.on('mousedown', function (event) {
event.stopPropagation();
}).on('mouseover', '.notification', function (event) {
(0, _jquery2.default)(event.currentTarget).addClass('hover');
}).on('mouseout', '.notification', function (event) {
(0, _jquery2.default)(event.currentTarget).removeClass('hover');
}).on('click', '.notification__print-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var page = $el.data('page');
print_notifications(page);
});
(0, _jquery2.default)(window).bind('resize', function () {
setBoxPosition();
});
setBoxPosition();
};
var addNotifications = function addNotifications(notificationContent) {
// var box = $('#notification_box');
$notificationBoxContainer.empty().append(notificationContent);
if ($notificationBoxContainer.is(':visible')) {
setBoxHeight();
}
if ((0, _jquery2.default)('.notification.unread', $notificationBoxContainer).length > 0) {
(0, _jquery2.default)('.counter', $notificationTrigger).empty().append((0, _jquery2.default)('.notification.unread', $notificationBoxContainer).length);
(0, _jquery2.default)('.counter', $notificationTrigger).css('visibility', 'visible');
} else {
(0, _jquery2.default)('.notification_trigger .counter').css('visibility', 'hidden').empty();
}
};
var setBoxHeight = function setBoxHeight() {
//var box = $('#notification_box');
var not = (0, _jquery2.default)('.notification', $notificationBoxContainer);
var n = not.length;
var not_t = (0, _jquery2.default)('.notification_title', $notificationBoxContainer);
var n_t = not_t.length;
var h = not.outerHeight() * n + not_t.outerHeight() * n_t;
h = h > 350 ? 350 : h;
$notificationBoxContainer.stop().animate({ height: h });
};
var setBoxPosition = function setBoxPosition() {
if ($notificationTrigger.length > 0) {
var leftOffset = Math.round($notificationTrigger.offset().left);
if (leftOffset == 0) {
$notificationBoxContainer.css({
left: 20
});
} else {
$notificationBoxContainer.css({
left: Math.round($notificationTrigger.offset().left - 1)
});
}
}
};
var print_notifications = function print_notifications(page) {
page = parseInt(page, 10);
var buttons = {};
buttons[localeService.t('fermer')] = function () {
$notificationDialog.dialog('close');
};
if ($notificationDialog.length === 0) {
(0, _jquery2.default)('body').append('<div id="notifications-dialog" class="loading"></div>');
$notificationDialog = (0, _jquery2.default)('#notifications-dialog');
}
$notificationDialog.dialog({
title: (0, _jquery2.default)('#notification-title').val(),
autoOpen: false,
closeOnEscape: true,
resizable: false,
draggable: false,
modal: true,
width: 500,
height: 400,
overlay: {
backgroundColor: '#000',
opacity: 0.7
},
close: function close(event, ui) {
$notificationDialog.dialog('destroy').remove();
}
}).dialog('option', 'buttons', buttons).dialog('open').on('click', '.notification_next .notification__print-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var page = $el.data('page');
print_notifications(page);
});
_jquery2.default.ajax({
type: 'GET',
url: '/user/notifications/',
dataType: 'json',
data: {
page: page
},
error: function error(data) {
$notificationDialog.removeClass('loading');
},
timeout: function timeout(data) {
$notificationDialog.removeClass('loading');
},
success: function success(data) {
$notificationDialog.removeClass('loading');
if (page === 0) {
$notificationDialog.empty();
} else {
(0, _jquery2.default)('.notification_next', $notificationDialog).remove();
}
var i = 0;
for (i in data.notifications) {
var id = 'notif_date_' + i;
var date_cont = (0, _jquery2.default)('#' + id);
if (date_cont.length === 0) {
$notificationDialog.append('<div id="' + id + '"><div class="notification_title">' + data.notifications[i].display + '</div></div>');
date_cont = (0, _jquery2.default)('#' + id);
}
var j = 0;
for (j in data.notifications[i].notifications) {
var loc_dat = data.notifications[i].notifications[j];
var html = '<div style="position:relative;" id="notification_' + loc_dat.id + '" class="notification">' + '<table style="width:100%;" cellspacing="0" cellpadding="0" border="0"><tr><td style="width:25px;">' + loc_dat.icon + '</td><td>' + '<div style="position:relative;" class="' + loc_dat.classname + '">' + loc_dat.text + ' <span class="time">' + loc_dat.time + '</span></div>' + '</td></tr></table>' + '</div>';
date_cont.append(html);
}
}
var next_ln = _jquery2.default.trim(data.next);
if (next_ln !== '') {
$notificationDialog.append('<div class="notification_next">' + next_ln + '</div>');
}
}
});
};
var read_notifications = function read_notifications() {
var notifications = [];
(0, _jquery2.default)('#notification_box .unread').each(function () {
notifications.push((0, _jquery2.default)(this).attr('id').split('_').pop());
});
_jquery2.default.ajax({
type: 'POST',
url: '/user/notifications/read/',
data: {
notifications: notifications.join('_')
},
success: function success(data) {
(0, _jquery2.default)('.notification_trigger .counter').css('visibility', 'hidden').empty();
}
});
};
var clear_notifications = function clear_notifications() {
var unread = (0, _jquery2.default)('#notification_box .unread');
if (unread.length === 0) {
return;
}
unread.removeClass('unread');
(0, _jquery2.default)('.notification_trigger .counter').css('visibility', 'hidden').empty();
};
return {
initialize: initialize,
addNotifications: addNotifications
};
};
exports.default = notifyLayout;
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rx = __webpack_require__(7);
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var notifyService = function notifyService(services) {
var configService = services.configService;
var url = configService.get('baseUrl');
var notificationEndPoint = 'session/notifications/';
var initialize = function initialize() {};
var getNotification = function getNotification(data) {
/*return ajax({
type: 'POST',
url: `${notificationEndPoint}`,
data: data,
dataType: 'json'
}).promise();*/
var notificationPromise = _jquery2.default.Deferred();
_jquery2.default.ajax({
type: 'POST',
url: '' + url + notificationEndPoint,
data: data,
dataType: 'json'
}).done(function (data) {
data.status = data.status || false;
if (data.status === 'ok') {
notificationPromise.resolve(data);
} else {
notificationPromise.reject(data);
}
}).fail(function (data) {
notificationPromise.reject(data);
});
return notificationPromise.promise();
};
var stream = _rx.Observable.fromPromise(getNotification);
return {
initialize: initialize,
getNotification: getNotification,
stream: stream
};
};
// import {ajax} from 'jquery';
exports.default = notifyService;
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _move = __webpack_require__(111);
var _move2 = _interopRequireDefault(_move);
var _edit = __webpack_require__(61);
var _edit2 = _interopRequireDefault(_edit);
var _delete = __webpack_require__(168);
var _delete2 = _interopRequireDefault(_delete);
var _export = __webpack_require__(68);
var _export2 = _interopRequireDefault(_export);
var _property = __webpack_require__(169);
var _property2 = _interopRequireDefault(_property);
var _push = __webpack_require__(170);
var _push2 = _interopRequireDefault(_push);
var _publish = __webpack_require__(175);
var _publish2 = _interopRequireDefault(_publish);
var _index = __webpack_require__(176);
var _index2 = _interopRequireDefault(_index);
var _print = __webpack_require__(72);
var _print2 = _interopRequireDefault(_print);
var _feedback = __webpack_require__(178);
var _feedback2 = _interopRequireDefault(_feedback);
var _bridge = __webpack_require__(179);
var _bridge2 = _interopRequireDefault(_bridge);
var _index3 = __webpack_require__(73);
var _index4 = _interopRequireDefault(_index3);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var toolbar = function toolbar(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $container = (0, _jquery2.default)('body');
var workzoneSelection = [];
var searchSelection = [];
appEvents.listenAll({
'broadcast.searchResultSelection': function broadcastSearchResultSelection(selection) {
searchSelection = selection.serialized;
},
'broadcast.workzoneResultSelection': function broadcastWorkzoneResultSelection(selection) {
workzoneSelection = selection.serialized;
}
});
var initialize = function initialize() {
_bindEvents();
return true;
};
/**
* Active group can be a Basket or story
*/
var _getGroupSelection = function _getGroupSelection() {
var activeGroupId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var $activeGroup = (0, _jquery2.default)('.SSTT.active');
if ($activeGroup.length > 0) {
activeGroupId = $activeGroup.attr('id').split('_').slice(1, 2).pop();
}
return activeGroupId;
};
var _getSelection = function _getSelection(from, originalSelection) {
var newSelection = {
list: [],
group: null, //
type: null // story | basket
};
switch (from) {
case 'search-result':
if (searchSelection.length > 0) {
newSelection.list = searchSelection;
} else {
newSelection.group = _getGroupSelection();
}
break;
case 'basket':
if (workzoneSelection.length > 0) {
newSelection.list = workzoneSelection;
} else {
newSelection.group = _getGroupSelection();
newSelection.type = 'basket';
}
break;
case 'story':
if (workzoneSelection.length > 0) {
newSelection.list = workzoneSelection;
} else {
newSelection.group = _getGroupSelection();
newSelection.type = 'story';
}
break;
default:
newSelection.group = _getGroupSelection();
}
//return originalSelection.concat(newSelection);
return (0, _lodash2.default)({}, originalSelection, newSelection);
};
var _prepareParams = function _prepareParams(selection) {
var params = {};
if (selection.list.length > 0) {
params.lst = selection.list;
}
if (selection.group !== null) {
if (selection.type === 'story') {
params.story = selection.group;
} else {
params.ssel = selection.group;
}
}
// require a list of records a basket group or a story
if (params.lst !== undefined || params.ssel !== undefined || params.story !== undefined) {
return params;
}
return false;
};
var _closeActionPanel = function _closeActionPanel() {
if ((0, _jquery2.default)('.tools-accordion').hasClass('active')) {
(0, _jquery2.default)('.rotate').removeClass('down');
(0, _jquery2.default)('.tools-accordion').removeClass('active');
var panel = (0, _jquery2.default)('.tools-accordion').next();
panel.css('maxHeight', '');
}
};
var _triggerModal = function _triggerModal(event, actionFn) {
var nodocselected = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var selectionSource = $el.data('selection-source');
var selection = _getSelection(selectionSource, {});
var params = _prepareParams(selection);
// require a list of records a basket group or a story
if (params !== false) {
return actionFn.apply(null, [params]);
} else {
if (nodocselected != false) {
alert(localeService.t('nodocselected'));
}
}
};
var _bindEvents = function _bindEvents() {
/**
* tools > selection ALL|NONE|per type
*/
$container.on('click', '.tools .answer_selector', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var actionName = $el.data('action-name');
var state = $el.data('action-state') === true ? true : false;
var type = $el.data('type');
switch (actionName) {
case 'select-toggle':
if (state) {
appEvents.emit('search.selection.unselectAll');
} else {
appEvents.emit('search.selection.selectAll');
}
break;
case 'select-all':
appEvents.emit('search.selection.selectAll');
break;
case 'unselect-all':
appEvents.emit('search.selection.unselectAll');
break;
case 'select-type':
appEvents.emit('search.selection.selectByType', { type: type });
break;
default:
}
$el.data('action-state', !state);
});
/**
* tools > Edit > VideoEditor
*/
$container.on('click', '.video-tools-record-action', function (event) {
_triggerModal(event, (0, _index4.default)(services).openModal, false);
});
/**
* tools > Edit > Move
*/
$container.on('click', '.TOOL_chgcoll_btn', function (event) {
//let moveRecordsInstance = moveRecords(services);
_triggerModal(event, (0, _move2.default)(services).openModal);
});
/**
* tools > Edit > Properties
*/
$container.on('click', '.TOOL_chgstatus_btn', function (event) {
_triggerModal(event, (0, _property2.default)(services).openModal);
});
/**
* tools > Push
*/
$container.on('click', '.TOOL_pushdoc_btn', function (event) {
_triggerModal(event, (0, _push2.default)(services).openModal);
});
/**
* tools > Push > Feedback
*/
$container.on('click', '.TOOL_feedback_btn', function (event) {
_triggerModal(event, (0, _feedback2.default)(services).openModal);
});
/**
* tools > Tools
*/
$container.on('click', '.TOOL_imgtools_btn', function (event) {
_triggerModal(event, (0, _index2.default)(services).openModal);
});
/**
* tools > Export
*/
$container.on('click', '.TOOL_disktt_btn', function (event) {
// can't be fully refactored
_triggerModal(event, (0, _export2.default)(services).openModal);
});
/**
* tools > Export > Print
*/
$container.on('click', '.TOOL_print_btn', function (event) {
_triggerModal(event, (0, _print2.default)(services).openModal);
});
/**
* tools > Push > Bridge
*/
$container.on('click', '.TOOL_bridge_btn', function (event) {
_triggerModal(event, (0, _bridge2.default)(services).openModal);
});
/**
* tools > Push > Publish
*/
$container.on('click', '.TOOL_publish_btn', function (event) {
_triggerModal(event, (0, _publish2.default)(services).openModal);
});
/**
* tools > Delete
*/
$container.on('click', '.TOOL_trash_btn', function (event) {
_triggerModal(event, (0, _delete2.default)(services).openModal);
});
/**
* tools > Edit
*/
$container.on('click', '.TOOL_ppen_btn', function (event) {
_triggerModal(event, (0, _edit2.default)(services).openModal);
});
/**
* tools > Delete Selection
*/
$container.on('click', '.TOOL_delete_selection_btn', function (event) {
var $diapoContainer = (0, _jquery2.default)(this.closest('.content'));
_.each($diapoContainer.find('.diapo.selected'), function (item) {
(0, _jquery2.default)(item).find('.WorkZoneElementRemover').trigger('click');
});
});
/**
* tools-accordion function
*/
$container.on('click', '.tools-accordion', function (event) {
(0, _jquery2.default)('.rotate').toggleClass("down");
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
$container.on('click', function (event) {
if ((0, _jquery2.default)(event.target).is('button.tools-accordion')) {
return;
} else {
_closeActionPanel();
}
});
};
return { initialize: initialize };
};
exports.default = toolbar;
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
var $dialog = null;
var moveRecord = function moveRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var openModal = function openModal(datas) {
$dialog = _dialog2.default.create(services, {
size: 'Small phrasea-black-dialog',
title: localeService.t('move'),
closeButton: true
});
//Add custom class to dialog wrapper
(0, _jquery2.default)('.phrasea-black-dialog').closest('.ui-dialog').addClass('black-dialog-wrap move-dialog');
return _getMovableRecords(datas).then(function (data) {
if (data.success !== undefined) {
if (data.success === true) {
$dialog.setContent(data.template);
_bindFormEvents();
} else {
if (data.message !== undefined) {
$dialog.setContent(data.message);
}
}
}
}, function (data) {
if (data.message !== undefined) {
$dialog.setContent(data.message);
}
});
};
var _bindFormEvents = function _bindFormEvents() {
$dialog = _dialog2.default.get(1);
var $form = $dialog.getDomElement();
var buttons = {};
buttons[localeService.t('valider')] = function () {
var coll_son = (0, _jquery2.default)('input[name="chg_coll_son"]:checked', $form).length > 0 ? '1' : '0';
var datas = {
lst: (0, _jquery2.default)('input[name="lst"]', $form).val(),
base_id: (0, _jquery2.default)('select[name="base_id"]', $form).val(),
chg_coll_son: coll_son
};
var buttonPanel = $dialog.getDomElement().closest('.ui-dialog').find('.ui-dialog-buttonpane');
(0, _jquery2.default)(":button:contains('" + localeService.t('valider') + "')", buttonPanel).attr('disabled', true).addClass('ui-state-disabled');
_postMovableRecords(datas).then(function (data) {
$dialog.close();
if (data.success) {
humane.info(data.message);
} else {
humane.error(data.message);
}
(0, _jquery2.default)(":button:contains('" + localeService.t('valider') + "')", buttonPanel).attr('disabled', false).removeClass('ui-state-disabled');
}, function () {});
return false;
};
$dialog.setOption('buttons', buttons);
};
var _getMovableRecords = function _getMovableRecords(datas) {
return _jquery2.default.ajax({
type: 'POST',
url: url + 'prod/records/movecollection/',
data: datas
});
};
var _postMovableRecords = function _postMovableRecords(datas) {
return _jquery2.default.ajax({
type: 'POST',
url: url + 'prod/records/movecollection/apply/',
dataType: 'json',
data: datas
});
};
return { openModal: openModal };
};
exports.default = moveRecord;
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
var _utils = __webpack_require__(39);
var _sprintfJs = __webpack_require__(59);
var _layout = __webpack_require__(113);
var _layout2 = _interopRequireDefault(_layout);
var _presets = __webpack_require__(114);
var _presets2 = _interopRequireDefault(_presets);
var _searchReplace = __webpack_require__(115);
var _searchReplace2 = _interopRequireDefault(_searchReplace);
var _preview = __webpack_require__(116);
var _preview2 = _interopRequireDefault(_preview);
var _thesaurusDatasource = __webpack_require__(143);
var _thesaurusDatasource2 = _interopRequireDefault(_thesaurusDatasource);
var _geonameDatasource = __webpack_require__(144);
var _geonameDatasource2 = _interopRequireDefault(_geonameDatasource);
var _mapbox = __webpack_require__(50);
var _mapbox2 = _interopRequireDefault(_mapbox);
var _emitter = __webpack_require__(15);
var _emitter2 = _interopRequireDefault(_emitter);
var _recordCollection = __webpack_require__(165);
var _recordCollection2 = _interopRequireDefault(_recordCollection);
var _fieldCollection = __webpack_require__(51);
var _fieldCollection2 = _interopRequireDefault(_fieldCollection);
var _statusCollection = __webpack_require__(167);
var _statusCollection2 = _interopRequireDefault(_statusCollection);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(14);
__webpack_require__(19);
var recordEditorService = function recordEditorService(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var recordEditorEvents = void 0;
var $container = null;
var options = {};
var recordConfig = {};
var ETHSeeker = void 0;
var $editorContainer = null;
var $ztextStatus = void 0;
var $editTextArea = void 0;
var $editMonoValTextArea = void 0;
var $editMultiValTextArea = void 0;
var $toolsTabs = void 0;
var $idExplain = void 0;
var initialize = function initialize(params) {
var _params;
var initWith = (_params = params, $container = _params.$container, recordConfig = _params.recordConfig, _params);
recordEditorEvents = new _emitter2.default();
options = {};
$editorContainer = options.$container = $container; //$('#idFrameE');
options.recordConfig = recordConfig || {};
options.textareaIsDirty = false;
options.fieldLastValue = '';
options.lastClickId = null;
options.sbas_id = false;
options.what = false;
options.newrepresent = false;
$ztextStatus = (0, _jquery2.default)('#ZTextStatus', options.$container);
$editTextArea = (0, _jquery2.default)('#idEditZTextArea', options.$container);
$editMonoValTextArea = (0, _jquery2.default)('#ZTextMonoValued', options.$container);
$editMultiValTextArea = (0, _jquery2.default)('#EditTextMultiValued', options.$container);
$toolsTabs = (0, _jquery2.default)('#EDIT_MID_R .tabs', options.$container);
$idExplain = (0, _jquery2.default)('#idExplain', options.$container);
$toolsTabs.tabs({
activate: function activate(event, ui) {
recordEditorEvents.emit('tabChange', {
tab: ui.newPanel.selector
});
}
});
_bindEvents();
startThisEditing(recordConfig);
};
var _bindEvents = function _bindEvents() {
onUserInputComplete = _underscore2.default.debounce(onUserInputComplete, 300);
recordEditorEvents.listenAll({
'recordEditor.addMultivaluedField': addValueInMultivaluedField,
'recordEditor.onUpdateFields': refreshFields,
'recordEditor.submitAllChanges': submitChanges,
'recordEditor.cancelAllChanges': cancelChanges,
'recordEditor.addValueFromDataSource': addValueFromDataSource,
'recordEditor.addPresetValuesFromDataSource': addPresetValuesFromDataSource,
/* eslint-disable quote-props */
appendTab: appendTab,
'recordEditor.activateToolTab': activateToolTab
});
// set grouping (regroupement) image
$editorContainer.parent().on('click', '.set-grouping-image-action', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
setRegDefault($el.data('index'), $el.data('record-id'));
});
$editorContainer.on('click', '.select-record-action', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
_onSelectRecord(event, $el.data('index'));
})
// status field edition
.on('click', '.edit-status-action', function (event) {
event.cancelBubble = true;
event.stopPropagation();
if (!options.textareaIsDirty || validateFieldChanges(event, 'ask_ok') === true) {
enableStatusField(event);
}
return false;
})
// edit field by name / set active for edition
.on('click', '.edit-field-action', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
if (!options.textareaIsDirty || validateFieldChanges(event, 'ask_ok') === true) {
onSelectField(event, $el.data('id'));
}
return false;
}).on('click', '.field-navigate-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dir = $el.data('direction') === 'forward' ? 1 : -1;
fieldNavigate(event, dir);
}).on('submit', '.add-multivalued-field-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var fieldValue = (0, _jquery2.default)('#' + $el.data('input-id')).val();
addValueInMultivaluedField({ value: fieldValue });
}).on('click', '.edit-multivalued-field-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
_editMultivaluedField($el, $el.data('index'));
}).on('click', '.toggle-status-field-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var state = $el.data('state') === true ? 1 : 0;
toggleStatus(event, $el.data('bit'), state);
}).on('click', '.commit-field-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
validateFieldChanges(event, $el.data('mode'));
}).on('click', '.apply-multi-desc-action', function (event) {
event.preventDefault();
submitChanges({ event: event });
}).on('click', '.cancel-multi-desc-action', function (event) {
event.preventDefault();
cancelChanges({ event: event });
}).on('mouseup mousedown keyup keydown', '#idEditZTextArea', function (event) {
switch (event.type) {
case 'mouseup':
_onTextareaMouseUp(event);
break;
case 'mousedown':
_onTextareaMouseDown(event);
break;
case 'keyup':
_onTextareaKeyUp(event);
break;
case 'keydown':
_onTextareaKeyDown(event);
break;
default:
}
});
};
var onGlobalKeydown = function onGlobalKeydown(event, specialKeyState) {
if (specialKeyState === undefined) {
var _specialKeyState = {
isCancelKey: false,
isShortcutKey: false
};
}
switch (event.keyCode) {
case 9:
// tab ou shift-tab
fieldNavigate(event, appCommons.utilsModule.is_shift_key(event) ? -1 : 1);
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
case 27:
cancelChanges({ event: event });
specialKeyState.isShortcutKey = true;
break;
case 33:
// pg up
if (!options.textareaIsDirty || validateFieldChanges(event, 'ask_ok')) {
skipImage(event, 1);
}
specialKeyState.isCancelKey = true;
break;
case 34:
// pg dn
if (!options.textareaIsDirty || validateFieldChanges(event, 'ask_ok')) {
skipImage(event, -1);
}
specialKeyState.isCancelKey = true;
break;
default:
}
return specialKeyState;
};
function startThisEditing(params) {
// sbas_id, what, regbasprid, ssel) {
var hasMultipleDatabases = params.hasMultipleDatabases,
databoxId = params.databoxId,
mode = params.mode,
notActionable = params.notActionable,
notActionableMsg = params.notActionableMsg,
state = params.state;
if (hasMultipleDatabases === true) {
(0, _jquery2.default)('#EDITWINDOW').hide();
// editor can't be run
(0, _jquery2.default)('#dialog-edit-many-sbas', options.$container).dialog({
modal: true,
resizable: false,
buttons: {
Ok: function Ok() {
(0, _jquery2.default)(this).dialog('close');
}
}
});
return;
}
if (notActionable > 0) {
alert(notActionableMsg);
}
options.sbas_id = databoxId;
options.what = mode;
options = (0, _lodash2.default)(options, state);
options.fieldCollection = new _fieldCollection2.default(state.T_fields);
options.statusCollection = new _statusCollection2.default(state.T_statbits);
options.recordCollection = new _recordCollection2.default(state.T_records, options.fieldCollection, options.statusCollection, state.T_sgval);
$editMultiValTextArea.bind('keyup', function () {
_reveal_mval((0, _jquery2.default)(this).val());
});
(0, _jquery2.default)('#divS div.edit_field:odd').addClass('odd');
(0, _jquery2.default)('#divS div').bind('mouseover', function () {
(0, _jquery2.default)(this).addClass('hover');
}).bind('mouseout', function () {
(0, _jquery2.default)(this).removeClass('hover');
});
(0, _jquery2.default)('#editcontextwrap').remove();
if ((0, _jquery2.default)('#editcontextwrap').length === 0) {
(0, _jquery2.default)('body').append('<div id="editcontextwrap"></div>');
}
// if is a group, only select the group
if (options.what === 'GRP') {
_toggleGroupSelection();
} else {
_edit_select_all();
}
/**Edit Story Select all item **/
(0, _jquery2.default)('#select-all-diapo').change(function () {
if (this.checked) {
_edit_select_all_right(true);
} else {
_edit_select_all_right(false);
}
});
(0, _jquery2.default)('.previewTips, .DCESTips, .fieldTips', options.$container).tooltip({
fixable: true,
fixableIndex: 1200
});
(0, _jquery2.default)('.infoTips', options.$container).tooltip();
if (options.what === 'GRP') {
(0, _jquery2.default)('#EDIT_FILM2 .reg_opts').show();
_jquery2.default.each((0, _jquery2.default)('#EDIT_FILM2 .contextMenuTrigger'), function () {
var id = (0, _jquery2.default)(this).attr('id').split('_').slice(1, 3).join('_');
(0, _jquery2.default)(this).contextMenu('#editContext_' + id + '', {
appendTo: '#editcontextwrap',
openEvt: 'click',
dropDown: true,
theme: 'vista',
showTransition: 'slideDown',
hideTransition: 'hide',
shadow: false
});
});
}
(0, _jquery2.default)('#idEditDateZone', options.$container).datepicker({
changeYear: true,
changeMonth: true,
dateFormat: 'yy/mm/dd',
onSelect: function onSelect(dateText, inst) {
var lval = $editTextArea.val();
if (lval !== dateText) {
options.fieldLastValue = lval;
$editTextArea.val(dateText);
$editTextArea.trigger('keyup.maxLength');
options.textareaIsDirty = true;
validateFieldChanges(null, 'ok');
}
}
});
checkRequiredFields();
try {
(0, _jquery2.default)('#divS .edit_field:first').trigger('mousedown');
} catch (err) {}
var recordEditorServices = {
configService: configService,
localeService: localeService,
recordEditorEvents: recordEditorEvents
};
(0, _layout2.default)(recordEditorServices).initialize({
$container: $editorContainer,
parentOptions: options
});
(0, _presets2.default)(recordEditorServices).initialize({
$container: $editorContainer,
parentOptions: options
});
// init plugins
(0, _searchReplace2.default)(recordEditorServices).initialize({
$container: $editorContainer,
parentOptions: options
});
(0, _preview2.default)(recordEditorServices).initialize({
$container: (0, _jquery2.default)('#TH_Opreview .PNB10'),
parentOptions: options
});
(0, _geonameDatasource2.default)(recordEditorServices).initialize({
$container: $editorContainer,
parentOptions: options,
$editTextArea: $editTextArea,
$editMultiValTextArea: $editMultiValTextArea
});
(0, _mapbox2.default)({
configService: configService,
localeService: localeService,
eventEmitter: recordEditorEvents
}).initialize({
$container: $editorContainer,
parentOptions: options,
searchable: true,
tabOptions: {
position: 2
},
editable: true
});
ETHSeeker = (0, _thesaurusDatasource2.default)(recordEditorServices).initialize({
$container: $editorContainer,
parentOptions: options,
$editTextArea: $editTextArea,
$editMultiValTextArea: $editMultiValTextArea
});
recordEditorEvents.emit('recordSelection.changed', {
selection: getRecordSelection()
});
}
function _toggleGroupSelection() {
var groupIndex = 0;
_onSelectRecord(false, groupIndex);
}
function skipImage(evt, step) {
var cache = (0, _jquery2.default)('#EDIT_FILM2');
var first = (0, _jquery2.default)('.diapo.selected:first', cache);
var last = (0, _jquery2.default)('.diapo.selected:last', cache);
var sel = (0, _jquery2.default)('.diapo.selected', cache);
sel.removeClass('selected');
var i = step === 1 ? parseInt(last.attr('pos'), 10) + 1 : parseInt(first.attr('pos'), 10) - 1;
if (i < 0) {
i = parseInt((0, _jquery2.default)('.diapo:last', cache).attr('pos'), 10);
} else if (i >= (0, _jquery2.default)('.diapo', cache).length) {
i = 0;
}
_onSelectRecord(evt, i);
}
function setRegDefault(n, record_id) {
options.newrepresent = record_id;
var src = (0, _jquery2.default)('#idEditDiapo_' + n).find('img.edit_IMGT').attr('src');
var style = (0, _jquery2.default)('#idEditDiapo_' + n).find('img.edit_IMGT').attr('style');
(0, _jquery2.default)('#EDIT_GRPDIAPO .edit_IMGT').attr('src', src).attr('style', style);
}
// // ---------------------------------------------------------------------------
// // on change de champ courant
// // ---------------------------------------------------------------------------
/**
* Set a field active by it's meta struct id
* Open it's editor
* @param evt
* @param fieldIndex
* @private
*/
function onSelectField(evt, fieldIndex) {
$editTextArea.blur();
$editMultiValTextArea.blur();
(0, _jquery2.default)('.editDiaButtons', options.$container).hide();
(0, _jquery2.default)($editTextArea, $editMultiValTextArea).unbind('keyup.maxLength');
var fields = options.fieldCollection.getFields();
var field = options.fieldCollection.getFieldByIndex(fieldIndex);
if (fieldIndex >= 0) {
// @TODO field edition area should be hooked by plugins
if (fields === undefined || fields.length === 0) {
return;
}
if (field !== undefined) {
var name = field.required ? field.label + '<span style="font-weight:bold;font-size:16px;"> * </span>' : field.label;
(0, _jquery2.default)('#idFieldNameEdit', options.$container).html(name);
var suggestedValuesCollection = options.recordCollection.getFieldSuggestedValues(); //{};
if (!_underscore2.default.isEmpty(suggestedValuesCollection[fieldIndex])) {
var selectElement = (0, _jquery2.default)('<select><option selected disabled>' + localeService.t("suggested_values") + '</option> </select>');
var selectIdValue = "idSelectSuggestedValues_" + fieldIndex;
selectElement.attr('id', selectIdValue);
_jquery2.default.each(suggestedValuesCollection[fieldIndex], function (key, value) {
var optionElement = (0, _jquery2.default)("<option></option>");
optionElement.attr("value", key);
optionElement.text(key);
selectElement.append(optionElement);
});
selectElement.on('change', function (e) {
if (field.multi === true) {
$editMultiValTextArea.val((0, _jquery2.default)(this).val());
$editMultiValTextArea.trigger('keyup.maxLength');
addValueInMultivaluedField({
value: $editMultiValTextArea.val()
});
} else {
if (appCommons.utilsModule.is_ctrl_key(e)) {
var t = $editTextArea.val();
$editTextArea.val(t + (t ? ' ; ' : '') + (0, _jquery2.default)(this).val());
} else {
$editTextArea.val((0, _jquery2.default)(this).val());
}
$editTextArea.trigger('keyup.maxLength');
options.textareaIsDirty = true;
if (field._status !== 2) {
validateFieldChanges(evt, 'ask_ok');
}
}
});
(0, _jquery2.default)('#idFieldSuggestedValues', options.$container).empty().append(selectElement);
(0, _jquery2.default)('#idFieldSuggestedValues', options.$container).css('visibility', 'visible');
(0, _jquery2.default)('.edit-zone-title', options.$container).css('height', 80);
(0, _jquery2.default)('#EDIT_EDIT', options.$container).css('top', 80);
} else {
(0, _jquery2.default)('#idFieldSuggestedValues', options.$container).css('visibility', 'hidden');
(0, _jquery2.default)('.edit-zone-title', options.$container).css('height', 45);
(0, _jquery2.default)('#EDIT_EDIT', options.$container).css('top', 45);
}
// attachFieldVocabularyAutocomplete
(0, _jquery2.default)($editTextArea, $editMultiValTextArea).autocomplete({
minLength: 2,
appendTo: '#idEditZone',
source: function source(request, response) {
_jquery2.default.ajax({
url: url + 'prod/records/edit/vocabulary/' + field.vocabularyControl + '/',
dataType: 'json',
data: {
sbas_id: options.sbas_id,
query: request.term
},
success: function success(data) {
response(data.results);
}
});
},
select: function select(event, ui) {
addValueInMultivaluedField({
value: ui.item.label,
vocabularyId: ui.item.id
});
return false;
}
});
// attachFieldLengthRestriction
if (field.maxLength > 0) {
$idExplain.html('');
(0, _jquery2.default)($editTextArea, $editMultiValTextArea).bind('keyup.maxLength', function (event) {
var $this = (0, _jquery2.default)(event.currentTarget);
var remaining = Math.max(field.maxLength - (0, _jquery2.default)(this).val().length, 0);
$idExplain.html('\n <span class=\'metadatas_restrictionsTips\' tooltipsrc="' + url + 'prod/tooltip/metas/restrictionsInfos/' + options.sbas_id + '/' + fieldIndex + '/">\n <img src=\'/assets/common/images/icons/help32.png\' /> Caracteres restants : ' + remaining + '</span>\n ');
(0, _jquery2.default)('.metadatas_restrictionsTips', $idExplain).tooltip();
}).trigger('keyup.maxLength');
} else {
$idExplain.html('');
}
if (!field.multi) {
// champ monovalue : textarea
(0, _jquery2.default)('.editDiaButtons', options.$container).hide();
if (field.type === 'date') {
$editTextArea.css('height', '16px');
(0, _jquery2.default)('#idEditDateZone', options.$container).show();
} else {
(0, _jquery2.default)('#idEditDateZone', options.$container).hide();
$editTextArea.css('height', '100%');
}
$ztextStatus.hide();
(0, _jquery2.default)('#ZTextMultiValued', options.$container).hide();
$editMonoValTextArea.show();
if (field._status === 2) {
// heterogene
$editTextArea.val(options.fieldLastValue = '');
$editTextArea.addClass('hetero');
(0, _jquery2.default)('#idDivButtons', options.$container).show(); // valeurs h<>t<EFBFBD>rog<6F>nes : les 3 boutons remplacer/ajouter/annuler
} else {
// homogene
$editTextArea.val(options.fieldLastValue = field._value);
$editTextArea.removeClass('hetero');
(0, _jquery2.default)('#idDivButtons', options.$container).hide(); // valeurs homog<6F>nes
if (field.type === 'date') {
var v = field._value.split(' ');
var d = v[0].split('/');
var dateObj = new Date();
if (d.length === 3) {
dateObj.setYear(d[0]);
dateObj.setMonth(d[1] - 1);
dateObj.setDate(d[2]);
}
if ((0, _jquery2.default)('#idEditDateZone', options.$container).data('ui-datepicker')) {
(0, _jquery2.default)('#idEditDateZone', options.$container).datepicker('setDate', dateObj);
}
}
}
options.textareaIsDirty = false;
(0, _jquery2.default)('#idEditZone', options.$container).show();
$editTextArea.trigger('keyup.maxLength');
self.setTimeout(function () {
return $editTextArea.focus();
}, 50);
} else {
// champ multivalue : liste
$ztextStatus.hide();
$editMonoValTextArea.hide();
(0, _jquery2.default)('#ZTextMultiValued', options.$container).show();
(0, _jquery2.default)('#idDivButtons', options.$container).hide(); // valeurs homogenes
_updateCurrentMval(fieldIndex);
$editMultiValTextArea.val('');
(0, _jquery2.default)('#idEditZone', options.$container).show();
$editMultiValTextArea.trigger('keyup.maxLength');
self.setTimeout(function () {
return $editMultiValTextArea.focus();
}, 50);
// reveal_mval();
}
}
} else {
// pas de champ, masquer la zone du textarea
(0, _jquery2.default)('#idEditZone', options.$container).hide();
(0, _jquery2.default)('.editDiaButtons', options.$container).hide();
}
setActiveField(fieldIndex);
}
function refreshFields(evt) {
(0, _jquery2.default)('.editDiaButtons', options.$container).hide();
// initialize values:
var initializedStatus = options.statusCollection.fillWithRecordValues(options.recordCollection.getRecords());
// tous les statusbits de la base
for (var statusIndex in initializedStatus) {
var ck0 = (0, _jquery2.default)('#idCheckboxStatbit0_' + statusIndex);
var ck1 = (0, _jquery2.default)('#idCheckboxStatbit1_' + statusIndex);
switch (initializedStatus[statusIndex]._value) {
case '0':
case 0:
ck0.removeClass('gui_ckbox_0 gui_ckbox_2').addClass('gui_ckbox_1');
ck1.removeClass('gui_ckbox_1 gui_ckbox_2').addClass('gui_ckbox_0');
break;
case '1':
case 1:
ck0.removeClass('gui_ckbox_1 gui_ckbox_2').addClass('gui_ckbox_0');
ck1.removeClass('gui_ckbox_0 gui_ckbox_2').addClass('gui_ckbox_1');
break;
case '2':
ck0.removeClass('gui_ckbox_0 gui_ckbox_1').addClass('gui_ckbox_2');
ck1.removeClass('gui_ckbox_0 gui_ckbox_1').addClass('gui_ckbox_2');
break;
default:
}
}
var nostatus = (0, _jquery2.default)('.diapo.selected.nostatus', options.$container).length;
var status_box = (0, _jquery2.default)('#ZTextStatus');
(0, _jquery2.default)('.nostatus, .somestatus, .displaystatus', status_box).hide();
if (nostatus === 0) {
(0, _jquery2.default)('.displaystatus', status_box).show();
} else {
var yesstatus = (0, _jquery2.default)('.diapo.selected', options.$container).length;
if (nostatus === yesstatus) {
(0, _jquery2.default)('.nostatus', status_box).show();
} else {
(0, _jquery2.default)('.somestatus, .displaystatus', status_box).show();
}
}
populateFields();
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
if (fieldIndex === -1) {
enableStatusField(evt);
} else {
onSelectField(evt, fieldIndex);
}
}
/**
* Populate all fields values from [1-n] records data
*/
function populateFields() {
var records = options.recordCollection.getRecords();
var fields = options.fieldCollection.getFields();
// tous les champs de la base
for (var f in fields) {
var currentField = options.fieldCollection.getFieldByIndex(f);
currentField._status = 0; // val unknown
for (var i in records) {
var currentRecord = options.recordCollection.getRecordByIndex(i);
if (!currentRecord._selected) {
continue;
}
var _v = '';
if (!currentRecord.fields[f].isEmpty()) {
// le champ existe dans la fiche
if (currentField.multi) {
// champ multi : on compare la concat des valeurs
_v = currentRecord.fields[f].getSerializedValues();
} else {
_v = currentRecord.fields[f].getValue().getValue();
}
}
if (currentField._status === 0) {
currentField._value = _v;
currentField._status = 1;
} else if (currentField._status === 1 && currentField._value !== _v) {
currentField._value = '*****';
currentField._status = 2;
break; // plus la peine de verifier le champ sur les autres records
}
}
var o = document.getElementById('idEditField_' + f);
if (o) {
// mixed
if (currentField._status === 2) {
o.innerHTML = "<span class='hetero'>xxxxx</span>";
} else {
var v = currentField._value;
v = v instanceof Array ? v.join(';') : v;
o.innerHTML = (0, _utils.cleanTags)(v).replace(/\n/gm, "<span style='color:#0080ff'>&para;</span><br/>");
}
}
options.fieldCollection.updateField(f, currentField);
}
}
/**
* enable pseudo-field "status"
* @param evt
*/
function enableStatusField(evt) {
(0, _jquery2.default)('.editDiaButtons', options.$container).hide();
$editTextArea.blur();
$editMultiValTextArea.blur();
(0, _jquery2.default)('#idFieldNameEdit', options.$container).html('[STATUS]');
$idExplain.html('&nbsp;');
(0, _jquery2.default)('#ZTextMultiValued', options.$container).hide();
$editMonoValTextArea.hide();
$ztextStatus.show();
(0, _jquery2.default)('#idEditZone', options.$container).show();
document.getElementById('editFakefocus').focus();
// options.curField = -1;
setActiveField(-1);
}
function _updateCurrentMval(metaStructId, highlightValue, vocabularyId) {
// on compare toutes les valeurs de chaque fiche selectionnee
options.T_mval = []; // tab des mots, pour trier
var a = []; // key : mot ; val : nbr d'occurences distinctes
var n = 0; // le nbr de records selectionnes
var records = options.recordCollection.getRecords();
for (var r in records) {
var currentRecord = options.recordCollection.getRecordByIndex(r);
if (!currentRecord._selected) {
continue;
}
currentRecord.fields[metaStructId].sort(_sortCompareMetas);
var values = currentRecord.fields[metaStructId].getValues();
for (var v in values) {
var word = values[v].getValue();
var key = values[v].getVocabularyId() + '%' + word;
if (typeof a[key] === 'undefined') {
a[key] = {
n: 0,
f: []
}; // n:nbr d'occurences DISTINCTES du mot ; f:flag presence mot dans r
options.T_mval.push(values[v]);
}
if (!a[key].f[r]) {
a[key].n++; // premiere apparition du mot dans le record r
}
a[key].f[r] = true; // on ne recomptera pas le mot s'il apparait a nouveau dans le meme record
}
n++;
}
options.T_mval.sort(_sortCompareMetas);
var t = '';
// pour lire le tableau 'a' dans l'ordre trie par 'editor.T_mval'
for (var i in options.T_mval) {
var value = options.T_mval[i];
var _word = value.getValue();
var _key = value.getVocabularyId() + '%' + _word;
var extra = value.getVocabularyId() ? '<img src="/assets/common/images/icons/ressource16.png" /> ' : '';
if (i > 0) {
if (value.getVocabularyId() !== null && options.T_mval[i - 1].getVocabularyId() === value.getVocabularyId()) {
continue;
}
if (value.getVocabularyId() === null && options.T_mval[i - 1].getVocabularyId() === null) {
if (options.T_mval[i - 1].getValue() === value.getValue()) {
continue; // on n'accepte pas les doublons
}
}
}
t += '<div data-index="' + i + '" class="edit-multivalued-field-action ' + ((value.getVocabularyId() === null || value.getVocabularyId() === vocabularyId) && highlightValue === _word ? ' hilighted ' : '') + (a[_key].n !== n ? ' hetero ' : '') + '">' + '<table><tr><td>' + extra + '<span class="value" vocabId="' + (value.getVocabularyId() ? value.getVocabularyId() : '') + '">' + (0, _jquery2.default)('<div/>').text(_word).html() + "</span></td><td class='options'>" + '<a href="#" class="add_all"><span class="icon-round-add_box-24px icomoon" style="font-size: 15px"></span></a> ' + '<a href="#" class="remove_all"><span class="icon-baseline-indeterminate_check_box-24px icomoon" style="font-size: 15px;"></span></a>' + '</td></tr></table>' + '</div>';
}
(0, _jquery2.default)('#ZTextMultiValued_values', options.$container).html(t);
(0, _jquery2.default)('#ZTextMultiValued_values .add_all', options.$container).unbind('click').bind('click', function () {
var container = (0, _jquery2.default)(this).closest('div');
var span = (0, _jquery2.default)('span.value', container);
var value = span.text();
var vocab_id = span.attr('vocabid');
addValueInMultivaluedField({
value: value,
vocabularyId: vocab_id
});
populateFields();
return false;
});
(0, _jquery2.default)('#ZTextMultiValued_values .remove_all', options.$container).unbind('click').bind('click', function () {
var container = (0, _jquery2.default)(this).closest('div');
var span = (0, _jquery2.default)('span.value', container);
var value = span.text();
var vocab_id = span.attr('vocabid');
removeValueFromMultivaluedField(value, vocab_id);
populateFields();
return false;
});
populateFields();
}
// ---------------------------------------------------------------------------------------------------------
// en mode textarea, on clique sur ok, cancel ou fusion
// appele egalement quand on essaye de changer de champ ou d'image : si ret=false on interdit le changement
// ---------------------------------------------------------------------------------------------------------
function validateFieldChanges(evt, action) {
// action : 'ok', 'fusion' ou 'cancel'
if (options.fieldCollection.getActiveFieldIndex() === '?') {
return true;
}
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
var currentField = options.fieldCollection.getActiveField();
var records = options.recordCollection.getRecords();
if (action === 'cancel') {
// on restore le contenu du champ
$editTextArea.val(options.fieldLastValue);
$editTextArea.trigger('keyup.maxLength');
options.textareaIsDirty = false;
return true;
}
if (action === 'ask_ok' && options.textareaIsDirty && currentField._status === 2) {
alert(localeService.t('edit_hetero'));
return false;
}
var o = document.getElementById('idEditField_' + fieldIndex);
if (o !== undefined) {
var t = $editTextArea.val();
for (var recordIndex in records) {
var record = options.recordCollection.getRecordByIndex(recordIndex);
if (!record._selected) {
continue; // on ne modifie pas les fiches non selectionnees
}
if (action === 'ok' || action === 'ask_ok') {
options.recordCollection.addRecordFieldValue(recordIndex, fieldIndex, {
value: t,
merge: false,
vocabularyId: null
});
} else if (action === 'fusion' || action === 'ask_fusion') {
options.recordCollection.addRecordFieldValue(recordIndex, fieldIndex, {
value: t,
merge: true,
vocabularyId: null
});
}
checkRequiredFields(recordIndex, fieldIndex);
}
}
populateFields();
options.textareaIsDirty = false;
onSelectField(evt, fieldIndex);
return true;
}
// ---------------------------------------------------------------------------
// on a clique sur une checkbox de status
// ---------------------------------------------------------------------------
function toggleStatus(evt, bit, val) {
var ck0 = (0, _jquery2.default)('#idCheckboxStatbit0_' + bit);
var ck1 = (0, _jquery2.default)('#idCheckboxStatbit1_' + bit);
switch (val) {
case 0:
ck0.attr('class', 'gui_ckbox_1');
ck1.attr('class', 'gui_ckbox_0');
break;
case 1:
ck0.attr('class', 'gui_ckbox_0');
ck1.attr('class', 'gui_ckbox_1');
break;
default:
}
options.recordCollection.setStatus(bit, val);
}
// ---------------------------------------------------------------------------
// on a clique sur une thumbnail
// ---------------------------------------------------------------------------
function _onSelectRecord(event, recordIndex) {
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
if (fieldIndex >= 0) {
if (options.textareaIsDirty && validateFieldChanges(event, 'ask_ok') === false) {
return;
}
}
var records = options.recordCollection.getRecords();
var record = options.recordCollection.getRecordByIndex(recordIndex);
// guideline : si on mousedown sur une selection, c'est qu'on risque de draguer, donc on ne desectionne pas
if (event && event.type === 'mousedown' && record._selected) {
return;
}
if (event && appCommons.utilsModule.is_shift_key(event) && options.lastClickId !== null) {
// shift donc on sel du editor.lastClickId a ici
var pos_from = options.T_pos[options.lastClickId];
var pos_to = options.T_pos[recordIndex];
if (pos_from > pos_to) {
var tmp = pos_from;
pos_from = pos_to;
pos_to = tmp;
}
for (var pos = pos_from; pos <= pos_to; pos++) {
var id = options.T_id[pos];
var _record = options.recordCollection.getRecordByIndex(id);
// toutes les fiches selectionnees
if (!_record._selected) {
_record._selected = true;
(0, _jquery2.default)('#idEditDiapo_' + id, options.$container).addClass('selected');
}
}
} else {
if (!event || !appCommons.utilsModule.is_ctrl_key(event)) {
// on deselectionne tout avant
for (var _recordIndex2 in records) {
var _record2 = options.recordCollection.getRecordByIndex(_recordIndex2);
// toutes les fiches selectionnees
if (_record2._selected) {
_record2._selected = false;
(0, _jquery2.default)('#idEditDiapo_' + _recordIndex2, options.$container).removeClass('selected');
}
}
}
if (recordIndex >= 0) {
record._selected = !record._selected;
if (record._selected) {
(0, _jquery2.default)('#idEditDiapo_' + recordIndex, options.$container).addClass('selected');
} else {
(0, _jquery2.default)('#idEditDiapo_' + recordIndex, options.$container).removeClass('selected');
}
}
}
var selection = [];
var allRecords = (0, _jquery2.default)('#EDIT_FILM2 .diapo');
var selected = (0, _jquery2.default)('#EDIT_FILM2 .diapo.selected');
if (selected.length === 1) {
var r = selected.attr('id').split('_').pop();
recordEditorEvents.emit('recordEditor.onSelectRecord', {
recordIndex: r
});
selection.push(r);
} else {
for (var _pos = 0; _pos < selected.length; _pos++) {
var $record = (0, _jquery2.default)(selected[_pos]);
selection.push($record.attr('id').split('_').pop());
}
recordEditorEvents.emit('recordSelection.changed', {
selection: getRecordSelection()
});
}
/**trigger select all checkbox**/
if (selected.length < allRecords.length) {
(0, _jquery2.default)("#select-all-diapo").removeAttr("checked");
} else {
if (selected.length == allRecords.length) {
(0, _jquery2.default)("#select-all-diapo").trigger("click");
}
};
options.lastClickId = recordIndex;
refreshFields(event);
}
function getRecordSelection() {
var selection = [];
var selected = (0, _jquery2.default)('#EDIT_FILM2 .diapo.selected');
for (var pos = 0; pos < selected.length; pos++) {
var $record = (0, _jquery2.default)(selected[pos]);
selection.push($record.attr('id').split('_').pop());
}
return selection;
}
// ----------------------------------------------------------------------------------
// on a clique sur le 'ok' general : save
// ----------------------------------------------------------------------------------
function submitChanges(fnParams) {
var event = fnParams.event;
if (options.textareaIsDirty && validateFieldChanges(event, 'ask_ok') === false) {
return false;
}
var required_fields = checkRequiredFields();
if (required_fields) {
alert(localeService.t('some_required_fields'));
return false;
}
(0, _jquery2.default)('#EDIT_ALL', options.$container).hide();
(0, _jquery2.default)('#EDIT_WORKING', options.$container).show();
var params = {
mds: options.recordCollection.gatherUpdatedRecords(),
sbid: options.sbas_id,
act: 'WORK',
lst: (0, _jquery2.default)('#edit_lst').val(),
act_option: 'SAVE' + options.what,
ssel: options.ssel
};
if (options.newrepresent !== false) {
params.newrepresent = options.newrepresent;
}
_jquery2.default.ajax({
url: url + 'prod/records/edit/apply/',
data: params,
type: 'POST',
success: function success(data) {
if (options.what === 'GRP' || options.what === 'SSEL') {
recordEditorEvents.emit('workzone.refresh', {
basketId: 'current'
});
}
closeModal();
// $('#Edit_copyPreset_dlg').remove();
// $('#EDITWINDOW').hide();
// $editorContainer.find('*').addBack().off();
recordEditorEvents.emit('preview.doReload');
return;
}
});
}
function cancelChanges(params) {
var event = params.event;
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
var dirty = false;
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
if (fieldIndex >= 0) {
if (options.textareaIsDirty && validateFieldChanges(event, 'ask_ok') === false) {
return;
}
}
dirty = options.recordCollection.isDirty();
if (!dirty || confirm(localeService.t('confirm_abandon'))) {
closeModal();
}
}
var closeModal = function closeModal() {
(0, _jquery2.default)('#Edit_copyPreset_dlg').remove();
(0, _jquery2.default)('#idFrameE .ww_content', options.$container).empty();
$toolsTabs.hide().tabs('destroy');
$container.find('*').addBack().off();
$container.fadeOut().empty();
options = {};
recordEditorEvents.dispose();
};
function setActiveField(fieldIndex) {
// let metaStructId = parseInt(options.curField, 10);
options.fieldCollection.setActiveField(fieldIndex);
fieldIndex = isNaN(fieldIndex) || fieldIndex < 0 ? 'status' : fieldIndex;
(0, _jquery2.default)('#divS div.active, #divS div.hover').removeClass('active hover');
(0, _jquery2.default)('#EditFieldBox_' + fieldIndex).addClass('active');
var cont = (0, _jquery2.default)('#divS');
var calc = (0, _jquery2.default)('#EditFieldBox_' + fieldIndex).offset().top - cont.offset().top; // hauteur relative par rapport au visible
if (calc > cont.height() || calc < 0) {
cont.scrollTop(calc + cont.scrollTop());
}
}
function _sortCompareMetas(a, b) {
if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) !== 'object') {
return -1;
}
if ((typeof b === 'undefined' ? 'undefined' : _typeof(b)) !== 'object') {
return 1;
}
var na = a.getValue().toUpperCase();
var nb = b.getValue().toUpperCase();
if (na === nb) {
return 0;
}
return na < nb ? -1 : 1;
}
function checkRequiredFields(inputRecordIndex, inputFieldIndex) {
var fieldCollection = options.fieldCollection.getFields();
var recordCollection = options.recordCollection.getRecords();
var requiredFields = false;
if (typeof inputRecordIndex === 'undefined') {
inputRecordIndex = false;
}
if (typeof inputFieldIndex === 'undefined') {
inputFieldIndex = false;
}
for (var fieldIndex in fieldCollection) {
var currentField = options.fieldCollection.getFieldByIndex(fieldIndex);
if (inputFieldIndex !== false && fieldIndex !== inputFieldIndex) {
continue;
}
if (!currentField.required) {
continue;
}
for (var recordIndex in recordCollection) {
var currentRecord = options.recordCollection.getRecordByIndex(recordIndex);
if (inputRecordIndex !== false && recordIndex !== inputRecordIndex) {
continue;
}
var elem = (0, _jquery2.default)('#idEditDiapo_' + recordIndex + ' .require_alert');
elem.hide();
if (!currentRecord.fields[fieldIndex]) {
elem.show();
requiredFields = true;
} else {
var checkRequired = '';
// le champ existe dans la fiche
if (currentField.multi) {
// champ multi : on compare la concat des valeurs
checkRequired = _jquery2.default.trim(currentRecord.fields[fieldIndex].getSerializedValues());
} else if (currentRecord.fields[fieldIndex].getValue()) {
checkRequired = _jquery2.default.trim(currentRecord.fields[fieldIndex].getValue().getValue());
}
if (checkRequired === '') {
elem.show();
requiredFields = true;
}
}
}
}
return requiredFields;
}
function _edit_select_all() {
var records = options.recordCollection.getRecords();
(0, _jquery2.default)('#EDIT_FILM2 .diapo', options.$container).addClass('selected');
for (var i in records) {
records[i]._selected = true;
}
options.lastClickId = 1;
refreshFields(null); // null : no evt available
}
function _edit_select_all_right(check) {
var records = options.recordCollection.getRecords();
console.log(records);
if (check == true) {
(0, _jquery2.default)('#EDIT_FILM2 .diapo', options.$container).addClass('selected');
} else {
(0, _jquery2.default)('#EDIT_FILM2 .diapo', options.$container).removeClass('selected');
}
for (var i in records) {
if (records[i].type !== "unknown") {
records[i]._selected = check;
}
}
options.lastClickId = 0;
refreshFields(null); // null : no evt available
}
// ---------------------------------------------------------------------------
// highlight la valeur en cours de saisie dans la liste des multi-valeurs
// appele par le onkeyup
// ---------------------------------------------------------------------------
function _reveal_mval(value, vocabularyId) {
var records = options.recordCollection.getRecords();
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
var currentField = options.fieldCollection.getActiveField();
var talt = void 0;
if (typeof vocabularyId === 'undefined') {
vocabularyId = null;
}
/*if (currentField.tbranch) {
if (value !== '') {
appEvents.emit('recordEditor.userInputValue', {
context: {
event: false,
currentField,
},
value
});
// ETHSeeker.search(value);
}
}*/
onUserInputComplete(false, value, currentField);
if (value !== '') {
// let nsel = 0;
for (var recordIndex in records) {
var currentRecord = options.recordCollection.getRecordByIndex(recordIndex);
if (currentRecord.fields[fieldIndex].hasValue(value, vocabularyId)) {
(0, _jquery2.default)('#idEditDiaButtonsP_' + recordIndex).hide();
talt = (0, _sprintfJs.sprintf)(localeService.t('editDelSimple'), value);
(0, _jquery2.default)('#idEditDiaButtonsM_' + recordIndex).show().attr('alt', talt).attr('Title', talt).unbind('click').bind('click', function () {
var indice = (0, _jquery2.default)(this).attr('id').split('_').pop();
_edit_diabutton(indice, 'del', value, vocabularyId);
});
} else {
(0, _jquery2.default)('#idEditDiaButtonsM_' + recordIndex).hide();
(0, _jquery2.default)('#idEditDiaButtonsP_' + recordIndex).show();
talt = (0, _sprintfJs.sprintf)(localeService.t('editAddSimple'), value);
(0, _jquery2.default)('#idEditDiaButtonsP_' + recordIndex).show().attr('alt', talt).attr('Title', talt).unbind('click').bind('click', function () {
var indice = (0, _jquery2.default)(this).attr('id').split('_').pop();
_edit_diabutton(indice, 'add', value, vocabularyId);
});
}
}
(0, _jquery2.default)('.editDiaButtons', options.$container).show();
}
$editMultiValTextArea.trigger('focus');
return true;
}
/**
* Remove a value from a multivalued field
* @param value
* @param vocabularyId
*/
function removeValueFromMultivaluedField(value, vocabularyId) {
var records = options.recordCollection.getRecords();
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
for (var recordIndex in records) {
var currentRecord = options.recordCollection.getRecordByIndex(recordIndex);
if (!currentRecord._selected) {
continue;
}
options.recordCollection.removeRecordFieldValue(recordIndex, fieldIndex, {
value: value,
vocabularyId: vocabularyId
});
}
refreshFields(null);
}
/**
* Add a value into a multivalued field
* @param params
*/
function addValueInMultivaluedField(params) {
var value = params.value,
vocabularyId = params.vocabularyId;
var records = options.recordCollection.getRecords();
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
vocabularyId = vocabularyId === undefined ? null : vocabularyId;
for (var recordIndex in records) {
var currentRecord = options.recordCollection.getRecordByIndex(recordIndex);
if (!currentRecord._selected) {
continue;
}
options.recordCollection.addRecordFieldValue(recordIndex, fieldIndex, {
value: value,
merge: false,
vocabularyId: vocabularyId
});
}
refreshFields(null);
}
// ---------------------------------------------------------------------------
// on a clique sur une des multi-valeurs dans la liste
// ---------------------------------------------------------------------------
function _editMultivaluedField(mvaldiv, ival) {
(0, _jquery2.default)(mvaldiv).parent().find('.hilighted').removeClass('hilighted');
(0, _jquery2.default)(mvaldiv).addClass('hilighted');
_reveal_mval(options.T_mval[ival].getValue(), options.T_mval[ival].getVocabularyId());
}
function _edit_diabutton(recordIndex, act, value, vocabularyId) {
var fieldIndex = options.fieldCollection.getActiveFieldIndex();
if (act === 'del') {
options.recordCollection.removeRecordFieldValue(recordIndex, fieldIndex, {
value: value,
vocabularyId: vocabularyId
});
}
if (act === 'add') {
options.recordCollection.addRecordFieldValue(recordIndex, fieldIndex, {
value: value,
merge: false,
vocabularyId: vocabularyId
});
}
_updateCurrentMval(fieldIndex, value, vocabularyId);
_reveal_mval(value, vocabularyId);
}
// ---------------------------------------------------------------------------
// change de champ (avec les fleches autour du nom champ)
// ---------------------------------------------------------------------------
// edit_chgFld
function fieldNavigate(evt, dir) {
var current_field = (0, _jquery2.default)('#divS .edit_field.active');
if (current_field.length === 0) {
current_field = (0, _jquery2.default)('#divS .edit_field:first');
current_field.trigger('click');
} else {
if (dir >= 0) {
current_field.next().trigger('click');
} else {
current_field.prev().trigger('click');
}
}
}
var _onTextareaKeyDown = function _onTextareaKeyDown(event) {
var currentField = options.fieldCollection.getActiveField();
var $el = (0, _jquery2.default)(event.currentTarget);
var cancelKey = false;
switch (event.keyCode) {
case 13:
case 10:
if (currentField.type === 'date') {
cancelKey = true;
}
break;
default:
}
if (cancelKey) {
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
return true;
};
// ----------------------------------------------------------------------------------------------
// des events sur le textarea pour tracker la selection (chercher dans le thesaurus...)
// ----------------------------------------------------------------------------------------------
var _onTextareaMouseDown = function _onTextareaMouseDown(evt) {
evt.cancelBubble = true;
return true;
};
// mouse up textarea
var _onTextareaMouseUp = function _onTextareaMouseUp(event, obj) {
var currentField = options.fieldCollection.getActiveField();
var $el = (0, _jquery2.default)(event.currentTarget);
var value = $el.val();
onUserInputComplete(event, value, currentField);
return true;
};
// key up textarea
var _onTextareaKeyUp = function _onTextareaKeyUp(event, obj) {
var currentField = options.fieldCollection.getActiveField();
var $el = (0, _jquery2.default)(event.currentTarget);
var cancelKey = false;
var o = void 0;
switch (event.keyCode) {
case 27:
// esc : on restore la valeur avant editing
// $("#btn_cancel", editor.$container).parent().css("backgroundColor", "#000000");
validateFieldChanges(event, 'cancel');
// self.setTimeout("document.getElementById('btn_cancel').parentNode.style.backgroundColor = '';", 100);
cancelKey = true;
break;
default:
}
if (cancelKey) {
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
if (!options.textareaIsDirty && $editTextArea.val() !== options.fieldLastValue) {
options.textareaIsDirty = true;
}
var searchValue = $el.val(); // obj.value;
onUserInputComplete(event, searchValue, currentField);
return true;
};
/**
* debounceable method
* @param event
* @param value
* @param field
*/
var onUserInputComplete = function onUserInputComplete(event, value, field) {
if (value !== '') {
recordEditorEvents.emit('recordEditor.userInputValue', {
event: event,
value: value,
field: field
});
}
};
/**
* add field value from a datasource
* if the field is not specified, use active one
* @param params
*/
var addValueFromDataSource = function addValueFromDataSource(params) {
var value = params.value,
field = params.field;
if (field === undefined || field === null) {
field = options.fieldCollection.getActiveField();
}
if (field.multi) {
$editMultiValTextArea.val(value);
$editMultiValTextArea.trigger('keyup.maxLength');
recordEditorEvents.emit('recordEditor.addMultivaluedField', {
value: $editMultiValTextArea.val()
});
} else {
$editTextArea.val(value);
$editTextArea.trigger('keyup.maxLength');
options.textareaIsDirty = true;
}
};
/**
* Bulk field update
* @param params
*/
var addPresetValuesFromDataSource = function addPresetValuesFromDataSource(params) {
var data = params.data;
var mode = params.mode || '';
var preselectedRecord = params.recordIndex || false;
var records = options.recordCollection.getRecords();
var fields = options.fieldCollection.getFields();
for (var fieldIndex in fields) {
var field = options.fieldCollection.getFieldByIndex(fieldIndex);
field.preset = null;
if (typeof data.fields[field.name] !== 'undefined') {
field.preset = data.fields[field.name];
}
options.fieldCollection.updateField(fieldIndex, field);
}
// apply new preset value on each record's fields
for (var recordIndex in records) {
var record = options.recordCollection.getRecordByIndex(recordIndex);
if (!record._selected) {
continue;
}
for (var _fieldIndex in fields) {
var _field = options.fieldCollection.getFieldByIndex(_fieldIndex);
if (_field.preset !== null) {
for (var val in _field.preset) {
if (preselectedRecord !== false) {
if (preselectedRecord !== recordIndex) {
// only update preselected record
continue;
}
}
// don't update filled fields in emptyOnly mode:
if (mode === 'emptyOnly' && _field._value !== '' && !record.fields[_fieldIndex].isDirty()) {
continue;
}
options.recordCollection.addRecordFieldValue(recordIndex, _fieldIndex, {
value: _field.preset[val].trim(),
merge: false,
vocabularyId: null
});
}
}
}
}
recordEditorEvents.emit('recordEditor.onUpdateFields');
};
/**
* get selected records field values
* @returns {Array}
*/
var loadSelectedRecords = function loadSelectedRecords() {
var records = options.recordCollection.getRecords();
var fields = options.fieldCollection.getFields();
var selectedRecords = [];
for (var recordIndex in records) {
var recordFieldValue = {};
var record = options.recordCollection.getRecordByIndex(recordIndex);
if (!record._selected) {
continue;
}
for (var _recordIndex in options.recordConfig.records) {
if (options.recordConfig.records[_recordIndex].id === record.rid) {
recordFieldValue["technicalInfo"] = options.recordConfig.records[_recordIndex].technicalInfo;
}
}
for (var fieldIndex in fields) {
var field = options.fieldCollection.getFieldByIndex(fieldIndex);
var value = null;
// retrieve original record value (of field)
if (field.multi) {
value = record.fields[fieldIndex].getSerializedValues();
} else {
var fieldData = record.fields[fieldIndex].getValue();
if (fieldData !== null) {
if (fieldData.datas !== undefined) {
value = fieldData.datas.value;
}
}
}
recordFieldValue[field.name] = value;
}
selectedRecords.push(recordFieldValue);
}
return selectedRecords;
};
var appendTab = function appendTab(params) {
var tabProperties = params.tabProperties,
position = params.position;
var $appendAfterTab = (0, _jquery2.default)('.tabs ul li:eq(' + (position - 1) + ')', $container);
var newTab = '<li><a href="#' + tabProperties.id + '">' + tabProperties.title + '</a></li>';
$appendAfterTab.after(newTab);
var appendAfterTabContent = (0, _jquery2.default)('.tabs > div:eq(' + (position - 1) + ')', $container);
appendAfterTabContent.after('<div id="' + tabProperties.id + '"></div>');
try {
$toolsTabs.tabs('refresh');
} catch (e) {}
recordEditorEvents.emit('appendTab.complete', {
origParams: params,
selection: loadSelectedRecords()
});
};
var activateToolTab = function activateToolTab(tabId) {
$toolsTabs.tabs('option', 'active', $toolsTabs.find('#' + tabId).index() - 1);
};
return {
initialize: initialize
//onGlobalKeydown: onGlobalKeydown,
};
};
exports.default = recordEditorService;
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var recordEditorLayout = function recordEditorLayout(services) {
var configService = services.configService,
localeService = services.localeService,
recordEditorEvents = services.recordEditorEvents;
var $container = null;
var parentOptions = {};
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, parentOptions = _options.parentOptions, _options);
(0, _jquery2.default)(window).bind('resize', function () {
recordEditorEvents.emit('recordEditor.uiResize');
_setSizeLimits();
});
_hsplit1();
_vsplit2();
_vsplit1();
(0, _jquery2.default)('#EDIT_TOP', parentOptions.$container).resizable({
handles: 's',
minHeight: 100,
resize: function resize() {
_hsplit1();
recordEditorEvents.emit('recordEditor.uiResize');
},
stop: function stop() {
_hsplit1();
appCommons.userModule.setPref('editing_top_box', Math.floor((0, _jquery2.default)('#EDIT_TOP').height() * 100 / (0, _jquery2.default)('#EDIT_ALL').height()));
_setSizeLimits();
}
});
(0, _jquery2.default)('#divS_wrapper', parentOptions.$container).resizable({
handles: 'e',
minWidth: 200,
resize: function resize() {
_vsplit1();
recordEditorEvents.emit('recordEditor.uiResize');
},
stop: function stop() {
appCommons.userModule.setPref('editing_right_box', Math.floor((0, _jquery2.default)('#divS').width() * 100 / (0, _jquery2.default)('#EDIT_MID_L').width()));
_vsplit1();
_setSizeLimits();
}
});
(0, _jquery2.default)('#EDIT_MID_R').css('left', (0, _jquery2.default)('#EDIT_MID_L').position().left + (0, _jquery2.default)('#EDIT_MID_L').width() + 15).resizable({
handles: 'w',
minWidth: 200,
resize: function resize() {
_vsplit2();
recordEditorEvents.emit('recordEditor.uiResize');
},
stop: function stop() {
appCommons.userModule.setPref('editing_left_box', Math.floor((0, _jquery2.default)('#EDIT_MID_R').width() * 100 / (0, _jquery2.default)('#EDIT_MID').width()));
_vsplit2();
_setSizeLimits();
}
});
(0, _jquery2.default)('#EDIT_ZOOMSLIDER', parentOptions.$container).slider({
min: 60,
max: 300,
value: parentOptions.recordConfig.diapoSize,
slide: function slide(event, ui) {
var v = (0, _jquery2.default)(ui.value)[0];
(0, _jquery2.default)('#EDIT_FILM2 .diapo', parentOptions.$container).width(v).height(v);
},
change: function change(event, ui) {
parentOptions.recordConfig.diapoSize = (0, _jquery2.default)(ui.value)[0];
appCommons.userModule.setPref('editing_images_size', parentOptions.recordConfig.diapoSize);
}
});
_setSizeLimits();
};
function _setSizeLimits() {
if (!(0, _jquery2.default)('#EDITWINDOW').is(':visible')) {
return;
}
if ((0, _jquery2.default)('#EDIT_TOP').data('ui-resizable')) {
(0, _jquery2.default)('#EDIT_TOP').resizable('option', 'maxHeight', (0, _jquery2.default)('#EDIT_ALL').height() - (0, _jquery2.default)('#buttonEditing').height() - 10 - 160);
}
if ((0, _jquery2.default)('#divS_wrapper').data('ui-resizable')) {
(0, _jquery2.default)('#divS_wrapper').resizable('option', 'maxWidth', (0, _jquery2.default)('#EDIT_MID_L').width() - 270);
}
if ((0, _jquery2.default)('#EDIT_MID_R').data('ui-resizable')) {
(0, _jquery2.default)('#EDIT_MID_R').resizable('option', 'maxWidth', (0, _jquery2.default)('#EDIT_MID_R').width() + (0, _jquery2.default)('#idEditZone').width() - 240);
}
}
function _hsplit1() {
var el = (0, _jquery2.default)('#EDIT_TOP');
if (el.length === 0) {
return;
}
var h = (0, _jquery2.default)(el).outerHeight();
(0, _jquery2.default)(el).height(h);
var t = (0, _jquery2.default)(el).offset().top + h;
(0, _jquery2.default)('#EDIT_MID', parentOptions.$container).css('top', t + 'px');
}
function _vsplit1() {
(0, _jquery2.default)('#divS_wrapper').height('auto');
var el = (0, _jquery2.default)('#divS_wrapper');
if (el.length === 0) {
return;
}
var a = (0, _jquery2.default)(el).width();
el.width(a);
(0, _jquery2.default)('#idEditZone', parentOptions.$container).css('left', a + 20);
}
function _vsplit2() {
var el = (0, _jquery2.default)('#EDIT_MID_R');
if (el.length === 0) {
return;
}
var a = (0, _jquery2.default)(el).width();
el.width(a);
var v = (0, _jquery2.default)('#EDIT_ALL').width() - a - 35;
(0, _jquery2.default)('#EDIT_MID_L', parentOptions.$container).width(v);
}
return { initialize: initialize };
};
exports.default = recordEditorLayout;
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _utils = __webpack_require__(39);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var presetsModule = function presetsModule(services) {
var configService = services.configService,
localeService = services.localeService,
recordEditorEvents = services.recordEditorEvents;
var url = configService.get('baseUrl');
var $container = null;
var parentOptions = {};
var recordCollection = void 0;
var fieldCollection = void 0;
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, parentOptions = _options.parentOptions, _options);
recordCollection = parentOptions.recordCollection;
fieldCollection = parentOptions.fieldCollection;
initPresetsModal();
};
var initPresetsModal = function initPresetsModal() {
var buttons = {};
buttons[localeService.t('valider')] = function (event) {
(0, _jquery2.default)(this).dialog('close');
recordEditorEvents.emit('recordEditor.submitAllChanges', { event: event });
};
buttons[localeService.t('annuler')] = function (event) {
(0, _jquery2.default)(this).dialog('close');
recordEditorEvents.emit('recordEditor.cancelAllChanges', { event: event });
};
(0, _jquery2.default)('#EDIT_CLOSEDIALOG', $container).dialog({
autoOpen: false,
closeOnEscape: true,
resizable: false,
draggable: false,
modal: true,
buttons: buttons
});
buttons[localeService.t('valider')] = function () {
var form = (0, _jquery2.default)('#Edit_copyPreset_dlg FORM');
var jtitle = (0, _jquery2.default)('.EDIT_presetTitle', form);
if (jtitle.val() === '') {
alert(localeService.t('needTitle'));
jtitle[0].focus();
return;
}
var addFields = [];
(0, _jquery2.default)(':checkbox', form).each(function (idx, elem) {
var $el = (0, _jquery2.default)(elem);
if ($el.is(':checked')) {
var fieldIndex = $el.val();
var foundField = fieldCollection.getFieldByIndex(fieldIndex);
var field = {
name: foundField.name,
value: []
};
var tval;
if (foundField.multi) {
field.value = _jquery2.default.map(foundField._value.split(';'), function (obj, idx) {
return obj.trim();
});
} else {
field.value = [foundField._value.trim()];
}
addFields.push(field);
}
});
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/records/edit/presets',
data: {
sbas_id: parentOptions.sbas_id,
title: jtitle.val(),
fields: addFields
},
dataType: 'json',
success: function success(data, textStatus) {
_preset_paint(data);
if ((0, _jquery2.default)('#Edit_copyPreset_dlg').data('ui-dialog')) {
(0, _jquery2.default)('#Edit_copyPreset_dlg').dialog('close');
}
}
});
};
buttons[localeService.t('annuler')] = function () {
(0, _jquery2.default)(this).dialog('close');
};
(0, _jquery2.default)('#Edit_copyPreset_dlg', $container).dialog({
stack: true,
closeOnEscape: true,
resizable: false,
draggable: false,
autoOpen: false,
modal: true,
width: 600,
title: localeService.t('newPreset'),
close: function close(event, ui) {
(0, _jquery2.default)(this).dialog('widget').css('z-index', 'auto');
},
open: function open(event, ui) {
(0, _jquery2.default)(this).dialog('widget').css('z-index', '5000');
(0, _jquery2.default)('.EDIT_presetTitle')[0].focus();
},
buttons: buttons
});
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/records/edit/presets',
data: {
sbas_id: parentOptions.sbas_id
},
dataType: 'json',
success: function success(data, textStatus) {
_preset_paint(data);
}
});
$container.on('click', '#TH_Opresets button.adder', function () {
//$('#TH_Opresets button.adder').bind('click', function () {
_preset_copy();
});
};
function _preset_paint(data) {
(0, _jquery2.default)('.EDIT_presets_list', parentOptions.$container).html(data.html);
$container.on('click', '.EDIT_presets_list A.triangle', function () {
(0, _jquery2.default)(this).parent().parent().toggleClass('opened');
return false;
});
$container.on('dblclick', '.EDIT_presets_list A.title', function () {
var preset_id = (0, _jquery2.default)(this).parent().parent().attr('id');
if (preset_id.substr(0, 12) === 'EDIT_PRESET_') {
_preset_load(preset_id.substr(12));
}
return false;
});
$container.on('click', '.EDIT_presets_list A.delete', function () {
var li = (0, _jquery2.default)(this).closest('LI');
var preset_id = li.attr('id');
var title = (0, _jquery2.default)(this).parent().children('.title').html();
if (preset_id.substr(0, 12) === 'EDIT_PRESET_' && confirm("supprimer le preset '" + title + "' ?")) {
_preset_delete(preset_id.substr(12), li);
}
return false;
});
}
function _preset_copy() {
var html = '';
var fields = fieldCollection.getFields();
for (var fieldIndex in fields) {
var field = fieldCollection.getFieldByIndex(fieldIndex);
if (field._status === 1) {
if (field.readonly) {
continue;
}
var c = field._value === '' ? '' : 'checked="1"';
html += '<div><label class="checkbox" for="new_preset_' + field.name + '"><input type="checkbox" class="checkbox" id="new_preset_' + field.name + '" value="' + fieldIndex + '" ' + c + '/>' + '<b>' + field.label + ' : </b></label> ';
html += (0, _utils.cleanTags)(field._value) + '</div>';
}
}
(0, _jquery2.default)('#Edit_copyPreset_dlg FORM DIV').html(html);
var $dialog = (0, _jquery2.default)('#Edit_copyPreset_dlg');
if ($dialog.data('ui-dialog')) {
// to show dialog on top of edit window
$dialog.dialog('widget').css('z-index', 1300);
$dialog.dialog('open');
}
}
function _preset_delete(presetId, li) {
_jquery2.default.ajax({
type: 'DELETE',
url: url + 'prod/records/edit/presets/' + presetId,
data: {},
dataType: 'json',
success: function success(data, textStatus) {
li.remove();
}
});
}
function _preset_load(presetId) {
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/records/edit/presets/' + presetId,
data: {},
dataType: 'json',
success: function success(data, textStatus) {
if ((0, _jquery2.default)('#Edit_copyPreset_dlg').data('ui-dialog')) {
(0, _jquery2.default)('#Edit_copyPreset_dlg').dialog('close');
}
var records = recordCollection.getRecords();
var fields = fieldCollection.getFields();
for (var fieldIndex in fields) {
var field = fieldCollection.getFieldByIndex(fieldIndex);
field.preset = null;
if (typeof data.fields[field.name] !== 'undefined') {
field.preset = data.fields[field.name];
}
fieldCollection.updateField(fieldIndex, field);
}
for (var recordIndex in records) {
var record = recordCollection.getRecordByIndex(recordIndex);
if (!record._selected) {
continue;
}
for (var _fieldIndex in fields) {
var _field = fieldCollection.getFieldByIndex(_fieldIndex);
if (_field.preset !== null) {
for (var val in _field.preset) {
// fix : some (old, malformed) presets values may need trim()
recordCollection.addRecordFieldValue(recordIndex, _fieldIndex, {
value: _field.preset[val].trim(), merge: false, vocabularyId: null
});
}
}
}
}
recordEditorEvents.emit('recordEditor.onUpdateFields');
}
});
}
return { initialize: initialize };
};
exports.default = presetsModule;
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
/**
* Editor Right tab plugin
*/
// EditReplace
var searchReplace = function searchReplace(services) {
var configService = services.configService,
localeService = services.localeService,
recordEditorEvents = services.recordEditorEvents;
var $container = null;
var tRecords = {};
var parentOptions = {};
recordEditorEvents.listenAll({
'recordEditor.plugin.searchReplace.replace': 'replace'
});
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, parentOptions = _options.parentOptions, _options);
// recordCollection = parentOptions.recordCollection;
tRecords = parentOptions.recordCollection.getRecords();
(0, _jquery2.default)($container).on('click', '.record-editor-searchReplace-action', function (event) {
event.preventDefault();
var ntRecords = replace(tRecords);
// @TODO - reactivate humane
// humane.info($.sprintf(localeService.t('nFieldsChanged', n)));
recordEditorEvents.emit('recordEditor.onUpdateFields', ntRecords);
});
(0, _jquery2.default)($container).on('change', '.record-editor-toggle-replace-mode-action', function (event) {
event.preventDefault();
_toggleReplaceMode(event.currentTarget);
});
};
var replace = function replace(tRecords) {
var field = (0, _jquery2.default)('#EditSRField', $container).val();
var search = (0, _jquery2.default)('#EditSearch', $container).val();
var replace = (0, _jquery2.default)('#EditReplace', $container).val();
var where = (0, _jquery2.default)('[name=EditSR_Where]:checked', $container).val();
var commut = '';
var rgxp = (0, _jquery2.default)('#EditSROptionRX', $container).prop('checked') ? true : false;
var r_search;
if (rgxp) {
r_search = search;
commut = ((0, _jquery2.default)('#EditSR_RXG', $container).prop('checked') ? 'g' : '') + ((0, _jquery2.default)('#EditSR_RXI', $container).prop('checked') ? 'i' : '');
} else {
commut = (0, _jquery2.default)('#EditSR_case', $container).prop('checked') ? 'g' : 'gi';
r_search = '';
for (var i = 0; i < search.length; i++) {
var c = search.charAt(i);
if ('^$[]()|.*+?\\'.indexOf(c) !== -1) {
r_search += '\\';
}
r_search += c;
}
if (where === 'exact') {
r_search = '^' + r_search + '$';
}
}
search = new RegExp(r_search, commut);
var f = void 0;
var n = 0;
for (var r in tRecords) {
if (!tRecords[r]._selected) {
continue;
}
for (f in tRecords[r].fields) {
if (field === '' || field === f) {
n += tRecords[r].fields[f].replaceValue(search, replace);
}
}
}
return (0, _lodash2.default)({}, tRecords);
};
function _toggleReplaceMode(ckRegExp) {
if (ckRegExp.checked) {
(0, _jquery2.default)('#EditSR_TX', $container).hide();
(0, _jquery2.default)('#EditSR_RX', $container).show();
} else {
(0, _jquery2.default)('#EditSR_RX', $container).hide();
(0, _jquery2.default)('#EditSR_TX', $container).show();
}
}
return { initialize: initialize };
};
exports.default = searchReplace;
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _pym = __webpack_require__(17);
var _pym2 = _interopRequireDefault(_pym);
var _videoEditor = __webpack_require__(117);
var _videoEditor2 = _interopRequireDefault(_videoEditor);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//require('jquery-ui');
var preview = function preview(services) {
var configService = services.configService,
localeService = services.localeService,
recordEditorEvents = services.recordEditorEvents;
var $container = null;
var parentOptions = {};
var activeThumbnailFrame = false;
var lastRecordIndex = false;
recordEditorEvents.listenAll({
// @TODO debounce
'recordEditor.uiResize': onResize,
'recordSelection.changed': onSelectionChange,
'recordEditor.onSelectRecord': renderPreview,
'recordEditor.tabChange': tabChanged
});
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, parentOptions = _options.parentOptions, _options);
};
function onResize() {
var selected = (0, _jquery2.default)('#EDIT_FILM2 .diapo.selected');
if (selected.length !== 1) {
return false;
}
var id = selected.attr('id').split('_').pop();
var zoomable = (0, _jquery2.default)('img.record.zoomable', $container.parent());
if (zoomable.length > 0 && zoomable.hasClass('zoomed')) {
return false;
}
var h = parseInt((0, _jquery2.default)($container.children()).attr('data-original-height'), 10);
var w = parseInt((0, _jquery2.default)($container.children()).attr('data-original-width'), 10);
var t = 0;
var de = 0;
var margX = 20;
var margY = 20;
if ((0, _jquery2.default)('img.record.record_audio', $container).length > 0) {
margY = 100;
de = 60;
}
var containerWidth = $container.parent().width();
var containerHeight = $container.parent().height();
// if(datas.doctype != 'flash')
// {
var ratioP = w / h;
var ratioD = containerWidth / containerHeight;
if (ratioD > ratioP) {
// je regle la hauteur d'abord
if (parseInt(h, 10) + margY > containerHeight) {
h = Math.round(containerHeight - margY);
w = Math.round(h * ratioP);
}
} else {
if (parseInt(w, 10) + margX > containerWidth) {
w = Math.round(containerWidth - margX);
h = Math.round(w / ratioP);
}
}
t = Math.round((containerHeight - h - de) / 2);
var l = Math.round((containerWidth - w) / 2);
(0, _jquery2.default)('.record', $container.parent()).css({
width: w,
height: h,
top: t,
left: l,
margin: '0 auto',
display: 'block'
}).attr('width', w).attr('height', h);
}
function tabChanged(params) {
if (params.tab === '#TH_Opreview') {
//redraw preview
var selected = (0, _jquery2.default)('#EDIT_FILM2 .diapo.selected');
if (selected.length !== 1) {
return false;
}
var id = selected.attr('id').split('_').pop();
renderPreview({
recordIndex: id
});
}
}
function renderPreview(params) {
var recordIndex = params.recordIndex;
lastRecordIndex = recordIndex;
var currentRecord = parentOptions.recordCollection.getRecordByIndex(recordIndex);
$container.empty();
switch (currentRecord.type) {
case 'video':
case 'audio':
case 'document':
var customId = 'phraseanet-embed-editor-frame';
var $template = (0, _jquery2.default)(currentRecord.template);
$template.attr('id', customId);
$container.append($template.get(0));
activeThumbnailFrame = new _pym2.default.Parent(customId, currentRecord.data.preview.url);
activeThumbnailFrame.iframe.setAttribute('allowfullscreen', '');
break;
case 'image':
default:
$container.append(currentRecord.template);
onResize();
}
if ((0, _jquery2.default)('img.PREVIEW_PIC.zoomable').length > 0) {
(0, _jquery2.default)('img.PREVIEW_PIC.zoomable').draggable();
}
/**Resize video on edit**/
if (currentRecord.type == 'video') {
/*resize of VIDEO */
var resizeVideo = function resizeVideo() {
if ((0, _jquery2.default)('#phraseanet-embed-editor-frame iframe').length > 0) {
var $sel = (0, _jquery2.default)('#phraseanet-embed-editor-frame');
var $window = (0, _jquery2.default)('#TH_Opreview').height();
// V is for "video" ; K is for "container" ; N is for "new"
var VW = (0, _jquery2.default)('#phraseanet-embed-editor-frame ').data("original-width");
var VH = (0, _jquery2.default)('#phraseanet-embed-editor-frame ').data("original-height");
var KW = $sel.width();
var KH = $sel.height();
KH = $window - 20;
var NW, NH;
if ((NH = VH / VW * (NW = KW)) > KH) {
// try to fit exact horizontally, adjust vertically
// too bad... new height overflows container height
NW = VW / VH * (NH = KH); // so fit exact vertically, adjust horizontally
}
(0, _jquery2.default)("#phraseanet-embed-editor-frame iframe").css('width', NW).css('height', NH);
}
};
resizeVideo();
(0, _jquery2.default)('#phraseanet-embed-editor-frame').css('text-align', 'center');
(0, _jquery2.default)(window).on("load resize ", function (e) {
resizeVideo();
});
(0, _jquery2.default)(window).click(".ui-tabs-anchor", function (e) {
resizeVideo();
});
}
/**end Resize video on edit**/
}
/**
* refresh preview if only one record is selected
* @param params
*/
function onSelectionChange(params) {
var selection = params.selection;
if (selection.length === 1) {
renderPreview({
recordIndex: selection[0]
});
}
}
return { initialize: initialize };
};
exports.default = preview;
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _videojsFlash = __webpack_require__(62);
var _videojsFlash2 = _interopRequireDefault(_videojsFlash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var videoEditor = function videoEditor(services) {
var configService = services.configService,
localeService = services.localeService,
recordEditorEvents = services.recordEditorEvents;
var $container = null;
var parentOptions = {};
var data = void 0;
var rangeCapture = void 0;
var rangeCaptureInstance = void 0;
var options = {
playbackRates: [],
fluid: true
};
var initialize = function initialize(params) {
var _params;
var initWith = (_params = params, $container = _params.$container, parentOptions = _params.parentOptions, data = _params.data, _params);
if (data.videoEditorConfig !== null) {
options.seekBackwardStep = data.videoEditorConfig.seekBackwardStep;
options.seekForwardStep = data.videoEditorConfig.seekForwardStep;
options.playbackRates = data.videoEditorConfig.playbackRates === undefined ? [1, 2, 3] : data.videoEditorConfig.playbackRates;
options.vttFieldValue = false;
options.ChapterVttFieldName = data.videoEditorConfig.ChapterVttFieldName === undefined ? false : data.videoEditorConfig.ChapterVttFieldName;
}
options.techOrder = ['html5', 'flash'];
$container.addClass('video-range-editor-container');
// get default videoTextTrack value
if (options.ChapterVttFieldName !== false) {
var vttField = parentOptions.fieldCollection.getFieldByName(options.ChapterVttFieldName);
if (vttField !== false) {
options.vttFieldValue = vttField._value;
}
}
__webpack_require__.e/* require.ensure */(1/* duplicate */).then((function () {
// load videoJs lib
rangeCapture = __webpack_require__(87).default;
rangeCaptureInstance = rangeCapture(services);
rangeCaptureInstance.initialize(params, options);
// proxy resize event to rangeStream
recordEditorEvents.listenAll({
'recordEditor.uiResize': function recordEditorUiResize() {
rangeCaptureInstance.getPlayer().rangeStream.onNext({ action: 'resize' });
}
});
rangeCaptureInstance.getPlayer().rangeStream.subscribe(function (params) {
switch (params.action) {
case 'export-vtt-ranges':
if (options.ChapterVttFieldName !== false) {
var presets = {
fields: {}
};
presets.fields[options.ChapterVttFieldName] = [params.data];
recordEditorEvents.emit('recordEditor.addPresetValuesFromDataSource', {
data: presets
});
}
break;
default:
}
});
}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
};
return { initialize: initialize };
};
exports.default = videoEditor;
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
/**
* @license
* Video.js 6.13.0 <http://videojs.com/>
* Copyright Brightcove, Inc. <https://www.brightcove.com/>
* Available under Apache License Version 2.0
* <https://github.com/videojs/video.js/blob/master/LICENSE>
*
* Includes vtt.js <https://github.com/mozilla/vtt.js>
* Available under Apache License Version 2.0
* <https://github.com/mozilla/vtt.js/blob/master/LICENSE>
*/
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var window = _interopDefault(__webpack_require__(43));
var document = _interopDefault(__webpack_require__(83));
var tsml = _interopDefault(__webpack_require__(84));
var safeParseTuple = _interopDefault(__webpack_require__(85));
var xhr = _interopDefault(__webpack_require__(86));
var vtt = _interopDefault(__webpack_require__(138));
var version = "6.13.0";
/**
* @file browser.js
* @module browser
*/
var USER_AGENT = window.navigator && window.navigator.userAgent || '';
var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);
var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
/*
* Device is an iPhone
*
* @type {Boolean}
* @constant
* @private
*/
var IS_IPAD = /iPad/i.test(USER_AGENT);
// The Facebook app's UIWebView identifies as both an iPhone and iPad, so
// to identify iPhones, we need to exclude iPads.
// http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
var IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
var IS_IPOD = /iPod/i.test(USER_AGENT);
var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
var IOS_VERSION = function () {
var match = USER_AGENT.match(/OS (\d+)_/i);
if (match && match[1]) {
return match[1];
}
return null;
}();
var IS_ANDROID = /Android/i.test(USER_AGENT);
var ANDROID_VERSION = function () {
// This matches Android Major.Minor.Patch versions
// ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
if (!match) {
return null;
}
var major = match[1] && parseFloat(match[1]);
var minor = match[2] && parseFloat(match[2]);
if (major && minor) {
return parseFloat(match[1] + '.' + match[2]);
} else if (major) {
return major;
}
return null;
}();
// Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser
var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3;
var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
var IS_EDGE = /Edge/i.test(USER_AGENT);
var IS_CHROME = !IS_EDGE && (/Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT));
var CHROME_VERSION = function () {
var match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
if (match && match[2]) {
return parseFloat(match[2]);
}
return null;
}();
var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT);
var IE_VERSION = function () {
var result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
var version = result && parseFloat(result[1]);
if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
// IE 11 has a different user agent string than other IE versions
version = 11.0;
}
return version;
}();
var IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
var IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
var TOUCH_ENABLED = isReal() && ('ontouchstart' in window || window.navigator.maxTouchPoints || window.DocumentTouch && window.document instanceof window.DocumentTouch);
var BACKGROUND_SIZE_SUPPORTED = isReal() && 'backgroundSize' in window.document.createElement('video').style;
var browser = (Object.freeze || Object)({
IS_IPAD: IS_IPAD,
IS_IPHONE: IS_IPHONE,
IS_IPOD: IS_IPOD,
IS_IOS: IS_IOS,
IOS_VERSION: IOS_VERSION,
IS_ANDROID: IS_ANDROID,
ANDROID_VERSION: ANDROID_VERSION,
IS_OLD_ANDROID: IS_OLD_ANDROID,
IS_NATIVE_ANDROID: IS_NATIVE_ANDROID,
IS_FIREFOX: IS_FIREFOX,
IS_EDGE: IS_EDGE,
IS_CHROME: IS_CHROME,
CHROME_VERSION: CHROME_VERSION,
IS_IE8: IS_IE8,
IE_VERSION: IE_VERSION,
IS_SAFARI: IS_SAFARI,
IS_ANY_SAFARI: IS_ANY_SAFARI,
TOUCH_ENABLED: TOUCH_ENABLED,
BACKGROUND_SIZE_SUPPORTED: BACKGROUND_SIZE_SUPPORTED
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var inherits = function (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 possibleConstructorReturn = function (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;
};
var taggedTemplateLiteralLoose = function (strings, raw) {
strings.raw = raw;
return strings;
};
/**
* @file obj.js
* @module obj
*/
/**
* @callback obj:EachCallback
*
* @param {Mixed} value
* The current key for the object that is being iterated over.
*
* @param {string} key
* The current key-value for object that is being iterated over
*/
/**
* @callback obj:ReduceCallback
*
* @param {Mixed} accum
* The value that is accumulating over the reduce loop.
*
* @param {Mixed} value
* The current key for the object that is being iterated over.
*
* @param {string} key
* The current key-value for object that is being iterated over
*
* @return {Mixed}
* The new accumulated value.
*/
var toString = Object.prototype.toString;
/**
* Get the keys of an Object
*
* @param {Object}
* The Object to get the keys from
*
* @return {string[]}
* An array of the keys from the object. Returns an empty array if the
* object passed in was invalid or had no keys.
*
* @private
*/
var keys = function keys(object) {
return isObject(object) ? Object.keys(object) : [];
};
/**
* Array-like iteration for objects.
*
* @param {Object} object
* The object to iterate over
*
* @param {obj:EachCallback} fn
* The callback function which is called for each key in the object.
*/
function each(object, fn) {
keys(object).forEach(function (key) {
return fn(object[key], key);
});
}
/**
* Array-like reduce for objects.
*
* @param {Object} object
* The Object that you want to reduce.
*
* @param {Function} fn
* A callback function which is called for each key in the object. It
* receives the accumulated value and the per-iteration value and key
* as arguments.
*
* @param {Mixed} [initial = 0]
* Starting value
*
* @return {Mixed}
* The final accumulated value.
*/
function reduce(object, fn) {
var initial = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
return keys(object).reduce(function (accum, key) {
return fn(accum, object[key], key);
}, initial);
}
/**
* Object.assign-style object shallow merge/extend.
*
* @param {Object} target
* @param {Object} ...sources
* @return {Object}
*/
function assign(target) {
for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
sources[_key - 1] = arguments[_key];
}
if (Object.assign) {
return Object.assign.apply(Object, [target].concat(sources));
}
sources.forEach(function (source) {
if (!source) {
return;
}
each(source, function (value, key) {
target[key] = value;
});
});
return target;
}
/**
* Returns whether a value is an object of any kind - including DOM nodes,
* arrays, regular expressions, etc. Not functions, though.
*
* This avoids the gotcha where using `typeof` on a `null` value
* results in `'object'`.
*
* @param {Object} value
* @return {Boolean}
*/
function isObject(value) {
return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object';
}
/**
* Returns whether an object appears to be a "plain" object - that is, a
* direct instance of `Object`.
*
* @param {Object} value
* @return {Boolean}
*/
function isPlain(value) {
return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object;
}
/**
* @file create-logger.js
* @module create-logger
*/
// This is the private tracking variable for the logging history.
var history = [];
/**
* Log messages to the console and history based on the type of message
*
* @private
* @param {string} type
* The name of the console method to use.
*
* @param {Array} args
* The arguments to be passed to the matching console method.
*/
var LogByTypeFactory = function LogByTypeFactory(name, log) {
return function (type, level, args, stringify) {
var lvl = log.levels[level];
var lvlRegExp = new RegExp('^(' + lvl + ')$');
if (type !== 'log') {
// Add the type to the front of the message when it's not "log".
args.unshift(type.toUpperCase() + ':');
}
// Add console prefix after adding to history.
args.unshift(name + ':');
// Add a clone of the args at this point to history.
if (history) {
history.push([].concat(args));
}
// If there's no console then don't try to output messages, but they will
// still be stored in history.
if (!window.console) {
return;
}
// Was setting these once outside of this function, but containing them
// in the function makes it easier to test cases where console doesn't exist
// when the module is executed.
var fn = window.console[type];
if (!fn && type === 'debug') {
// Certain browsers don't have support for console.debug. For those, we
// should default to the closest comparable log.
fn = window.console.info || window.console.log;
}
// Bail out if there's no console or if this type is not allowed by the
// current logging level.
if (!fn || !lvl || !lvlRegExp.test(type)) {
return;
}
// IEs previous to 11 log objects uselessly as "[object Object]"; so, JSONify
// objects and arrays for those less-capable browsers.
if (stringify) {
args = args.map(function (a) {
if (isObject(a) || Array.isArray(a)) {
try {
return JSON.stringify(a);
} catch (x) {
return String(a);
}
}
// Cast to string before joining, so we get null and undefined explicitly
// included in output (as we would in a modern console).
return String(a);
}).join(' ');
}
// Old IE versions do not allow .apply() for console methods (they are
// reported as objects rather than functions).
if (!fn.apply) {
fn(args);
} else {
fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
}
};
};
function createLogger$1(name) {
// This is the private tracking variable for logging level.
var level = 'info';
// the curried logByType bound to the specific log and history
var logByType = void 0;
/**
* Logs plain debug messages. Similar to `console.log`.
*
* Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
* of our JSDoc template, we cannot properly document this as both a function
* and a namespace, so its function signature is documented here.
*
* #### Arguments
* ##### *args
* Mixed[]
*
* Any combination of values that could be passed to `console.log()`.
*
* #### Return Value
*
* `undefined`
*
* @namespace
* @param {Mixed[]} args
* One or more messages or objects that should be logged.
*/
var log = function log() {
var stringify = log.stringify || IE_VERSION && IE_VERSION < 11;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
logByType('log', level, args, stringify);
};
// This is the logByType helper that the logging methods below use
logByType = LogByTypeFactory(name, log);
/**
* Create a new sublogger which chains the old name to the new name.
*
* For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
* ```js
* mylogger('foo');
* // > VIDEOJS: player: foo
* ```
*
* @param {string} name
* The name to add call the new logger
* @return {Object}
*/
log.createLogger = function (subname) {
return createLogger$1(name + ': ' + subname);
};
/**
* Enumeration of available logging levels, where the keys are the level names
* and the values are `|`-separated strings containing logging methods allowed
* in that logging level. These strings are used to create a regular expression
* matching the function name being called.
*
* Levels provided by Video.js are:
*
* - `off`: Matches no calls. Any value that can be cast to `false` will have
* this effect. The most restrictive.
* - `all`: Matches only Video.js-provided functions (`debug`, `log`,
* `log.warn`, and `log.error`).
* - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
* - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
* - `warn`: Matches `log.warn` and `log.error` calls.
* - `error`: Matches only `log.error` calls.
*
* @type {Object}
*/
log.levels = {
all: 'debug|log|warn|error',
off: '',
debug: 'debug|log|warn|error',
info: 'log|warn|error',
warn: 'warn|error',
error: 'error',
DEFAULT: level
};
/**
* Get or set the current logging level.
*
* If a string matching a key from {@link module:log.levels} is provided, acts
* as a setter.
*
* @param {string} [lvl]
* Pass a valid level to set a new logging level.
*
* @return {string}
* The current logging level.
*/
log.level = function (lvl) {
if (typeof lvl === 'string') {
if (!log.levels.hasOwnProperty(lvl)) {
throw new Error('"' + lvl + '" in not a valid log level');
}
level = lvl;
}
return level;
};
/**
* Returns an array containing everything that has been logged to the history.
*
* This array is a shallow clone of the internal history record. However, its
* contents are _not_ cloned; so, mutating objects inside this array will
* mutate them in history.
*
* @return {Array}
*/
log.history = function () {
return history ? [].concat(history) : [];
};
/**
* Allows you to filter the history by the given logger name
*
* @param {string} fname
* The name to filter by
*
* @return {Array}
* The filtered list to return
*/
log.history.filter = function (fname) {
return (history || []).filter(function (historyItem) {
// if the first item in each historyItem includes `fname`, then it's a match
return new RegExp('.*' + fname + '.*').test(historyItem[0]);
});
};
/**
* Clears the internal history tracking, but does not prevent further history
* tracking.
*/
log.history.clear = function () {
if (history) {
history.length = 0;
}
};
/**
* Disable history tracking if it is currently enabled.
*/
log.history.disable = function () {
if (history !== null) {
history.length = 0;
history = null;
}
};
/**
* Enable history tracking if it is currently disabled.
*/
log.history.enable = function () {
if (history === null) {
history = [];
}
};
/**
* Logs error messages. Similar to `console.error`.
*
* @param {Mixed[]} args
* One or more messages or objects that should be logged as an error
*/
log.error = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return logByType('error', level, args);
};
/**
* Logs warning messages. Similar to `console.warn`.
*
* @param {Mixed[]} args
* One or more messages or objects that should be logged as a warning.
*/
log.warn = function () {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return logByType('warn', level, args);
};
/**
* Logs debug messages. Similar to `console.debug`, but may also act as a comparable
* log if `console.debug` is not available
*
* @param {Mixed[]} args
* One or more messages or objects that should be logged as debug.
*/
log.debug = function () {
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return logByType('debug', level, args);
};
return log;
}
/**
* @file log.js
* @module log
*/
var log = createLogger$1('VIDEOJS');
var createLogger = log.createLogger;
/**
* @file computed-style.js
* @module computed-style
*/
/**
* A safe getComputedStyle with an IE8 fallback.
*
* This is needed because in Firefox, if the player is loaded in an iframe with
* `display:none`, then `getComputedStyle` returns `null`, so, we do a null-check to
* make sure that the player doesn't break in these cases.
*
* @param {Element} el
* The element you want the computed style of
*
* @param {string} prop
* The property name you want
*
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
*
* @static
* @const
*/
function computedStyle(el, prop) {
if (!el || !prop) {
return '';
}
if (typeof window.getComputedStyle === 'function') {
var cs = window.getComputedStyle(el);
return cs ? cs[prop] : '';
}
return el.currentStyle[prop] || '';
}
var _templateObject = taggedTemplateLiteralLoose(['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.'], ['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.']);
/**
* @file dom.js
* @module dom
*/
/**
* Detect if a value is a string with any non-whitespace characters.
*
* @param {string} str
* The string to check
*
* @return {boolean}
* - True if the string is non-blank
* - False otherwise
*
*/
function isNonBlankString(str) {
return typeof str === 'string' && /\S/.test(str);
}
/**
* Throws an error if the passed string has whitespace. This is used by
* class methods to be relatively consistent with the classList API.
*
* @param {string} str
* The string to check for whitespace.
*
* @throws {Error}
* Throws an error if there is whitespace in the string.
*
*/
function throwIfWhitespace(str) {
if (/\s/.test(str)) {
throw new Error('class has illegal whitespace characters');
}
}
/**
* Produce a regular expression for matching a className within an elements className.
*
* @param {string} className
* The className to generate the RegExp for.
*
* @return {RegExp}
* The RegExp that will check for a specific `className` in an elements
* className.
*/
function classRegExp(className) {
return new RegExp('(^|\\s)' + className + '($|\\s)');
}
/**
* Whether the current DOM interface appears to be real.
*
* @return {Boolean}
*/
function isReal() {
return (
// Both document and window will never be undefined thanks to `global`.
document === window.document &&
// In IE < 9, DOM methods return "object" as their type, so all we can
// confidently check is that it exists.
typeof document.createElement !== 'undefined'
);
}
/**
* Determines, via duck typing, whether or not a value is a DOM element.
*
* @param {Mixed} value
* The thing to check
*
* @return {boolean}
* - True if it is a DOM element
* - False otherwise
*/
function isEl(value) {
return isObject(value) && value.nodeType === 1;
}
/**
* Determines if the current DOM is embedded in an iframe.
*
* @return {boolean}
*
*/
function isInFrame() {
// We need a try/catch here because Safari will throw errors when attempting
// to get either `parent` or `self`
try {
return window.parent !== window.self;
} catch (x) {
return true;
}
}
/**
* Creates functions to query the DOM using a given method.
*
* @param {string} method
* The method to create the query with.
*
* @return {Function}
* The query method
*/
function createQuerier(method) {
return function (selector, context) {
if (!isNonBlankString(selector)) {
return document[method](null);
}
if (isNonBlankString(context)) {
context = document.querySelector(context);
}
var ctx = isEl(context) ? context : document;
return ctx[method] && ctx[method](selector);
};
}
/**
* Creates an element and applies properties.
*
* @param {string} [tagName='div']
* Name of tag to be created.
*
* @param {Object} [properties={}]
* Element properties to be applied.
*
* @param {Object} [attributes={}]
* Element attributes to be applied.
*
* @param {String|Element|TextNode|Array|Function} [content]
* Contents for the element (see: {@link dom:normalizeContent})
*
* @return {Element}
* The element that was created.
*/
function createEl() {
var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div';
var properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var content = arguments[3];
var el = document.createElement(tagName);
Object.getOwnPropertyNames(properties).forEach(function (propName) {
var val = properties[propName];
// See #2176
// We originally were accepting both properties and attributes in the
// same object, but that doesn't work so well.
if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') {
log.warn(tsml(_templateObject, propName, val));
el.setAttribute(propName, val);
// Handle textContent since it's not supported everywhere and we have a
// method for it.
} else if (propName === 'textContent') {
textContent(el, val);
} else {
el[propName] = val;
}
});
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
el.setAttribute(attrName, attributes[attrName]);
});
if (content) {
appendContent(el, content);
}
return el;
}
/**
* Injects text into an element, replacing any existing contents entirely.
*
* @param {Element} el
* The element to add text content into
*
* @param {string} text
* The text content to add.
*
* @return {Element}
* The element with added text content.
*/
function textContent(el, text) {
if (typeof el.textContent === 'undefined') {
el.innerText = text;
} else {
el.textContent = text;
}
return el;
}
/**
* Insert an element as the first child node of another
*
* @param {Element} child
* Element to insert
*
* @param {Element} parent
* Element to insert child into
*/
function prependTo(child, parent) {
if (parent.firstChild) {
parent.insertBefore(child, parent.firstChild);
} else {
parent.appendChild(child);
}
}
/**
* Check if an element has a CSS class
*
* @param {Element} element
* Element to check
*
* @param {string} classToCheck
* Class name to check for
*
* @return {boolean}
* - True if the element had the class
* - False otherwise.
*
* @throws {Error}
* Throws an error if `classToCheck` has white space.
*/
function hasClass(element, classToCheck) {
throwIfWhitespace(classToCheck);
if (element.classList) {
return element.classList.contains(classToCheck);
}
return classRegExp(classToCheck).test(element.className);
}
/**
* Add a CSS class name to an element
*
* @param {Element} element
* Element to add class name to.
*
* @param {string} classToAdd
* Class name to add.
*
* @return {Element}
* The dom element with the added class name.
*/
function addClass(element, classToAdd) {
if (element.classList) {
element.classList.add(classToAdd);
// Don't need to `throwIfWhitespace` here because `hasElClass` will do it
// in the case of classList not being supported.
} else if (!hasClass(element, classToAdd)) {
element.className = (element.className + ' ' + classToAdd).trim();
}
return element;
}
/**
* Remove a CSS class name from an element
*
* @param {Element} element
* Element to remove a class name from.
*
* @param {string} classToRemove
* Class name to remove
*
* @return {Element}
* The dom element with class name removed.
*/
function removeClass(element, classToRemove) {
if (element.classList) {
element.classList.remove(classToRemove);
} else {
throwIfWhitespace(classToRemove);
element.className = element.className.split(/\s+/).filter(function (c) {
return c !== classToRemove;
}).join(' ');
}
return element;
}
/**
* The callback definition for toggleElClass.
*
* @callback Dom~PredicateCallback
* @param {Element} element
* The DOM element of the Component.
*
* @param {string} classToToggle
* The `className` that wants to be toggled
*
* @return {boolean|undefined}
* - If true the `classToToggle` will get added to `element`.
* - If false the `classToToggle` will get removed from `element`.
* - If undefined this callback will be ignored
*/
/**
* Adds or removes a CSS class name on an element depending on an optional
* condition or the presence/absence of the class name.
*
* @param {Element} element
* The element to toggle a class name on.
*
* @param {string} classToToggle
* The class that should be toggled
*
* @param {boolean|PredicateCallback} [predicate]
* See the return value for {@link Dom~PredicateCallback}
*
* @return {Element}
* The element with a class that has been toggled.
*/
function toggleClass(element, classToToggle, predicate) {
// This CANNOT use `classList` internally because IE does not support the
// second parameter to the `classList.toggle()` method! Which is fine because
// `classList` will be used by the add/remove functions.
var has = hasClass(element, classToToggle);
if (typeof predicate === 'function') {
predicate = predicate(element, classToToggle);
}
if (typeof predicate !== 'boolean') {
predicate = !has;
}
// If the necessary class operation matches the current state of the
// element, no action is required.
if (predicate === has) {
return;
}
if (predicate) {
addClass(element, classToToggle);
} else {
removeClass(element, classToToggle);
}
return element;
}
/**
* Apply attributes to an HTML element.
*
* @param {Element} el
* Element to add attributes to.
*
* @param {Object} [attributes]
* Attributes to be applied.
*/
function setAttributes(el, attributes) {
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var attrValue = attributes[attrName];
if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
el.removeAttribute(attrName);
} else {
el.setAttribute(attrName, attrValue === true ? '' : attrValue);
}
});
}
/**
* Get an element's attribute values, as defined on the HTML tag
* Attributes are not the same as properties. They're defined on the tag
* or with setAttribute (which shouldn't be used with HTML)
* This will return true or false for boolean attributes.
*
* @param {Element} tag
* Element from which to get tag attributes.
*
* @return {Object}
* All attributes of the element.
*/
function getAttributes(tag) {
var obj = {};
// known boolean attributes
// we can check for matching boolean properties, but older browsers
// won't know about HTML5 boolean attributes that we still read from
var knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
if (tag && tag.attributes && tag.attributes.length > 0) {
var attrs = tag.attributes;
for (var i = attrs.length - 1; i >= 0; i--) {
var attrName = attrs[i].name;
var attrVal = attrs[i].value;
// check for known booleans
// the matching element property will return a value for typeof
if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
// the value of an included boolean attribute is typically an empty
// string ('') which would equal false if we just check for a false value.
// we also don't want support bad code like autoplay='false'
attrVal = attrVal !== null ? true : false;
}
obj[attrName] = attrVal;
}
}
return obj;
}
/**
* Get the value of an element's attribute
*
* @param {Element} el
* A DOM element
*
* @param {string} attribute
* Attribute to get the value of
*
* @return {string}
* value of the attribute
*/
function getAttribute(el, attribute) {
return el.getAttribute(attribute);
}
/**
* Set the value of an element's attribute
*
* @param {Element} el
* A DOM element
*
* @param {string} attribute
* Attribute to set
*
* @param {string} value
* Value to set the attribute to
*/
function setAttribute(el, attribute, value) {
el.setAttribute(attribute, value);
}
/**
* Remove an element's attribute
*
* @param {Element} el
* A DOM element
*
* @param {string} attribute
* Attribute to remove
*/
function removeAttribute(el, attribute) {
el.removeAttribute(attribute);
}
/**
* Attempt to block the ability to select text while dragging controls
*/
function blockTextSelection() {
document.body.focus();
document.onselectstart = function () {
return false;
};
}
/**
* Turn off text selection blocking
*/
function unblockTextSelection() {
document.onselectstart = function () {
return true;
};
}
/**
* Identical to the native `getBoundingClientRect` function, but ensures that
* the method is supported at all (it is in all browsers we claim to support)
* and that the element is in the DOM before continuing.
*
* This wrapper function also shims properties which are not provided by some
* older browsers (namely, IE8).
*
* Additionally, some browsers do not support adding properties to a
* `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
* properties (except `x` and `y` which are not widely supported). This helps
* avoid implementations where keys are non-enumerable.
*
* @param {Element} el
* Element whose `ClientRect` we want to calculate.
*
* @return {Object|undefined}
* Always returns a plain
*/
function getBoundingClientRect(el) {
if (el && el.getBoundingClientRect && el.parentNode) {
var rect = el.getBoundingClientRect();
var result = {};
['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(function (k) {
if (rect[k] !== undefined) {
result[k] = rect[k];
}
});
if (!result.height) {
result.height = parseFloat(computedStyle(el, 'height'));
}
if (!result.width) {
result.width = parseFloat(computedStyle(el, 'width'));
}
return result;
}
}
/**
* The postion of a DOM element on the page.
*
* @typedef {Object} module:dom~Position
*
* @property {number} left
* Pixels to the left
*
* @property {number} top
* Pixels on top
*/
/**
* Offset Left.
* getBoundingClientRect technique from
* John Resig
*
* @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
*
* @param {Element} el
* Element from which to get offset
*
* @return {module:dom~Position}
* The position of the element that was passed in.
*/
function findPosition(el) {
var box = void 0;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0
};
}
var docEl = document.documentElement;
var body = document.body;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var scrollLeft = window.pageXOffset || body.scrollLeft;
var left = box.left + scrollLeft - clientLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var scrollTop = window.pageYOffset || body.scrollTop;
var top = box.top + scrollTop - clientTop;
// Android sometimes returns slightly off decimal values, so need to round
return {
left: Math.round(left),
top: Math.round(top)
};
}
/**
* x and y coordinates for a dom element or mouse pointer
*
* @typedef {Object} Dom~Coordinates
*
* @property {number} x
* x coordinate in pixels
*
* @property {number} y
* y coordinate in pixels
*/
/**
* Get pointer position in element
* Returns an object with x and y coordinates.
* The base on the coordinates are the bottom left of the element.
*
* @param {Element} el
* Element on which to get the pointer position on
*
* @param {EventTarget~Event} event
* Event object
*
* @return {Dom~Coordinates}
* A Coordinates object corresponding to the mouse position.
*
*/
function getPointerPosition(el, event) {
var position = {};
var box = findPosition(el);
var boxW = el.offsetWidth;
var boxH = el.offsetHeight;
var boxY = box.top;
var boxX = box.left;
var pageY = event.pageY;
var pageX = event.pageX;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
pageY = event.changedTouches[0].pageY;
}
position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH));
position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));
return position;
}
/**
* Determines, via duck typing, whether or not a value is a text node.
*
* @param {Mixed} value
* Check if this value is a text node.
*
* @return {boolean}
* - True if it is a text node
* - False otherwise
*/
function isTextNode(value) {
return isObject(value) && value.nodeType === 3;
}
/**
* Empties the contents of an element.
*
* @param {Element} el
* The element to empty children from
*
* @return {Element}
* The element with no children
*/
function emptyEl(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
return el;
}
/**
* Normalizes content for eventual insertion into the DOM.
*
* This allows a wide range of content definition methods, but protects
* from falling into the trap of simply writing to `innerHTML`, which is
* an XSS concern.
*
* The content for an element can be passed in multiple types and
* combinations, whose behavior is as follows:
*
* @param {String|Element|TextNode|Array|Function} content
* - String: Normalized into a text node.
* - Element/TextNode: Passed through.
* - Array: A one-dimensional array of strings, elements, nodes, or functions
* (which return single strings, elements, or nodes).
* - Function: If the sole argument, is expected to produce a string, element,
* node, or array as defined above.
*
* @return {Array}
* All of the content that was passed in normalized.
*/
function normalizeContent(content) {
// First, invoke content if it is a function. If it produces an array,
// that needs to happen before normalization.
if (typeof content === 'function') {
content = content();
}
// Next up, normalize to an array, so one or many items can be normalized,
// filtered, and returned.
return (Array.isArray(content) ? content : [content]).map(function (value) {
// First, invoke value if it is a function to produce a new value,
// which will be subsequently normalized to a Node of some kind.
if (typeof value === 'function') {
value = value();
}
if (isEl(value) || isTextNode(value)) {
return value;
}
if (typeof value === 'string' && /\S/.test(value)) {
return document.createTextNode(value);
}
}).filter(function (value) {
return value;
});
}
/**
* Normalizes and appends content to an element.
*
* @param {Element} el
* Element to append normalized content to.
*
*
* @param {String|Element|TextNode|Array|Function} content
* See the `content` argument of {@link dom:normalizeContent}
*
* @return {Element}
* The element with appended normalized content.
*/
function appendContent(el, content) {
normalizeContent(content).forEach(function (node) {
return el.appendChild(node);
});
return el;
}
/**
* Normalizes and inserts content into an element; this is identical to
* `appendContent()`, except it empties the element first.
*
* @param {Element} el
* Element to insert normalized content into.
*
* @param {String|Element|TextNode|Array|Function} content
* See the `content` argument of {@link dom:normalizeContent}
*
* @return {Element}
* The element with inserted normalized content.
*
*/
function insertContent(el, content) {
return appendContent(emptyEl(el), content);
}
/**
* Check if event was a single left click
*
* @param {EventTarget~Event} event
* Event object
*
* @return {boolean}
* - True if a left click
* - False if not a left click
*/
function isSingleLeftClick(event) {
// Note: if you create something draggable, be sure to
// call it on both `mousedown` and `mousemove` event,
// otherwise `mousedown` should be enough for a button
if (event.button === undefined && event.buttons === undefined) {
// Why do we need `buttons` ?
// Because, middle mouse sometimes have this:
// e.button === 0 and e.buttons === 4
// Furthermore, we want to prevent combination click, something like
// HOLD middlemouse then left click, that would be
// e.button === 0, e.buttons === 5
// just `button` is not gonna work
// Alright, then what this block does ?
// this is for chrome `simulate mobile devices`
// I want to support this as well
return true;
}
if (event.button === 0 && event.buttons === undefined) {
// Touch screen, sometimes on some specific device, `buttons`
// doesn't have anything (safari on ios, blackberry...)
return true;
}
if (IE_VERSION === 9) {
// Ignore IE9
return true;
}
if (event.button !== 0 || event.buttons !== 1) {
// This is the reason we have those if else block above
// if any special case we can catch and let it slide
// we do it above, when get to here, this definitely
// is-not-left-click
return false;
}
return true;
}
/**
* Finds a single DOM element matching `selector` within the optional
* `context` of another DOM element (defaulting to `document`).
*
* @param {string} selector
* A valid CSS selector, which will be passed to `querySelector`.
*
* @param {Element|String} [context=document]
* A DOM element within which to query. Can also be a selector
* string in which case the first matching element will be used
* as context. If missing (or no element matches selector), falls
* back to `document`.
*
* @return {Element|null}
* The element that was found or null.
*/
var $ = createQuerier('querySelector');
/**
* Finds a all DOM elements matching `selector` within the optional
* `context` of another DOM element (defaulting to `document`).
*
* @param {string} selector
* A valid CSS selector, which will be passed to `querySelectorAll`.
*
* @param {Element|String} [context=document]
* A DOM element within which to query. Can also be a selector
* string in which case the first matching element will be used
* as context. If missing (or no element matches selector), falls
* back to `document`.
*
* @return {NodeList}
* A element list of elements that were found. Will be empty if none were found.
*
*/
var $$ = createQuerier('querySelectorAll');
var Dom = (Object.freeze || Object)({
isReal: isReal,
isEl: isEl,
isInFrame: isInFrame,
createEl: createEl,
textContent: textContent,
prependTo: prependTo,
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
setAttributes: setAttributes,
getAttributes: getAttributes,
getAttribute: getAttribute,
setAttribute: setAttribute,
removeAttribute: removeAttribute,
blockTextSelection: blockTextSelection,
unblockTextSelection: unblockTextSelection,
getBoundingClientRect: getBoundingClientRect,
findPosition: findPosition,
getPointerPosition: getPointerPosition,
isTextNode: isTextNode,
emptyEl: emptyEl,
normalizeContent: normalizeContent,
appendContent: appendContent,
insertContent: insertContent,
isSingleLeftClick: isSingleLeftClick,
$: $,
$$: $$
});
/**
* @file guid.js
* @module guid
*/
/**
* Unique ID for an element or function
* @type {Number}
*/
var _guid = 1;
/**
* Get a unique auto-incrementing ID by number that has not been returned before.
*
* @return {number}
* A new unique ID.
*/
function newGUID() {
return _guid++;
}
/**
* @file dom-data.js
* @module dom-data
*/
/**
* Element Data Store.
*
* Allows for binding data to an element without putting it directly on the
* element. Ex. Event listeners are stored here.
* (also from jsninja.com, slightly modified and updated for closure compiler)
*
* @type {Object}
* @private
*/
var elData = {};
/*
* Unique attribute name to store an element's guid in
*
* @type {String}
* @constant
* @private
*/
var elIdAttr = 'vdata' + new Date().getTime();
/**
* Returns the cache object where data for an element is stored
*
* @param {Element} el
* Element to store data for.
*
* @return {Object}
* The cache object for that el that was passed in.
*/
function getData(el) {
var id = el[elIdAttr];
if (!id) {
id = el[elIdAttr] = newGUID();
}
if (!elData[id]) {
elData[id] = {};
}
return elData[id];
}
/**
* Returns whether or not an element has cached data
*
* @param {Element} el
* Check if this element has cached data.
*
* @return {boolean}
* - True if the DOM element has cached data.
* - False otherwise.
*/
function hasData(el) {
var id = el[elIdAttr];
if (!id) {
return false;
}
return !!Object.getOwnPropertyNames(elData[id]).length;
}
/**
* Delete data for the element from the cache and the guid attr from getElementById
*
* @param {Element} el
* Remove cached data for this element.
*/
function removeData(el) {
var id = el[elIdAttr];
if (!id) {
return;
}
// Remove all stored data
delete elData[id];
// Remove the elIdAttr property from the DOM node
try {
delete el[elIdAttr];
} catch (e) {
if (el.removeAttribute) {
el.removeAttribute(elIdAttr);
} else {
// IE doesn't appear to support removeAttribute on the document element
el[elIdAttr] = null;
}
}
}
/**
* @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
* (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
* This should work very similarly to jQuery's events, however it's based off the book version which isn't as
* robust as jquery's, so there's probably some differences.
*
* @module events
*/
/**
* Clean up the listener cache and dispatchers
*
* @param {Element|Object} elem
* Element to clean up
*
* @param {string} type
* Type of event to clean up
*/
function _cleanUpEvents(elem, type) {
var data = getData(elem);
// Remove the events of a particular type if there are none left
if (data.handlers[type].length === 0) {
delete data.handlers[type];
// data.handlers[type] = null;
// Setting to null was causing an error with data.handlers
// Remove the meta-handler from the element
if (elem.removeEventListener) {
elem.removeEventListener(type, data.dispatcher, false);
} else if (elem.detachEvent) {
elem.detachEvent('on' + type, data.dispatcher);
}
}
// Remove the events object if there are no types left
if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
}
// Finally remove the element data if there is no data left
if (Object.getOwnPropertyNames(data).length === 0) {
removeData(elem);
}
}
/**
* Loops through an array of event types and calls the requested method for each type.
*
* @param {Function} fn
* The event method we want to use.
*
* @param {Element|Object} elem
* Element or object to bind listeners to
*
* @param {string} type
* Type of event to bind to.
*
* @param {EventTarget~EventListener} callback
* Event listener.
*/
function _handleMultipleEvents(fn, elem, types, callback) {
types.forEach(function (type) {
// Call the event method for each one of the types
fn(elem, type, callback);
});
}
/**
* Fix a native event to have standard property values
*
* @param {Object} event
* Event object to fix.
*
* @return {Object}
* Fixed event object.
*/
function fixEvent(event) {
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Test if fixing up is needed
// Used to check if !event.stopPropagation instead of isPropagationStopped
// But native events return true for stopPropagation, but don't have
// other expected methods like isPropagationStopped. Seems to be a problem
// with the Javascript Ninja code. So we're just overriding all events now.
if (!event || !event.isPropagationStopped) {
var old = event || window.event;
event = {};
// Clone the old object so that we can modify the values event = {};
// IE8 Doesn't like when you mess with native event properties
// Firefox returns false for event.hasOwnProperty('type') and other props
// which makes copying more difficult.
// TODO: Probably best to create a whitelist of event props
for (var key in old) {
// Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
// Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
// and webkitMovementX/Y
if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') {
// Chrome 32+ warns if you try to copy deprecated returnValue, but
// we still want to if preventDefault isn't supported (IE8).
if (!(key === 'returnValue' && old.preventDefault)) {
event[key] = old[key];
}
}
}
// The event occurred on this element
if (!event.target) {
event.target = event.srcElement || document;
}
// Handle which other element the event is related to
if (!event.relatedTarget) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Stop the default browser action
event.preventDefault = function () {
if (old.preventDefault) {
old.preventDefault();
}
event.returnValue = false;
old.returnValue = false;
event.defaultPrevented = true;
};
event.defaultPrevented = false;
// Stop the event from bubbling
event.stopPropagation = function () {
if (old.stopPropagation) {
old.stopPropagation();
}
event.cancelBubble = true;
old.cancelBubble = true;
event.isPropagationStopped = returnTrue;
};
event.isPropagationStopped = returnFalse;
// Stop the event from bubbling and executing other handlers
event.stopImmediatePropagation = function () {
if (old.stopImmediatePropagation) {
old.stopImmediatePropagation();
}
event.isImmediatePropagationStopped = returnTrue;
event.stopPropagation();
};
event.isImmediatePropagationStopped = returnFalse;
// Handle mouse position
if (event.clientX !== null && event.clientX !== undefined) {
var doc = document.documentElement;
var body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Handle key presses
event.which = event.charCode || event.keyCode;
// Fix button for mouse clicks:
// 0 == left; 1 == middle; 2 == right
if (event.button !== null && event.button !== undefined) {
// The following is disabled because it does not pass videojs-standard
// and... yikes.
/* eslint-disable */
event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
/* eslint-enable */
}
}
// Returns fixed-up instance
return event;
}
/**
* Whether passive event listeners are supported
*/
var _supportsPassive = false;
(function () {
try {
var opts = Object.defineProperty({}, 'passive', {
get: function get() {
_supportsPassive = true;
}
});
window.addEventListener('test', null, opts);
window.removeEventListener('test', null, opts);
} catch (e) {
// disregard
}
})();
/**
* Touch events Chrome expects to be passive
*/
var passiveEvents = ['touchstart', 'touchmove'];
/**
* Add an event listener to element
* It stores the handler function in a separate cache object
* and adds a generic handler to the element's event,
* along with a unique id (guid) to the element.
*
* @param {Element|Object} elem
* Element or object to bind listeners to
*
* @param {string|string[]} type
* Type of event to bind to.
*
* @param {EventTarget~EventListener} fn
* Event listener.
*/
function on(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(on, elem, type, fn);
}
var data = getData(elem);
// We need a place to store all our handler data
if (!data.handlers) {
data.handlers = {};
}
if (!data.handlers[type]) {
data.handlers[type] = [];
}
if (!fn.guid) {
fn.guid = newGUID();
}
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event, hash) {
if (data.disabled) {
return;
}
event = fixEvent(event);
var handlers = data.handlers[event.type];
if (handlers) {
// Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
var handlersCopy = handlers.slice(0);
for (var m = 0, n = handlersCopy.length; m < n; m++) {
if (event.isImmediatePropagationStopped()) {
break;
} else {
try {
handlersCopy[m].call(elem, event, hash);
} catch (e) {
log.error(e);
}
}
}
}
};
}
if (data.handlers[type].length === 1) {
if (elem.addEventListener) {
var options = false;
if (_supportsPassive && passiveEvents.indexOf(type) > -1) {
options = { passive: true };
}
elem.addEventListener(type, data.dispatcher, options);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, data.dispatcher);
}
}
}
/**
* Removes event listeners from an element
*
* @param {Element|Object} elem
* Object to remove listeners from.
*
* @param {string|string[]} [type]
* Type of listener to remove. Don't include to remove all events from element.
*
* @param {EventTarget~EventListener} [fn]
* Specific listener to remove. Don't include to remove listeners for an event
* type.
*/
function off(elem, type, fn) {
// Don't want to add a cache object through getElData if not needed
if (!hasData(elem)) {
return;
}
var data = getData(elem);
// If no events exist, nothing to unbind
if (!data.handlers) {
return;
}
if (Array.isArray(type)) {
return _handleMultipleEvents(off, elem, type, fn);
}
// Utility function
var removeType = function removeType(el, t) {
data.handlers[t] = [];
_cleanUpEvents(el, t);
};
// Are we removing all bound events?
if (type === undefined) {
for (var t in data.handlers) {
if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
removeType(elem, t);
}
}
return;
}
var handlers = data.handlers[type];
// If no handlers exist, nothing to unbind
if (!handlers) {
return;
}
// If no listener was provided, remove all listeners for type
if (!fn) {
removeType(elem, type);
return;
}
// We're only removing a single handler
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
_cleanUpEvents(elem, type);
}
/**
* Trigger an event for an element
*
* @param {Element|Object} elem
* Element to trigger an event on
*
* @param {EventTarget~Event|string} event
* A string (the type) or an event object with a type attribute
*
* @param {Object} [hash]
* data hash to pass along with the event
*
* @return {boolean|undefined}
* - Returns the opposite of `defaultPrevented` if default was prevented
* - Otherwise returns undefined
*/
function trigger(elem, event, hash) {
// Fetches element data and a reference to the parent (for bubbling).
// Don't want to add a data object to cache for every parent,
// so checking hasElData first.
var elemData = hasData(elem) ? getData(elem) : {};
var parent = elem.parentNode || elem.ownerDocument;
// type = event.type || event,
// handler;
// If an event name was passed as a string, creates an event out of it
if (typeof event === 'string') {
event = { type: event, target: elem };
} else if (!event.target) {
event.target = elem;
}
// Normalizes the event properties.
event = fixEvent(event);
// If the passed element has a dispatcher, executes the established handlers.
if (elemData.dispatcher) {
elemData.dispatcher.call(elem, event, hash);
}
// Unless explicitly stopped or the event does not bubble (e.g. media events)
// recursively calls this function to bubble the event up the DOM.
if (parent && !event.isPropagationStopped() && event.bubbles === true) {
trigger.call(null, parent, event, hash);
// If at the top of the DOM, triggers the default action unless disabled.
} else if (!parent && !event.defaultPrevented) {
var targetData = getData(event.target);
// Checks if the target has a default action for this event.
if (event.target[event.type]) {
// Temporarily disables event dispatching on the target as we have already executed the handler.
targetData.disabled = true;
// Executes the default action.
if (typeof event.target[event.type] === 'function') {
event.target[event.type]();
}
// Re-enables event dispatching.
targetData.disabled = false;
}
}
// Inform the triggerer if the default was prevented by returning false
return !event.defaultPrevented;
}
/**
* Trigger a listener only once for an event
*
* @param {Element|Object} elem
* Element or object to bind to.
*
* @param {string|string[]} type
* Name/type of event
*
* @param {Event~EventListener} fn
* Event Listener function
*/
function one(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(one, elem, type, fn);
}
var func = function func() {
off(elem, type, func);
fn.apply(this, arguments);
};
// copy the guid to the new function so it can removed using the original function's ID
func.guid = fn.guid = fn.guid || newGUID();
on(elem, type, func);
}
var Events = (Object.freeze || Object)({
fixEvent: fixEvent,
on: on,
off: off,
trigger: trigger,
one: one
});
/**
* @file setup.js - Functions for setting up a player without
* user interaction based on the data-setup `attribute` of the video tag.
*
* @module setup
*/
var _windowLoaded = false;
var videojs$2 = void 0;
/**
* Set up any tags that have a data-setup `attribute` when the player is started.
*/
var autoSetup = function autoSetup() {
// Protect against breakage in non-browser environments and check global autoSetup option.
if (!isReal() || videojs$2.options.autoSetup === false) {
return;
}
// One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack*
// var vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
// var audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
// var mediaEls = vids.concat(audios);
// Because IE8 doesn't support calling slice on a node list, we need to loop
// through each list of elements to build up a new, combined list of elements.
var vids = document.getElementsByTagName('video');
var audios = document.getElementsByTagName('audio');
var divs = document.getElementsByTagName('video-js');
var mediaEls = [];
if (vids && vids.length > 0) {
for (var i = 0, e = vids.length; i < e; i++) {
mediaEls.push(vids[i]);
}
}
if (audios && audios.length > 0) {
for (var _i = 0, _e = audios.length; _i < _e; _i++) {
mediaEls.push(audios[_i]);
}
}
if (divs && divs.length > 0) {
for (var _i2 = 0, _e2 = divs.length; _i2 < _e2; _i2++) {
mediaEls.push(divs[_i2]);
}
}
// Check if any media elements exist
if (mediaEls && mediaEls.length > 0) {
for (var _i3 = 0, _e3 = mediaEls.length; _i3 < _e3; _i3++) {
var mediaEl = mediaEls[_i3];
// Check if element exists, has getAttribute func.
// IE seems to consider typeof el.getAttribute == 'object' instead of
// 'function' like expected, at least when loading the player immediately.
if (mediaEl && mediaEl.getAttribute) {
// Make sure this player hasn't already been set up.
if (mediaEl.player === undefined) {
var options = mediaEl.getAttribute('data-setup');
// Check if data-setup attr exists.
// We only auto-setup if they've added the data-setup attr.
if (options !== null) {
// Create new video.js instance.
videojs$2(mediaEl);
}
}
// If getAttribute isn't defined, we need to wait for the DOM.
} else {
autoSetupTimeout(1);
break;
}
}
// No videos were found, so keep looping unless page is finished loading.
} else if (!_windowLoaded) {
autoSetupTimeout(1);
}
};
/**
* Wait until the page is loaded before running autoSetup. This will be called in
* autoSetup if `hasLoaded` returns false.
*
* @param {number} wait
* How long to wait in ms
*
* @param {module:videojs} [vjs]
* The videojs library function
*/
function autoSetupTimeout(wait, vjs) {
if (vjs) {
videojs$2 = vjs;
}
window.setTimeout(autoSetup, wait);
}
if (isReal() && document.readyState === 'complete') {
_windowLoaded = true;
} else {
/**
* Listen for the load event on window, and set _windowLoaded to true.
*
* @listens load
*/
one(window, 'load', function () {
_windowLoaded = true;
});
}
/**
* @file stylesheet.js
* @module stylesheet
*/
/**
* Create a DOM syle element given a className for it.
*
* @param {string} className
* The className to add to the created style element.
*
* @return {Element}
* The element that was created.
*/
var createStyleElement = function createStyleElement(className) {
var style = document.createElement('style');
style.className = className;
return style;
};
/**
* Add text to a DOM element.
*
* @param {Element} el
* The Element to add text content to.
*
* @param {string} content
* The text to add to the element.
*/
var setTextContent = function setTextContent(el, content) {
if (el.styleSheet) {
el.styleSheet.cssText = content;
} else {
el.textContent = content;
}
};
/**
* @file fn.js
* @module fn
*/
/**
* Bind (a.k.a proxy or Context). A simple method for changing the context of a function
* It also stores a unique id on the function so it can be easily removed from events.
*
* @param {Mixed} context
* The object to bind as scope.
*
* @param {Function} fn
* The function to be bound to a scope.
*
* @param {number} [uid]
* An optional unique ID for the function to be set
*
* @return {Function}
* The new function that will be bound into the context given
*/
var bind = function bind(context, fn, uid) {
// Make sure the function has a unique ID
if (!fn.guid) {
fn.guid = newGUID();
}
// Create the new function that changes the context
var bound = function bound() {
return fn.apply(context, arguments);
};
// Allow for the ability to individualize this function
// Needed in the case where multiple objects might share the same prototype
// IF both items add an event listener with the same function, then you try to remove just one
// it will remove both because they both have the same guid.
// when using this, you need to use the bind method when you remove the listener as well.
// currently used in text tracks
bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
return bound;
};
/**
* Wraps the given function, `fn`, with a new function that only invokes `fn`
* at most once per every `wait` milliseconds.
*
* @param {Function} fn
* The function to be throttled.
*
* @param {Number} wait
* The number of milliseconds by which to throttle.
*
* @return {Function}
*/
var throttle = function throttle(fn, wait) {
var last = Date.now();
var throttled = function throttled() {
var now = Date.now();
if (now - last >= wait) {
fn.apply(undefined, arguments);
last = now;
}
};
return throttled;
};
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked.
*
* Inspired by lodash and underscore implementations.
*
* @param {Function} func
* The function to wrap with debounce behavior.
*
* @param {number} wait
* The number of milliseconds to wait after the last invocation.
*
* @param {boolean} [immediate]
* Whether or not to invoke the function immediately upon creation.
*
* @param {Object} [context=window]
* The "context" in which the debounced function should debounce. For
* example, if this function should be tied to a Video.js player,
* the player can be passed here. Alternatively, defaults to the
* global `window` object.
*
* @return {Function}
* A debounced function.
*/
var debounce = function debounce(func, wait, immediate) {
var context = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : window;
var timeout = void 0;
var cancel = function cancel() {
context.clearTimeout(timeout);
timeout = null;
};
/* eslint-disable consistent-this */
var debounced = function debounced() {
var self = this;
var args = arguments;
var _later = function later() {
timeout = null;
_later = null;
if (!immediate) {
func.apply(self, args);
}
};
if (!timeout && immediate) {
func.apply(self, args);
}
context.clearTimeout(timeout);
timeout = context.setTimeout(_later, wait);
};
/* eslint-enable consistent-this */
debounced.cancel = cancel;
return debounced;
};
/**
* @file src/js/event-target.js
*/
/**
* `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
* adds shorthand functions that wrap around lengthy functions. For example:
* the `on` function is a wrapper around `addEventListener`.
*
* @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
* @class EventTarget
*/
var EventTarget = function EventTarget() {};
/**
* A Custom DOM event.
*
* @typedef {Object} EventTarget~Event
* @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
*/
/**
* All event listeners should follow the following format.
*
* @callback EventTarget~EventListener
* @this {EventTarget}
*
* @param {EventTarget~Event} event
* the event that triggered this function
*
* @param {Object} [hash]
* hash of data sent during the event
*/
/**
* An object containing event names as keys and booleans as values.
*
* > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
* will have extra functionality. See that function for more information.
*
* @property EventTarget.prototype.allowedEvents_
* @private
*/
EventTarget.prototype.allowedEvents_ = {};
/**
* Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
* function that will get called when an event with a certain name gets triggered.
*
* @param {string|string[]} type
* An event name or an array of event names.
*
* @param {EventTarget~EventListener} fn
* The function to call with `EventTarget`s
*/
EventTarget.prototype.on = function (type, fn) {
// Remove the addEventListener alias before calling Events.on
// so we don't get into an infinite type loop
var ael = this.addEventListener;
this.addEventListener = function () {};
on(this, type, fn);
this.addEventListener = ael;
};
/**
* An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
* the standard DOM API.
*
* @function
* @see {@link EventTarget#on}
*/
EventTarget.prototype.addEventListener = EventTarget.prototype.on;
/**
* Removes an `event listener` for a specific event from an instance of `EventTarget`.
* This makes it so that the `event listener` will no longer get called when the
* named event happens.
*
* @param {string|string[]} type
* An event name or an array of event names.
*
* @param {EventTarget~EventListener} fn
* The function to remove.
*/
EventTarget.prototype.off = function (type, fn) {
off(this, type, fn);
};
/**
* An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
* the standard DOM API.
*
* @function
* @see {@link EventTarget#off}
*/
EventTarget.prototype.removeEventListener = EventTarget.prototype.off;
/**
* This function will add an `event listener` that gets triggered only once. After the
* first trigger it will get removed. This is like adding an `event listener`
* with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
*
* @param {string|string[]} type
* An event name or an array of event names.
*
* @param {EventTarget~EventListener} fn
* The function to be called once for each event name.
*/
EventTarget.prototype.one = function (type, fn) {
// Remove the addEventListener alialing Events.on
// so we don't get into an infinite type loop
var ael = this.addEventListener;
this.addEventListener = function () {};
one(this, type, fn);
this.addEventListener = ael;
};
/**
* This function causes an event to happen. This will then cause any `event listeners`
* that are waiting for that event, to get called. If there are no `event listeners`
* for an event then nothing will happen.
*
* If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
* Trigger will also call the `on` + `uppercaseEventName` function.
*
* Example:
* 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
* `onClick` if it exists.
*
* @param {string|EventTarget~Event|Object} event
* The name of the event, an `Event`, or an object with a key of type set to
* an event name.
*/
EventTarget.prototype.trigger = function (event) {
var type = event.type || event;
if (typeof event === 'string') {
event = { type: type };
}
event = fixEvent(event);
if (this.allowedEvents_[type] && this['on' + type]) {
this['on' + type](event);
}
trigger(this, event);
};
/**
* An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
* the standard DOM API.
*
* @function
* @see {@link EventTarget#trigger}
*/
EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger;
/**
* @file mixins/evented.js
* @module evented
*/
/**
* Returns whether or not an object has had the evented mixin applied.
*
* @param {Object} object
* An object to test.
*
* @return {boolean}
* Whether or not the object appears to be evented.
*/
var isEvented = function isEvented(object) {
return object instanceof EventTarget || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(function (k) {
return typeof object[k] === 'function';
});
};
/**
* Whether a value is a valid event type - non-empty string or array.
*
* @private
* @param {string|Array} type
* The type value to test.
*
* @return {boolean}
* Whether or not the type is a valid event type.
*/
var isValidEventType = function isValidEventType(type) {
return (
// The regex here verifies that the `type` contains at least one non-
// whitespace character.
typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length
);
};
/**
* Validates a value to determine if it is a valid event target. Throws if not.
*
* @private
* @throws {Error}
* If the target does not appear to be a valid event target.
*
* @param {Object} target
* The object to test.
*/
var validateTarget = function validateTarget(target) {
if (!target.nodeName && !isEvented(target)) {
throw new Error('Invalid target; must be a DOM node or evented object.');
}
};
/**
* Validates a value to determine if it is a valid event target. Throws if not.
*
* @private
* @throws {Error}
* If the type does not appear to be a valid event type.
*
* @param {string|Array} type
* The type to test.
*/
var validateEventType = function validateEventType(type) {
if (!isValidEventType(type)) {
throw new Error('Invalid event type; must be a non-empty string or array.');
}
};
/**
* Validates a value to determine if it is a valid listener. Throws if not.
*
* @private
* @throws {Error}
* If the listener is not a function.
*
* @param {Function} listener
* The listener to test.
*/
var validateListener = function validateListener(listener) {
if (typeof listener !== 'function') {
throw new Error('Invalid listener; must be a function.');
}
};
/**
* Takes an array of arguments given to `on()` or `one()`, validates them, and
* normalizes them into an object.
*
* @private
* @param {Object} self
* The evented object on which `on()` or `one()` was called. This
* object will be bound as the `this` value for the listener.
*
* @param {Array} args
* An array of arguments passed to `on()` or `one()`.
*
* @return {Object}
* An object containing useful values for `on()` or `one()` calls.
*/
var normalizeListenArgs = function normalizeListenArgs(self, args) {
// If the number of arguments is less than 3, the target is always the
// evented object itself.
var isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
var target = void 0;
var type = void 0;
var listener = void 0;
if (isTargetingSelf) {
target = self.eventBusEl_;
// Deal with cases where we got 3 arguments, but we are still listening to
// the evented object itself.
if (args.length >= 3) {
args.shift();
}
type = args[0];
listener = args[1];
} else {
target = args[0];
type = args[1];
listener = args[2];
}
validateTarget(target);
validateEventType(type);
validateListener(listener);
listener = bind(self, listener);
return { isTargetingSelf: isTargetingSelf, target: target, type: type, listener: listener };
};
/**
* Adds the listener to the event type(s) on the target, normalizing for
* the type of target.
*
* @private
* @param {Element|Object} target
* A DOM node or evented object.
*
* @param {string} method
* The event binding method to use ("on" or "one").
*
* @param {string|Array} type
* One or more event type(s).
*
* @param {Function} listener
* A listener function.
*/
var listen = function listen(target, method, type, listener) {
validateTarget(target);
if (target.nodeName) {
Events[method](target, type, listener);
} else {
target[method](type, listener);
}
};
/**
* Contains methods that provide event capabilites to an object which is passed
* to {@link module:evented|evented}.
*
* @mixin EventedMixin
*/
var EventedMixin = {
/**
* Add a listener to an event (or events) on this object or another evented
* object.
*
* @param {string|Array|Element|Object} targetOrType
* If this is a string or array, it represents the event type(s)
* that will trigger the listener.
*
* Another evented object can be passed here instead, which will
* cause the listener to listen for events on _that_ object.
*
* In either case, the listener's `this` value will be bound to
* this object.
*
* @param {string|Array|Function} typeOrListener
* If the first argument was a string or array, this should be the
* listener function. Otherwise, this is a string or array of event
* type(s).
*
* @param {Function} [listener]
* If the first argument was another evented object, this will be
* the listener function.
*/
on: function on$$1() {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _normalizeListenArgs = normalizeListenArgs(this, args),
isTargetingSelf = _normalizeListenArgs.isTargetingSelf,
target = _normalizeListenArgs.target,
type = _normalizeListenArgs.type,
listener = _normalizeListenArgs.listener;
listen(target, 'on', type, listener);
// If this object is listening to another evented object.
if (!isTargetingSelf) {
// If this object is disposed, remove the listener.
var removeListenerOnDispose = function removeListenerOnDispose() {
return _this.off(target, type, listener);
};
// Use the same function ID as the listener so we can remove it later it
// using the ID of the original listener.
removeListenerOnDispose.guid = listener.guid;
// Add a listener to the target's dispose event as well. This ensures
// that if the target is disposed BEFORE this object, we remove the
// removal listener that was just added. Otherwise, we create a memory leak.
var removeRemoverOnTargetDispose = function removeRemoverOnTargetDispose() {
return _this.off('dispose', removeListenerOnDispose);
};
// Use the same function ID as the listener so we can remove it later
// it using the ID of the original listener.
removeRemoverOnTargetDispose.guid = listener.guid;
listen(this, 'on', 'dispose', removeListenerOnDispose);
listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
}
},
/**
* Add a listener to an event (or events) on this object or another evented
* object. The listener will only be called once and then removed.
*
* @param {string|Array|Element|Object} targetOrType
* If this is a string or array, it represents the event type(s)
* that will trigger the listener.
*
* Another evented object can be passed here instead, which will
* cause the listener to listen for events on _that_ object.
*
* In either case, the listener's `this` value will be bound to
* this object.
*
* @param {string|Array|Function} typeOrListener
* If the first argument was a string or array, this should be the
* listener function. Otherwise, this is a string or array of event
* type(s).
*
* @param {Function} [listener]
* If the first argument was another evented object, this will be
* the listener function.
*/
one: function one$$1() {
var _this2 = this;
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var _normalizeListenArgs2 = normalizeListenArgs(this, args),
isTargetingSelf = _normalizeListenArgs2.isTargetingSelf,
target = _normalizeListenArgs2.target,
type = _normalizeListenArgs2.type,
listener = _normalizeListenArgs2.listener;
// Targeting this evented object.
if (isTargetingSelf) {
listen(target, 'one', type, listener);
// Targeting another evented object.
} else {
var wrapper = function wrapper() {
for (var _len3 = arguments.length, largs = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
largs[_key3] = arguments[_key3];
}
_this2.off(target, type, wrapper);
listener.apply(null, largs);
};
// Use the same function ID as the listener so we can remove it later
// it using the ID of the original listener.
wrapper.guid = listener.guid;
listen(target, 'one', type, wrapper);
}
},
/**
* Removes listener(s) from event(s) on an evented object.
*
* @param {string|Array|Element|Object} [targetOrType]
* If this is a string or array, it represents the event type(s).
*
* Another evented object can be passed here instead, in which case
* ALL 3 arguments are _required_.
*
* @param {string|Array|Function} [typeOrListener]
* If the first argument was a string or array, this may be the
* listener function. Otherwise, this is a string or array of event
* type(s).
*
* @param {Function} [listener]
* If the first argument was another evented object, this will be
* the listener function; otherwise, _all_ listeners bound to the
* event type(s) will be removed.
*/
off: function off$$1(targetOrType, typeOrListener, listener) {
// Targeting this evented object.
if (!targetOrType || isValidEventType(targetOrType)) {
off(this.eventBusEl_, targetOrType, typeOrListener);
// Targeting another evented object.
} else {
var target = targetOrType;
var type = typeOrListener;
// Fail fast and in a meaningful way!
validateTarget(target);
validateEventType(type);
validateListener(listener);
// Ensure there's at least a guid, even if the function hasn't been used
listener = bind(this, listener);
// Remove the dispose listener on this evented object, which was given
// the same guid as the event listener in on().
this.off('dispose', listener);
if (target.nodeName) {
off(target, type, listener);
off(target, 'dispose', listener);
} else if (isEvented(target)) {
target.off(type, listener);
target.off('dispose', listener);
}
}
},
/**
* Fire an event on this evented object, causing its listeners to be called.
*
* @param {string|Object} event
* An event type or an object with a type property.
*
* @param {Object} [hash]
* An additional object to pass along to listeners.
*
* @returns {boolean}
* Whether or not the default behavior was prevented.
*/
trigger: function trigger$$1(event, hash) {
return trigger(this.eventBusEl_, event, hash);
}
};
/**
* Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
*
* @param {Object} target
* The object to which to add event methods.
*
* @param {Object} [options={}]
* Options for customizing the mixin behavior.
*
* @param {String} [options.eventBusKey]
* By default, adds a `eventBusEl_` DOM element to the target object,
* which is used as an event bus. If the target object already has a
* DOM element that should be used, pass its key here.
*
* @return {Object}
* The target object.
*/
function evented(target) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var eventBusKey = options.eventBusKey;
// Set or create the eventBusEl_.
if (eventBusKey) {
if (!target[eventBusKey].nodeName) {
throw new Error('The eventBusKey "' + eventBusKey + '" does not refer to an element.');
}
target.eventBusEl_ = target[eventBusKey];
} else {
target.eventBusEl_ = createEl('span', { className: 'vjs-event-bus' });
}
assign(target, EventedMixin);
// When any evented object is disposed, it removes all its listeners.
target.on('dispose', function () {
target.off();
window.setTimeout(function () {
target.eventBusEl_ = null;
}, 0);
});
return target;
}
/**
* @file mixins/stateful.js
* @module stateful
*/
/**
* Contains methods that provide statefulness to an object which is passed
* to {@link module:stateful}.
*
* @mixin StatefulMixin
*/
var StatefulMixin = {
/**
* A hash containing arbitrary keys and values representing the state of
* the object.
*
* @type {Object}
*/
state: {},
/**
* Set the state of an object by mutating its
* {@link module:stateful~StatefulMixin.state|state} object in place.
*
* @fires module:stateful~StatefulMixin#statechanged
* @param {Object|Function} stateUpdates
* A new set of properties to shallow-merge into the plugin state.
* Can be a plain object or a function returning a plain object.
*
* @returns {Object|undefined}
* An object containing changes that occurred. If no changes
* occurred, returns `undefined`.
*/
setState: function setState(stateUpdates) {
var _this = this;
// Support providing the `stateUpdates` state as a function.
if (typeof stateUpdates === 'function') {
stateUpdates = stateUpdates();
}
var changes = void 0;
each(stateUpdates, function (value, key) {
// Record the change if the value is different from what's in the
// current state.
if (_this.state[key] !== value) {
changes = changes || {};
changes[key] = {
from: _this.state[key],
to: value
};
}
_this.state[key] = value;
});
// Only trigger "statechange" if there were changes AND we have a trigger
// function. This allows us to not require that the target object be an
// evented object.
if (changes && isEvented(this)) {
/**
* An event triggered on an object that is both
* {@link module:stateful|stateful} and {@link module:evented|evented}
* indicating that its state has changed.
*
* @event module:stateful~StatefulMixin#statechanged
* @type {Object}
* @property {Object} changes
* A hash containing the properties that were changed and
* the values they were changed `from` and `to`.
*/
this.trigger({
changes: changes,
type: 'statechanged'
});
}
return changes;
}
};
/**
* Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
* object.
*
* If the target object is {@link module:evented|evented} and has a
* `handleStateChanged` method, that method will be automatically bound to the
* `statechanged` event on itself.
*
* @param {Object} target
* The object to be made stateful.
*
* @param {Object} [defaultState]
* A default set of properties to populate the newly-stateful object's
* `state` property.
*
* @returns {Object}
* Returns the `target`.
*/
function stateful(target, defaultState) {
assign(target, StatefulMixin);
// This happens after the mixing-in because we need to replace the `state`
// added in that step.
target.state = assign({}, target.state, defaultState);
// Auto-bind the `handleStateChanged` method of the target object if it exists.
if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
target.on('statechanged', target.handleStateChanged);
}
return target;
}
/**
* @file to-title-case.js
* @module to-title-case
*/
/**
* Uppercase the first letter of a string.
*
* @param {string} string
* String to be uppercased
*
* @return {string}
* The string with an uppercased first letter
*/
function toTitleCase(string) {
if (typeof string !== 'string') {
return string;
}
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* Compares the TitleCase versions of the two strings for equality.
*
* @param {string} str1
* The first string to compare
*
* @param {string} str2
* The second string to compare
*
* @return {boolean}
* Whether the TitleCase versions of the strings are equal
*/
function titleCaseEquals(str1, str2) {
return toTitleCase(str1) === toTitleCase(str2);
}
/**
* @file merge-options.js
* @module merge-options
*/
/**
* Deep-merge one or more options objects, recursively merging **only** plain
* object properties.
*
* @param {Object[]} sources
* One or more objects to merge into a new object.
*
* @returns {Object}
* A new object that is the merged result of all sources.
*/
function mergeOptions() {
var result = {};
for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) {
sources[_key] = arguments[_key];
}
sources.forEach(function (source) {
if (!source) {
return;
}
each(source, function (value, key) {
if (!isPlain(value)) {
result[key] = value;
return;
}
if (!isPlain(result[key])) {
result[key] = {};
}
result[key] = mergeOptions(result[key], value);
});
});
return result;
}
/**
* Player Component - Base class for all UI objects
*
* @file component.js
*/
/**
* Base class for all UI Components.
* Components are UI objects which represent both a javascript object and an element
* in the DOM. They can be children of other components, and can have
* children themselves.
*
* Components can also use methods from {@link EventTarget}
*/
var Component = function () {
/**
* A callback that is called when a component is ready. Does not have any
* paramters and any callback value will be ignored.
*
* @callback Component~ReadyCallback
* @this Component
*/
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Object[]} [options.children]
* An array of children objects to intialize this component with. Children objects have
* a name property that will be used if more than one component of the same type needs to be
* added.
*
* @param {Component~ReadyCallback} [ready]
* Function that gets called when the `Component` is ready.
*/
function Component(player, options, ready) {
classCallCheck(this, Component);
// The component might be the player itself and we can't pass `this` to super
if (!player && this.play) {
this.player_ = player = this; // eslint-disable-line
} else {
this.player_ = player;
}
// Make a copy of prototype.options_ to protect against overriding defaults
this.options_ = mergeOptions({}, this.options_);
// Updated options with supplied options
options = this.options_ = mergeOptions(this.options_, options);
// Get ID from options or options element if one is supplied
this.id_ = options.id || options.el && options.el.id;
// If there was no ID from the options, generate one
if (!this.id_) {
// Don't require the player ID function in the case of mock players
var id = player && player.id && player.id() || 'no_player';
this.id_ = id + '_component_' + newGUID();
}
this.name_ = options.name || null;
// Create element if one wasn't provided in options
if (options.el) {
this.el_ = options.el;
} else if (options.createEl !== false) {
this.el_ = this.createEl();
}
// if evented is anything except false, we want to mixin in evented
if (options.evented !== false) {
// Make this an evented object and use `el_`, if available, as its event bus
evented(this, { eventBusKey: this.el_ ? 'el_' : null });
}
stateful(this, this.constructor.defaultState);
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
// Add any child components in options
if (options.initChildren !== false) {
this.initChildren();
}
this.ready(ready);
// Don't want to trigger ready here or it will before init is actually
// finished for all children that run this constructor
if (options.reportTouchActivity !== false) {
this.enableTouchActivity();
}
}
/**
* Dispose of the `Component` and all child components.
*
* @fires Component#dispose
*/
Component.prototype.dispose = function dispose() {
/**
* Triggered when a `Component` is disposed.
*
* @event Component#dispose
* @type {EventTarget~Event}
*
* @property {boolean} [bubbles=false]
* set to false so that the close event does not
* bubble up
*/
this.trigger({ type: 'dispose', bubbles: false });
// Dispose all children.
if (this.children_) {
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i].dispose) {
this.children_[i].dispose();
}
}
}
// Delete child references
this.children_ = null;
this.childIndex_ = null;
this.childNameIndex_ = null;
if (this.el_) {
// Remove element from DOM
if (this.el_.parentNode) {
this.el_.parentNode.removeChild(this.el_);
}
removeData(this.el_);
this.el_ = null;
}
// remove reference to the player after disposing of the element
this.player_ = null;
};
/**
* Return the {@link Player} that the `Component` has attached to.
*
* @return {Player}
* The player that this `Component` has attached to.
*/
Component.prototype.player = function player() {
return this.player_;
};
/**
* Deep merge of options objects with new options.
* > Note: When both `obj` and `options` contain properties whose values are objects.
* The two properties get merged using {@link module:mergeOptions}
*
* @param {Object} obj
* The object that contains new options.
*
* @return {Object}
* A new object of `this.options_` and `obj` merged together.
*
* @deprecated since version 5
*/
Component.prototype.options = function options(obj) {
log.warn('this.options() has been deprecated and will be moved to the constructor in 6.0');
if (!obj) {
return this.options_;
}
this.options_ = mergeOptions(this.options_, obj);
return this.options_;
};
/**
* Get the `Component`s DOM element
*
* @return {Element}
* The DOM element for this `Component`.
*/
Component.prototype.el = function el() {
return this.el_;
};
/**
* Create the `Component`s DOM element.
*
* @param {string} [tagName]
* Element's DOM node type. e.g. 'div'
*
* @param {Object} [properties]
* An object of properties that should be set.
*
* @param {Object} [attributes]
* An object of attributes that should be set.
*
* @return {Element}
* The element that gets created.
*/
Component.prototype.createEl = function createEl$$1(tagName, properties, attributes) {
return createEl(tagName, properties, attributes);
};
/**
* Localize a string given the string in english.
*
* If tokens are provided, it'll try and run a simple token replacement on the provided string.
* The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
*
* If a `defaultValue` is provided, it'll use that over `string`,
* if a value isn't found in provided language files.
* This is useful if you want to have a descriptive key for token replacement
* but have a succinct localized string and not require `en.json` to be included.
*
* Currently, it is used for the progress bar timing.
* ```js
* {
* "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
* }
* ```
* It is then used like so:
* ```js
* this.localize('progress bar timing: currentTime={1} duration{2}',
* [this.player_.currentTime(), this.player_.duration()],
* '{1} of {2}');
* ```
*
* Which outputs something like: `01:23 of 24:56`.
*
*
* @param {string} string
* The string to localize and the key to lookup in the language files.
* @param {string[]} [tokens]
* If the current item has token replacements, provide the tokens here.
* @param {string} [defaultValue]
* Defaults to `string`. Can be a default value to use for token replacement
* if the lookup key is needed to be separate.
*
* @return {string}
* The localized string or if no localization exists the english string.
*/
Component.prototype.localize = function localize(string, tokens) {
var defaultValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : string;
var code = this.player_.language && this.player_.language();
var languages = this.player_.languages && this.player_.languages();
var language = languages && languages[code];
var primaryCode = code && code.split('-')[0];
var primaryLang = languages && languages[primaryCode];
var localizedString = defaultValue;
if (language && language[string]) {
localizedString = language[string];
} else if (primaryLang && primaryLang[string]) {
localizedString = primaryLang[string];
}
if (tokens) {
localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
var value = tokens[index - 1];
var ret = value;
if (typeof value === 'undefined') {
ret = match;
}
return ret;
});
}
return localizedString;
};
/**
* Return the `Component`s DOM element. This is where children get inserted.
* This will usually be the the same as the element returned in {@link Component#el}.
*
* @return {Element}
* The content element for this `Component`.
*/
Component.prototype.contentEl = function contentEl() {
return this.contentEl_ || this.el_;
};
/**
* Get this `Component`s ID
*
* @return {string}
* The id of this `Component`
*/
Component.prototype.id = function id() {
return this.id_;
};
/**
* Get the `Component`s name. The name gets used to reference the `Component`
* and is set during registration.
*
* @return {string}
* The name of this `Component`.
*/
Component.prototype.name = function name() {
return this.name_;
};
/**
* Get an array of all child components
*
* @return {Array}
* The children
*/
Component.prototype.children = function children() {
return this.children_;
};
/**
* Returns the child `Component` with the given `id`.
*
* @param {string} id
* The id of the child `Component` to get.
*
* @return {Component|undefined}
* The child `Component` with the given `id` or undefined.
*/
Component.prototype.getChildById = function getChildById(id) {
return this.childIndex_[id];
};
/**
* Returns the child `Component` with the given `name`.
*
* @param {string} name
* The name of the child `Component` to get.
*
* @return {Component|undefined}
* The child `Component` with the given `name` or undefined.
*/
Component.prototype.getChild = function getChild(name) {
if (!name) {
return;
}
name = toTitleCase(name);
return this.childNameIndex_[name];
};
/**
* Add a child `Component` inside the current `Component`.
*
*
* @param {string|Component} child
* The name or instance of a child to add.
*
* @param {Object} [options={}]
* The key/value store of options that will get passed to children of
* the child.
*
* @param {number} [index=this.children_.length]
* The index to attempt to add a child into.
*
* @return {Component}
* The `Component` that gets added as a child. When using a string the
* `Component` will get created by this process.
*/
Component.prototype.addChild = function addChild(child) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.children_.length;
var component = void 0;
var componentName = void 0;
// If child is a string, create component with options
if (typeof child === 'string') {
componentName = toTitleCase(child);
var componentClassName = options.componentClass || componentName;
// Set name through options
options.name = componentName;
// Create a new object & element for this controls set
// If there's no .player_, this is a player
var ComponentClass = Component.getComponent(componentClassName);
if (!ComponentClass) {
throw new Error('Component ' + componentClassName + ' does not exist');
}
// data stored directly on the videojs object may be
// misidentified as a component to retain
// backwards-compatibility with 4.x. check to make sure the
// component class can be instantiated.
if (typeof ComponentClass !== 'function') {
return null;
}
component = new ComponentClass(this.player_ || this, options);
// child is a component instance
} else {
component = child;
}
this.children_.splice(index, 0, component);
if (typeof component.id === 'function') {
this.childIndex_[component.id()] = component;
}
// If a name wasn't used to create the component, check if we can use the
// name function of the component
componentName = componentName || component.name && toTitleCase(component.name());
if (componentName) {
this.childNameIndex_[componentName] = component;
}
// Add the UI object's element to the container div (box)
// Having an element is not required
if (typeof component.el === 'function' && component.el()) {
var childNodes = this.contentEl().children;
var refNode = childNodes[index] || null;
this.contentEl().insertBefore(component.el(), refNode);
}
// Return so it can stored on parent object if desired.
return component;
};
/**
* Remove a child `Component` from this `Component`s list of children. Also removes
* the child `Component`s element from this `Component`s element.
*
* @param {Component} component
* The child `Component` to remove.
*/
Component.prototype.removeChild = function removeChild(component) {
if (typeof component === 'string') {
component = this.getChild(component);
}
if (!component || !this.children_) {
return;
}
var childFound = false;
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i] === component) {
childFound = true;
this.children_.splice(i, 1);
break;
}
}
if (!childFound) {
return;
}
this.childIndex_[component.id()] = null;
this.childNameIndex_[component.name()] = null;
var compEl = component.el();
if (compEl && compEl.parentNode === this.contentEl()) {
this.contentEl().removeChild(component.el());
}
};
/**
* Add and initialize default child `Component`s based upon options.
*/
Component.prototype.initChildren = function initChildren() {
var _this = this;
var children = this.options_.children;
if (children) {
// `this` is `parent`
var parentOptions = this.options_;
var handleAdd = function handleAdd(child) {
var name = child.name;
var opts = child.opts;
// Allow options for children to be set at the parent options
// e.g. videojs(id, { controlBar: false });
// instead of videojs(id, { children: { controlBar: false });
if (parentOptions[name] !== undefined) {
opts = parentOptions[name];
}
// Allow for disabling default components
// e.g. options['children']['posterImage'] = false
if (opts === false) {
return;
}
// Allow options to be passed as a simple boolean if no configuration
// is necessary.
if (opts === true) {
opts = {};
}
// We also want to pass the original player options
// to each component as well so they don't need to
// reach back into the player for options later.
opts.playerOptions = _this.options_.playerOptions;
// Create and add the child component.
// Add a direct reference to the child by name on the parent instance.
// If two of the same component are used, different names should be supplied
// for each
var newChild = _this.addChild(name, opts);
if (newChild) {
_this[name] = newChild;
}
};
// Allow for an array of children details to passed in the options
var workingChildren = void 0;
var Tech = Component.getComponent('Tech');
if (Array.isArray(children)) {
workingChildren = children;
} else {
workingChildren = Object.keys(children);
}
workingChildren
// children that are in this.options_ but also in workingChildren would
// give us extra children we do not want. So, we want to filter them out.
.concat(Object.keys(this.options_).filter(function (child) {
return !workingChildren.some(function (wchild) {
if (typeof wchild === 'string') {
return child === wchild;
}
return child === wchild.name;
});
})).map(function (child) {
var name = void 0;
var opts = void 0;
if (typeof child === 'string') {
name = child;
opts = children[name] || _this.options_[name] || {};
} else {
name = child.name;
opts = child;
}
return { name: name, opts: opts };
}).filter(function (child) {
// we have to make sure that child.name isn't in the techOrder since
// techs are registerd as Components but can't aren't compatible
// See https://github.com/videojs/video.js/issues/2772
var c = Component.getComponent(child.opts.componentClass || toTitleCase(child.name));
return c && !Tech.isTech(c);
}).forEach(handleAdd);
}
};
/**
* Builds the default DOM class name. Should be overriden by sub-components.
*
* @return {string}
* The DOM class name for this object.
*
* @abstract
*/
Component.prototype.buildCSSClass = function buildCSSClass() {
// Child classes can include a function that does:
// return 'CLASS NAME' + this._super();
return '';
};
/**
* Bind a listener to the component's ready state.
* Different from event listeners in that if the ready event has already happened
* it will trigger the function immediately.
*
* @return {Component}
* Returns itself; method can be chained.
*/
Component.prototype.ready = function ready(fn) {
var sync = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!fn) {
return;
}
if (!this.isReady_) {
this.readyQueue_ = this.readyQueue_ || [];
this.readyQueue_.push(fn);
return;
}
if (sync) {
fn.call(this);
} else {
// Call the function asynchronously by default for consistency
this.setTimeout(fn, 1);
}
};
/**
* Trigger all the ready listeners for this `Component`.
*
* @fires Component#ready
*/
Component.prototype.triggerReady = function triggerReady() {
this.isReady_ = true;
// Ensure ready is triggered asynchronously
this.setTimeout(function () {
var readyQueue = this.readyQueue_;
// Reset Ready Queue
this.readyQueue_ = [];
if (readyQueue && readyQueue.length > 0) {
readyQueue.forEach(function (fn) {
fn.call(this);
}, this);
}
// Allow for using event listeners also
/**
* Triggered when a `Component` is ready.
*
* @event Component#ready
* @type {EventTarget~Event}
*/
this.trigger('ready');
}, 1);
};
/**
* Find a single DOM element matching a `selector`. This can be within the `Component`s
* `contentEl()` or another custom context.
*
* @param {string} selector
* A valid CSS selector, which will be passed to `querySelector`.
*
* @param {Element|string} [context=this.contentEl()]
* A DOM element within which to query. Can also be a selector string in
* which case the first matching element will get used as context. If
* missing `this.contentEl()` gets used. If `this.contentEl()` returns
* nothing it falls back to `document`.
*
* @return {Element|null}
* the dom element that was found, or null
*
* @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
*/
Component.prototype.$ = function $$$1(selector, context) {
return $(selector, context || this.contentEl());
};
/**
* Finds all DOM element matching a `selector`. This can be within the `Component`s
* `contentEl()` or another custom context.
*
* @param {string} selector
* A valid CSS selector, which will be passed to `querySelectorAll`.
*
* @param {Element|string} [context=this.contentEl()]
* A DOM element within which to query. Can also be a selector string in
* which case the first matching element will get used as context. If
* missing `this.contentEl()` gets used. If `this.contentEl()` returns
* nothing it falls back to `document`.
*
* @return {NodeList}
* a list of dom elements that were found
*
* @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
*/
Component.prototype.$$ = function $$$$1(selector, context) {
return $$(selector, context || this.contentEl());
};
/**
* Check if a component's element has a CSS class name.
*
* @param {string} classToCheck
* CSS class name to check.
*
* @return {boolean}
* - True if the `Component` has the class.
* - False if the `Component` does not have the class`
*/
Component.prototype.hasClass = function hasClass$$1(classToCheck) {
return hasClass(this.el_, classToCheck);
};
/**
* Add a CSS class name to the `Component`s element.
*
* @param {string} classToAdd
* CSS class name to add
*/
Component.prototype.addClass = function addClass$$1(classToAdd) {
addClass(this.el_, classToAdd);
};
/**
* Remove a CSS class name from the `Component`s element.
*
* @param {string} classToRemove
* CSS class name to remove
*/
Component.prototype.removeClass = function removeClass$$1(classToRemove) {
removeClass(this.el_, classToRemove);
};
/**
* Add or remove a CSS class name from the component's element.
* - `classToToggle` gets added when {@link Component#hasClass} would return false.
* - `classToToggle` gets removed when {@link Component#hasClass} would return true.
*
* @param {string} classToToggle
* The class to add or remove based on (@link Component#hasClass}
*
* @param {boolean|Dom~predicate} [predicate]
* An {@link Dom~predicate} function or a boolean
*/
Component.prototype.toggleClass = function toggleClass$$1(classToToggle, predicate) {
toggleClass(this.el_, classToToggle, predicate);
};
/**
* Show the `Component`s element if it is hidden by removing the
* 'vjs-hidden' class name from it.
*/
Component.prototype.show = function show() {
this.removeClass('vjs-hidden');
};
/**
* Hide the `Component`s element if it is currently showing by adding the
* 'vjs-hidden` class name to it.
*/
Component.prototype.hide = function hide() {
this.addClass('vjs-hidden');
};
/**
* Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
* class name to it. Used during fadeIn/fadeOut.
*
* @private
*/
Component.prototype.lockShowing = function lockShowing() {
this.addClass('vjs-lock-showing');
};
/**
* Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
* class name from it. Used during fadeIn/fadeOut.
*
* @private
*/
Component.prototype.unlockShowing = function unlockShowing() {
this.removeClass('vjs-lock-showing');
};
/**
* Get the value of an attribute on the `Component`s element.
*
* @param {string} attribute
* Name of the attribute to get the value from.
*
* @return {string|null}
* - The value of the attribute that was asked for.
* - Can be an empty string on some browsers if the attribute does not exist
* or has no value
* - Most browsers will return null if the attibute does not exist or has
* no value.
*
* @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
*/
Component.prototype.getAttribute = function getAttribute$$1(attribute) {
return getAttribute(this.el_, attribute);
};
/**
* Set the value of an attribute on the `Component`'s element
*
* @param {string} attribute
* Name of the attribute to set.
*
* @param {string} value
* Value to set the attribute to.
*
* @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
*/
Component.prototype.setAttribute = function setAttribute$$1(attribute, value) {
setAttribute(this.el_, attribute, value);
};
/**
* Remove an attribute from the `Component`s element.
*
* @param {string} attribute
* Name of the attribute to remove.
*
* @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
*/
Component.prototype.removeAttribute = function removeAttribute$$1(attribute) {
removeAttribute(this.el_, attribute);
};
/**
* Get or set the width of the component based upon the CSS styles.
* See {@link Component#dimension} for more detailed information.
*
* @param {number|string} [num]
* The width that you want to set postfixed with '%', 'px' or nothing.
*
* @param {boolean} [skipListeners]
* Skip the componentresize event trigger
*
* @return {number|string}
* The width when getting, zero if there is no width. Can be a string
* postpixed with '%' or 'px'.
*/
Component.prototype.width = function width(num, skipListeners) {
return this.dimension('width', num, skipListeners);
};
/**
* Get or set the height of the component based upon the CSS styles.
* See {@link Component#dimension} for more detailed information.
*
* @param {number|string} [num]
* The height that you want to set postfixed with '%', 'px' or nothing.
*
* @param {boolean} [skipListeners]
* Skip the componentresize event trigger
*
* @return {number|string}
* The width when getting, zero if there is no width. Can be a string
* postpixed with '%' or 'px'.
*/
Component.prototype.height = function height(num, skipListeners) {
return this.dimension('height', num, skipListeners);
};
/**
* Set both the width and height of the `Component` element at the same time.
*
* @param {number|string} width
* Width to set the `Component`s element to.
*
* @param {number|string} height
* Height to set the `Component`s element to.
*/
Component.prototype.dimensions = function dimensions(width, height) {
// Skip componentresize listeners on width for optimization
this.width(width, true);
this.height(height);
};
/**
* Get or set width or height of the `Component` element. This is the shared code
* for the {@link Component#width} and {@link Component#height}.
*
* Things to know:
* - If the width or height in an number this will return the number postfixed with 'px'.
* - If the width/height is a percent this will return the percent postfixed with '%'
* - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
* defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
* See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
* for more information
* - If you want the computed style of the component, use {@link Component#currentWidth}
* and {@link {Component#currentHeight}
*
* @fires Component#componentresize
*
* @param {string} widthOrHeight
8 'width' or 'height'
*
* @param {number|string} [num]
8 New dimension
*
* @param {boolean} [skipListeners]
* Skip componentresize event trigger
*
* @return {number}
* The dimension when getting or 0 if unset
*/
Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) {
if (num !== undefined) {
// Set to zero if null or literally NaN (NaN !== NaN)
if (num === null || num !== num) {
num = 0;
}
// Check if using css width/height (% or px) and adjust
if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
this.el_.style[widthOrHeight] = num;
} else if (num === 'auto') {
this.el_.style[widthOrHeight] = '';
} else {
this.el_.style[widthOrHeight] = num + 'px';
}
// skipListeners allows us to avoid triggering the resize event when setting both width and height
if (!skipListeners) {
/**
* Triggered when a component is resized.
*
* @event Component#componentresize
* @type {EventTarget~Event}
*/
this.trigger('componentresize');
}
return;
}
// Not setting a value, so getting it
// Make sure element exists
if (!this.el_) {
return 0;
}
// Get dimension value from style
var val = this.el_.style[widthOrHeight];
var pxIndex = val.indexOf('px');
if (pxIndex !== -1) {
// Return the pixel value with no 'px'
return parseInt(val.slice(0, pxIndex), 10);
}
// No px so using % or no style was set, so falling back to offsetWidth/height
// If component has display:none, offset will return 0
// TODO: handle display:none and no dimension style using px
return parseInt(this.el_['offset' + toTitleCase(widthOrHeight)], 10);
};
/**
* Get the computed width or the height of the component's element.
*
* Uses `window.getComputedStyle`.
*
* @param {string} widthOrHeight
* A string containing 'width' or 'height'. Whichever one you want to get.
*
* @return {number}
* The dimension that gets asked for or 0 if nothing was set
* for that dimension.
*/
Component.prototype.currentDimension = function currentDimension(widthOrHeight) {
var computedWidthOrHeight = 0;
if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
throw new Error('currentDimension only accepts width or height value');
}
if (typeof window.getComputedStyle === 'function') {
var computedStyle = window.getComputedStyle(this.el_);
computedWidthOrHeight = computedStyle.getPropertyValue(widthOrHeight) || computedStyle[widthOrHeight];
}
// remove 'px' from variable and parse as integer
computedWidthOrHeight = parseFloat(computedWidthOrHeight);
// if the computed value is still 0, it's possible that the browser is lying
// and we want to check the offset values.
// This code also runs on IE8 and wherever getComputedStyle doesn't exist.
if (computedWidthOrHeight === 0) {
var rule = 'offset' + toTitleCase(widthOrHeight);
computedWidthOrHeight = this.el_[rule];
}
return computedWidthOrHeight;
};
/**
* An object that contains width and height values of the `Component`s
* computed style. Uses `window.getComputedStyle`.
*
* @typedef {Object} Component~DimensionObject
*
* @property {number} width
* The width of the `Component`s computed style.
*
* @property {number} height
* The height of the `Component`s computed style.
*/
/**
* Get an object that contains computed width and height values of the
* component's element.
*
* Uses `window.getComputedStyle`.
*
* @return {Component~DimensionObject}
* The computed dimensions of the component's element.
*/
Component.prototype.currentDimensions = function currentDimensions() {
return {
width: this.currentDimension('width'),
height: this.currentDimension('height')
};
};
/**
* Get the computed width of the component's element.
*
* Uses `window.getComputedStyle`.
*
* @return {number}
* The computed width of the component's element.
*/
Component.prototype.currentWidth = function currentWidth() {
return this.currentDimension('width');
};
/**
* Get the computed height of the component's element.
*
* Uses `window.getComputedStyle`.
*
* @return {number}
* The computed height of the component's element.
*/
Component.prototype.currentHeight = function currentHeight() {
return this.currentDimension('height');
};
/**
* Set the focus to this component
*/
Component.prototype.focus = function focus() {
this.el_.focus();
};
/**
* Remove the focus from this component
*/
Component.prototype.blur = function blur() {
this.el_.blur();
};
/**
* Emit a 'tap' events when touch event support gets detected. This gets used to
* support toggling the controls through a tap on the video. They get enabled
* because every sub-component would have extra overhead otherwise.
*
* @private
* @fires Component#tap
* @listens Component#touchstart
* @listens Component#touchmove
* @listens Component#touchleave
* @listens Component#touchcancel
* @listens Component#touchend
*/
Component.prototype.emitTapEvents = function emitTapEvents() {
// Track the start time so we can determine how long the touch lasted
var touchStart = 0;
var firstTouch = null;
// Maximum movement allowed during a touch event to still be considered a tap
// Other popular libs use anywhere from 2 (hammer.js) to 15,
// so 10 seems like a nice, round number.
var tapMovementThreshold = 10;
// The maximum length a touch can be while still being considered a tap
var touchTimeThreshold = 200;
var couldBeTap = void 0;
this.on('touchstart', function (event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length === 1) {
// Copy pageX/pageY from the object
firstTouch = {
pageX: event.touches[0].pageX,
pageY: event.touches[0].pageY
};
// Record start time so we can detect a tap vs. "touch and hold"
touchStart = new Date().getTime();
// Reset couldBeTap tracking
couldBeTap = true;
}
});
this.on('touchmove', function (event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length > 1) {
couldBeTap = false;
} else if (firstTouch) {
// Some devices will throw touchmoves for all but the slightest of taps.
// So, if we moved only a small distance, this could still be a tap
var xdiff = event.touches[0].pageX - firstTouch.pageX;
var ydiff = event.touches[0].pageY - firstTouch.pageY;
var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
if (touchDistance > tapMovementThreshold) {
couldBeTap = false;
}
}
});
var noTap = function noTap() {
couldBeTap = false;
};
// TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
this.on('touchleave', noTap);
this.on('touchcancel', noTap);
// When the touch ends, measure how long it took and trigger the appropriate
// event
this.on('touchend', function (event) {
firstTouch = null;
// Proceed only if the touchmove/leave/cancel event didn't happen
if (couldBeTap === true) {
// Measure how long the touch lasted
var touchTime = new Date().getTime() - touchStart;
// Make sure the touch was less than the threshold to be considered a tap
if (touchTime < touchTimeThreshold) {
// Don't let browser turn this into a click
event.preventDefault();
/**
* Triggered when a `Component` is tapped.
*
* @event Component#tap
* @type {EventTarget~Event}
*/
this.trigger('tap');
// It may be good to copy the touchend event object and change the
// type to tap, if the other event properties aren't exact after
// Events.fixEvent runs (e.g. event.target)
}
}
});
};
/**
* This function reports user activity whenever touch events happen. This can get
* turned off by any sub-components that wants touch events to act another way.
*
* Report user touch activity when touch events occur. User activity gets used to
* determine when controls should show/hide. It is simple when it comes to mouse
* events, because any mouse event should show the controls. So we capture mouse
* events that bubble up to the player and report activity when that happens.
* With touch events it isn't as easy as `touchstart` and `touchend` toggle player
* controls. So touch events can't help us at the player level either.
*
* User activity gets checked asynchronously. So what could happen is a tap event
* on the video turns the controls off. Then the `touchend` event bubbles up to
* the player. Which, if it reported user activity, would turn the controls right
* back on. We also don't want to completely block touch events from bubbling up.
* Furthermore a `touchmove` event and anything other than a tap, should not turn
* controls back on.
*
* @listens Component#touchstart
* @listens Component#touchmove
* @listens Component#touchend
* @listens Component#touchcancel
*/
Component.prototype.enableTouchActivity = function enableTouchActivity() {
// Don't continue if the root player doesn't support reporting user activity
if (!this.player() || !this.player().reportUserActivity) {
return;
}
// listener for reporting that the user is active
var report = bind(this.player(), this.player().reportUserActivity);
var touchHolding = void 0;
this.on('touchstart', function () {
report();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
this.clearInterval(touchHolding);
// report at the same interval as activityCheck
touchHolding = this.setInterval(report, 250);
});
var touchEnd = function touchEnd(event) {
report();
// stop the interval that maintains activity if the touch is holding
this.clearInterval(touchHolding);
};
this.on('touchmove', report);
this.on('touchend', touchEnd);
this.on('touchcancel', touchEnd);
};
/**
* A callback that has no parameters and is bound into `Component`s context.
*
* @callback Component~GenericCallback
* @this Component
*/
/**
* Creates a function that runs after an `x` millisecond timeout. This function is a
* wrapper around `window.setTimeout`. There are a few reasons to use this one
* instead though:
* 1. It gets cleared via {@link Component#clearTimeout} when
* {@link Component#dispose} gets called.
* 2. The function callback will gets turned into a {@link Component~GenericCallback}
*
* > Note: You can't use `window.clearTimeout` on the id returned by this function. This
* will cause its dispose listener not to get cleaned up! Please use
* {@link Component#clearTimeout} or {@link Component#dispose} instead.
*
* @param {Component~GenericCallback} fn
* The function that will be run after `timeout`.
*
* @param {number} timeout
* Timeout in milliseconds to delay before executing the specified function.
*
* @return {number}
* Returns a timeout ID that gets used to identify the timeout. It can also
* get used in {@link Component#clearTimeout} to clear the timeout that
* was set.
*
* @listens Component#dispose
* @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
*/
Component.prototype.setTimeout = function setTimeout(fn, timeout) {
var _this2 = this;
// declare as variables so they are properly available in timeout function
// eslint-disable-next-line
var timeoutId, disposeFn;
fn = bind(this, fn);
timeoutId = window.setTimeout(function () {
_this2.off('dispose', disposeFn);
fn();
}, timeout);
disposeFn = function disposeFn() {
return _this2.clearTimeout(timeoutId);
};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.on('dispose', disposeFn);
return timeoutId;
};
/**
* Clears a timeout that gets created via `window.setTimeout` or
* {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
* use this function instead of `window.clearTimout`. If you don't your dispose
* listener will not get cleaned up until {@link Component#dispose}!
*
* @param {number} timeoutId
* The id of the timeout to clear. The return value of
* {@link Component#setTimeout} or `window.setTimeout`.
*
* @return {number}
* Returns the timeout id that was cleared.
*
* @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
*/
Component.prototype.clearTimeout = function clearTimeout(timeoutId) {
window.clearTimeout(timeoutId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.off('dispose', disposeFn);
return timeoutId;
};
/**
* Creates a function that gets run every `x` milliseconds. This function is a wrapper
* around `window.setInterval`. There are a few reasons to use this one instead though.
* 1. It gets cleared via {@link Component#clearInterval} when
* {@link Component#dispose} gets called.
* 2. The function callback will be a {@link Component~GenericCallback}
*
* @param {Component~GenericCallback} fn
* The function to run every `x` seconds.
*
* @param {number} interval
* Execute the specified function every `x` milliseconds.
*
* @return {number}
* Returns an id that can be used to identify the interval. It can also be be used in
* {@link Component#clearInterval} to clear the interval.
*
* @listens Component#dispose
* @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
*/
Component.prototype.setInterval = function setInterval(fn, interval) {
var _this3 = this;
fn = bind(this, fn);
var intervalId = window.setInterval(fn, interval);
var disposeFn = function disposeFn() {
return _this3.clearInterval(intervalId);
};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.on('dispose', disposeFn);
return intervalId;
};
/**
* Clears an interval that gets created via `window.setInterval` or
* {@link Component#setInterval}. If you set an inteval via {@link Component#setInterval}
* use this function instead of `window.clearInterval`. If you don't your dispose
* listener will not get cleaned up until {@link Component#dispose}!
*
* @param {number} intervalId
* The id of the interval to clear. The return value of
* {@link Component#setInterval} or `window.setInterval`.
*
* @return {number}
* Returns the interval id that was cleared.
*
* @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
*/
Component.prototype.clearInterval = function clearInterval(intervalId) {
window.clearInterval(intervalId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.off('dispose', disposeFn);
return intervalId;
};
/**
* Queues up a callback to be passed to requestAnimationFrame (rAF), but
* with a few extra bonuses:
*
* - Supports browsers that do not support rAF by falling back to
* {@link Component#setTimeout}.
*
* - The callback is turned into a {@link Component~GenericCallback} (i.e.
* bound to the component).
*
* - Automatic cancellation of the rAF callback is handled if the component
* is disposed before it is called.
*
* @param {Component~GenericCallback} fn
* A function that will be bound to this component and executed just
* before the browser's next repaint.
*
* @return {number}
* Returns an rAF ID that gets used to identify the timeout. It can
* also be used in {@link Component#cancelAnimationFrame} to cancel
* the animation frame callback.
*
* @listens Component#dispose
* @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
*/
Component.prototype.requestAnimationFrame = function requestAnimationFrame(fn) {
var _this4 = this;
// declare as variables so they are properly available in rAF function
// eslint-disable-next-line
var id, disposeFn;
if (this.supportsRaf_) {
fn = bind(this, fn);
id = window.requestAnimationFrame(function () {
_this4.off('dispose', disposeFn);
fn();
});
disposeFn = function disposeFn() {
return _this4.cancelAnimationFrame(id);
};
disposeFn.guid = 'vjs-raf-' + id;
this.on('dispose', disposeFn);
return id;
}
// Fall back to using a timer.
return this.setTimeout(fn, 1000 / 60);
};
/**
* Cancels a queued callback passed to {@link Component#requestAnimationFrame}
* (rAF).
*
* If you queue an rAF callback via {@link Component#requestAnimationFrame},
* use this function instead of `window.cancelAnimationFrame`. If you don't,
* your dispose listener will not get cleaned up until {@link Component#dispose}!
*
* @param {number} id
* The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
*
* @return {number}
* Returns the rAF ID that was cleared.
*
* @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
*/
Component.prototype.cancelAnimationFrame = function cancelAnimationFrame(id) {
if (this.supportsRaf_) {
window.cancelAnimationFrame(id);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-raf-' + id;
this.off('dispose', disposeFn);
return id;
}
// Fall back to using a timer.
return this.clearTimeout(id);
};
/**
* Register a `Component` with `videojs` given the name and the component.
*
* > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
* should be registered using {@link Tech.registerTech} or
* {@link videojs:videojs.registerTech}.
*
* > NOTE: This function can also be seen on videojs as
* {@link videojs:videojs.registerComponent}.
*
* @param {string} name
* The name of the `Component` to register.
*
* @param {Component} ComponentToRegister
* The `Component` class to register.
*
* @return {Component}
* The `Component` that was registered.
*/
Component.registerComponent = function registerComponent(name, ComponentToRegister) {
if (typeof name !== 'string' || !name) {
throw new Error('Illegal component name, "' + name + '"; must be a non-empty string.');
}
var Tech = Component.getComponent('Tech');
// We need to make sure this check is only done if Tech has been registered.
var isTech = Tech && Tech.isTech(ComponentToRegister);
var isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype);
if (isTech || !isComp) {
var reason = void 0;
if (isTech) {
reason = 'techs must be registered using Tech.registerTech()';
} else {
reason = 'must be a Component subclass';
}
throw new Error('Illegal component, "' + name + '"; ' + reason + '.');
}
name = toTitleCase(name);
if (!Component.components_) {
Component.components_ = {};
}
var Player = Component.getComponent('Player');
if (name === 'Player' && Player && Player.players) {
var players = Player.players;
var playerNames = Object.keys(players);
// If we have players that were disposed, then their name will still be
// in Players.players. So, we must loop through and verify that the value
// for each item is not null. This allows registration of the Player component
// after all players have been disposed or before any were created.
if (players && playerNames.length > 0 && playerNames.map(function (pname) {
return players[pname];
}).every(Boolean)) {
throw new Error('Can not register Player component after player has been created.');
}
}
Component.components_[name] = ComponentToRegister;
return ComponentToRegister;
};
/**
* Get a `Component` based on the name it was registered with.
*
* @param {string} name
* The Name of the component to get.
*
* @return {Component}
* The `Component` that got registered under the given name.
*
* @deprecated In `videojs` 6 this will not return `Component`s that were not
* registered using {@link Component.registerComponent}. Currently we
* check the global `videojs` object for a `Component` name and
* return that if it exists.
*/
Component.getComponent = function getComponent(name) {
if (!name) {
return;
}
name = toTitleCase(name);
if (Component.components_ && Component.components_[name]) {
return Component.components_[name];
}
};
return Component;
}();
/**
* Whether or not this component supports `requestAnimationFrame`.
*
* This is exposed primarily for testing purposes.
*
* @private
* @type {Boolean}
*/
Component.prototype.supportsRaf_ = typeof window.requestAnimationFrame === 'function' && typeof window.cancelAnimationFrame === 'function';
Component.registerComponent('Component', Component);
/**
* @file time-ranges.js
* @module time-ranges
*/
/**
* Returns the time for the specified index at the start or end
* of a TimeRange object.
*
* @function time-ranges:indexFunction
*
* @param {number} [index=0]
* The range number to return the time for.
*
* @return {number}
* The time that offset at the specified index.
*
* @depricated index must be set to a value, in the future this will throw an error.
*/
/**
* An object that contains ranges of time for various reasons.
*
* @typedef {Object} TimeRange
*
* @property {number} length
* The number of time ranges represented by this Object
*
* @property {time-ranges:indexFunction} start
* Returns the time offset at which a specified time range begins.
*
* @property {time-ranges:indexFunction} end
* Returns the time offset at which a specified time range ends.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
*/
/**
* Check if any of the time ranges are over the maximum index.
*
* @param {string} fnName
* The function name to use for logging
*
* @param {number} index
* The index to check
*
* @param {number} maxIndex
* The maximum possible index
*
* @throws {Error} if the timeRanges provided are over the maxIndex
*/
function rangeCheck(fnName, index, maxIndex) {
if (typeof index !== 'number' || index < 0 || index > maxIndex) {
throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is non-numeric or out of bounds (0-' + maxIndex + ').');
}
}
/**
* Get the time for the specified index at the start or end
* of a TimeRange object.
*
* @param {string} fnName
* The function name to use for logging
*
* @param {string} valueIndex
* The proprety that should be used to get the time. should be 'start' or 'end'
*
* @param {Array} ranges
* An array of time ranges
*
* @param {Array} [rangeIndex=0]
* The index to start the search at
*
* @return {number}
* The time that offset at the specified index.
*
*
* @depricated rangeIndex must be set to a value, in the future this will throw an error.
* @throws {Error} if rangeIndex is more than the length of ranges
*/
function getRange(fnName, valueIndex, ranges, rangeIndex) {
rangeCheck(fnName, rangeIndex, ranges.length - 1);
return ranges[rangeIndex][valueIndex];
}
/**
* Create a time range object given ranges of time.
*
* @param {Array} [ranges]
* An array of time ranges.
*/
function createTimeRangesObj(ranges) {
if (ranges === undefined || ranges.length === 0) {
return {
length: 0,
start: function start() {
throw new Error('This TimeRanges object is empty');
},
end: function end() {
throw new Error('This TimeRanges object is empty');
}
};
}
return {
length: ranges.length,
start: getRange.bind(null, 'start', 0, ranges),
end: getRange.bind(null, 'end', 1, ranges)
};
}
/**
* Should create a fake `TimeRange` object which mimics an HTML5 time range instance.
*
* @param {number|Array} start
* The start of a single range or an array of ranges
*
* @param {number} end
* The end of a single range.
*
* @private
*/
function createTimeRanges(start, end) {
if (Array.isArray(start)) {
return createTimeRangesObj(start);
} else if (start === undefined || end === undefined) {
return createTimeRangesObj();
}
return createTimeRangesObj([[start, end]]);
}
/**
* @file buffer.js
* @module buffer
*/
/**
* Compute the percentage of the media that has been buffered.
*
* @param {TimeRange} buffered
* The current `TimeRange` object representing buffered time ranges
*
* @param {number} duration
* Total duration of the media
*
* @return {number}
* Percent buffered of the total duration in decimal form.
*/
function bufferedPercent(buffered, duration) {
var bufferedDuration = 0;
var start = void 0;
var end = void 0;
if (!duration) {
return 0;
}
if (!buffered || !buffered.length) {
buffered = createTimeRanges(0, 0);
}
for (var i = 0; i < buffered.length; i++) {
start = buffered.start(i);
end = buffered.end(i);
// buffered end can be bigger than duration by a very small fraction
if (end > duration) {
end = duration;
}
bufferedDuration += end - start;
}
return bufferedDuration / duration;
}
/**
* @file fullscreen-api.js
* @module fullscreen-api
* @private
*/
/**
* Store the browser-specific methods for the fullscreen API.
*
* @type {Object}
* @see [Specification]{@link https://fullscreen.spec.whatwg.org}
* @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
*/
var FullscreenApi = {};
// browser API methods
var apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'],
// WebKit
['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'],
// Old WebKit (Safari 5.1)
['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'],
// Mozilla
['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'],
// Microsoft
['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']];
var specApi = apiMap[0];
var browserApi = void 0;
// determine the supported set of functions
for (var i = 0; i < apiMap.length; i++) {
// check for exitFullscreen function
if (apiMap[i][1] in document) {
browserApi = apiMap[i];
break;
}
}
// map the browser API names to the spec API names
if (browserApi) {
for (var _i = 0; _i < browserApi.length; _i++) {
FullscreenApi[specApi[_i]] = browserApi[_i];
}
}
/**
* @file media-error.js
*/
/**
* A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
*
* @param {number|string|Object|MediaError} value
* This can be of multiple types:
* - number: should be a standard error code
* - string: an error message (the code will be 0)
* - Object: arbitrary properties
* - `MediaError` (native): used to populate a video.js `MediaError` object
* - `MediaError` (video.js): will return itself if it's already a
* video.js `MediaError` object.
*
* @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
* @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
*
* @class MediaError
*/
function MediaError(value) {
// Allow redundant calls to this constructor to avoid having `instanceof`
// checks peppered around the code.
if (value instanceof MediaError) {
return value;
}
if (typeof value === 'number') {
this.code = value;
} else if (typeof value === 'string') {
// default code is zero, so this is a custom error
this.message = value;
} else if (isObject(value)) {
// We assign the `code` property manually because native `MediaError` objects
// do not expose it as an own/enumerable property of the object.
if (typeof value.code === 'number') {
this.code = value.code;
}
assign(this, value);
}
if (!this.message) {
this.message = MediaError.defaultMessages[this.code] || '';
}
}
/**
* The error code that refers two one of the defined `MediaError` types
*
* @type {Number}
*/
MediaError.prototype.code = 0;
/**
* An optional message that to show with the error. Message is not part of the HTML5
* video spec but allows for more informative custom errors.
*
* @type {String}
*/
MediaError.prototype.message = '';
/**
* An optional status code that can be set by plugins to allow even more detail about
* the error. For example a plugin might provide a specific HTTP status code and an
* error message for that code. Then when the plugin gets that error this class will
* know how to display an error message for it. This allows a custom message to show
* up on the `Player` error overlay.
*
* @type {Array}
*/
MediaError.prototype.status = null;
/**
* Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
* specification listed under {@link MediaError} for more information.
*
* @enum {array}
* @readonly
* @property {string} 0 - MEDIA_ERR_CUSTOM
* @property {string} 1 - MEDIA_ERR_CUSTOM
* @property {string} 2 - MEDIA_ERR_ABORTED
* @property {string} 3 - MEDIA_ERR_NETWORK
* @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
* @property {string} 5 - MEDIA_ERR_ENCRYPTED
*/
MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
/**
* The default `MediaError` messages based on the {@link MediaError.errorTypes}.
*
* @type {Array}
* @constant
*/
MediaError.defaultMessages = {
1: 'You aborted the media playback',
2: 'A network error caused the media download to fail part-way.',
3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
5: 'The media is encrypted and we do not have the keys to decrypt it.'
};
// Add types as properties on MediaError
// e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
MediaError[MediaError.errorTypes[errNum]] = errNum;
// values should be accessible on both the class and instance
MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
}
/**
* Returns whether an object is `Promise`-like (i.e. has a `then` method).
*
* @param {Object} value
* An object that may or may not be `Promise`-like.
*
* @return {Boolean}
* Whether or not the object is `Promise`-like.
*/
function isPromise(value) {
return value !== undefined && value !== null && typeof value.then === 'function';
}
/**
* Silence a Promise-like object.
*
* This is useful for avoiding non-harmful, but potentially confusing "uncaught
* play promise" rejection error messages.
*
* @param {Object} value
* An object that may or may not be `Promise`-like.
*/
function silencePromise(value) {
if (isPromise(value)) {
value.then(null, function (e) {});
}
}
/**
* @file text-track-list-converter.js Utilities for capturing text track state and
* re-creating tracks based on a capture.
*
* @module text-track-list-converter
*/
/**
* Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
* represents the {@link TextTrack}'s state.
*
* @param {TextTrack} track
* The text track to query.
*
* @return {Object}
* A serializable javascript representation of the TextTrack.
* @private
*/
var trackToJson_ = function trackToJson_(track) {
var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) {
if (track[prop]) {
acc[prop] = track[prop];
}
return acc;
}, {
cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
return {
startTime: cue.startTime,
endTime: cue.endTime,
text: cue.text,
id: cue.id
};
})
});
return ret;
};
/**
* Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
* state of all {@link TextTrack}s currently configured. The return array is compatible with
* {@link text-track-list-converter:jsonToTextTracks}.
*
* @param {Tech} tech
* The tech object to query
*
* @return {Array}
* A serializable javascript representation of the {@link Tech}s
* {@link TextTrackList}.
*/
var textTracksToJson = function textTracksToJson(tech) {
var trackEls = tech.$$('track');
var trackObjs = Array.prototype.map.call(trackEls, function (t) {
return t.track;
});
var tracks = Array.prototype.map.call(trackEls, function (trackEl) {
var json = trackToJson_(trackEl.track);
if (trackEl.src) {
json.src = trackEl.src;
}
return json;
});
return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
return trackObjs.indexOf(track) === -1;
}).map(trackToJson_));
};
/**
* Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
* object {@link TextTrack} representations.
*
* @param {Array} json
* An array of `TextTrack` representation objects, like those that would be
* produced by `textTracksToJson`.
*
* @param {Tech} tech
* The `Tech` to create the `TextTrack`s on.
*/
var jsonToTextTracks = function jsonToTextTracks(json, tech) {
json.forEach(function (track) {
var addedTrack = tech.addRemoteTextTrack(track).track;
if (!track.src && track.cues) {
track.cues.forEach(function (cue) {
return addedTrack.addCue(cue);
});
}
});
return tech.textTracks();
};
var textTrackConverter = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ };
/**
* @file modal-dialog.js
*/
var MODAL_CLASS_NAME = 'vjs-modal-dialog';
var ESC = 27;
/**
* The `ModalDialog` displays over the video and its controls, which blocks
* interaction with the player until it is closed.
*
* Modal dialogs include a "Close" button and will close when that button
* is activated - or when ESC is pressed anywhere.
*
* @extends Component
*/
var ModalDialog = function (_Component) {
inherits(ModalDialog, _Component);
/**
* Create an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Mixed} [options.content=undefined]
* Provide customized content for this modal.
*
* @param {string} [options.description]
* A text description for the modal, primarily for accessibility.
*
* @param {boolean} [options.fillAlways=false]
* Normally, modals are automatically filled only the first time
* they open. This tells the modal to refresh its content
* every time it opens.
*
* @param {string} [options.label]
* A text label for the modal, primarily for accessibility.
*
* @param {boolean} [options.temporary=true]
* If `true`, the modal can only be opened once; it will be
* disposed as soon as it's closed.
*
* @param {boolean} [options.uncloseable=false]
* If `true`, the user will not be able to close the modal
* through the UI in the normal ways. Programmatic closing is
* still possible.
*/
function ModalDialog(player, options) {
classCallCheck(this, ModalDialog);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false;
_this.closeable(!_this.options_.uncloseable);
_this.content(_this.options_.content);
// Make sure the contentEl is defined AFTER any children are initialized
// because we only want the contents of the modal in the contentEl
// (not the UI elements like the close button).
_this.contentEl_ = createEl('div', {
className: MODAL_CLASS_NAME + '-content'
}, {
role: 'document'
});
_this.descEl_ = createEl('p', {
className: MODAL_CLASS_NAME + '-description vjs-control-text',
id: _this.el().getAttribute('aria-describedby')
});
textContent(_this.descEl_, _this.description());
_this.el_.appendChild(_this.descEl_);
_this.el_.appendChild(_this.contentEl_);
return _this;
}
/**
* Create the `ModalDialog`'s DOM element
*
* @return {Element}
* The DOM element that gets created.
*/
ModalDialog.prototype.createEl = function createEl$$1() {
return _Component.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass(),
tabIndex: -1
}, {
'aria-describedby': this.id() + '_description',
'aria-hidden': 'true',
'aria-label': this.label(),
'role': 'dialog'
});
};
ModalDialog.prototype.dispose = function dispose() {
this.contentEl_ = null;
this.descEl_ = null;
this.previouslyActiveEl_ = null;
_Component.prototype.dispose.call(this);
};
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
ModalDialog.prototype.buildCSSClass = function buildCSSClass() {
return MODAL_CLASS_NAME + ' vjs-hidden ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Handles `keydown` events on the document, looking for ESC, which closes
* the modal.
*
* @param {EventTarget~Event} e
* The keypress that triggered this event.
*
* @listens keydown
*/
ModalDialog.prototype.handleKeyPress = function handleKeyPress(e) {
if (e.which === ESC && this.closeable()) {
this.close();
}
};
/**
* Returns the label string for this modal. Primarily used for accessibility.
*
* @return {string}
* the localized or raw label of this modal.
*/
ModalDialog.prototype.label = function label() {
return this.localize(this.options_.label || 'Modal Window');
};
/**
* Returns the description string for this modal. Primarily used for
* accessibility.
*
* @return {string}
* The localized or raw description of this modal.
*/
ModalDialog.prototype.description = function description() {
var desc = this.options_.description || this.localize('This is a modal window.');
// Append a universal closeability message if the modal is closeable.
if (this.closeable()) {
desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
}
return desc;
};
/**
* Opens the modal.
*
* @fires ModalDialog#beforemodalopen
* @fires ModalDialog#modalopen
*/
ModalDialog.prototype.open = function open() {
if (!this.opened_) {
var player = this.player();
/**
* Fired just before a `ModalDialog` is opened.
*
* @event ModalDialog#beforemodalopen
* @type {EventTarget~Event}
*/
this.trigger('beforemodalopen');
this.opened_ = true;
// Fill content if the modal has never opened before and
// never been filled.
if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
this.fill();
}
// If the player was playing, pause it and take note of its previously
// playing state.
this.wasPlaying_ = !player.paused();
if (this.options_.pauseOnOpen && this.wasPlaying_) {
player.pause();
}
if (this.closeable()) {
this.on(this.el_.ownerDocument, 'keydown', bind(this, this.handleKeyPress));
}
// Hide controls and note if they were enabled.
this.hadControls_ = player.controls();
player.controls(false);
this.show();
this.conditionalFocus_();
this.el().setAttribute('aria-hidden', 'false');
/**
* Fired just after a `ModalDialog` is opened.
*
* @event ModalDialog#modalopen
* @type {EventTarget~Event}
*/
this.trigger('modalopen');
this.hasBeenOpened_ = true;
}
};
/**
* If the `ModalDialog` is currently open or closed.
*
* @param {boolean} [value]
* If given, it will open (`true`) or close (`false`) the modal.
*
* @return {boolean}
* the current open state of the modaldialog
*/
ModalDialog.prototype.opened = function opened(value) {
if (typeof value === 'boolean') {
this[value ? 'open' : 'close']();
}
return this.opened_;
};
/**
* Closes the modal, does nothing if the `ModalDialog` is
* not open.
*
* @fires ModalDialog#beforemodalclose
* @fires ModalDialog#modalclose
*/
ModalDialog.prototype.close = function close() {
if (!this.opened_) {
return;
}
var player = this.player();
/**
* Fired just before a `ModalDialog` is closed.
*
* @event ModalDialog#beforemodalclose
* @type {EventTarget~Event}
*/
this.trigger('beforemodalclose');
this.opened_ = false;
if (this.wasPlaying_ && this.options_.pauseOnOpen) {
player.play();
}
if (this.closeable()) {
this.off(this.el_.ownerDocument, 'keydown', bind(this, this.handleKeyPress));
}
if (this.hadControls_) {
player.controls(true);
}
this.hide();
this.el().setAttribute('aria-hidden', 'true');
/**
* Fired just after a `ModalDialog` is closed.
*
* @event ModalDialog#modalclose
* @type {EventTarget~Event}
*/
this.trigger('modalclose');
this.conditionalBlur_();
if (this.options_.temporary) {
this.dispose();
}
};
/**
* Check to see if the `ModalDialog` is closeable via the UI.
*
* @param {boolean} [value]
* If given as a boolean, it will set the `closeable` option.
*
* @return {boolean}
* Returns the final value of the closable option.
*/
ModalDialog.prototype.closeable = function closeable(value) {
if (typeof value === 'boolean') {
var closeable = this.closeable_ = !!value;
var close = this.getChild('closeButton');
// If this is being made closeable and has no close button, add one.
if (closeable && !close) {
// The close button should be a child of the modal - not its
// content element, so temporarily change the content element.
var temp = this.contentEl_;
this.contentEl_ = this.el_;
close = this.addChild('closeButton', { controlText: 'Close Modal Dialog' });
this.contentEl_ = temp;
this.on(close, 'close', this.close);
}
// If this is being made uncloseable and has a close button, remove it.
if (!closeable && close) {
this.off(close, 'close', this.close);
this.removeChild(close);
close.dispose();
}
}
return this.closeable_;
};
/**
* Fill the modal's content element with the modal's "content" option.
* The content element will be emptied before this change takes place.
*/
ModalDialog.prototype.fill = function fill() {
this.fillWith(this.content());
};
/**
* Fill the modal's content element with arbitrary content.
* The content element will be emptied before this change takes place.
*
* @fires ModalDialog#beforemodalfill
* @fires ModalDialog#modalfill
*
* @param {Mixed} [content]
* The same rules apply to this as apply to the `content` option.
*/
ModalDialog.prototype.fillWith = function fillWith(content) {
var contentEl = this.contentEl();
var parentEl = contentEl.parentNode;
var nextSiblingEl = contentEl.nextSibling;
/**
* Fired just before a `ModalDialog` is filled with content.
*
* @event ModalDialog#beforemodalfill
* @type {EventTarget~Event}
*/
this.trigger('beforemodalfill');
this.hasBeenFilled_ = true;
// Detach the content element from the DOM before performing
// manipulation to avoid modifying the live DOM multiple times.
parentEl.removeChild(contentEl);
this.empty();
insertContent(contentEl, content);
/**
* Fired just after a `ModalDialog` is filled with content.
*
* @event ModalDialog#modalfill
* @type {EventTarget~Event}
*/
this.trigger('modalfill');
// Re-inject the re-filled content element.
if (nextSiblingEl) {
parentEl.insertBefore(contentEl, nextSiblingEl);
} else {
parentEl.appendChild(contentEl);
}
// make sure that the close button is last in the dialog DOM
var closeButton = this.getChild('closeButton');
if (closeButton) {
parentEl.appendChild(closeButton.el_);
}
};
/**
* Empties the content element. This happens anytime the modal is filled.
*
* @fires ModalDialog#beforemodalempty
* @fires ModalDialog#modalempty
*/
ModalDialog.prototype.empty = function empty() {
/**
* Fired just before a `ModalDialog` is emptied.
*
* @event ModalDialog#beforemodalempty
* @type {EventTarget~Event}
*/
this.trigger('beforemodalempty');
emptyEl(this.contentEl());
/**
* Fired just after a `ModalDialog` is emptied.
*
* @event ModalDialog#modalempty
* @type {EventTarget~Event}
*/
this.trigger('modalempty');
};
/**
* Gets or sets the modal content, which gets normalized before being
* rendered into the DOM.
*
* This does not update the DOM or fill the modal, but it is called during
* that process.
*
* @param {Mixed} [value]
* If defined, sets the internal content value to be used on the
* next call(s) to `fill`. This value is normalized before being
* inserted. To "clear" the internal content value, pass `null`.
*
* @return {Mixed}
* The current content of the modal dialog
*/
ModalDialog.prototype.content = function content(value) {
if (typeof value !== 'undefined') {
this.content_ = value;
}
return this.content_;
};
/**
* conditionally focus the modal dialog if focus was previously on the player.
*
* @private
*/
ModalDialog.prototype.conditionalFocus_ = function conditionalFocus_() {
var activeEl = document.activeElement;
var playerEl = this.player_.el_;
this.previouslyActiveEl_ = null;
if (playerEl.contains(activeEl) || playerEl === activeEl) {
this.previouslyActiveEl_ = activeEl;
this.focus();
this.on(document, 'keydown', this.handleKeyDown);
}
};
/**
* conditionally blur the element and refocus the last focused element
*
* @private
*/
ModalDialog.prototype.conditionalBlur_ = function conditionalBlur_() {
if (this.previouslyActiveEl_) {
this.previouslyActiveEl_.focus();
this.previouslyActiveEl_ = null;
}
this.off(document, 'keydown', this.handleKeyDown);
};
/**
* Keydown handler. Attached when modal is focused.
*
* @listens keydown
*/
ModalDialog.prototype.handleKeyDown = function handleKeyDown(event) {
// exit early if it isn't a tab key
if (event.which !== 9) {
return;
}
var focusableEls = this.focusableEls_();
var activeEl = this.el_.querySelector(':focus');
var focusIndex = void 0;
for (var i = 0; i < focusableEls.length; i++) {
if (activeEl === focusableEls[i]) {
focusIndex = i;
break;
}
}
if (document.activeElement === this.el_) {
focusIndex = 0;
}
if (event.shiftKey && focusIndex === 0) {
focusableEls[focusableEls.length - 1].focus();
event.preventDefault();
} else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
focusableEls[0].focus();
event.preventDefault();
}
};
/**
* get all focusable elements
*
* @private
*/
ModalDialog.prototype.focusableEls_ = function focusableEls_() {
var allChildren = this.el_.querySelectorAll('*');
return Array.prototype.filter.call(allChildren, function (child) {
return (child instanceof window.HTMLAnchorElement || child instanceof window.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window.HTMLInputElement || child instanceof window.HTMLSelectElement || child instanceof window.HTMLTextAreaElement || child instanceof window.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window.HTMLIFrameElement || child instanceof window.HTMLObjectElement || child instanceof window.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');
});
};
return ModalDialog;
}(Component);
/**
* Default options for `ModalDialog` default options.
*
* @type {Object}
* @private
*/
ModalDialog.prototype.options_ = {
pauseOnOpen: true,
temporary: true
};
Component.registerComponent('ModalDialog', ModalDialog);
/**
* @file track-list.js
*/
/**
* Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
* {@link VideoTrackList}
*
* @extends EventTarget
*/
var TrackList = function (_EventTarget) {
inherits(TrackList, _EventTarget);
/**
* Create an instance of this class
*
* @param {Track[]} tracks
* A list of tracks to initialize the list with.
*
* @param {Object} [list]
* The child object with inheritance done manually for ie8.
*
* @abstract
*/
function TrackList() {
var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var _ret;
var list = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
classCallCheck(this, TrackList);
var _this = possibleConstructorReturn(this, _EventTarget.call(this));
if (!list) {
list = _this; // eslint-disable-line
if (IS_IE8) {
list = document.createElement('custom');
for (var prop in TrackList.prototype) {
if (prop !== 'constructor') {
list[prop] = TrackList.prototype[prop];
}
}
}
}
list.tracks_ = [];
/**
* @memberof TrackList
* @member {number} length
* The current number of `Track`s in the this Trackist.
* @instance
*/
Object.defineProperty(list, 'length', {
get: function get$$1() {
return this.tracks_.length;
}
});
for (var i = 0; i < tracks.length; i++) {
list.addTrack(tracks[i]);
}
// must return the object, as for ie8 it will not be this
// but a reference to a document object
return _ret = list, possibleConstructorReturn(_this, _ret);
}
/**
* Add a {@link Track} to the `TrackList`
*
* @param {Track} track
* The audio, video, or text track to add to the list.
*
* @fires TrackList#addtrack
*/
TrackList.prototype.addTrack = function addTrack(track) {
var index = this.tracks_.length;
if (!('' + index in this)) {
Object.defineProperty(this, index, {
get: function get$$1() {
return this.tracks_[index];
}
});
}
// Do not add duplicate tracks
if (this.tracks_.indexOf(track) === -1) {
this.tracks_.push(track);
/**
* Triggered when a track is added to a track list.
*
* @event TrackList#addtrack
* @type {EventTarget~Event}
* @property {Track} track
* A reference to track that was added.
*/
this.trigger({
track: track,
type: 'addtrack'
});
}
};
/**
* Remove a {@link Track} from the `TrackList`
*
* @param {Track} rtrack
* The audio, video, or text track to remove from the list.
*
* @fires TrackList#removetrack
*/
TrackList.prototype.removeTrack = function removeTrack(rtrack) {
var track = void 0;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] === rtrack) {
track = this[i];
if (track.off) {
track.off();
}
this.tracks_.splice(i, 1);
break;
}
}
if (!track) {
return;
}
/**
* Triggered when a track is removed from track list.
*
* @event TrackList#removetrack
* @type {EventTarget~Event}
* @property {Track} track
* A reference to track that was removed.
*/
this.trigger({
track: track,
type: 'removetrack'
});
};
/**
* Get a Track from the TrackList by a tracks id
*
* @param {String} id - the id of the track to get
* @method getTrackById
* @return {Track}
* @private
*/
TrackList.prototype.getTrackById = function getTrackById(id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var track = this[i];
if (track.id === id) {
result = track;
break;
}
}
return result;
};
return TrackList;
}(EventTarget);
/**
* Triggered when a different track is selected/enabled.
*
* @event TrackList#change
* @type {EventTarget~Event}
*/
/**
* Events that can be called with on + eventName. See {@link EventHandler}.
*
* @property {Object} TrackList#allowedEvents_
* @private
*/
TrackList.prototype.allowedEvents_ = {
change: 'change',
addtrack: 'addtrack',
removetrack: 'removetrack'
};
// emulate attribute EventHandler support to allow for feature detection
for (var event in TrackList.prototype.allowedEvents_) {
TrackList.prototype['on' + event] = null;
}
/**
* @file audio-track-list.js
*/
/**
* Anywhere we call this function we diverge from the spec
* as we only support one enabled audiotrack at a time
*
* @param {AudioTrackList} list
* list to work on
*
* @param {AudioTrack} track
* The track to skip
*
* @private
*/
var disableOthers = function disableOthers(list, track) {
for (var i = 0; i < list.length; i++) {
if (!Object.keys(list[i]).length || track.id === list[i].id) {
continue;
}
// another audio track is enabled, disable it
list[i].enabled = false;
}
};
/**
* The current list of {@link AudioTrack} for a media file.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
* @extends TrackList
*/
var AudioTrackList = function (_TrackList) {
inherits(AudioTrackList, _TrackList);
/**
* Create an instance of this class.
*
* @param {AudioTrack[]} [tracks=[]]
* A list of `AudioTrack` to instantiate the list with.
*/
function AudioTrackList() {
var _this, _ret;
var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
classCallCheck(this, AudioTrackList);
var list = void 0;
// make sure only 1 track is enabled
// sorted from last index to first index
for (var i = tracks.length - 1; i >= 0; i--) {
if (tracks[i].enabled) {
disableOthers(tracks, tracks[i]);
break;
}
}
// IE8 forces us to implement inheritance ourselves
// as it does not support Object.defineProperty properly
if (IS_IE8) {
list = document.createElement('custom');
for (var prop in TrackList.prototype) {
if (prop !== 'constructor') {
list[prop] = TrackList.prototype[prop];
}
}
for (var _prop in AudioTrackList.prototype) {
if (_prop !== 'constructor') {
list[_prop] = AudioTrackList.prototype[_prop];
}
}
}
list = (_this = possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this);
list.changing_ = false;
return _ret = list, possibleConstructorReturn(_this, _ret);
}
/**
* Add an {@link AudioTrack} to the `AudioTrackList`.
*
* @param {AudioTrack} track
* The AudioTrack to add to the list
*
* @fires TrackList#addtrack
*/
AudioTrackList.prototype.addTrack = function addTrack(track) {
var _this2 = this;
if (track.enabled) {
disableOthers(this, track);
}
_TrackList.prototype.addTrack.call(this, track);
// native tracks don't have this
if (!track.addEventListener) {
return;
}
/**
* @listens AudioTrack#enabledchange
* @fires TrackList#change
*/
track.addEventListener('enabledchange', function () {
// when we are disabling other tracks (since we don't support
// more than one track at a time) we will set changing_
// to true so that we don't trigger additional change events
if (_this2.changing_) {
return;
}
_this2.changing_ = true;
disableOthers(_this2, track);
_this2.changing_ = false;
_this2.trigger('change');
});
};
return AudioTrackList;
}(TrackList);
/**
* @file video-track-list.js
*/
/**
* Un-select all other {@link VideoTrack}s that are selected.
*
* @param {VideoTrackList} list
* list to work on
*
* @param {VideoTrack} track
* The track to skip
*
* @private
*/
var disableOthers$1 = function disableOthers(list, track) {
for (var i = 0; i < list.length; i++) {
if (!Object.keys(list[i]).length || track.id === list[i].id) {
continue;
}
// another video track is enabled, disable it
list[i].selected = false;
}
};
/**
* The current list of {@link VideoTrack} for a video.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
* @extends TrackList
*/
var VideoTrackList = function (_TrackList) {
inherits(VideoTrackList, _TrackList);
/**
* Create an instance of this class.
*
* @param {VideoTrack[]} [tracks=[]]
* A list of `VideoTrack` to instantiate the list with.
*/
function VideoTrackList() {
var _this, _ret;
var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
classCallCheck(this, VideoTrackList);
var list = void 0;
// make sure only 1 track is enabled
// sorted from last index to first index
for (var i = tracks.length - 1; i >= 0; i--) {
if (tracks[i].selected) {
disableOthers$1(tracks, tracks[i]);
break;
}
}
// IE8 forces us to implement inheritance ourselves
// as it does not support Object.defineProperty properly
if (IS_IE8) {
list = document.createElement('custom');
for (var prop in TrackList.prototype) {
if (prop !== 'constructor') {
list[prop] = TrackList.prototype[prop];
}
}
for (var _prop in VideoTrackList.prototype) {
if (_prop !== 'constructor') {
list[_prop] = VideoTrackList.prototype[_prop];
}
}
}
list = (_this = possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this);
list.changing_ = false;
/**
* @member {number} VideoTrackList#selectedIndex
* The current index of the selected {@link VideoTrack`}.
*/
Object.defineProperty(list, 'selectedIndex', {
get: function get$$1() {
for (var _i = 0; _i < this.length; _i++) {
if (this[_i].selected) {
return _i;
}
}
return -1;
},
set: function set$$1() {}
});
return _ret = list, possibleConstructorReturn(_this, _ret);
}
/**
* Add a {@link VideoTrack} to the `VideoTrackList`.
*
* @param {VideoTrack} track
* The VideoTrack to add to the list
*
* @fires TrackList#addtrack
*/
VideoTrackList.prototype.addTrack = function addTrack(track) {
var _this2 = this;
if (track.selected) {
disableOthers$1(this, track);
}
_TrackList.prototype.addTrack.call(this, track);
// native tracks don't have this
if (!track.addEventListener) {
return;
}
/**
* @listens VideoTrack#selectedchange
* @fires TrackList#change
*/
track.addEventListener('selectedchange', function () {
if (_this2.changing_) {
return;
}
_this2.changing_ = true;
disableOthers$1(_this2, track);
_this2.changing_ = false;
_this2.trigger('change');
});
};
return VideoTrackList;
}(TrackList);
/**
* @file text-track-list.js
*/
/**
* The current list of {@link TextTrack} for a media file.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
* @extends TrackList
*/
var TextTrackList = function (_TrackList) {
inherits(TextTrackList, _TrackList);
/**
* Create an instance of this class.
*
* @param {TextTrack[]} [tracks=[]]
* A list of `TextTrack` to instantiate the list with.
*/
function TextTrackList() {
var _this, _ret;
var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
classCallCheck(this, TextTrackList);
var list = void 0;
// IE8 forces us to implement inheritance ourselves
// as it does not support Object.defineProperty properly
if (IS_IE8) {
list = document.createElement('custom');
for (var prop in TrackList.prototype) {
if (prop !== 'constructor') {
list[prop] = TrackList.prototype[prop];
}
}
for (var _prop in TextTrackList.prototype) {
if (_prop !== 'constructor') {
list[_prop] = TextTrackList.prototype[_prop];
}
}
}
list = (_this = possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this);
return _ret = list, possibleConstructorReturn(_this, _ret);
}
/**
* Add a {@link TextTrack} to the `TextTrackList`
*
* @param {TextTrack} track
* The text track to add to the list.
*
* @fires TrackList#addtrack
*/
TextTrackList.prototype.addTrack = function addTrack(track) {
_TrackList.prototype.addTrack.call(this, track);
/**
* @listens TextTrack#modechange
* @fires TrackList#change
*/
track.addEventListener('modechange', bind(this, function () {
this.trigger('change');
}));
var nonLanguageTextTrackKind = ['metadata', 'chapters'];
if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
track.addEventListener('modechange', bind(this, function () {
this.trigger('selectedlanguagechange');
}));
}
};
return TextTrackList;
}(TrackList);
/**
* @file html-track-element-list.js
*/
/**
* The current list of {@link HtmlTrackElement}s.
*/
var HtmlTrackElementList = function () {
/**
* Create an instance of this class.
*
* @param {HtmlTrackElement[]} [tracks=[]]
* A list of `HtmlTrackElement` to instantiate the list with.
*/
function HtmlTrackElementList() {
var trackElements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
classCallCheck(this, HtmlTrackElementList);
var list = this; // eslint-disable-line
if (IS_IE8) {
list = document.createElement('custom');
for (var prop in HtmlTrackElementList.prototype) {
if (prop !== 'constructor') {
list[prop] = HtmlTrackElementList.prototype[prop];
}
}
}
list.trackElements_ = [];
/**
* @memberof HtmlTrackElementList
* @member {number} length
* The current number of `Track`s in the this Trackist.
* @instance
*/
Object.defineProperty(list, 'length', {
get: function get$$1() {
return this.trackElements_.length;
}
});
for (var i = 0, length = trackElements.length; i < length; i++) {
list.addTrackElement_(trackElements[i]);
}
if (IS_IE8) {
return list;
}
}
/**
* Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
*
* @param {HtmlTrackElement} trackElement
* The track element to add to the list.
*
* @private
*/
HtmlTrackElementList.prototype.addTrackElement_ = function addTrackElement_(trackElement) {
var index = this.trackElements_.length;
if (!('' + index in this)) {
Object.defineProperty(this, index, {
get: function get$$1() {
return this.trackElements_[index];
}
});
}
// Do not add duplicate elements
if (this.trackElements_.indexOf(trackElement) === -1) {
this.trackElements_.push(trackElement);
}
};
/**
* Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
* {@link TextTrack}.
*
* @param {TextTrack} track
* The track associated with a track element.
*
* @return {HtmlTrackElement|undefined}
* The track element that was found or undefined.
*
* @private
*/
HtmlTrackElementList.prototype.getTrackElementByTrack_ = function getTrackElementByTrack_(track) {
var trackElement_ = void 0;
for (var i = 0, length = this.trackElements_.length; i < length; i++) {
if (track === this.trackElements_[i].track) {
trackElement_ = this.trackElements_[i];
break;
}
}
return trackElement_;
};
/**
* Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
*
* @param {HtmlTrackElement} trackElement
* The track element to remove from the list.
*
* @private
*/
HtmlTrackElementList.prototype.removeTrackElement_ = function removeTrackElement_(trackElement) {
for (var i = 0, length = this.trackElements_.length; i < length; i++) {
if (trackElement === this.trackElements_[i]) {
this.trackElements_.splice(i, 1);
break;
}
}
};
return HtmlTrackElementList;
}();
/**
* @file text-track-cue-list.js
*/
/**
* @typedef {Object} TextTrackCueList~TextTrackCue
*
* @property {string} id
* The unique id for this text track cue
*
* @property {number} startTime
* The start time for this text track cue
*
* @property {number} endTime
* The end time for this text track cue
*
* @property {boolean} pauseOnExit
* Pause when the end time is reached if true.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
*/
/**
* A List of TextTrackCues.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
*/
var TextTrackCueList = function () {
/**
* Create an instance of this class..
*
* @param {Array} cues
* A list of cues to be initialized with
*/
function TextTrackCueList(cues) {
classCallCheck(this, TextTrackCueList);
var list = this; // eslint-disable-line
if (IS_IE8) {
list = document.createElement('custom');
for (var prop in TextTrackCueList.prototype) {
if (prop !== 'constructor') {
list[prop] = TextTrackCueList.prototype[prop];
}
}
}
TextTrackCueList.prototype.setCues_.call(list, cues);
/**
* @memberof TextTrackCueList
* @member {number} length
* The current number of `TextTrackCue`s in the TextTrackCueList.
* @instance
*/
Object.defineProperty(list, 'length', {
get: function get$$1() {
return this.length_;
}
});
if (IS_IE8) {
return list;
}
}
/**
* A setter for cues in this list. Creates getters
* an an index for the cues.
*
* @param {Array} cues
* An array of cues to set
*
* @private
*/
TextTrackCueList.prototype.setCues_ = function setCues_(cues) {
var oldLength = this.length || 0;
var i = 0;
var l = cues.length;
this.cues_ = cues;
this.length_ = cues.length;
var defineProp = function defineProp(index) {
if (!('' + index in this)) {
Object.defineProperty(this, '' + index, {
get: function get$$1() {
return this.cues_[index];
}
});
}
};
if (oldLength < l) {
i = oldLength;
for (; i < l; i++) {
defineProp.call(this, i);
}
}
};
/**
* Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
*
* @param {string} id
* The id of the cue that should be searched for.
*
* @return {TextTrackCueList~TextTrackCue|null}
* A single cue or null if none was found.
*/
TextTrackCueList.prototype.getCueById = function getCueById(id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var cue = this[i];
if (cue.id === id) {
result = cue;
break;
}
}
return result;
};
return TextTrackCueList;
}();
/**
* @file track-kinds.js
*/
/**
* All possible `VideoTrackKind`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
* @typedef VideoTrack~Kind
* @enum
*/
var VideoTrackKind = {
alternative: 'alternative',
captions: 'captions',
main: 'main',
sign: 'sign',
subtitles: 'subtitles',
commentary: 'commentary'
};
/**
* All possible `AudioTrackKind`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
* @typedef AudioTrack~Kind
* @enum
*/
var AudioTrackKind = {
'alternative': 'alternative',
'descriptions': 'descriptions',
'main': 'main',
'main-desc': 'main-desc',
'translation': 'translation',
'commentary': 'commentary'
};
/**
* All possible `TextTrackKind`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
* @typedef TextTrack~Kind
* @enum
*/
var TextTrackKind = {
subtitles: 'subtitles',
captions: 'captions',
descriptions: 'descriptions',
chapters: 'chapters',
metadata: 'metadata'
};
/**
* All possible `TextTrackMode`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
* @typedef TextTrack~Mode
* @enum
*/
var TextTrackMode = {
disabled: 'disabled',
hidden: 'hidden',
showing: 'showing'
};
/**
* @file track.js
*/
/**
* A Track class that contains all of the common functionality for {@link AudioTrack},
* {@link VideoTrack}, and {@link TextTrack}.
*
* > Note: This class should not be used directly
*
* @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
* @extends EventTarget
* @abstract
*/
var Track = function (_EventTarget) {
inherits(Track, _EventTarget);
/**
* Create an instance of this class.
*
* @param {Object} [options={}]
* Object of option names and values
*
* @param {string} [options.kind='']
* A valid kind for the track type you are creating.
*
* @param {string} [options.id='vjs_track_' + Guid.newGUID()]
* A unique id for this AudioTrack.
*
* @param {string} [options.label='']
* The menu label for this track.
*
* @param {string} [options.language='']
* A valid two character language code.
*
* @abstract
*/
function Track() {
var _ret;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, Track);
var _this = possibleConstructorReturn(this, _EventTarget.call(this));
var track = _this; // eslint-disable-line
if (IS_IE8) {
track = document.createElement('custom');
for (var prop in Track.prototype) {
if (prop !== 'constructor') {
track[prop] = Track.prototype[prop];
}
}
}
var trackProps = {
id: options.id || 'vjs_track_' + newGUID(),
kind: options.kind || '',
label: options.label || '',
language: options.language || ''
};
/**
* @memberof Track
* @member {string} id
* The id of this track. Cannot be changed after creation.
* @instance
*
* @readonly
*/
/**
* @memberof Track
* @member {string} kind
* The kind of track that this is. Cannot be changed after creation.
* @instance
*
* @readonly
*/
/**
* @memberof Track
* @member {string} label
* The label of this track. Cannot be changed after creation.
* @instance
*
* @readonly
*/
/**
* @memberof Track
* @member {string} language
* The two letter language code for this track. Cannot be changed after
* creation.
* @instance
*
* @readonly
*/
var _loop = function _loop(key) {
Object.defineProperty(track, key, {
get: function get$$1() {
return trackProps[key];
},
set: function set$$1() {}
});
};
for (var key in trackProps) {
_loop(key);
}
return _ret = track, possibleConstructorReturn(_this, _ret);
}
return Track;
}(EventTarget);
/**
* @file url.js
* @module url
*/
/**
* @typedef {Object} url:URLObject
*
* @property {string} protocol
* The protocol of the url that was parsed.
*
* @property {string} hostname
* The hostname of the url that was parsed.
*
* @property {string} port
* The port of the url that was parsed.
*
* @property {string} pathname
* The pathname of the url that was parsed.
*
* @property {string} search
* The search query of the url that was parsed.
*
* @property {string} hash
* The hash of the url that was parsed.
*
* @property {string} host
* The host of the url that was parsed.
*/
/**
* Resolve and parse the elements of a URL.
*
* @param {String} url
* The url to parse
*
* @return {url:URLObject}
* An object of url details
*/
var parseUrl = function parseUrl(url) {
var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
// add the url to an anchor and let the browser parse the URL
var a = document.createElement('a');
a.href = url;
// IE8 (and 9?) Fix
// ie8 doesn't parse the URL correctly until the anchor is actually
// added to the body, and an innerHTML is needed to trigger the parsing
var addToBody = a.host === '' && a.protocol !== 'file:';
var div = void 0;
if (addToBody) {
div = document.createElement('div');
div.innerHTML = '<a href="' + url + '"></a>';
a = div.firstChild;
// prevent the div from affecting layout
div.setAttribute('style', 'display:none; position:absolute;');
document.body.appendChild(div);
}
// Copy the specific URL properties to a new object
// This is also needed for IE8 because the anchor loses its
// properties when it's removed from the dom
var details = {};
for (var i = 0; i < props.length; i++) {
details[props[i]] = a[props[i]];
}
// IE9 adds the port to the host property unlike everyone else. If
// a port identifier is added for standard ports, strip it.
if (details.protocol === 'http:') {
details.host = details.host.replace(/:80$/, '');
}
if (details.protocol === 'https:') {
details.host = details.host.replace(/:443$/, '');
}
if (!details.protocol) {
details.protocol = window.location.protocol;
}
if (addToBody) {
document.body.removeChild(div);
}
return details;
};
/**
* Get absolute version of relative URL. Used to tell flash correct URL.
*
*
* @param {string} url
* URL to make absolute
*
* @return {string}
* Absolute URL
*
* @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
*/
var getAbsoluteURL = function getAbsoluteURL(url) {
// Check if absolute URL
if (!url.match(/^https?:\/\//)) {
// Convert to absolute URL. Flash hosted off-site needs an absolute URL.
var div = document.createElement('div');
div.innerHTML = '<a href="' + url + '">x</a>';
url = div.firstChild.href;
}
return url;
};
/**
* Returns the extension of the passed file name. It will return an empty string
* if passed an invalid path.
*
* @param {string} path
* The fileName path like '/path/to/file.mp4'
*
* @returns {string}
* The extension in lower case or an empty string if no
* extension could be found.
*/
var getFileExtension = function getFileExtension(path) {
if (typeof path === 'string') {
var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i;
var pathParts = splitPathRe.exec(path);
if (pathParts) {
return pathParts.pop().toLowerCase();
}
}
return '';
};
/**
* Returns whether the url passed is a cross domain request or not.
*
* @param {string} url
* The url to check.
*
* @return {boolean}
* Whether it is a cross domain request or not.
*/
var isCrossOrigin = function isCrossOrigin(url) {
var winLoc = window.location;
var urlInfo = parseUrl(url);
// IE8 protocol relative urls will return ':' for protocol
var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
// Check if url is for another domain/origin
// IE8 doesn't know location.origin, so we won't rely on it here
var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
return crossOrigin;
};
var Url = (Object.freeze || Object)({
parseUrl: parseUrl,
getAbsoluteURL: getAbsoluteURL,
getFileExtension: getFileExtension,
isCrossOrigin: isCrossOrigin
});
/**
* @file text-track.js
*/
/**
* Takes a webvtt file contents and parses it into cues
*
* @param {string} srcContent
* webVTT file contents
*
* @param {TextTrack} track
* TextTrack to add cues to. Cues come from the srcContent.
*
* @private
*/
var parseCues = function parseCues(srcContent, track) {
var parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder());
var errors = [];
parser.oncue = function (cue) {
track.addCue(cue);
};
parser.onparsingerror = function (error) {
errors.push(error);
};
parser.onflush = function () {
track.trigger({
type: 'loadeddata',
target: track
});
};
parser.parse(srcContent);
if (errors.length > 0) {
if (window.console && window.console.groupCollapsed) {
window.console.groupCollapsed('Text Track parsing errors for ' + track.src);
}
errors.forEach(function (error) {
return log.error(error);
});
if (window.console && window.console.groupEnd) {
window.console.groupEnd();
}
}
parser.flush();
};
/**
* Load a `TextTrack` from a specifed url.
*
* @param {string} src
* Url to load track from.
*
* @param {TextTrack} track
* Track to add cues to. Comes from the content at the end of `url`.
*
* @private
*/
var loadTrack = function loadTrack(src, track) {
var opts = {
uri: src
};
var crossOrigin = isCrossOrigin(src);
if (crossOrigin) {
opts.cors = crossOrigin;
}
xhr(opts, bind(this, function (err, response, responseBody) {
if (err) {
return log.error(err, response);
}
track.loaded_ = true;
// Make sure that vttjs has loaded, otherwise, wait till it finished loading
// NOTE: this is only used for the alt/video.novtt.js build
if (typeof window.WebVTT !== 'function') {
if (track.tech_) {
var loadHandler = function loadHandler() {
return parseCues(responseBody, track);
};
track.tech_.on('vttjsloaded', loadHandler);
track.tech_.on('vttjserror', function () {
log.error('vttjs failed to load, stopping trying to process ' + track.src);
track.tech_.off('vttjsloaded', loadHandler);
});
}
} else {
parseCues(responseBody, track);
}
}));
};
/**
* A representation of a single `TextTrack`.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
* @extends Track
*/
var TextTrack = function (_Track) {
inherits(TextTrack, _Track);
/**
* Create an instance of this class.
*
* @param {Object} options={}
* Object of option names and values
*
* @param {Tech} options.tech
* A reference to the tech that owns this TextTrack.
*
* @param {TextTrack~Kind} [options.kind='subtitles']
* A valid text track kind.
*
* @param {TextTrack~Mode} [options.mode='disabled']
* A valid text track mode.
*
* @param {string} [options.id='vjs_track_' + Guid.newGUID()]
* A unique id for this TextTrack.
*
* @param {string} [options.label='']
* The menu label for this track.
*
* @param {string} [options.language='']
* A valid two character language code.
*
* @param {string} [options.srclang='']
* A valid two character language code. An alternative, but deprioritized
* vesion of `options.language`
*
* @param {string} [options.src]
* A url to TextTrack cues.
*
* @param {boolean} [options.default]
* If this track should default to on or off.
*/
function TextTrack() {
var _this, _ret;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, TextTrack);
if (!options.tech) {
throw new Error('A tech was not provided.');
}
var settings = mergeOptions(options, {
kind: TextTrackKind[options.kind] || 'subtitles',
language: options.language || options.srclang || ''
});
var mode = TextTrackMode[settings.mode] || 'disabled';
var default_ = settings['default'];
if (settings.kind === 'metadata' || settings.kind === 'chapters') {
mode = 'hidden';
}
// on IE8 this will be a document element
// for every other browser this will be a normal object
var tt = (_this = possibleConstructorReturn(this, _Track.call(this, settings)), _this);
tt.tech_ = settings.tech;
if (IS_IE8) {
for (var prop in TextTrack.prototype) {
if (prop !== 'constructor') {
tt[prop] = TextTrack.prototype[prop];
}
}
}
tt.cues_ = [];
tt.activeCues_ = [];
var cues = new TextTrackCueList(tt.cues_);
var activeCues = new TextTrackCueList(tt.activeCues_);
var changed = false;
var timeupdateHandler = bind(tt, function () {
// Accessing this.activeCues for the side-effects of updating itself
// due to it's nature as a getter function. Do not remove or cues will
// stop updating!
// Use the setter to prevent deletion from uglify (pure_getters rule)
this.activeCues = this.activeCues;
if (changed) {
this.trigger('cuechange');
changed = false;
}
});
if (mode !== 'disabled') {
tt.tech_.ready(function () {
tt.tech_.on('timeupdate', timeupdateHandler);
}, true);
}
/**
* @memberof TextTrack
* @member {boolean} default
* If this track was set to be on or off by default. Cannot be changed after
* creation.
* @instance
*
* @readonly
*/
Object.defineProperty(tt, 'default', {
get: function get$$1() {
return default_;
},
set: function set$$1() {}
});
/**
* @memberof TextTrack
* @member {string} mode
* Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
* not be set if setting to an invalid mode.
* @instance
*
* @fires TextTrack#modechange
*/
Object.defineProperty(tt, 'mode', {
get: function get$$1() {
return mode;
},
set: function set$$1(newMode) {
var _this2 = this;
if (!TextTrackMode[newMode]) {
return;
}
mode = newMode;
if (mode !== 'disabled') {
this.tech_.ready(function () {
_this2.tech_.on('timeupdate', timeupdateHandler);
}, true);
} else {
this.tech_.off('timeupdate', timeupdateHandler);
}
/**
* An event that fires when mode changes on this track. This allows
* the TextTrackList that holds this track to act accordingly.
*
* > Note: This is not part of the spec!
*
* @event TextTrack#modechange
* @type {EventTarget~Event}
*/
this.trigger('modechange');
}
});
/**
* @memberof TextTrack
* @member {TextTrackCueList} cues
* The text track cue list for this TextTrack.
* @instance
*/
Object.defineProperty(tt, 'cues', {
get: function get$$1() {
if (!this.loaded_) {
return null;
}
return cues;
},
set: function set$$1() {}
});
/**
* @memberof TextTrack
* @member {TextTrackCueList} activeCues
* The list text track cues that are currently active for this TextTrack.
* @instance
*/
Object.defineProperty(tt, 'activeCues', {
get: function get$$1() {
if (!this.loaded_) {
return null;
}
// nothing to do
if (this.cues.length === 0) {
return activeCues;
}
var ct = this.tech_.currentTime();
var active = [];
for (var i = 0, l = this.cues.length; i < l; i++) {
var cue = this.cues[i];
if (cue.startTime <= ct && cue.endTime >= ct) {
active.push(cue);
} else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) {
active.push(cue);
}
}
changed = false;
if (active.length !== this.activeCues_.length) {
changed = true;
} else {
for (var _i = 0; _i < active.length; _i++) {
if (this.activeCues_.indexOf(active[_i]) === -1) {
changed = true;
}
}
}
this.activeCues_ = active;
activeCues.setCues_(this.activeCues_);
return activeCues;
},
// /!\ Keep this setter empty (see the timeupdate handler above)
set: function set$$1() {}
});
if (settings.src) {
tt.src = settings.src;
loadTrack(settings.src, tt);
} else {
tt.loaded_ = true;
}
return _ret = tt, possibleConstructorReturn(_this, _ret);
}
/**
* Add a cue to the internal list of cues.
*
* @param {TextTrack~Cue} cue
* The cue to add to our internal list
*/
TextTrack.prototype.addCue = function addCue(originalCue) {
var cue = originalCue;
if (window.vttjs && !(originalCue instanceof window.vttjs.VTTCue)) {
cue = new window.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
for (var prop in originalCue) {
if (!(prop in cue)) {
cue[prop] = originalCue[prop];
}
}
// make sure that `id` is copied over
cue.id = originalCue.id;
cue.originalCue_ = originalCue;
}
var tracks = this.tech_.textTracks();
for (var i = 0; i < tracks.length; i++) {
if (tracks[i] !== this) {
tracks[i].removeCue(cue);
}
}
this.cues_.push(cue);
this.cues.setCues_(this.cues_);
};
/**
* Remove a cue from our internal list
*
* @param {TextTrack~Cue} removeCue
* The cue to remove from our internal list
*/
TextTrack.prototype.removeCue = function removeCue(_removeCue) {
var i = this.cues_.length;
while (i--) {
var cue = this.cues_[i];
if (cue === _removeCue || cue.originalCue_ && cue.originalCue_ === _removeCue) {
this.cues_.splice(i, 1);
this.cues.setCues_(this.cues_);
break;
}
}
};
return TextTrack;
}(Track);
/**
* cuechange - One or more cues in the track have become active or stopped being active.
*/
TextTrack.prototype.allowedEvents_ = {
cuechange: 'cuechange'
};
/**
* A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
* only one `AudioTrack` in the list will be enabled at a time.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
* @extends Track
*/
var AudioTrack = function (_Track) {
inherits(AudioTrack, _Track);
/**
* Create an instance of this class.
*
* @param {Object} [options={}]
* Object of option names and values
*
* @param {AudioTrack~Kind} [options.kind='']
* A valid audio track kind
*
* @param {string} [options.id='vjs_track_' + Guid.newGUID()]
* A unique id for this AudioTrack.
*
* @param {string} [options.label='']
* The menu label for this track.
*
* @param {string} [options.language='']
* A valid two character language code.
*
* @param {boolean} [options.enabled]
* If this track is the one that is currently playing. If this track is part of
* an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
*/
function AudioTrack() {
var _this, _ret;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, AudioTrack);
var settings = mergeOptions(options, {
kind: AudioTrackKind[options.kind] || ''
});
// on IE8 this will be a document element
// for every other browser this will be a normal object
var track = (_this = possibleConstructorReturn(this, _Track.call(this, settings)), _this);
var enabled = false;
if (IS_IE8) {
for (var prop in AudioTrack.prototype) {
if (prop !== 'constructor') {
track[prop] = AudioTrack.prototype[prop];
}
}
}
/**
* @memberof AudioTrack
* @member {boolean} enabled
* If this `AudioTrack` is enabled or not. When setting this will
* fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
* @instance
*
* @fires VideoTrack#selectedchange
*/
Object.defineProperty(track, 'enabled', {
get: function get$$1() {
return enabled;
},
set: function set$$1(newEnabled) {
// an invalid or unchanged value
if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
return;
}
enabled = newEnabled;
/**
* An event that fires when enabled changes on this track. This allows
* the AudioTrackList that holds this track to act accordingly.
*
* > Note: This is not part of the spec! Native tracks will do
* this internally without an event.
*
* @event AudioTrack#enabledchange
* @type {EventTarget~Event}
*/
this.trigger('enabledchange');
}
});
// if the user sets this track to selected then
// set selected to that true value otherwise
// we keep it false
if (settings.enabled) {
track.enabled = settings.enabled;
}
track.loaded_ = true;
return _ret = track, possibleConstructorReturn(_this, _ret);
}
return AudioTrack;
}(Track);
/**
* A representation of a single `VideoTrack`.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
* @extends Track
*/
var VideoTrack = function (_Track) {
inherits(VideoTrack, _Track);
/**
* Create an instance of this class.
*
* @param {Object} [options={}]
* Object of option names and values
*
* @param {string} [options.kind='']
* A valid {@link VideoTrack~Kind}
*
* @param {string} [options.id='vjs_track_' + Guid.newGUID()]
* A unique id for this AudioTrack.
*
* @param {string} [options.label='']
* The menu label for this track.
*
* @param {string} [options.language='']
* A valid two character language code.
*
* @param {boolean} [options.selected]
* If this track is the one that is currently playing.
*/
function VideoTrack() {
var _this, _ret;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, VideoTrack);
var settings = mergeOptions(options, {
kind: VideoTrackKind[options.kind] || ''
});
// on IE8 this will be a document element
// for every other browser this will be a normal object
var track = (_this = possibleConstructorReturn(this, _Track.call(this, settings)), _this);
var selected = false;
if (IS_IE8) {
for (var prop in VideoTrack.prototype) {
if (prop !== 'constructor') {
track[prop] = VideoTrack.prototype[prop];
}
}
}
/**
* @memberof VideoTrack
* @member {boolean} selected
* If this `VideoTrack` is selected or not. When setting this will
* fire {@link VideoTrack#selectedchange} if the state of selected changed.
* @instance
*
* @fires VideoTrack#selectedchange
*/
Object.defineProperty(track, 'selected', {
get: function get$$1() {
return selected;
},
set: function set$$1(newSelected) {
// an invalid or unchanged value
if (typeof newSelected !== 'boolean' || newSelected === selected) {
return;
}
selected = newSelected;
/**
* An event that fires when selected changes on this track. This allows
* the VideoTrackList that holds this track to act accordingly.
*
* > Note: This is not part of the spec! Native tracks will do
* this internally without an event.
*
* @event VideoTrack#selectedchange
* @type {EventTarget~Event}
*/
this.trigger('selectedchange');
}
});
// if the user sets this track to selected then
// set selected to that true value otherwise
// we keep it false
if (settings.selected) {
track.selected = settings.selected;
}
return _ret = track, possibleConstructorReturn(_this, _ret);
}
return VideoTrack;
}(Track);
/**
* @file html-track-element.js
*/
/**
* @memberof HTMLTrackElement
* @typedef {HTMLTrackElement~ReadyState}
* @enum {number}
*/
var NONE = 0;
var LOADING = 1;
var LOADED = 2;
var ERROR = 3;
/**
* A single track represented in the DOM.
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
* @extends EventTarget
*/
var HTMLTrackElement = function (_EventTarget) {
inherits(HTMLTrackElement, _EventTarget);
/**
* Create an instance of this class.
*
* @param {Object} options={}
* Object of option names and values
*
* @param {Tech} options.tech
* A reference to the tech that owns this HTMLTrackElement.
*
* @param {TextTrack~Kind} [options.kind='subtitles']
* A valid text track kind.
*
* @param {TextTrack~Mode} [options.mode='disabled']
* A valid text track mode.
*
* @param {string} [options.id='vjs_track_' + Guid.newGUID()]
* A unique id for this TextTrack.
*
* @param {string} [options.label='']
* The menu label for this track.
*
* @param {string} [options.language='']
* A valid two character language code.
*
* @param {string} [options.srclang='']
* A valid two character language code. An alternative, but deprioritized
* vesion of `options.language`
*
* @param {string} [options.src]
* A url to TextTrack cues.
*
* @param {boolean} [options.default]
* If this track should default to on or off.
*/
function HTMLTrackElement() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, HTMLTrackElement);
var _this = possibleConstructorReturn(this, _EventTarget.call(this));
var readyState = void 0;
var trackElement = _this; // eslint-disable-line
if (IS_IE8) {
trackElement = document.createElement('custom');
for (var prop in HTMLTrackElement.prototype) {
if (prop !== 'constructor') {
trackElement[prop] = HTMLTrackElement.prototype[prop];
}
}
}
var track = new TextTrack(options);
trackElement.kind = track.kind;
trackElement.src = track.src;
trackElement.srclang = track.language;
trackElement.label = track.label;
trackElement['default'] = track['default'];
/**
* @memberof HTMLTrackElement
* @member {HTMLTrackElement~ReadyState} readyState
* The current ready state of the track element.
* @instance
*/
Object.defineProperty(trackElement, 'readyState', {
get: function get$$1() {
return readyState;
}
});
/**
* @memberof HTMLTrackElement
* @member {TextTrack} track
* The underlying TextTrack object.
* @instance
*
*/
Object.defineProperty(trackElement, 'track', {
get: function get$$1() {
return track;
}
});
readyState = NONE;
/**
* @listens TextTrack#loadeddata
* @fires HTMLTrackElement#load
*/
track.addEventListener('loadeddata', function () {
readyState = LOADED;
trackElement.trigger({
type: 'load',
target: trackElement
});
});
if (IS_IE8) {
var _ret;
return _ret = trackElement, possibleConstructorReturn(_this, _ret);
}
return _this;
}
return HTMLTrackElement;
}(EventTarget);
HTMLTrackElement.prototype.allowedEvents_ = {
load: 'load'
};
HTMLTrackElement.NONE = NONE;
HTMLTrackElement.LOADING = LOADING;
HTMLTrackElement.LOADED = LOADED;
HTMLTrackElement.ERROR = ERROR;
/*
* This file contains all track properties that are used in
* player.js, tech.js, html5.js and possibly other techs in the future.
*/
var NORMAL = {
audio: {
ListClass: AudioTrackList,
TrackClass: AudioTrack,
capitalName: 'Audio'
},
video: {
ListClass: VideoTrackList,
TrackClass: VideoTrack,
capitalName: 'Video'
},
text: {
ListClass: TextTrackList,
TrackClass: TextTrack,
capitalName: 'Text'
}
};
Object.keys(NORMAL).forEach(function (type) {
NORMAL[type].getterName = type + 'Tracks';
NORMAL[type].privateName = type + 'Tracks_';
});
var REMOTE = {
remoteText: {
ListClass: TextTrackList,
TrackClass: TextTrack,
capitalName: 'RemoteText',
getterName: 'remoteTextTracks',
privateName: 'remoteTextTracks_'
},
remoteTextEl: {
ListClass: HtmlTrackElementList,
TrackClass: HTMLTrackElement,
capitalName: 'RemoteTextTrackEls',
getterName: 'remoteTextTrackEls',
privateName: 'remoteTextTrackEls_'
}
};
var ALL = mergeOptions(NORMAL, REMOTE);
REMOTE.names = Object.keys(REMOTE);
NORMAL.names = Object.keys(NORMAL);
ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
/**
* @file tech.js
*/
/**
* An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
* that just contains the src url alone.
* * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
* `var SourceString = 'http://example.com/some-video.mp4';`
*
* @typedef {Object|string} Tech~SourceObject
*
* @property {string} src
* The url to the source
*
* @property {string} type
* The mime type of the source
*/
/**
* A function used by {@link Tech} to create a new {@link TextTrack}.
*
* @private
*
* @param {Tech} self
* An instance of the Tech class.
*
* @param {string} kind
* `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
*
* @param {string} [label]
* Label to identify the text track
*
* @param {string} [language]
* Two letter language abbreviation
*
* @param {Object} [options={}]
* An object with additional text track options
*
* @return {TextTrack}
* The text track that was created.
*/
function createTrackHelper(self, kind, label, language) {
var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
var tracks = self.textTracks();
options.kind = kind;
if (label) {
options.label = label;
}
if (language) {
options.language = language;
}
options.tech = self;
var track = new ALL.text.TrackClass(options);
tracks.addTrack(track);
return track;
}
/**
* This is the base class for media playback technology controllers, such as
* {@link Flash} and {@link HTML5}
*
* @extends Component
*/
var Tech = function (_Component) {
inherits(Tech, _Component);
/**
* Create an instance of this Tech.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} ready
* Callback function to call when the `HTML5` Tech is ready.
*/
function Tech() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var ready = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
classCallCheck(this, Tech);
// we don't want the tech to report user activity automatically.
// This is done manually in addControlsListeners
options.reportTouchActivity = false;
// keep track of whether the current source has played at all to
// implement a very limited played()
var _this = possibleConstructorReturn(this, _Component.call(this, null, options, ready));
_this.hasStarted_ = false;
_this.on('playing', function () {
this.hasStarted_ = true;
});
_this.on('loadstart', function () {
this.hasStarted_ = false;
});
ALL.names.forEach(function (name) {
var props = ALL[name];
if (options && options[props.getterName]) {
_this[props.privateName] = options[props.getterName];
}
});
// Manually track progress in cases where the browser/flash player doesn't report it.
if (!_this.featuresProgressEvents) {
_this.manualProgressOn();
}
// Manually track timeupdates in cases where the browser/flash player doesn't report it.
if (!_this.featuresTimeupdateEvents) {
_this.manualTimeUpdatesOn();
}
['Text', 'Audio', 'Video'].forEach(function (track) {
if (options['native' + track + 'Tracks'] === false) {
_this['featuresNative' + track + 'Tracks'] = false;
}
});
if (options.nativeCaptions === false || options.nativeTextTracks === false) {
_this.featuresNativeTextTracks = false;
} else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
_this.featuresNativeTextTracks = true;
}
if (!_this.featuresNativeTextTracks) {
_this.emulateTextTracks();
}
_this.autoRemoteTextTracks_ = new ALL.text.ListClass();
_this.initTrackListeners();
// Turn on component tap events only if not using native controls
if (!options.nativeControlsForTouch) {
_this.emitTapEvents();
}
if (_this.constructor) {
_this.name_ = _this.constructor.name || 'Unknown Tech';
}
return _this;
}
/**
* A special function to trigger source set in a way that will allow player
* to re-trigger if the player or tech are not ready yet.
*
* @fires Tech#sourceset
* @param {string} src The source string at the time of the source changing.
*/
Tech.prototype.triggerSourceset = function triggerSourceset(src) {
var _this2 = this;
if (!this.isReady_) {
// on initial ready we have to trigger source set
// 1ms after ready so that player can watch for it.
this.one('ready', function () {
return _this2.setTimeout(function () {
return _this2.triggerSourceset(src);
}, 1);
});
}
/**
* Fired when the source is set on the tech causing the media element
* to reload.
*
* @see {@link Player#event:sourceset}
* @event Tech#sourceset
* @type {EventTarget~Event}
*/
this.trigger({
src: src,
type: 'sourceset'
});
};
/* Fallbacks for unsupported event types
================================================================================ */
/**
* Polyfill the `progress` event for browsers that don't support it natively.
*
* @see {@link Tech#trackProgress}
*/
Tech.prototype.manualProgressOn = function manualProgressOn() {
this.on('durationchange', this.onDurationChange);
this.manualProgress = true;
// Trigger progress watching when a source begins loading
this.one('ready', this.trackProgress);
};
/**
* Turn off the polyfill for `progress` events that was created in
* {@link Tech#manualProgressOn}
*/
Tech.prototype.manualProgressOff = function manualProgressOff() {
this.manualProgress = false;
this.stopTrackingProgress();
this.off('durationchange', this.onDurationChange);
};
/**
* This is used to trigger a `progress` event when the buffered percent changes. It
* sets an interval function that will be called every 500 milliseconds to check if the
* buffer end percent has changed.
*
* > This function is called by {@link Tech#manualProgressOn}
*
* @param {EventTarget~Event} event
* The `ready` event that caused this to run.
*
* @listens Tech#ready
* @fires Tech#progress
*/
Tech.prototype.trackProgress = function trackProgress(event) {
this.stopTrackingProgress();
this.progressInterval = this.setInterval(bind(this, function () {
// Don't trigger unless buffered amount is greater than last time
var numBufferedPercent = this.bufferedPercent();
if (this.bufferedPercent_ !== numBufferedPercent) {
/**
* See {@link Player#progress}
*
* @event Tech#progress
* @type {EventTarget~Event}
*/
this.trigger('progress');
}
this.bufferedPercent_ = numBufferedPercent;
if (numBufferedPercent === 1) {
this.stopTrackingProgress();
}
}), 500);
};
/**
* Update our internal duration on a `durationchange` event by calling
* {@link Tech#duration}.
*
* @param {EventTarget~Event} event
* The `durationchange` event that caused this to run.
*
* @listens Tech#durationchange
*/
Tech.prototype.onDurationChange = function onDurationChange(event) {
this.duration_ = this.duration();
};
/**
* Get and create a `TimeRange` object for buffering.
*
* @return {TimeRange}
* The time range object that was created.
*/
Tech.prototype.buffered = function buffered() {
return createTimeRanges(0, 0);
};
/**
* Get the percentage of the current video that is currently buffered.
*
* @return {number}
* A number from 0 to 1 that represents the decimal percentage of the
* video that is buffered.
*
*/
Tech.prototype.bufferedPercent = function bufferedPercent$$1() {
return bufferedPercent(this.buffered(), this.duration_);
};
/**
* Turn off the polyfill for `progress` events that was created in
* {@link Tech#manualProgressOn}
* Stop manually tracking progress events by clearing the interval that was set in
* {@link Tech#trackProgress}.
*/
Tech.prototype.stopTrackingProgress = function stopTrackingProgress() {
this.clearInterval(this.progressInterval);
};
/**
* Polyfill the `timeupdate` event for browsers that don't support it.
*
* @see {@link Tech#trackCurrentTime}
*/
Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
this.manualTimeUpdates = true;
this.on('play', this.trackCurrentTime);
this.on('pause', this.stopTrackingCurrentTime);
};
/**
* Turn off the polyfill for `timeupdate` events that was created in
* {@link Tech#manualTimeUpdatesOn}
*/
Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
this.manualTimeUpdates = false;
this.stopTrackingCurrentTime();
this.off('play', this.trackCurrentTime);
this.off('pause', this.stopTrackingCurrentTime);
};
/**
* Sets up an interval function to track current time and trigger `timeupdate` every
* 250 milliseconds.
*
* @listens Tech#play
* @triggers Tech#timeupdate
*/
Tech.prototype.trackCurrentTime = function trackCurrentTime() {
if (this.currentTimeInterval) {
this.stopTrackingCurrentTime();
}
this.currentTimeInterval = this.setInterval(function () {
/**
* Triggered at an interval of 250ms to indicated that time is passing in the video.
*
* @event Tech#timeupdate
* @type {EventTarget~Event}
*/
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
// 42 = 24 fps // 250 is what Webkit uses // FF uses 15
}, 250);
};
/**
* Stop the interval function created in {@link Tech#trackCurrentTime} so that the
* `timeupdate` event is no longer triggered.
*
* @listens {Tech#pause}
*/
Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() {
this.clearInterval(this.currentTimeInterval);
// #1002 - if the video ends right before the next timeupdate would happen,
// the progress bar won't make it all the way to the end
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
};
/**
* Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
* {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
*
* @fires Component#dispose
*/
Tech.prototype.dispose = function dispose() {
// clear out all tracks because we can't reuse them between techs
this.clearTracks(NORMAL.names);
// Turn off any manual progress or timeupdate tracking
if (this.manualProgress) {
this.manualProgressOff();
}
if (this.manualTimeUpdates) {
this.manualTimeUpdatesOff();
}
_Component.prototype.dispose.call(this);
};
/**
* Clear out a single `TrackList` or an array of `TrackLists` given their names.
*
* > Note: Techs without source handlers should call this between sources for `video`
* & `audio` tracks. You don't want to use them between tracks!
*
* @param {string[]|string} types
* TrackList names to clear, valid names are `video`, `audio`, and
* `text`.
*/
Tech.prototype.clearTracks = function clearTracks(types) {
var _this3 = this;
types = [].concat(types);
// clear out all tracks because we can't reuse them between techs
types.forEach(function (type) {
var list = _this3[type + 'Tracks']() || [];
var i = list.length;
while (i--) {
var track = list[i];
if (type === 'text') {
_this3.removeRemoteTextTrack(track);
}
list.removeTrack(track);
}
});
};
/**
* Remove any TextTracks added via addRemoteTextTrack that are
* flagged for automatic garbage collection
*/
Tech.prototype.cleanupAutoTextTracks = function cleanupAutoTextTracks() {
var list = this.autoRemoteTextTracks_ || [];
var i = list.length;
while (i--) {
var track = list[i];
this.removeRemoteTextTrack(track);
}
};
/**
* Reset the tech, which will removes all sources and reset the internal readyState.
*
* @abstract
*/
Tech.prototype.reset = function reset() {};
/**
* Get or set an error on the Tech.
*
* @param {MediaError} [err]
* Error to set on the Tech
*
* @return {MediaError|null}
* The current error object on the tech, or null if there isn't one.
*/
Tech.prototype.error = function error(err) {
if (err !== undefined) {
this.error_ = new MediaError(err);
this.trigger('error');
}
return this.error_;
};
/**
* Returns the `TimeRange`s that have been played through for the current source.
*
* > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
* It only checks wether the source has played at all or not.
*
* @return {TimeRange}
* - A single time range if this video has played
* - An empty set of ranges if not.
*/
Tech.prototype.played = function played() {
if (this.hasStarted_) {
return createTimeRanges(0, 0);
}
return createTimeRanges();
};
/**
* Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
* previously called.
*
* @fires Tech#timeupdate
*/
Tech.prototype.setCurrentTime = function setCurrentTime() {
// improve the accuracy of manual timeupdates
if (this.manualTimeUpdates) {
/**
* A manual `timeupdate` event.
*
* @event Tech#timeupdate
* @type {EventTarget~Event}
*/
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
}
};
/**
* Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
* {@link TextTrackList} events.
*
* This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
*
* @fires Tech#audiotrackchange
* @fires Tech#videotrackchange
* @fires Tech#texttrackchange
*/
Tech.prototype.initTrackListeners = function initTrackListeners() {
var _this4 = this;
/**
* Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
*
* @event Tech#audiotrackchange
* @type {EventTarget~Event}
*/
/**
* Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
*
* @event Tech#videotrackchange
* @type {EventTarget~Event}
*/
/**
* Triggered when tracks are added or removed on the Tech {@link TextTrackList}
*
* @event Tech#texttrackchange
* @type {EventTarget~Event}
*/
NORMAL.names.forEach(function (name) {
var props = NORMAL[name];
var trackListChanges = function trackListChanges() {
_this4.trigger(name + 'trackchange');
};
var tracks = _this4[props.getterName]();
tracks.addEventListener('removetrack', trackListChanges);
tracks.addEventListener('addtrack', trackListChanges);
_this4.on('dispose', function () {
tracks.removeEventListener('removetrack', trackListChanges);
tracks.removeEventListener('addtrack', trackListChanges);
});
});
};
/**
* Emulate TextTracks using vtt.js if necessary
*
* @fires Tech#vttjsloaded
* @fires Tech#vttjserror
*/
Tech.prototype.addWebVttScript_ = function addWebVttScript_() {
var _this5 = this;
if (window.WebVTT) {
return;
}
// Initially, Tech.el_ is a child of a dummy-div wait until the Component system
// signals that the Tech is ready at which point Tech.el_ is part of the DOM
// before inserting the WebVTT script
if (document.body.contains(this.el())) {
// load via require if available and vtt.js script location was not passed in
// as an option. novtt builds will turn the above require call into an empty object
// which will cause this if check to always fail.
if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) {
this.trigger('vttjsloaded');
return;
}
// load vtt.js via the script location option or the cdn of no location was
// passed in
var script = document.createElement('script');
script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.12.4/vtt.min.js';
script.onload = function () {
/**
* Fired when vtt.js is loaded.
*
* @event Tech#vttjsloaded
* @type {EventTarget~Event}
*/
_this5.trigger('vttjsloaded');
};
script.onerror = function () {
/**
* Fired when vtt.js was not loaded due to an error
*
* @event Tech#vttjsloaded
* @type {EventTarget~Event}
*/
_this5.trigger('vttjserror');
};
this.on('dispose', function () {
script.onload = null;
script.onerror = null;
});
// but have not loaded yet and we set it to true before the inject so that
// we don't overwrite the injected window.WebVTT if it loads right away
window.WebVTT = true;
this.el().parentNode.appendChild(script);
} else {
this.ready(this.addWebVttScript_);
}
};
/**
* Emulate texttracks
*
*/
Tech.prototype.emulateTextTracks = function emulateTextTracks() {
var _this6 = this;
var tracks = this.textTracks();
var remoteTracks = this.remoteTextTracks();
var handleAddTrack = function handleAddTrack(e) {
return tracks.addTrack(e.track);
};
var handleRemoveTrack = function handleRemoveTrack(e) {
return tracks.removeTrack(e.track);
};
remoteTracks.on('addtrack', handleAddTrack);
remoteTracks.on('removetrack', handleRemoveTrack);
this.addWebVttScript_();
var updateDisplay = function updateDisplay() {
return _this6.trigger('texttrackchange');
};
var textTracksChanges = function textTracksChanges() {
updateDisplay();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.removeEventListener('cuechange', updateDisplay);
if (track.mode === 'showing') {
track.addEventListener('cuechange', updateDisplay);
}
}
};
textTracksChanges();
tracks.addEventListener('change', textTracksChanges);
tracks.addEventListener('addtrack', textTracksChanges);
tracks.addEventListener('removetrack', textTracksChanges);
this.on('dispose', function () {
remoteTracks.off('addtrack', handleAddTrack);
remoteTracks.off('removetrack', handleRemoveTrack);
tracks.removeEventListener('change', textTracksChanges);
tracks.removeEventListener('addtrack', textTracksChanges);
tracks.removeEventListener('removetrack', textTracksChanges);
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.removeEventListener('cuechange', updateDisplay);
}
});
};
/**
* Create and returns a remote {@link TextTrack} object.
*
* @param {string} kind
* `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
*
* @param {string} [label]
* Label to identify the text track
*
* @param {string} [language]
* Two letter language abbreviation
*
* @return {TextTrack}
* The TextTrack that gets created.
*/
Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!kind) {
throw new Error('TextTrack kind is required but was not provided');
}
return createTrackHelper(this, kind, label, language);
};
/**
* Create an emulated TextTrack for use by addRemoteTextTrack
*
* This is intended to be overridden by classes that inherit from
* Tech in order to create native or custom TextTracks.
*
* @param {Object} options
* The object should contain the options to initialize the TextTrack with.
*
* @param {string} [options.kind]
* `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
*
* @param {string} [options.label].
* Label to identify the text track
*
* @param {string} [options.language]
* Two letter language abbreviation.
*
* @return {HTMLTrackElement}
* The track element that gets created.
*/
Tech.prototype.createRemoteTextTrack = function createRemoteTextTrack(options) {
var track = mergeOptions(options, {
tech: this
});
return new REMOTE.remoteTextEl.TrackClass(track);
};
/**
* Creates a remote text track object and returns an html track element.
*
* > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
*
* @param {Object} options
* See {@link Tech#createRemoteTextTrack} for more detailed properties.
*
* @param {boolean} [manualCleanup=true]
* - When false: the TextTrack will be automatically removed from the video
* element whenever the source changes
* - When True: The TextTrack will have to be cleaned up manually
*
* @return {HTMLTrackElement}
* An Html Track Element.
*
* @deprecated The default functionality for this function will be equivalent
* to "manualCleanup=false" in the future. The manualCleanup parameter will
* also be removed.
*/
Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack() {
var _this7 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var manualCleanup = arguments[1];
var htmlTrackElement = this.createRemoteTextTrack(options);
if (manualCleanup !== true && manualCleanup !== false) {
// deprecation warning
log.warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js');
manualCleanup = true;
}
// store HTMLTrackElement and TextTrack to remote list
this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
this.remoteTextTracks().addTrack(htmlTrackElement.track);
if (manualCleanup !== true) {
// create the TextTrackList if it doesn't exist
this.ready(function () {
return _this7.autoRemoteTextTracks_.addTrack(htmlTrackElement.track);
});
}
return htmlTrackElement;
};
/**
* Remove a remote text track from the remote `TextTrackList`.
*
* @param {TextTrack} track
* `TextTrack` to remove from the `TextTrackList`
*/
Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
// remove HTMLTrackElement and TextTrack from remote list
this.remoteTextTrackEls().removeTrackElement_(trackElement);
this.remoteTextTracks().removeTrack(track);
this.autoRemoteTextTracks_.removeTrack(track);
};
/**
* Gets available media playback quality metrics as specified by the W3C's Media
* Playback Quality API.
*
* @see [Spec]{@link https://wicg.github.io/media-playback-quality}
*
* @return {Object}
* An object with supported media playback quality metrics
*
* @abstract
*/
Tech.prototype.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
return {};
};
/**
* A method to set a poster from a `Tech`.
*
* @abstract
*/
Tech.prototype.setPoster = function setPoster() {};
/**
* A method to check for the presence of the 'playsinine' <video> attribute.
*
* @abstract
*/
Tech.prototype.playsinline = function playsinline() {};
/**
* A method to set or unset the 'playsinine' <video> attribute.
*
* @abstract
*/
Tech.prototype.setPlaysinline = function setPlaysinline() {};
/*
* Check if the tech can support the given mime-type.
*
* The base tech does not support any type, but source handlers might
* overwrite this.
*
* @param {string} type
* The mimetype to check for support
*
* @return {string}
* 'probably', 'maybe', or empty string
*
* @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
*
* @abstract
*/
Tech.prototype.canPlayType = function canPlayType() {
return '';
};
/**
* Check if the type is supported by this tech.
*
* The base tech does not support any type, but source handlers might
* overwrite this.
*
* @param {string} type
* The media type to check
* @return {string} Returns the native video element's response
*/
Tech.canPlayType = function canPlayType() {
return '';
};
/**
* Check if the tech can support the given source
* @param {Object} srcObj
* The source object
* @param {Object} options
* The options passed to the tech
* @return {string} 'probably', 'maybe', or '' (empty string)
*/
Tech.canPlaySource = function canPlaySource(srcObj, options) {
return Tech.canPlayType(srcObj.type);
};
/*
* Return whether the argument is a Tech or not.
* Can be passed either a Class like `Html5` or a instance like `player.tech_`
*
* @param {Object} component
* The item to check
*
* @return {boolean}
* Whether it is a tech or not
* - True if it is a tech
* - False if it is not
*/
Tech.isTech = function isTech(component) {
return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
};
/**
* Registers a `Tech` into a shared list for videojs.
*
* @param {string} name
* Name of the `Tech` to register.
*
* @param {Object} tech
* The `Tech` class to register.
*/
Tech.registerTech = function registerTech(name, tech) {
if (!Tech.techs_) {
Tech.techs_ = {};
}
if (!Tech.isTech(tech)) {
throw new Error('Tech ' + name + ' must be a Tech');
}
if (!Tech.canPlayType) {
throw new Error('Techs must have a static canPlayType method on them');
}
if (!Tech.canPlaySource) {
throw new Error('Techs must have a static canPlaySource method on them');
}
name = toTitleCase(name);
Tech.techs_[name] = tech;
if (name !== 'Tech') {
// camel case the techName for use in techOrder
Tech.defaultTechOrder_.push(name);
}
return tech;
};
/**
* Get a `Tech` from the shared list by name.
*
* @param {string} name
* `camelCase` or `TitleCase` name of the Tech to get
*
* @return {Tech|undefined}
* The `Tech` or undefined if there was no tech with the name requsted.
*/
Tech.getTech = function getTech(name) {
if (!name) {
return;
}
name = toTitleCase(name);
if (Tech.techs_ && Tech.techs_[name]) {
return Tech.techs_[name];
}
if (window && window.videojs && window.videojs[name]) {
log.warn('The ' + name + ' tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)');
return window.videojs[name];
}
};
return Tech;
}(Component);
/**
* Get the {@link VideoTrackList}
*
* @returns {VideoTrackList}
* @method Tech.prototype.videoTracks
*/
/**
* Get the {@link AudioTrackList}
*
* @returns {AudioTrackList}
* @method Tech.prototype.audioTracks
*/
/**
* Get the {@link TextTrackList}
*
* @returns {TextTrackList}
* @method Tech.prototype.textTracks
*/
/**
* Get the remote element {@link TextTrackList}
*
* @returns {TextTrackList}
* @method Tech.prototype.remoteTextTracks
*/
/**
* Get the remote element {@link HtmlTrackElementList}
*
* @returns {HtmlTrackElementList}
* @method Tech.prototype.remoteTextTrackEls
*/
ALL.names.forEach(function (name) {
var props = ALL[name];
Tech.prototype[props.getterName] = function () {
this[props.privateName] = this[props.privateName] || new props.ListClass();
return this[props.privateName];
};
});
/**
* List of associated text tracks
*
* @type {TextTrackList}
* @private
* @property Tech#textTracks_
*/
/**
* List of associated audio tracks.
*
* @type {AudioTrackList}
* @private
* @property Tech#audioTracks_
*/
/**
* List of associated video tracks.
*
* @type {VideoTrackList}
* @private
* @property Tech#videoTracks_
*/
/**
* Boolean indicating wether the `Tech` supports volume control.
*
* @type {boolean}
* @default
*/
Tech.prototype.featuresVolumeControl = true;
/**
* Boolean indicating whether the `Tech` supports muting volume.
*
* @type {bolean}
* @default
*/
Tech.prototype.featuresMuteControl = true;
/**
* Boolean indicating whether the `Tech` supports fullscreen resize control.
* Resizing plugins using request fullscreen reloads the plugin
*
* @type {boolean}
* @default
*/
Tech.prototype.featuresFullscreenResize = false;
/**
* Boolean indicating wether the `Tech` supports changing the speed at which the video
* plays. Examples:
* - Set player to play 2x (twice) as fast
* - Set player to play 0.5x (half) as fast
*
* @type {boolean}
* @default
*/
Tech.prototype.featuresPlaybackRate = false;
/**
* Boolean indicating wether the `Tech` supports the `progress` event. This is currently
* not triggered by video-js-swf. This will be used to determine if
* {@link Tech#manualProgressOn} should be called.
*
* @type {boolean}
* @default
*/
Tech.prototype.featuresProgressEvents = false;
/**
* Boolean indicating wether the `Tech` supports the `sourceset` event.
*
* A tech should set this to `true` and then use {@link Tech#triggerSourceset}
* to trigger a {@link Tech#event:sourceset} at the earliest time after getting
* a new source.
*
* @type {boolean}
* @default
*/
Tech.prototype.featuresSourceset = false;
/**
* Boolean indicating wether the `Tech` supports the `timeupdate` event. This is currently
* not triggered by video-js-swf. This will be used to determine if
* {@link Tech#manualTimeUpdates} should be called.
*
* @type {boolean}
* @default
*/
Tech.prototype.featuresTimeupdateEvents = false;
/**
* Boolean indicating wether the `Tech` supports the native `TextTrack`s.
* This will help us integrate with native `TextTrack`s if the browser supports them.
*
* @type {boolean}
* @default
*/
Tech.prototype.featuresNativeTextTracks = false;
/**
* A functional mixin for techs that want to use the Source Handler pattern.
* Source handlers are scripts for handling specific formats.
* The source handler pattern is used for adaptive formats (HLS, DASH) that
* manually load video data and feed it into a Source Buffer (Media Source Extensions)
* Example: `Tech.withSourceHandlers.call(MyTech);`
*
* @param {Tech} _Tech
* The tech to add source handler functions to.
*
* @mixes Tech~SourceHandlerAdditions
*/
Tech.withSourceHandlers = function (_Tech) {
/**
* Register a source handler
*
* @param {Function} handler
* The source handler class
*
* @param {number} [index]
* Register it at the following index
*/
_Tech.registerSourceHandler = function (handler, index) {
var handlers = _Tech.sourceHandlers;
if (!handlers) {
handlers = _Tech.sourceHandlers = [];
}
if (index === undefined) {
// add to the end of the list
index = handlers.length;
}
handlers.splice(index, 0, handler);
};
/**
* Check if the tech can support the given type. Also checks the
* Techs sourceHandlers.
*
* @param {string} type
* The mimetype to check.
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
_Tech.canPlayType = function (type) {
var handlers = _Tech.sourceHandlers || [];
var can = void 0;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canPlayType(type);
if (can) {
return can;
}
}
return '';
};
/**
* Returns the first source handler that supports the source.
*
* TODO: Answer question: should 'probably' be prioritized over 'maybe'
*
* @param {Tech~SourceObject} source
* The source object
*
* @param {Object} options
* The options passed to the tech
*
* @return {SourceHandler|null}
* The first source handler that supports the source or null if
* no SourceHandler supports the source
*/
_Tech.selectSourceHandler = function (source, options) {
var handlers = _Tech.sourceHandlers || [];
var can = void 0;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canHandleSource(source, options);
if (can) {
return handlers[i];
}
}
return null;
};
/**
* Check if the tech can support the given source.
*
* @param {Tech~SourceObject} srcObj
* The source object
*
* @param {Object} options
* The options passed to the tech
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
_Tech.canPlaySource = function (srcObj, options) {
var sh = _Tech.selectSourceHandler(srcObj, options);
if (sh) {
return sh.canHandleSource(srcObj, options);
}
return '';
};
/**
* When using a source handler, prefer its implementation of
* any function normally provided by the tech.
*/
var deferrable = ['seekable', 'seeking', 'duration'];
/**
* A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
* function if it exists, with a fallback to the Techs seekable function.
*
* @method _Tech.seekable
*/
/**
* A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
* function if it exists, otherwise it will fallback to the techs duration function.
*
* @method _Tech.duration
*/
deferrable.forEach(function (fnName) {
var originalFn = this[fnName];
if (typeof originalFn !== 'function') {
return;
}
this[fnName] = function () {
if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
}
return originalFn.apply(this, arguments);
};
}, _Tech.prototype);
/**
* Create a function for setting the source using a source object
* and source handlers.
* Should never be called unless a source handler was found.
*
* @param {Tech~SourceObject} source
* A source object with src and type keys
*/
_Tech.prototype.setSource = function (source) {
var sh = _Tech.selectSourceHandler(source, this.options_);
if (!sh) {
// Fall back to a native source hander when unsupported sources are
// deliberately set
if (_Tech.nativeSourceHandler) {
sh = _Tech.nativeSourceHandler;
} else {
log.error('No source hander found for the current source.');
}
}
// Dispose any existing source handler
this.disposeSourceHandler();
this.off('dispose', this.disposeSourceHandler);
if (sh !== _Tech.nativeSourceHandler) {
this.currentSource_ = source;
}
this.sourceHandler_ = sh.handleSource(source, this, this.options_);
this.on('dispose', this.disposeSourceHandler);
};
/**
* Clean up any existing SourceHandlers and listeners when the Tech is disposed.
*
* @listens Tech#dispose
*/
_Tech.prototype.disposeSourceHandler = function () {
// if we have a source and get another one
// then we are loading something new
// than clear all of our current tracks
if (this.currentSource_) {
this.clearTracks(['audio', 'video']);
this.currentSource_ = null;
}
// always clean up auto-text tracks
this.cleanupAutoTextTracks();
if (this.sourceHandler_) {
if (this.sourceHandler_.dispose) {
this.sourceHandler_.dispose();
}
this.sourceHandler_ = null;
}
};
};
// The base Tech class needs to be registered as a Component. It is the only
// Tech that can be registered as a Component.
Component.registerComponent('Tech', Tech);
Tech.registerTech('Tech', Tech);
/**
* A list of techs that should be added to techOrder on Players
*
* @private
*/
Tech.defaultTechOrder_ = [];
var middlewares = {};
var middlewareInstances = {};
var TERMINATOR = {};
function use(type, middleware) {
middlewares[type] = middlewares[type] || [];
middlewares[type].push(middleware);
}
function setSource(player, src, next) {
player.setTimeout(function () {
return setSourceHelper(src, middlewares[src.type], next, player);
}, 1);
}
function setTech(middleware, tech) {
middleware.forEach(function (mw) {
return mw.setTech && mw.setTech(tech);
});
}
/**
* Calls a getter on the tech first, through each middleware
* from right to left to the player.
*/
function get$1(middleware, tech, method) {
return middleware.reduceRight(middlewareIterator(method), tech[method]());
}
/**
* Takes the argument given to the player and calls the setter method on each
* middlware from left to right to the tech.
*/
function set$1(middleware, tech, method, arg) {
return tech[method](middleware.reduce(middlewareIterator(method), arg));
}
/**
* Takes the argument given to the player and calls the `call` version of the method
* on each middleware from left to right.
* Then, call the passed in method on the tech and return the result unchanged
* back to the player, through middleware, this time from right to left.
*/
function mediate(middleware, tech, method) {
var arg = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var callMethod = 'call' + toTitleCase(method);
var middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
var terminated = middlewareValue === TERMINATOR;
var returnValue = terminated ? null : tech[method](middlewareValue);
executeRight(middleware, method, returnValue, terminated);
return returnValue;
}
var allowedGetters = {
buffered: 1,
currentTime: 1,
duration: 1,
seekable: 1,
played: 1,
paused: 1
};
var allowedSetters = {
setCurrentTime: 1
};
var allowedMediators = {
play: 1,
pause: 1
};
function middlewareIterator(method) {
return function (value, mw) {
// if the previous middleware terminated, pass along the termination
if (value === TERMINATOR) {
return TERMINATOR;
}
if (mw[method]) {
return mw[method](value);
}
return value;
};
}
function executeRight(mws, method, value, terminated) {
for (var i = mws.length - 1; i >= 0; i--) {
var mw = mws[i];
if (mw[method]) {
mw[method](terminated, value);
}
}
}
function clearCacheForPlayer(player) {
middlewareInstances[player.id()] = null;
}
/**
* {
* [playerId]: [[mwFactory, mwInstance], ...]
* }
*/
function getOrCreateFactory(player, mwFactory) {
var mws = middlewareInstances[player.id()];
var mw = null;
if (mws === undefined || mws === null) {
mw = mwFactory(player);
middlewareInstances[player.id()] = [[mwFactory, mw]];
return mw;
}
for (var i = 0; i < mws.length; i++) {
var _mws$i = mws[i],
mwf = _mws$i[0],
mwi = _mws$i[1];
if (mwf !== mwFactory) {
continue;
}
mw = mwi;
}
if (mw === null) {
mw = mwFactory(player);
mws.push([mwFactory, mw]);
}
return mw;
}
function setSourceHelper() {
var src = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var middleware = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var next = arguments[2];
var player = arguments[3];
var acc = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
var lastRun = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var mwFactory = middleware[0],
mwrest = middleware.slice(1);
// if mwFactory is a string, then we're at a fork in the road
if (typeof mwFactory === 'string') {
setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
// if we have an mwFactory, call it with the player to get the mw,
// then call the mw's setSource method
} else if (mwFactory) {
var mw = getOrCreateFactory(player, mwFactory);
// if setSource isn't present, implicitly select this middleware
if (!mw.setSource) {
acc.push(mw);
return setSourceHelper(src, mwrest, next, player, acc, lastRun);
}
mw.setSource(assign({}, src), function (err, _src) {
// something happened, try the next middleware on the current level
// make sure to use the old src
if (err) {
return setSourceHelper(src, mwrest, next, player, acc, lastRun);
}
// we've succeeded, now we need to go deeper
acc.push(mw);
// if it's the same type, continue down the current chain
// otherwise, we want to go down the new chain
setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
});
} else if (mwrest.length) {
setSourceHelper(src, mwrest, next, player, acc, lastRun);
} else if (lastRun) {
next(src, acc);
} else {
setSourceHelper(src, middlewares['*'], next, player, acc, true);
}
}
/**
* Mimetypes
*
* @see http://hul.harvard.edu/ois/////systems/wax/wax-public-help/mimetypes.htm
* @typedef Mimetypes~Kind
* @enum
*/
var MimetypesKind = {
opus: 'video/ogg',
ogv: 'video/ogg',
mp4: 'video/mp4',
mov: 'video/mp4',
m4v: 'video/mp4',
mkv: 'video/x-matroska',
mp3: 'audio/mpeg',
aac: 'audio/aac',
oga: 'audio/ogg',
m3u8: 'application/x-mpegURL'
};
/**
* Get the mimetype of a given src url if possible
*
* @param {string} src
* The url to the src
*
* @return {string}
* return the mimetype if it was known or empty string otherwise
*/
var getMimetype = function getMimetype() {
var src = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var ext = getFileExtension(src);
var mimetype = MimetypesKind[ext.toLowerCase()];
return mimetype || '';
};
/**
* Find the mime type of a given source string if possible. Uses the player
* source cache.
*
* @param {Player} player
* The player object
*
* @param {string} src
* The source string
*
* @return {string}
* The type that was found
*/
var findMimetype = function findMimetype(player, src) {
if (!src) {
return '';
}
// 1. check for the type in the `source` cache
if (player.cache_.source.src === src && player.cache_.source.type) {
return player.cache_.source.type;
}
// 2. see if we have this source in our `currentSources` cache
var matchingSources = player.cache_.sources.filter(function (s) {
return s.src === src;
});
if (matchingSources.length) {
return matchingSources[0].type;
}
// 3. look for the src url in source elements and use the type there
var sources = player.$$('source');
for (var i = 0; i < sources.length; i++) {
var s = sources[i];
if (s.type && s.src && s.src === src) {
return s.type;
}
}
// 4. finally fallback to our list of mime types based on src url extension
return getMimetype(src);
};
/**
* @module filter-source
*/
/**
* Filter out single bad source objects or multiple source objects in an
* array. Also flattens nested source object arrays into a 1 dimensional
* array of source objects.
*
* @param {Tech~SourceObject|Tech~SourceObject[]} src
* The src object to filter
*
* @return {Tech~SourceObject[]}
* An array of sourceobjects containing only valid sources
*
* @private
*/
var filterSource = function filterSource(src) {
// traverse array
if (Array.isArray(src)) {
var newsrc = [];
src.forEach(function (srcobj) {
srcobj = filterSource(srcobj);
if (Array.isArray(srcobj)) {
newsrc = newsrc.concat(srcobj);
} else if (isObject(srcobj)) {
newsrc.push(srcobj);
}
});
src = newsrc;
} else if (typeof src === 'string' && src.trim()) {
// convert string into object
src = [fixSource({ src: src })];
} else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
// src is already valid
src = [fixSource(src)];
} else {
// invalid source, turn it into an empty array
src = [];
}
return src;
};
/**
* Checks src mimetype, adding it when possible
*
* @param {Tech~SourceObject} src
* The src object to check
* @return {Tech~SourceObject}
* src Object with known type
*/
function fixSource(src) {
var mimetype = getMimetype(src.src);
if (!src.type && mimetype) {
src.type = mimetype;
}
return src;
}
/**
* @file loader.js
*/
/**
* The `MediaLoader` is the `Component` that decides which playback technology to load
* when a player is initialized.
*
* @extends Component
*/
var MediaLoader = function (_Component) {
inherits(MediaLoader, _Component);
/**
* Create an instance of this class.
*
* @param {Player} player
* The `Player` that this class should attach to.
*
* @param {Object} [options]
* The key/value stroe of player options.
*
* @param {Component~ReadyCallback} [ready]
* The function that is run when this component is ready.
*/
function MediaLoader(player, options, ready) {
classCallCheck(this, MediaLoader);
// MediaLoader has no element
var options_ = mergeOptions({ createEl: false }, options);
// If there are no sources when the player is initialized,
// load the first supported playback technology.
var _this = possibleConstructorReturn(this, _Component.call(this, player, options_, ready));
if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
var techName = toTitleCase(j[i]);
var tech = Tech.getTech(techName);
// Support old behavior of techs being registered as components.
// Remove once that deprecated behavior is removed.
if (!techName) {
tech = Component.getComponent(techName);
}
// Check if the browser supports this technology
if (tech && tech.isSupported()) {
player.loadTech_(techName);
break;
}
}
} else {
// Loop through playback technologies (HTML5, Flash) and check for support.
// Then load the best source.
// A few assumptions here:
// All playback technologies respect preload false.
player.src(options.playerOptions.sources);
}
return _this;
}
return MediaLoader;
}(Component);
Component.registerComponent('MediaLoader', MediaLoader);
/**
* @file button.js
*/
/**
* Clickable Component which is clickable or keyboard actionable,
* but is not a native HTML button.
*
* @extends Component
*/
var ClickableComponent = function (_Component) {
inherits(ClickableComponent, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function ClickableComponent(player, options) {
classCallCheck(this, ClickableComponent);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.emitTapEvents();
_this.enable();
return _this;
}
/**
* Create the `Component`s DOM element.
*
* @param {string} [tag=div]
* The element's node type.
*
* @param {Object} [props={}]
* An object of properties that should be set on the element.
*
* @param {Object} [attributes={}]
* An object of attributes that should be set on the element.
*
* @return {Element}
* The element that gets created.
*/
ClickableComponent.prototype.createEl = function createEl$$1() {
var tag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div';
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
props = assign({
innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>',
className: this.buildCSSClass(),
tabIndex: 0
}, props);
if (tag === 'button') {
log.error('Creating a ClickableComponent with an HTML element of ' + tag + ' is not supported; use a Button instead.');
}
// Add ARIA attributes for clickable element which is not a native HTML button
attributes = assign({
role: 'button'
}, attributes);
this.tabIndex_ = props.tabIndex;
var el = _Component.prototype.createEl.call(this, tag, props, attributes);
this.createControlTextEl(el);
return el;
};
ClickableComponent.prototype.dispose = function dispose() {
// remove controlTextEl_ on dipose
this.controlTextEl_ = null;
_Component.prototype.dispose.call(this);
};
/**
* Create a control text element on this `Component`
*
* @param {Element} [el]
* Parent element for the control text.
*
* @return {Element}
* The control text element that gets created.
*/
ClickableComponent.prototype.createControlTextEl = function createControlTextEl(el) {
this.controlTextEl_ = createEl('span', {
className: 'vjs-control-text'
}, {
// let the screen reader user know that the text of the element may change
'aria-live': 'polite'
});
if (el) {
el.appendChild(this.controlTextEl_);
}
this.controlText(this.controlText_, el);
return this.controlTextEl_;
};
/**
* Get or set the localize text to use for the controls on the `Component`.
*
* @param {string} [text]
* Control text for element.
*
* @param {Element} [el=this.el()]
* Element to set the title on.
*
* @return {string}
* - The control text when getting
*/
ClickableComponent.prototype.controlText = function controlText(text) {
var el = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.el();
if (text === undefined) {
return this.controlText_ || 'Need Text';
}
var localizedText = this.localize(text);
this.controlText_ = text;
textContent(this.controlTextEl_, localizedText);
if (!this.nonIconControl) {
// Set title attribute if only an icon is shown
el.setAttribute('title', localizedText);
}
};
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
ClickableComponent.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Enable this `Component`s element.
*/
ClickableComponent.prototype.enable = function enable() {
if (!this.enabled_) {
this.enabled_ = true;
this.removeClass('vjs-disabled');
this.el_.setAttribute('aria-disabled', 'false');
if (typeof this.tabIndex_ !== 'undefined') {
this.el_.setAttribute('tabIndex', this.tabIndex_);
}
this.on(['tap', 'click'], this.handleClick);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
}
};
/**
* Disable this `Component`s element.
*/
ClickableComponent.prototype.disable = function disable() {
this.enabled_ = false;
this.addClass('vjs-disabled');
this.el_.setAttribute('aria-disabled', 'true');
if (typeof this.tabIndex_ !== 'undefined') {
this.el_.removeAttribute('tabIndex');
}
this.off(['tap', 'click'], this.handleClick);
this.off('focus', this.handleFocus);
this.off('blur', this.handleBlur);
};
/**
* This gets called when a `ClickableComponent` gets:
* - Clicked (via the `click` event, listening starts in the constructor)
* - Tapped (via the `tap` event, listening starts in the constructor)
* - The following things happen in order:
* 1. {@link ClickableComponent#handleFocus} is called via a `focus` event on the
* `ClickableComponent`.
* 2. {@link ClickableComponent#handleFocus} adds a listener for `keydown` on using
* {@link ClickableComponent#handleKeyPress}.
* 3. `ClickableComponent` has not had a `blur` event (`blur` means that focus was lost). The user presses
* the space or enter key.
* 4. {@link ClickableComponent#handleKeyPress} calls this function with the `keydown`
* event as a parameter.
*
* @param {EventTarget~Event} event
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
* @abstract
*/
ClickableComponent.prototype.handleClick = function handleClick(event) {};
/**
* This gets called when a `ClickableComponent` gains focus via a `focus` event.
* Turns on listening for `keydown` events. When they happen it
* calls `this.handleKeyPress`.
*
* @param {EventTarget~Event} event
* The `focus` event that caused this function to be called.
*
* @listens focus
*/
ClickableComponent.prototype.handleFocus = function handleFocus(event) {
on(document, 'keydown', bind(this, this.handleKeyPress));
};
/**
* Called when this ClickableComponent has focus and a key gets pressed down. By
* default it will call `this.handleClick` when the key is space or enter.
*
* @param {EventTarget~Event} event
* The `keydown` event that caused this function to be called.
*
* @listens keydown
*/
ClickableComponent.prototype.handleKeyPress = function handleKeyPress(event) {
// Support Space (32) or Enter (13) key operation to fire a click event
if (event.which === 32 || event.which === 13) {
event.preventDefault();
this.trigger('click');
} else if (_Component.prototype.handleKeyPress) {
// Pass keypress handling up for unsupported keys
_Component.prototype.handleKeyPress.call(this, event);
}
};
/**
* Called when a `ClickableComponent` loses focus. Turns off the listener for
* `keydown` events. Which Stops `this.handleKeyPress` from getting called.
*
* @param {EventTarget~Event} event
* The `blur` event that caused this function to be called.
*
* @listens blur
*/
ClickableComponent.prototype.handleBlur = function handleBlur(event) {
off(document, 'keydown', bind(this, this.handleKeyPress));
};
return ClickableComponent;
}(Component);
Component.registerComponent('ClickableComponent', ClickableComponent);
/**
* @file poster-image.js
*/
/**
* A `ClickableComponent` that handles showing the poster image for the player.
*
* @extends ClickableComponent
*/
var PosterImage = function (_ClickableComponent) {
inherits(PosterImage, _ClickableComponent);
/**
* Create an instance of this class.
*
* @param {Player} player
* The `Player` that this class should attach to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function PosterImage(player, options) {
classCallCheck(this, PosterImage);
var _this = possibleConstructorReturn(this, _ClickableComponent.call(this, player, options));
_this.update();
player.on('posterchange', bind(_this, _this.update));
return _this;
}
/**
* Clean up and dispose of the `PosterImage`.
*/
PosterImage.prototype.dispose = function dispose() {
this.player().off('posterchange', this.update);
_ClickableComponent.prototype.dispose.call(this);
};
/**
* Create the `PosterImage`s DOM element.
*
* @return {Element}
* The element that gets created.
*/
PosterImage.prototype.createEl = function createEl$$1() {
var el = createEl('div', {
className: 'vjs-poster',
// Don't want poster to be tabbable.
tabIndex: -1
});
// To ensure the poster image resizes while maintaining its original aspect
// ratio, use a div with `background-size` when available. For browsers that
// do not support `background-size` (e.g. IE8), fall back on using a regular
// img element.
if (!BACKGROUND_SIZE_SUPPORTED) {
this.fallbackImg_ = createEl('img');
el.appendChild(this.fallbackImg_);
}
return el;
};
/**
* An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
*
* @listens Player#posterchange
*
* @param {EventTarget~Event} [event]
* The `Player#posterchange` event that triggered this function.
*/
PosterImage.prototype.update = function update(event) {
var url = this.player().poster();
this.setSrc(url);
// If there's no poster source we should display:none on this component
// so it's not still clickable or right-clickable
if (url) {
this.show();
} else {
this.hide();
}
};
/**
* Set the source of the `PosterImage` depending on the display method.
*
* @param {string} url
* The URL to the source for the `PosterImage`.
*/
PosterImage.prototype.setSrc = function setSrc(url) {
if (this.fallbackImg_) {
this.fallbackImg_.src = url;
} else {
var backgroundImage = '';
// Any falsey values should stay as an empty string, otherwise
// this will throw an extra error
if (url) {
backgroundImage = 'url("' + url + '")';
}
this.el_.style.backgroundImage = backgroundImage;
}
};
/**
* An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
* {@link ClickableComponent#handleClick} for instances where this will be triggered.
*
* @listens tap
* @listens click
* @listens keydown
*
* @param {EventTarget~Event} event
+ The `click`, `tap` or `keydown` event that caused this function to be called.
*/
PosterImage.prototype.handleClick = function handleClick(event) {
// We don't want a click to trigger playback when controls are disabled
if (!this.player_.controls()) {
return;
}
if (this.player_.paused()) {
silencePromise(this.player_.play());
} else {
this.player_.pause();
}
};
return PosterImage;
}(ClickableComponent);
Component.registerComponent('PosterImage', PosterImage);
/**
* @file text-track-display.js
*/
var darkGray = '#222';
var lightGray = '#ccc';
var fontMap = {
monospace: 'monospace',
sansSerif: 'sans-serif',
serif: 'serif',
monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
monospaceSerif: '"Courier New", monospace',
proportionalSansSerif: 'sans-serif',
proportionalSerif: 'serif',
casual: '"Comic Sans MS", Impact, fantasy',
script: '"Monotype Corsiva", cursive',
smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
};
/**
* Construct an rgba color from a given hex color code.
*
* @param {number} color
* Hex number for color, like #f0e or #f604e2.
*
* @param {number} opacity
* Value for opacity, 0.0 - 1.0.
*
* @return {string}
* The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
*/
function constructColor(color, opacity) {
var hex = void 0;
if (color.length === 4) {
// color looks like "#f0e"
hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
} else if (color.length === 7) {
// color looks like "#f604e2"
hex = color.slice(1);
} else {
throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
}
return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
}
/**
* Try to update the style of a DOM element. Some style changes will throw an error,
* particularly in IE8. Those should be noops.
*
* @param {Element} el
* The DOM element to be styled.
*
* @param {string} style
* The CSS property on the element that should be styled.
*
* @param {string} rule
* The style rule that should be applied to the property.
*
* @private
*/
function tryUpdateStyle(el, style, rule) {
try {
el.style[style] = rule;
} catch (e) {
// Satisfies linter.
return;
}
}
/**
* The component for displaying text track cues.
*
* @extends Component
*/
var TextTrackDisplay = function (_Component) {
inherits(TextTrackDisplay, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} [ready]
* The function to call when `TextTrackDisplay` is ready.
*/
function TextTrackDisplay(player, options, ready) {
classCallCheck(this, TextTrackDisplay);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options, ready));
var updateDisplayHandler = bind(_this, _this.updateDisplay);
player.on('loadstart', bind(_this, _this.toggleDisplay));
player.on('texttrackchange', updateDisplayHandler);
player.on('loadstart', bind(_this, _this.preselectTrack));
// This used to be called during player init, but was causing an error
// if a track should show by default and the display hadn't loaded yet.
// Should probably be moved to an external track loader when we support
// tracks that don't need a display.
player.ready(bind(_this, function () {
if (player.tech_ && player.tech_.featuresNativeTextTracks) {
this.hide();
return;
}
player.on('fullscreenchange', updateDisplayHandler);
player.on('playerresize', updateDisplayHandler);
if (window.addEventListener) {
window.addEventListener('orientationchange', updateDisplayHandler);
}
player.on('dispose', function () {
return window.removeEventListener('orientationchange', updateDisplayHandler);
});
var tracks = this.options_.playerOptions.tracks || [];
for (var i = 0; i < tracks.length; i++) {
this.player_.addRemoteTextTrack(tracks[i], true);
}
this.preselectTrack();
}));
return _this;
}
/**
* Preselect a track following this precedence:
* - matches the previously selected {@link TextTrack}'s language and kind
* - matches the previously selected {@link TextTrack}'s language only
* - is the first default captions track
* - is the first default descriptions track
*
* @listens Player#loadstart
*/
TextTrackDisplay.prototype.preselectTrack = function preselectTrack() {
var modes = { captions: 1, subtitles: 1 };
var trackList = this.player_.textTracks();
var userPref = this.player_.cache_.selectedLanguage;
var firstDesc = void 0;
var firstCaptions = void 0;
var preferredTrack = void 0;
for (var i = 0; i < trackList.length; i++) {
var track = trackList[i];
if (userPref && userPref.enabled && userPref.language === track.language) {
// Always choose the track that matches both language and kind
if (track.kind === userPref.kind) {
preferredTrack = track;
// or choose the first track that matches language
} else if (!preferredTrack) {
preferredTrack = track;
}
// clear everything if offTextTrackMenuItem was clicked
} else if (userPref && !userPref.enabled) {
preferredTrack = null;
firstDesc = null;
firstCaptions = null;
} else if (track['default']) {
if (track.kind === 'descriptions' && !firstDesc) {
firstDesc = track;
} else if (track.kind in modes && !firstCaptions) {
firstCaptions = track;
}
}
}
// The preferredTrack matches the user preference and takes
// precendence over all the other tracks.
// So, display the preferredTrack before the first default track
// and the subtitles/captions track before the descriptions track
if (preferredTrack) {
preferredTrack.mode = 'showing';
} else if (firstCaptions) {
firstCaptions.mode = 'showing';
} else if (firstDesc) {
firstDesc.mode = 'showing';
}
};
/**
* Turn display of {@link TextTrack}'s from the current state into the other state.
* There are only two states:
* - 'shown'
* - 'hidden'
*
* @listens Player#loadstart
*/
TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() {
if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
this.hide();
} else {
this.show();
}
};
/**
* Create the {@link Component}'s DOM element.
*
* @return {Element}
* The element that was created.
*/
TextTrackDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-text-track-display'
}, {
'aria-live': 'off',
'aria-atomic': 'true'
});
};
/**
* Clear all displayed {@link TextTrack}s.
*/
TextTrackDisplay.prototype.clearDisplay = function clearDisplay() {
if (typeof window.WebVTT === 'function') {
window.WebVTT.processCues(window, [], this.el_);
}
};
/**
* Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
* a {@link Player#fullscreenchange} is fired.
*
* @listens Player#texttrackchange
* @listens Player#fullscreenchange
*/
TextTrackDisplay.prototype.updateDisplay = function updateDisplay() {
var tracks = this.player_.textTracks();
this.clearDisplay();
// Track display prioritization model: if multiple tracks are 'showing',
// display the first 'subtitles' or 'captions' track which is 'showing',
// otherwise display the first 'descriptions' track which is 'showing'
var descriptionsTrack = null;
var captionsSubtitlesTrack = null;
var i = tracks.length;
while (i--) {
var track = tracks[i];
if (track.mode === 'showing') {
if (track.kind === 'descriptions') {
descriptionsTrack = track;
} else {
captionsSubtitlesTrack = track;
}
}
}
if (captionsSubtitlesTrack) {
if (this.getAttribute('aria-live') !== 'off') {
this.setAttribute('aria-live', 'off');
}
this.updateForTrack(captionsSubtitlesTrack);
} else if (descriptionsTrack) {
if (this.getAttribute('aria-live') !== 'assertive') {
this.setAttribute('aria-live', 'assertive');
}
this.updateForTrack(descriptionsTrack);
}
};
/**
* Add an {@link Texttrack} to to the {@link Tech}s {@link TextTrackList}.
*
* @param {TextTrack} track
* Text track object to be added to the list.
*/
TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) {
if (typeof window.WebVTT !== 'function' || !track.activeCues) {
return;
}
var cues = [];
for (var _i = 0; _i < track.activeCues.length; _i++) {
cues.push(track.activeCues[_i]);
}
window.WebVTT.processCues(window, cues, this.el_);
if (!this.player_.textTrackSettings) {
return;
}
var overrides = this.player_.textTrackSettings.getValues();
var i = cues.length;
while (i--) {
var cue = cues[i];
if (!cue) {
continue;
}
var cueDiv = cue.displayState;
if (overrides.color) {
cueDiv.firstChild.style.color = overrides.color;
}
if (overrides.textOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
}
if (overrides.backgroundColor) {
cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
}
if (overrides.backgroundOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
}
if (overrides.windowColor) {
if (overrides.windowOpacity) {
tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
} else {
cueDiv.style.backgroundColor = overrides.windowColor;
}
}
if (overrides.edgeStyle) {
if (overrides.edgeStyle === 'dropshadow') {
cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray;
} else if (overrides.edgeStyle === 'raised') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray;
} else if (overrides.edgeStyle === 'depressed') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray;
} else if (overrides.edgeStyle === 'uniform') {
cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray;
}
}
if (overrides.fontPercent && overrides.fontPercent !== 1) {
var fontSize = window.parseFloat(cueDiv.style.fontSize);
cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
cueDiv.style.height = 'auto';
cueDiv.style.top = 'auto';
cueDiv.style.bottom = '2px';
}
if (overrides.fontFamily && overrides.fontFamily !== 'default') {
if (overrides.fontFamily === 'small-caps') {
cueDiv.firstChild.style.fontVariant = 'small-caps';
} else {
cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
}
}
}
};
return TextTrackDisplay;
}(Component);
Component.registerComponent('TextTrackDisplay', TextTrackDisplay);
/**
* @file loading-spinner.js
*/
/**
* A loading spinner for use during waiting/loading events.
*
* @extends Component
*/
var LoadingSpinner = function (_Component) {
inherits(LoadingSpinner, _Component);
function LoadingSpinner() {
classCallCheck(this, LoadingSpinner);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
/**
* Create the `LoadingSpinner`s DOM element.
*
* @return {Element}
* The dom element that gets created.
*/
LoadingSpinner.prototype.createEl = function createEl$$1() {
var isAudio = this.player_.isAudio();
var playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
var controlText = createEl('span', {
className: 'vjs-control-text',
innerHTML: this.localize('{1} is loading.', [playerType])
});
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-loading-spinner',
dir: 'ltr'
});
el.appendChild(controlText);
return el;
};
return LoadingSpinner;
}(Component);
Component.registerComponent('LoadingSpinner', LoadingSpinner);
/**
* @file button.js
*/
/**
* Base class for all buttons.
*
* @extends ClickableComponent
*/
var Button = function (_ClickableComponent) {
inherits(Button, _ClickableComponent);
function Button() {
classCallCheck(this, Button);
return possibleConstructorReturn(this, _ClickableComponent.apply(this, arguments));
}
/**
* Create the `Button`s DOM element.
*
* @param {string} [tag="button"]
* The element's node type. This argument is IGNORED: no matter what
* is passed, it will always create a `button` element.
*
* @param {Object} [props={}]
* An object of properties that should be set on the element.
*
* @param {Object} [attributes={}]
* An object of attributes that should be set on the element.
*
* @return {Element}
* The element that gets created.
*/
Button.prototype.createEl = function createEl(tag) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
tag = 'button';
props = assign({
innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>',
className: this.buildCSSClass()
}, props);
// Add attributes for button element
attributes = assign({
// Necessary since the default button type is "submit"
type: 'button'
}, attributes);
var el = Component.prototype.createEl.call(this, tag, props, attributes);
this.createControlTextEl(el);
return el;
};
/**
* Add a child `Component` inside of this `Button`.
*
* @param {string|Component} child
* The name or instance of a child to add.
*
* @param {Object} [options={}]
* The key/value store of options that will get passed to children of
* the child.
*
* @return {Component}
* The `Component` that gets added as a child. When using a string the
* `Component` will get created by this process.
*
* @deprecated since version 5
*/
Button.prototype.addChild = function addChild(child) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var className = this.constructor.name;
log.warn('Adding an actionable (user controllable) child to a Button (' + className + ') is not supported; use a ClickableComponent instead.');
// Avoid the error message generated by ClickableComponent's addChild method
return Component.prototype.addChild.call(this, child, options);
};
/**
* Enable the `Button` element so that it can be activated or clicked. Use this with
* {@link Button#disable}.
*/
Button.prototype.enable = function enable() {
_ClickableComponent.prototype.enable.call(this);
this.el_.removeAttribute('disabled');
};
/**
* Disable the `Button` element so that it cannot be activated or clicked. Use this with
* {@link Button#enable}.
*/
Button.prototype.disable = function disable() {
_ClickableComponent.prototype.disable.call(this);
this.el_.setAttribute('disabled', 'disabled');
};
/**
* This gets called when a `Button` has focus and `keydown` is triggered via a key
* press.
*
* @param {EventTarget~Event} event
* The event that caused this function to get called.
*
* @listens keydown
*/
Button.prototype.handleKeyPress = function handleKeyPress(event) {
// Ignore Space (32) or Enter (13) key operation, which is handled by the browser for a button.
if (event.which === 32 || event.which === 13) {
return;
}
// Pass keypress handling up for unsupported keys
_ClickableComponent.prototype.handleKeyPress.call(this, event);
};
return Button;
}(ClickableComponent);
Component.registerComponent('Button', Button);
/**
* @file big-play-button.js
*/
/**
* The initial play button that shows before the video has played. The hiding of the
* `BigPlayButton` get done via CSS and `Player` states.
*
* @extends Button
*/
var BigPlayButton = function (_Button) {
inherits(BigPlayButton, _Button);
function BigPlayButton(player, options) {
classCallCheck(this, BigPlayButton);
var _this = possibleConstructorReturn(this, _Button.call(this, player, options));
_this.mouseused_ = false;
_this.on('mousedown', _this.handleMouseDown);
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object. Always returns 'vjs-big-play-button'.
*/
BigPlayButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-big-play-button';
};
/**
* This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
* for more detailed information on what a click can be.
*
* @param {EventTarget~Event} event
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
BigPlayButton.prototype.handleClick = function handleClick(event) {
var playPromise = this.player_.play();
// exit early if clicked via the mouse
if (this.mouseused_ && event.clientX && event.clientY) {
silencePromise(playPromise);
return;
}
var cb = this.player_.getChild('controlBar');
var playToggle = cb && cb.getChild('playToggle');
if (!playToggle) {
this.player_.focus();
return;
}
var playFocus = function playFocus() {
return playToggle.focus();
};
if (isPromise(playPromise)) {
playPromise.then(playFocus, function () {});
} else {
this.setTimeout(playFocus, 1);
}
};
BigPlayButton.prototype.handleKeyPress = function handleKeyPress(event) {
this.mouseused_ = false;
_Button.prototype.handleKeyPress.call(this, event);
};
BigPlayButton.prototype.handleMouseDown = function handleMouseDown(event) {
this.mouseused_ = true;
};
return BigPlayButton;
}(Button);
/**
* The text that should display over the `BigPlayButton`s controls. Added to for localization.
*
* @type {string}
* @private
*/
BigPlayButton.prototype.controlText_ = 'Play Video';
Component.registerComponent('BigPlayButton', BigPlayButton);
/**
* @file close-button.js
*/
/**
* The `CloseButton` is a `{@link Button}` that fires a `close` event when
* it gets clicked.
*
* @extends Button
*/
var CloseButton = function (_Button) {
inherits(CloseButton, _Button);
/**
* Creates an instance of the this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function CloseButton(player, options) {
classCallCheck(this, CloseButton);
var _this = possibleConstructorReturn(this, _Button.call(this, player, options));
_this.controlText(options && options.controlText || _this.localize('Close'));
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
CloseButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-close-button ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* This gets called when a `CloseButton` gets clicked. See
* {@link ClickableComponent#handleClick} for more information on when this will be
* triggered
*
* @param {EventTarget~Event} event
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
* @fires CloseButton#close
*/
CloseButton.prototype.handleClick = function handleClick(event) {
/**
* Triggered when the a `CloseButton` is clicked.
*
* @event CloseButton#close
* @type {EventTarget~Event}
*
* @property {boolean} [bubbles=false]
* set to false so that the close event does not
* bubble up to parents if there is no listener
*/
this.trigger({ type: 'close', bubbles: false });
};
return CloseButton;
}(Button);
Component.registerComponent('CloseButton', CloseButton);
/**
* @file play-toggle.js
*/
/**
* Button to toggle between play and pause.
*
* @extends Button
*/
var PlayToggle = function (_Button) {
inherits(PlayToggle, _Button);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function PlayToggle(player, options) {
classCallCheck(this, PlayToggle);
var _this = possibleConstructorReturn(this, _Button.call(this, player, options));
_this.on(player, 'play', _this.handlePlay);
_this.on(player, 'pause', _this.handlePause);
_this.on(player, 'ended', _this.handleEnded);
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
PlayToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* This gets called when an `PlayToggle` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
PlayToggle.prototype.handleClick = function handleClick(event) {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
/**
* This gets called once after the video has ended and the user seeks so that
* we can change the replay button back to a play button.
*
* @param {EventTarget~Event} [event]
* The event that caused this function to run.
*
* @listens Player#seeked
*/
PlayToggle.prototype.handleSeeked = function handleSeeked(event) {
this.removeClass('vjs-ended');
if (this.player_.paused()) {
this.handlePause(event);
} else {
this.handlePlay(event);
}
};
/**
* Add the vjs-playing class to the element so it can change appearance.
*
* @param {EventTarget~Event} [event]
* The event that caused this function to run.
*
* @listens Player#play
*/
PlayToggle.prototype.handlePlay = function handlePlay(event) {
this.removeClass('vjs-ended');
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
// change the button text to "Pause"
this.controlText('Pause');
};
/**
* Add the vjs-paused class to the element so it can change appearance.
*
* @param {EventTarget~Event} [event]
* The event that caused this function to run.
*
* @listens Player#pause
*/
PlayToggle.prototype.handlePause = function handlePause(event) {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
// change the button text to "Play"
this.controlText('Play');
};
/**
* Add the vjs-ended class to the element so it can change appearance
*
* @param {EventTarget~Event} [event]
* The event that caused this function to run.
*
* @listens Player#ended
*/
PlayToggle.prototype.handleEnded = function handleEnded(event) {
this.removeClass('vjs-playing');
this.addClass('vjs-ended');
// change the button text to "Replay"
this.controlText('Replay');
// on the next seek remove the replay button
this.one(this.player_, 'seeked', this.handleSeeked);
};
return PlayToggle;
}(Button);
/**
* The text that should display over the `PlayToggle`s controls. Added for localization.
*
* @type {string}
* @private
*/
PlayToggle.prototype.controlText_ = 'Play';
Component.registerComponent('PlayToggle', PlayToggle);
/**
* @file format-time.js
* @module format-time
*/
/**
* Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds)
* will force a number of leading zeros to cover the length of the guide.
*
* @param {number} seconds
* Number of seconds to be turned into a string
*
* @param {number} guide
* Number (in seconds) to model the string after
*
* @return {string}
* Time formatted as H:MM:SS or M:SS
*/
var defaultImplementation = function defaultImplementation(seconds, guide) {
seconds = seconds < 0 ? 0 : seconds;
var s = Math.floor(seconds % 60);
var m = Math.floor(seconds / 60 % 60);
var h = Math.floor(seconds / 3600);
var gm = Math.floor(guide / 60 % 60);
var gh = Math.floor(guide / 3600);
// handle invalid times
if (isNaN(seconds) || seconds === Infinity) {
// '-' is false for all relational operators (e.g. <, >=) so this setting
// will add the minimum number of fields specified by the guide
h = m = s = '-';
}
// Check if we need to show hours
h = h > 0 || gh > 0 ? h + ':' : '';
// If hours are showing, we may need to add a leading zero.
// Always show at least one digit of minutes.
m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
// Check if leading zero is need for seconds
s = s < 10 ? '0' + s : s;
return h + m + s;
};
var implementation = defaultImplementation;
/**
* Replaces the default formatTime implementation with a custom implementation.
*
* @param {Function} customImplementation
* A function which will be used in place of the default formatTime implementation.
* Will receive the current time in seconds and the guide (in seconds) as arguments.
*/
function setFormatTime(customImplementation) {
implementation = customImplementation;
}
/**
* Resets formatTime to the default implementation.
*/
function resetFormatTime() {
implementation = defaultImplementation;
}
var formatTime = function (seconds) {
var guide = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : seconds;
return implementation(seconds, guide);
};
/**
* @file time-display.js
*/
/**
* Displays the time left in the video
*
* @extends Component
*/
var TimeDisplay = function (_Component) {
inherits(TimeDisplay, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function TimeDisplay(player, options) {
classCallCheck(this, TimeDisplay);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.throttledUpdateContent = throttle(bind(_this, _this.updateContent), 25);
_this.on(player, 'timeupdate', _this.throttledUpdateContent);
return _this;
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
TimeDisplay.prototype.createEl = function createEl$$1(plainName) {
var className = this.buildCSSClass();
var el = _Component.prototype.createEl.call(this, 'div', {
className: className + ' vjs-time-control vjs-control',
innerHTML: '<span class="vjs-control-text">' + this.localize(this.labelText_) + '\xA0</span>'
});
this.contentEl_ = createEl('span', {
className: className + '-display'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
this.updateTextNode_();
el.appendChild(this.contentEl_);
return el;
};
TimeDisplay.prototype.dispose = function dispose() {
this.contentEl_ = null;
this.textNode_ = null;
_Component.prototype.dispose.call(this);
};
/**
* Updates the "remaining time" text node with new content using the
* contents of the `formattedTime_` property.
*
* @private
*/
TimeDisplay.prototype.updateTextNode_ = function updateTextNode_() {
if (!this.contentEl_) {
return;
}
while (this.contentEl_.firstChild) {
this.contentEl_.removeChild(this.contentEl_.firstChild);
}
this.textNode_ = document.createTextNode(this.formattedTime_ || this.formatTime_(0));
this.contentEl_.appendChild(this.textNode_);
};
/**
* Generates a formatted time for this component to use in display.
*
* @param {number} time
* A numeric time, in seconds.
*
* @return {string}
* A formatted time
*
* @private
*/
TimeDisplay.prototype.formatTime_ = function formatTime_(time) {
return formatTime(time);
};
/**
* Updates the time display text node if it has what was passed in changed
* the formatted time.
*
* @param {number} time
* The time to update to
*
* @private
*/
TimeDisplay.prototype.updateFormattedTime_ = function updateFormattedTime_(time) {
var formattedTime = this.formatTime_(time);
if (formattedTime === this.formattedTime_) {
return;
}
this.formattedTime_ = formattedTime;
this.requestAnimationFrame(this.updateTextNode_);
};
/**
* To be filled out in the child class, should update the displayed time
* in accordance with the fact that the current time has changed.
*
* @param {EventTarget~Event} [event]
* The `timeupdate` event that caused this to run.
*
* @listens Player#timeupdate
*/
TimeDisplay.prototype.updateContent = function updateContent(event) {};
return TimeDisplay;
}(Component);
/**
* The text that is added to the `TimeDisplay` for screen reader users.
*
* @type {string}
* @private
*/
TimeDisplay.prototype.labelText_ = 'Time';
/**
* The text that should display over the `TimeDisplay`s controls. Added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controlText_ is not used in non-active display Components
*/
TimeDisplay.prototype.controlText_ = 'Time';
Component.registerComponent('TimeDisplay', TimeDisplay);
/**
* @file current-time-display.js
*/
/**
* Displays the current time
*
* @extends Component
*/
var CurrentTimeDisplay = function (_TimeDisplay) {
inherits(CurrentTimeDisplay, _TimeDisplay);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function CurrentTimeDisplay(player, options) {
classCallCheck(this, CurrentTimeDisplay);
var _this = possibleConstructorReturn(this, _TimeDisplay.call(this, player, options));
_this.on(player, 'ended', _this.handleEnded);
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
CurrentTimeDisplay.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-current-time';
};
/**
* Update current time display
*
* @param {EventTarget~Event} [event]
* The `timeupdate` event that caused this function to run.
*
* @listens Player#timeupdate
*/
CurrentTimeDisplay.prototype.updateContent = function updateContent(event) {
// Allows for smooth scrubbing, when player can't keep up.
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
this.updateFormattedTime_(time);
};
/**
* When the player fires ended there should be no time left. Sadly
* this is not always the case, lets make it seem like that is the case
* for users.
*
* @param {EventTarget~Event} [event]
* The `ended` event that caused this to run.
*
* @listens Player#ended
*/
CurrentTimeDisplay.prototype.handleEnded = function handleEnded(event) {
if (!this.player_.duration()) {
return;
}
this.updateFormattedTime_(this.player_.duration());
};
return CurrentTimeDisplay;
}(TimeDisplay);
/**
* The text that is added to the `CurrentTimeDisplay` for screen reader users.
*
* @type {string}
* @private
*/
CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
/**
* The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controlText_ is not used in non-active display Components
*/
CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
Component.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
/**
* @file duration-display.js
*/
/**
* Displays the duration
*
* @extends Component
*/
var DurationDisplay = function (_TimeDisplay) {
inherits(DurationDisplay, _TimeDisplay);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function DurationDisplay(player, options) {
classCallCheck(this, DurationDisplay);
// we do not want to/need to throttle duration changes,
// as they should always display the changed duration as
// it has changed
var _this = possibleConstructorReturn(this, _TimeDisplay.call(this, player, options));
_this.on(player, 'durationchange', _this.updateContent);
// Also listen for timeupdate (in the parent) and loadedmetadata because removing those
// listeners could have broken dependent applications/libraries. These
// can likely be removed for 7.0.
_this.on(player, 'loadedmetadata', _this.throttledUpdateContent);
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
DurationDisplay.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-duration';
};
/**
* Update duration time display.
*
* @param {EventTarget~Event} [event]
* The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
* this function to be called.
*
* @listens Player#durationchange
* @listens Player#timeupdate
* @listens Player#loadedmetadata
*/
DurationDisplay.prototype.updateContent = function updateContent(event) {
var duration = this.player_.duration();
if (duration && this.duration_ !== duration) {
this.duration_ = duration;
this.updateFormattedTime_(duration);
}
};
return DurationDisplay;
}(TimeDisplay);
/**
* The text that is added to the `DurationDisplay` for screen reader users.
*
* @type {string}
* @private
*/
DurationDisplay.prototype.labelText_ = 'Duration';
/**
* The text that should display over the `DurationDisplay`s controls. Added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controlText_ is not used in non-active display Components
*/
DurationDisplay.prototype.controlText_ = 'Duration';
Component.registerComponent('DurationDisplay', DurationDisplay);
/**
* @file time-divider.js
*/
/**
* The separator between the current time and duration.
* Can be hidden if it's not needed in the design.
*
* @extends Component
*/
var TimeDivider = function (_Component) {
inherits(TimeDivider, _Component);
function TimeDivider() {
classCallCheck(this, TimeDivider);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
/**
* Create the component's DOM element
*
* @return {Element}
* The element that was created.
*/
TimeDivider.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-time-control vjs-time-divider',
innerHTML: '<div><span>/</span></div>'
});
};
return TimeDivider;
}(Component);
Component.registerComponent('TimeDivider', TimeDivider);
/**
* @file remaining-time-display.js
*/
/**
* Displays the time left in the video
*
* @extends Component
*/
var RemainingTimeDisplay = function (_TimeDisplay) {
inherits(RemainingTimeDisplay, _TimeDisplay);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function RemainingTimeDisplay(player, options) {
classCallCheck(this, RemainingTimeDisplay);
var _this = possibleConstructorReturn(this, _TimeDisplay.call(this, player, options));
_this.on(player, 'durationchange', _this.throttledUpdateContent);
_this.on(player, 'ended', _this.handleEnded);
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
RemainingTimeDisplay.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-remaining-time';
};
/**
* The remaining time display prefixes numbers with a "minus" character.
*
* @param {number} time
* A numeric time, in seconds.
*
* @return {string}
* A formatted time
*
* @private
*/
RemainingTimeDisplay.prototype.formatTime_ = function formatTime_(time) {
// TODO: The "-" should be decorative, and not announced by a screen reader
return '-' + _TimeDisplay.prototype.formatTime_.call(this, time);
};
/**
* Update remaining time display.
*
* @param {EventTarget~Event} [event]
* The `timeupdate` or `durationchange` event that caused this to run.
*
* @listens Player#timeupdate
* @listens Player#durationchange
*/
RemainingTimeDisplay.prototype.updateContent = function updateContent(event) {
if (!this.player_.duration()) {
return;
}
// @deprecated We should only use remainingTimeDisplay
// as of video.js 7
if (this.player_.remainingTimeDisplay) {
this.updateFormattedTime_(this.player_.remainingTimeDisplay());
} else {
this.updateFormattedTime_(this.player_.remainingTime());
}
};
/**
* When the player fires ended there should be no time left. Sadly
* this is not always the case, lets make it seem like that is the case
* for users.
*
* @param {EventTarget~Event} [event]
* The `ended` event that caused this to run.
*
* @listens Player#ended
*/
RemainingTimeDisplay.prototype.handleEnded = function handleEnded(event) {
if (!this.player_.duration()) {
return;
}
this.updateFormattedTime_(0);
};
return RemainingTimeDisplay;
}(TimeDisplay);
/**
* The text that is added to the `RemainingTimeDisplay` for screen reader users.
*
* @type {string}
* @private
*/
RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
/**
* The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controlText_ is not used in non-active display Components
*/
RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
Component.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
/**
* @file live-display.js
*/
// TODO - Future make it click to snap to live
/**
* Displays the live indicator when duration is Infinity.
*
* @extends Component
*/
var LiveDisplay = function (_Component) {
inherits(LiveDisplay, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function LiveDisplay(player, options) {
classCallCheck(this, LiveDisplay);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.updateShowing();
_this.on(_this.player(), 'durationchange', _this.updateShowing);
return _this;
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
LiveDisplay.prototype.createEl = function createEl$$1() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-live-control vjs-control'
});
this.contentEl_ = createEl('div', {
className: 'vjs-live-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '\xA0</span>' + this.localize('LIVE')
}, {
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
LiveDisplay.prototype.dispose = function dispose() {
this.contentEl_ = null;
_Component.prototype.dispose.call(this);
};
/**
* Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
* it accordingly
*
* @param {EventTarget~Event} [event]
* The {@link Player#durationchange} event that caused this function to run.
*
* @listens Player#durationchange
*/
LiveDisplay.prototype.updateShowing = function updateShowing(event) {
if (this.player().duration() === Infinity) {
this.show();
} else {
this.hide();
}
};
return LiveDisplay;
}(Component);
Component.registerComponent('LiveDisplay', LiveDisplay);
/**
* @file slider.js
*/
/**
* The base functionality for a slider. Can be vertical or horizontal.
* For instance the volume bar or the seek bar on a video is a slider.
*
* @extends Component
*/
var Slider = function (_Component) {
inherits(Slider, _Component);
/**
* Create an instance of this class
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function Slider(player, options) {
classCallCheck(this, Slider);
// Set property names to bar to match with the child Slider class is looking for
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.bar = _this.getChild(_this.options_.barName);
// Set a horizontal or vertical class on the slider depending on the slider type
_this.vertical(!!_this.options_.vertical);
_this.enable();
return _this;
}
/**
* Are controls are currently enabled for this slider or not.
*
* @return {boolean}
* true if controls are enabled, false otherwise
*/
Slider.prototype.enabled = function enabled() {
return this.enabled_;
};
/**
* Enable controls for this slider if they are disabled
*/
Slider.prototype.enable = function enable() {
if (this.enabled()) {
return;
}
this.on('mousedown', this.handleMouseDown);
this.on('touchstart', this.handleMouseDown);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
this.on('click', this.handleClick);
this.on(this.player_, 'controlsvisible', this.update);
if (this.playerEvent) {
this.on(this.player_, this.playerEvent, this.update);
}
this.removeClass('disabled');
this.setAttribute('tabindex', 0);
this.enabled_ = true;
};
/**
* Disable controls for this slider if they are enabled
*/
Slider.prototype.disable = function disable() {
if (!this.enabled()) {
return;
}
var doc = this.bar.el_.ownerDocument;
this.off('mousedown', this.handleMouseDown);
this.off('touchstart', this.handleMouseDown);
this.off('focus', this.handleFocus);
this.off('blur', this.handleBlur);
this.off('click', this.handleClick);
this.off(this.player_, 'controlsvisible', this.update);
this.off(doc, 'mousemove', this.handleMouseMove);
this.off(doc, 'mouseup', this.handleMouseUp);
this.off(doc, 'touchmove', this.handleMouseMove);
this.off(doc, 'touchend', this.handleMouseUp);
this.removeAttribute('tabindex');
this.addClass('disabled');
if (this.playerEvent) {
this.off(this.player_, this.playerEvent, this.update);
}
this.enabled_ = false;
};
/**
* Create the `Button`s DOM element.
*
* @param {string} type
* Type of element to create.
*
* @param {Object} [props={}]
* List of properties in Object form.
*
* @param {Object} [attributes={}]
* list of attributes in Object form.
*
* @return {Element}
* The element that gets created.
*/
Slider.prototype.createEl = function createEl$$1(type) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider';
props = assign({
tabIndex: 0
}, props);
attributes = assign({
'role': 'slider',
'aria-valuenow': 0,
'aria-valuemin': 0,
'aria-valuemax': 100,
'tabIndex': 0
}, attributes);
return _Component.prototype.createEl.call(this, type, props, attributes);
};
/**
* Handle `mousedown` or `touchstart` events on the `Slider`.
*
* @param {EventTarget~Event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
* @fires Slider#slideractive
*/
Slider.prototype.handleMouseDown = function handleMouseDown(event) {
var doc = this.bar.el_.ownerDocument;
if (event.type === 'mousedown') {
event.preventDefault();
}
// Do not call preventDefault() on touchstart in Chrome
// to avoid console warnings. Use a 'touch-action: none' style
// instead to prevent unintented scrolling.
// https://developers.google.com/web/updates/2017/01/scrolling-intervention
if (event.type === 'touchstart' && !IS_CHROME) {
event.preventDefault();
}
blockTextSelection();
this.addClass('vjs-sliding');
/**
* Triggered when the slider is in an active state
*
* @event Slider#slideractive
* @type {EventTarget~Event}
*/
this.trigger('slideractive');
this.on(doc, 'mousemove', this.handleMouseMove);
this.on(doc, 'mouseup', this.handleMouseUp);
this.on(doc, 'touchmove', this.handleMouseMove);
this.on(doc, 'touchend', this.handleMouseUp);
this.handleMouseMove(event);
};
/**
* Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
* The `mousemove` and `touchmove` events will only only trigger this function during
* `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
* {@link Slider#handleMouseUp}.
*
* @param {EventTarget~Event} event
* `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
* this function
*
* @listens mousemove
* @listens touchmove
*/
Slider.prototype.handleMouseMove = function handleMouseMove(event) {};
/**
* Handle `mouseup` or `touchend` events on the `Slider`.
*
* @param {EventTarget~Event} event
* `mouseup` or `touchend` event that triggered this function.
*
* @listens touchend
* @listens mouseup
* @fires Slider#sliderinactive
*/
Slider.prototype.handleMouseUp = function handleMouseUp() {
var doc = this.bar.el_.ownerDocument;
unblockTextSelection();
this.removeClass('vjs-sliding');
/**
* Triggered when the slider is no longer in an active state.
*
* @event Slider#sliderinactive
* @type {EventTarget~Event}
*/
this.trigger('sliderinactive');
this.off(doc, 'mousemove', this.handleMouseMove);
this.off(doc, 'mouseup', this.handleMouseUp);
this.off(doc, 'touchmove', this.handleMouseMove);
this.off(doc, 'touchend', this.handleMouseUp);
this.update();
};
/**
* Update the progress bar of the `Slider`.
*
* @returns {number}
* The percentage of progress the progress bar represents as a
* number from 0 to 1.
*/
Slider.prototype.update = function update() {
// In VolumeBar init we have a setTimeout for update that pops and update
// to the end of the execution stack. The player is destroyed before then
// update will cause an error
if (!this.el_) {
return;
}
// If scrubbing, we could use a cached value to make the handle keep up
// with the user's mouse. On HTML5 browsers scrubbing is really smooth, but
// some flash players are slow, so we might want to utilize this later.
// var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration();
var progress = this.getPercent();
var bar = this.bar;
// If there's no bar...
if (!bar) {
return;
}
// Protect against no duration and other division issues
if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) {
progress = 0;
}
// Convert to a percentage for setting
var percentage = (progress * 100).toFixed(2) + '%';
var style = bar.el().style;
// Set the new bar width or height
if (this.vertical()) {
style.height = percentage;
} else {
style.width = percentage;
}
return progress;
};
/**
* Calculate distance for slider
*
* @param {EventTarget~Event} event
* The event that caused this function to run.
*
* @return {number}
* The current position of the Slider.
* - postition.x for vertical `Slider`s
* - postition.y for horizontal `Slider`s
*/
Slider.prototype.calculateDistance = function calculateDistance(event) {
var position = getPointerPosition(this.el_, event);
if (this.vertical()) {
return position.y;
}
return position.x;
};
/**
* Handle a `focus` event on this `Slider`.
*
* @param {EventTarget~Event} event
* The `focus` event that caused this function to run.
*
* @listens focus
*/
Slider.prototype.handleFocus = function handleFocus() {
this.on(this.bar.el_.ownerDocument, 'keydown', this.handleKeyPress);
};
/**
* Handle a `keydown` event on the `Slider`. Watches for left, rigth, up, and down
* arrow keys. This function will only be called when the slider has focus. See
* {@link Slider#handleFocus} and {@link Slider#handleBlur}.
*
* @param {EventTarget~Event} event
* the `keydown` event that caused this function to run.
*
* @listens keydown
*/
Slider.prototype.handleKeyPress = function handleKeyPress(event) {
// Left and Down Arrows
if (event.which === 37 || event.which === 40) {
event.preventDefault();
this.stepBack();
// Up and Right Arrows
} else if (event.which === 38 || event.which === 39) {
event.preventDefault();
this.stepForward();
}
};
/**
* Handle a `blur` event on this `Slider`.
*
* @param {EventTarget~Event} event
* The `blur` event that caused this function to run.
*
* @listens blur
*/
Slider.prototype.handleBlur = function handleBlur() {
this.off(this.bar.el_.ownerDocument, 'keydown', this.handleKeyPress);
};
/**
* Listener for click events on slider, used to prevent clicks
* from bubbling up to parent elements like button menus.
*
* @param {Object} event
* Event that caused this object to run
*/
Slider.prototype.handleClick = function handleClick(event) {
event.stopImmediatePropagation();
event.preventDefault();
};
/**
* Get/set if slider is horizontal for vertical
*
* @param {boolean} [bool]
* - true if slider is vertical,
* - false is horizontal
*
* @return {boolean}
* - true if slider is vertical, and getting
* - false if the slider is horizontal, and getting
*/
Slider.prototype.vertical = function vertical(bool) {
if (bool === undefined) {
return this.vertical_ || false;
}
this.vertical_ = !!bool;
if (this.vertical_) {
this.addClass('vjs-slider-vertical');
} else {
this.addClass('vjs-slider-horizontal');
}
};
return Slider;
}(Component);
Component.registerComponent('Slider', Slider);
/**
* @file load-progress-bar.js
*/
/**
* Shows loading progress
*
* @extends Component
*/
var LoadProgressBar = function (_Component) {
inherits(LoadProgressBar, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function LoadProgressBar(player, options) {
classCallCheck(this, LoadProgressBar);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.partEls_ = [];
_this.on(player, 'progress', _this.update);
return _this;
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
LoadProgressBar.prototype.createEl = function createEl$$1() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-load-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>'
});
};
LoadProgressBar.prototype.dispose = function dispose() {
this.partEls_ = null;
_Component.prototype.dispose.call(this);
};
/**
* Update progress bar
*
* @param {EventTarget~Event} [event]
* The `progress` event that caused this function to run.
*
* @listens Player#progress
*/
LoadProgressBar.prototype.update = function update(event) {
var buffered = this.player_.buffered();
var duration = this.player_.duration();
var bufferedEnd = this.player_.bufferedEnd();
var children = this.partEls_;
// get the percent width of a time compared to the total end
var percentify = function percentify(time, end) {
// no NaN
var percent = time / end || 0;
return (percent >= 1 ? 1 : percent) * 100 + '%';
};
// update the width of the progress bar
this.el_.style.width = percentify(bufferedEnd, duration);
// add child elements to represent the individual buffered time ranges
for (var i = 0; i < buffered.length; i++) {
var start = buffered.start(i);
var end = buffered.end(i);
var part = children[i];
if (!part) {
part = this.el_.appendChild(createEl());
children[i] = part;
}
// set the percent based on the width of the progress bar (bufferedEnd)
part.style.left = percentify(start, bufferedEnd);
part.style.width = percentify(end - start, bufferedEnd);
}
// remove unused buffered range elements
for (var _i = children.length; _i > buffered.length; _i--) {
this.el_.removeChild(children[_i - 1]);
}
children.length = buffered.length;
};
return LoadProgressBar;
}(Component);
Component.registerComponent('LoadProgressBar', LoadProgressBar);
/**
* @file time-tooltip.js
*/
/**
* Time tooltips display a time above the progress bar.
*
* @extends Component
*/
var TimeTooltip = function (_Component) {
inherits(TimeTooltip, _Component);
function TimeTooltip() {
classCallCheck(this, TimeTooltip);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
/**
* Create the time tooltip DOM element
*
* @return {Element}
* The element that was created.
*/
TimeTooltip.prototype.createEl = function createEl$$1() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-time-tooltip'
});
};
/**
* Updates the position of the time tooltip relative to the `SeekBar`.
*
* @param {Object} seekBarRect
* The `ClientRect` for the {@link SeekBar} element.
*
* @param {number} seekBarPoint
* A number from 0 to 1, representing a horizontal reference point
* from the left edge of the {@link SeekBar}
*/
TimeTooltip.prototype.update = function update(seekBarRect, seekBarPoint, content) {
var tooltipRect = getBoundingClientRect(this.el_);
var playerRect = getBoundingClientRect(this.player_.el());
var seekBarPointPx = seekBarRect.width * seekBarPoint;
// do nothing if either rect isn't available
// for example, if the player isn't in the DOM for testing
if (!playerRect || !tooltipRect) {
return;
}
// This is the space left of the `seekBarPoint` available within the bounds
// of the player. We calculate any gap between the left edge of the player
// and the left edge of the `SeekBar` and add the number of pixels in the
// `SeekBar` before hitting the `seekBarPoint`
var spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
// This is the space right of the `seekBarPoint` available within the bounds
// of the player. We calculate the number of pixels from the `seekBarPoint`
// to the right edge of the `SeekBar` and add to that any gap between the
// right edge of the `SeekBar` and the player.
var spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
// This is the number of pixels by which the tooltip will need to be pulled
// further to the right to center it over the `seekBarPoint`.
var pullTooltipBy = tooltipRect.width / 2;
// Adjust the `pullTooltipBy` distance to the left or right depending on
// the results of the space calculations above.
if (spaceLeftOfPoint < pullTooltipBy) {
pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
} else if (spaceRightOfPoint < pullTooltipBy) {
pullTooltipBy = spaceRightOfPoint;
}
// Due to the imprecision of decimal/ratio based calculations and varying
// rounding behaviors, there are cases where the spacing adjustment is off
// by a pixel or two. This adds insurance to these calculations.
if (pullTooltipBy < 0) {
pullTooltipBy = 0;
} else if (pullTooltipBy > tooltipRect.width) {
pullTooltipBy = tooltipRect.width;
}
this.el_.style.right = '-' + pullTooltipBy + 'px';
textContent(this.el_, content);
};
return TimeTooltip;
}(Component);
Component.registerComponent('TimeTooltip', TimeTooltip);
/**
* @file play-progress-bar.js
*/
/**
* Used by {@link SeekBar} to display media playback progress as part of the
* {@link ProgressControl}.
*
* @extends Component
*/
var PlayProgressBar = function (_Component) {
inherits(PlayProgressBar, _Component);
function PlayProgressBar() {
classCallCheck(this, PlayProgressBar);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
/**
* Create the the DOM element for this class.
*
* @return {Element}
* The element that was created.
*/
PlayProgressBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-play-progress vjs-slider-bar',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>'
});
};
/**
* Enqueues updates to its own DOM as well as the DOM of its
* {@link TimeTooltip} child.
*
* @param {Object} seekBarRect
* The `ClientRect` for the {@link SeekBar} element.
*
* @param {number} seekBarPoint
* A number from 0 to 1, representing a horizontal reference point
* from the left edge of the {@link SeekBar}
*/
PlayProgressBar.prototype.update = function update(seekBarRect, seekBarPoint) {
var _this2 = this;
// If there is an existing rAF ID, cancel it so we don't over-queue.
if (this.rafId_) {
this.cancelAnimationFrame(this.rafId_);
}
this.rafId_ = this.requestAnimationFrame(function () {
var time = _this2.player_.scrubbing() ? _this2.player_.getCache().currentTime : _this2.player_.currentTime();
var content = formatTime(time, _this2.player_.duration());
var timeTooltip = _this2.getChild('timeTooltip');
if (timeTooltip) {
timeTooltip.update(seekBarRect, seekBarPoint, content);
}
});
};
return PlayProgressBar;
}(Component);
/**
* Default options for {@link PlayProgressBar}.
*
* @type {Object}
* @private
*/
PlayProgressBar.prototype.options_ = {
children: []
};
// Time tooltips should not be added to a player on mobile devices or IE8
if ((!IE_VERSION || IE_VERSION > 8) && !IS_IOS && !IS_ANDROID) {
PlayProgressBar.prototype.options_.children.push('timeTooltip');
}
Component.registerComponent('PlayProgressBar', PlayProgressBar);
/**
* @file mouse-time-display.js
*/
/**
* The {@link MouseTimeDisplay} component tracks mouse movement over the
* {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
* indicating the time which is represented by a given point in the
* {@link ProgressControl}.
*
* @extends Component
*/
var MouseTimeDisplay = function (_Component) {
inherits(MouseTimeDisplay, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The {@link Player} that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function MouseTimeDisplay(player, options) {
classCallCheck(this, MouseTimeDisplay);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.update = throttle(bind(_this, _this.update), 25);
return _this;
}
/**
* Create the DOM element for this class.
*
* @return {Element}
* The element that was created.
*/
MouseTimeDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-mouse-display'
});
};
/**
* Enqueues updates to its own DOM as well as the DOM of its
* {@link TimeTooltip} child.
*
* @param {Object} seekBarRect
* The `ClientRect` for the {@link SeekBar} element.
*
* @param {number} seekBarPoint
* A number from 0 to 1, representing a horizontal reference point
* from the left edge of the {@link SeekBar}
*/
MouseTimeDisplay.prototype.update = function update(seekBarRect, seekBarPoint) {
var _this2 = this;
// If there is an existing rAF ID, cancel it so we don't over-queue.
if (this.rafId_) {
this.cancelAnimationFrame(this.rafId_);
}
this.rafId_ = this.requestAnimationFrame(function () {
var duration = _this2.player_.duration();
var content = formatTime(seekBarPoint * duration, duration);
_this2.el_.style.left = seekBarRect.width * seekBarPoint + 'px';
_this2.getChild('timeTooltip').update(seekBarRect, seekBarPoint, content);
});
};
return MouseTimeDisplay;
}(Component);
/**
* Default options for `MouseTimeDisplay`
*
* @type {Object}
* @private
*/
MouseTimeDisplay.prototype.options_ = {
children: ['timeTooltip']
};
Component.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
/**
* @file seek-bar.js
*/
// The number of seconds the `step*` functions move the timeline.
var STEP_SECONDS = 5;
// The interval at which the bar should update as it progresses.
var UPDATE_REFRESH_INTERVAL = 30;
/**
* Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
* as its `bar`.
*
* @extends Slider
*/
var SeekBar = function (_Slider) {
inherits(SeekBar, _Slider);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function SeekBar(player, options) {
classCallCheck(this, SeekBar);
var _this = possibleConstructorReturn(this, _Slider.call(this, player, options));
_this.setEventHandlers_();
return _this;
}
/**
* Sets the event handlers
*
* @private
*/
SeekBar.prototype.setEventHandlers_ = function setEventHandlers_() {
var _this2 = this;
this.update = throttle(bind(this, this.update), UPDATE_REFRESH_INTERVAL);
this.on(this.player_, 'timeupdate', this.update);
this.on(this.player_, 'ended', this.handleEnded);
// when playing, let's ensure we smoothly update the play progress bar
// via an interval
this.updateInterval = null;
this.on(this.player_, ['playing'], function () {
_this2.clearInterval(_this2.updateInterval);
_this2.updateInterval = _this2.setInterval(function () {
_this2.requestAnimationFrame(function () {
_this2.update();
});
}, UPDATE_REFRESH_INTERVAL);
});
this.on(this.player_, ['ended', 'pause', 'waiting'], function () {
_this2.clearInterval(_this2.updateInterval);
});
this.on(this.player_, ['timeupdate', 'ended'], this.update);
};
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
SeekBar.prototype.createEl = function createEl$$1() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-holder'
}, {
'aria-label': this.localize('Progress Bar')
});
};
/**
* This function updates the play progress bar and accessiblity
* attributes to whatever is passed in.
*
* @param {number} currentTime
* The currentTime value that should be used for accessiblity
*
* @param {number} percent
* The percentage as a decimal that the bar should be filled from 0-1.
*
* @private
*/
SeekBar.prototype.update_ = function update_(currentTime, percent) {
var duration = this.player_.duration();
// machine readable value of progress bar (percentage complete)
this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
// human readable value of progress bar (time complete)
this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
// Update the `PlayProgressBar`.
this.bar.update(getBoundingClientRect(this.el_), percent);
};
/**
* Update the seek bar's UI.
*
* @param {EventTarget~Event} [event]
* The `timeupdate` or `ended` event that caused this to run.
*
* @listens Player#timeupdate
*
* @returns {number}
* The current percent at a number from 0-1
*/
SeekBar.prototype.update = function update(event) {
var percent = _Slider.prototype.update.call(this);
this.update_(this.getCurrentTime_(), percent);
return percent;
};
/**
* Get the value of current time but allows for smooth scrubbing,
* when player can't keep up.
*
* @return {number}
* The current time value to display
*
* @private
*/
SeekBar.prototype.getCurrentTime_ = function getCurrentTime_() {
return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
};
/**
* We want the seek bar to be full on ended
* no matter what the actual internal values are. so we force it.
*
* @param {EventTarget~Event} [event]
* The `timeupdate` or `ended` event that caused this to run.
*
* @listens Player#ended
*/
SeekBar.prototype.handleEnded = function handleEnded(event) {
this.update_(this.player_.duration(), 1);
};
/**
* Get the percentage of media played so far.
*
* @return {number}
* The percentage of media played so far (0 to 1).
*/
SeekBar.prototype.getPercent = function getPercent() {
var percent = this.getCurrentTime_() / this.player_.duration();
return percent >= 1 ? 1 : percent;
};
/**
* Handle mouse down on seek bar
*
* @param {EventTarget~Event} event
* The `mousedown` event that caused this to run.
*
* @listens mousedown
*/
SeekBar.prototype.handleMouseDown = function handleMouseDown(event) {
if (!isSingleLeftClick(event)) {
return;
}
// Stop event propagation to prevent double fire in progress-control.js
event.stopPropagation();
this.player_.scrubbing(true);
this.videoWasPlaying = !this.player_.paused();
this.player_.pause();
_Slider.prototype.handleMouseDown.call(this, event);
};
/**
* Handle mouse move on seek bar
*
* @param {EventTarget~Event} event
* The `mousemove` event that caused this to run.
*
* @listens mousemove
*/
SeekBar.prototype.handleMouseMove = function handleMouseMove(event) {
if (!isSingleLeftClick(event)) {
return;
}
var newTime = this.calculateDistance(event) * this.player_.duration();
// Don't let video end while scrubbing.
if (newTime === this.player_.duration()) {
newTime = newTime - 0.1;
}
// Set new time (tell player to seek to new time)
this.player_.currentTime(newTime);
};
SeekBar.prototype.enable = function enable() {
_Slider.prototype.enable.call(this);
var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
if (!mouseTimeDisplay) {
return;
}
mouseTimeDisplay.show();
};
SeekBar.prototype.disable = function disable() {
_Slider.prototype.disable.call(this);
var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
if (!mouseTimeDisplay) {
return;
}
mouseTimeDisplay.hide();
};
/**
* Handle mouse up on seek bar
*
* @param {EventTarget~Event} event
* The `mouseup` event that caused this to run.
*
* @listens mouseup
*/
SeekBar.prototype.handleMouseUp = function handleMouseUp(event) {
_Slider.prototype.handleMouseUp.call(this, event);
// Stop event propagation to prevent double fire in progress-control.js
if (event) {
event.stopPropagation();
}
this.player_.scrubbing(false);
/**
* Trigger timeupdate because we're done seeking and the time has changed.
* This is particularly useful for if the player is paused to time the time displays.
*
* @event Tech#timeupdate
* @type {EventTarget~Event}
*/
this.player_.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
if (this.videoWasPlaying) {
silencePromise(this.player_.play());
}
};
/**
* Move more quickly fast forward for keyboard-only users
*/
SeekBar.prototype.stepForward = function stepForward() {
this.player_.currentTime(this.player_.currentTime() + STEP_SECONDS);
};
/**
* Move more quickly rewind for keyboard-only users
*/
SeekBar.prototype.stepBack = function stepBack() {
this.player_.currentTime(this.player_.currentTime() - STEP_SECONDS);
};
/**
* Toggles the playback state of the player
* This gets called when enter or space is used on the seekbar
*
* @param {EventTarget~Event} event
* The `keydown` event that caused this function to be called
*
*/
SeekBar.prototype.handleAction = function handleAction(event) {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
/**
* Called when this SeekBar has focus and a key gets pressed down. By
* default it will call `this.handleAction` when the key is space or enter.
*
* @param {EventTarget~Event} event
* The `keydown` event that caused this function to be called.
*
* @listens keydown
*/
SeekBar.prototype.handleKeyPress = function handleKeyPress(event) {
// Support Space (32) or Enter (13) key operation to fire a click event
if (event.which === 32 || event.which === 13) {
event.preventDefault();
this.handleAction(event);
} else if (_Slider.prototype.handleKeyPress) {
// Pass keypress handling up for unsupported keys
_Slider.prototype.handleKeyPress.call(this, event);
}
};
return SeekBar;
}(Slider);
/**
* Default options for the `SeekBar`
*
* @type {Object}
* @private
*/
SeekBar.prototype.options_ = {
children: ['loadProgressBar', 'playProgressBar'],
barName: 'playProgressBar'
};
// MouseTimeDisplay tooltips should not be added to a player on mobile devices or IE8
if ((!IE_VERSION || IE_VERSION > 8) && !IS_IOS && !IS_ANDROID) {
SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
}
/**
* Call the update event for this Slider when this event happens on the player.
*
* @type {string}
*/
SeekBar.prototype.playerEvent = 'timeupdate';
Component.registerComponent('SeekBar', SeekBar);
/**
* @file progress-control.js
*/
/**
* The Progress Control component contains the seek bar, load progress,
* and play progress.
*
* @extends Component
*/
var ProgressControl = function (_Component) {
inherits(ProgressControl, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function ProgressControl(player, options) {
classCallCheck(this, ProgressControl);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.handleMouseMove = throttle(bind(_this, _this.handleMouseMove), 25);
_this.throttledHandleMouseSeek = throttle(bind(_this, _this.handleMouseSeek), 25);
_this.enable();
return _this;
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
ProgressControl.prototype.createEl = function createEl$$1() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-control vjs-control'
});
};
/**
* When the mouse moves over the `ProgressControl`, the pointer position
* gets passed down to the `MouseTimeDisplay` component.
*
* @param {EventTarget~Event} event
* The `mousemove` event that caused this function to run.
*
* @listen mousemove
*/
ProgressControl.prototype.handleMouseMove = function handleMouseMove(event) {
var seekBar = this.getChild('seekBar');
if (seekBar) {
var mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
var seekBarEl = seekBar.el();
var seekBarRect = getBoundingClientRect(seekBarEl);
var seekBarPoint = getPointerPosition(seekBarEl, event).x;
// The default skin has a gap on either side of the `SeekBar`. This means
// that it's possible to trigger this behavior outside the boundaries of
// the `SeekBar`. This ensures we stay within it at all times.
if (seekBarPoint > 1) {
seekBarPoint = 1;
} else if (seekBarPoint < 0) {
seekBarPoint = 0;
}
if (mouseTimeDisplay) {
mouseTimeDisplay.update(seekBarRect, seekBarPoint);
}
}
};
/**
* A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
*
* @method ProgressControl#throttledHandleMouseSeek
* @param {EventTarget~Event} event
* The `mousemove` event that caused this function to run.
*
* @listen mousemove
* @listen touchmove
*/
/**
* Handle `mousemove` or `touchmove` events on the `ProgressControl`.
*
* @param {EventTarget~Event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousemove
* @listens touchmove
*/
ProgressControl.prototype.handleMouseSeek = function handleMouseSeek(event) {
var seekBar = this.getChild('seekBar');
if (seekBar) {
seekBar.handleMouseMove(event);
}
};
/**
* Are controls are currently enabled for this progress control.
*
* @return {boolean}
* true if controls are enabled, false otherwise
*/
ProgressControl.prototype.enabled = function enabled() {
return this.enabled_;
};
/**
* Disable all controls on the progress control and its children
*/
ProgressControl.prototype.disable = function disable() {
this.children().forEach(function (child) {
return child.disable && child.disable();
});
if (!this.enabled()) {
return;
}
this.off(['mousedown', 'touchstart'], this.handleMouseDown);
this.off(this.el_, 'mousemove', this.handleMouseMove);
this.handleMouseUp();
this.addClass('disabled');
this.enabled_ = false;
};
/**
* Enable all controls on the progress control and its children
*/
ProgressControl.prototype.enable = function enable() {
this.children().forEach(function (child) {
return child.enable && child.enable();
});
if (this.enabled()) {
return;
}
this.on(['mousedown', 'touchstart'], this.handleMouseDown);
this.on(this.el_, 'mousemove', this.handleMouseMove);
this.removeClass('disabled');
this.enabled_ = true;
};
/**
* Handle `mousedown` or `touchstart` events on the `ProgressControl`.
*
* @param {EventTarget~Event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
*/
ProgressControl.prototype.handleMouseDown = function handleMouseDown(event) {
var doc = this.el_.ownerDocument;
var seekBar = this.getChild('seekBar');
if (seekBar) {
seekBar.handleMouseDown(event);
}
this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
this.on(doc, 'mouseup', this.handleMouseUp);
this.on(doc, 'touchend', this.handleMouseUp);
};
/**
* Handle `mouseup` or `touchend` events on the `ProgressControl`.
*
* @param {EventTarget~Event} event
* `mouseup` or `touchend` event that triggered this function.
*
* @listens touchend
* @listens mouseup
*/
ProgressControl.prototype.handleMouseUp = function handleMouseUp(event) {
var doc = this.el_.ownerDocument;
var seekBar = this.getChild('seekBar');
if (seekBar) {
seekBar.handleMouseUp(event);
}
this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
this.off(doc, 'mouseup', this.handleMouseUp);
this.off(doc, 'touchend', this.handleMouseUp);
};
return ProgressControl;
}(Component);
/**
* Default options for `ProgressControl`
*
* @type {Object}
* @private
*/
ProgressControl.prototype.options_ = {
children: ['seekBar']
};
Component.registerComponent('ProgressControl', ProgressControl);
/**
* @file fullscreen-toggle.js
*/
/**
* Toggle fullscreen video
*
* @extends Button
*/
var FullscreenToggle = function (_Button) {
inherits(FullscreenToggle, _Button);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function FullscreenToggle(player, options) {
classCallCheck(this, FullscreenToggle);
var _this = possibleConstructorReturn(this, _Button.call(this, player, options));
_this.on(player, 'fullscreenchange', _this.handleFullscreenChange);
if (document[FullscreenApi.fullscreenEnabled] === false) {
_this.disable();
}
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handles fullscreenchange on the player and change control text accordingly.
*
* @param {EventTarget~Event} [event]
* The {@link Player#fullscreenchange} event that caused this function to be
* called.
*
* @listens Player#fullscreenchange
*/
FullscreenToggle.prototype.handleFullscreenChange = function handleFullscreenChange(event) {
if (this.player_.isFullscreen()) {
this.controlText('Non-Fullscreen');
} else {
this.controlText('Fullscreen');
}
};
/**
* This gets called when an `FullscreenToggle` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
FullscreenToggle.prototype.handleClick = function handleClick(event) {
if (!this.player_.isFullscreen()) {
this.player_.requestFullscreen();
} else {
this.player_.exitFullscreen();
}
};
return FullscreenToggle;
}(Button);
/**
* The text that should display over the `FullscreenToggle`s controls. Added for localization.
*
* @type {string}
* @private
*/
FullscreenToggle.prototype.controlText_ = 'Fullscreen';
Component.registerComponent('FullscreenToggle', FullscreenToggle);
/**
* Check if volume control is supported and if it isn't hide the
* `Component` that was passed using the `vjs-hidden` class.
*
* @param {Component} self
* The component that should be hidden if volume is unsupported
*
* @param {Player} player
* A reference to the player
*
* @private
*/
var checkVolumeSupport = function checkVolumeSupport(self, player) {
// hide volume controls when they're not supported by the current tech
if (player.tech_ && !player.tech_.featuresVolumeControl) {
self.addClass('vjs-hidden');
}
self.on(player, 'loadstart', function () {
if (!player.tech_.featuresVolumeControl) {
self.addClass('vjs-hidden');
} else {
self.removeClass('vjs-hidden');
}
});
};
/**
* @file volume-level.js
*/
/**
* Shows volume level
*
* @extends Component
*/
var VolumeLevel = function (_Component) {
inherits(VolumeLevel, _Component);
function VolumeLevel() {
classCallCheck(this, VolumeLevel);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
VolumeLevel.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-level',
innerHTML: '<span class="vjs-control-text"></span>'
});
};
return VolumeLevel;
}(Component);
Component.registerComponent('VolumeLevel', VolumeLevel);
/**
* @file volume-bar.js
*/
// Required children
/**
* The bar that contains the volume level and can be clicked on to adjust the level
*
* @extends Slider
*/
var VolumeBar = function (_Slider) {
inherits(VolumeBar, _Slider);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function VolumeBar(player, options) {
classCallCheck(this, VolumeBar);
var _this = possibleConstructorReturn(this, _Slider.call(this, player, options));
_this.on('slideractive', _this.updateLastVolume_);
_this.on(player, 'volumechange', _this.updateARIAAttributes);
player.ready(function () {
return _this.updateARIAAttributes();
});
return _this;
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
VolumeBar.prototype.createEl = function createEl$$1() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-bar vjs-slider-bar'
}, {
'aria-label': this.localize('Volume Level'),
'aria-live': 'polite'
});
};
/**
* Handle mouse down on volume bar
*
* @param {EventTarget~Event} event
* The `mousedown` event that caused this to run.
*
* @listens mousedown
*/
VolumeBar.prototype.handleMouseDown = function handleMouseDown(event) {
if (!isSingleLeftClick(event)) {
return;
}
_Slider.prototype.handleMouseDown.call(this, event);
};
/**
* Handle movement events on the {@link VolumeMenuButton}.
*
* @param {EventTarget~Event} event
* The event that caused this function to run.
*
* @listens mousemove
*/
VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) {
if (!isSingleLeftClick(event)) {
return;
}
this.checkMuted();
this.player_.volume(this.calculateDistance(event));
};
/**
* If the player is muted unmute it.
*/
VolumeBar.prototype.checkMuted = function checkMuted() {
if (this.player_.muted()) {
this.player_.muted(false);
}
};
/**
* Get percent of volume level
*
* @return {number}
* Volume level percent as a decimal number.
*/
VolumeBar.prototype.getPercent = function getPercent() {
if (this.player_.muted()) {
return 0;
}
return this.player_.volume();
};
/**
* Increase volume level for keyboard users
*/
VolumeBar.prototype.stepForward = function stepForward() {
this.checkMuted();
this.player_.volume(this.player_.volume() + 0.1);
};
/**
* Decrease volume level for keyboard users
*/
VolumeBar.prototype.stepBack = function stepBack() {
this.checkMuted();
this.player_.volume(this.player_.volume() - 0.1);
};
/**
* Update ARIA accessibility attributes
*
* @param {EventTarget~Event} [event]
* The `volumechange` event that caused this function to run.
*
* @listens Player#volumechange
*/
VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes(event) {
var ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
this.el_.setAttribute('aria-valuenow', ariaValue);
this.el_.setAttribute('aria-valuetext', ariaValue + '%');
};
/**
* Returns the current value of the player volume as a percentage
*
* @private
*/
VolumeBar.prototype.volumeAsPercentage_ = function volumeAsPercentage_() {
return Math.round(this.player_.volume() * 100);
};
/**
* When user starts dragging the VolumeBar, store the volume and listen for
* the end of the drag. When the drag ends, if the volume was set to zero,
* set lastVolume to the stored volume.
*
* @listens slideractive
* @private
*/
VolumeBar.prototype.updateLastVolume_ = function updateLastVolume_() {
var _this2 = this;
var volumeBeforeDrag = this.player_.volume();
this.one('sliderinactive', function () {
if (_this2.player_.volume() === 0) {
_this2.player_.lastVolume_(volumeBeforeDrag);
}
});
};
return VolumeBar;
}(Slider);
/**
* Default options for the `VolumeBar`
*
* @type {Object}
* @private
*/
VolumeBar.prototype.options_ = {
children: ['volumeLevel'],
barName: 'volumeLevel'
};
/**
* Call the update event for this Slider when this event happens on the player.
*
* @type {string}
*/
VolumeBar.prototype.playerEvent = 'volumechange';
Component.registerComponent('VolumeBar', VolumeBar);
/**
* @file volume-control.js
*/
// Required children
/**
* The component for controlling the volume level
*
* @extends Component
*/
var VolumeControl = function (_Component) {
inherits(VolumeControl, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options={}]
* The key/value store of player options.
*/
function VolumeControl(player) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, VolumeControl);
options.vertical = options.vertical || false;
// Pass the vertical option down to the VolumeBar if
// the VolumeBar is turned on.
if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
options.volumeBar = options.volumeBar || {};
options.volumeBar.vertical = options.vertical;
}
// hide this control if volume support is missing
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
checkVolumeSupport(_this, player);
_this.throttledHandleMouseMove = throttle(bind(_this, _this.handleMouseMove), 25);
_this.on('mousedown', _this.handleMouseDown);
_this.on('touchstart', _this.handleMouseDown);
// while the slider is active (the mouse has been pressed down and
// is dragging) or in focus we do not want to hide the VolumeBar
_this.on(_this.volumeBar, ['focus', 'slideractive'], function () {
_this.volumeBar.addClass('vjs-slider-active');
_this.addClass('vjs-slider-active');
_this.trigger('slideractive');
});
_this.on(_this.volumeBar, ['blur', 'sliderinactive'], function () {
_this.volumeBar.removeClass('vjs-slider-active');
_this.removeClass('vjs-slider-active');
_this.trigger('sliderinactive');
});
return _this;
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
VolumeControl.prototype.createEl = function createEl() {
var orientationClass = 'vjs-volume-horizontal';
if (this.options_.vertical) {
orientationClass = 'vjs-volume-vertical';
}
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-control vjs-control ' + orientationClass
});
};
/**
* Handle `mousedown` or `touchstart` events on the `VolumeControl`.
*
* @param {EventTarget~Event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
*/
VolumeControl.prototype.handleMouseDown = function handleMouseDown(event) {
var doc = this.el_.ownerDocument;
this.on(doc, 'mousemove', this.throttledHandleMouseMove);
this.on(doc, 'touchmove', this.throttledHandleMouseMove);
this.on(doc, 'mouseup', this.handleMouseUp);
this.on(doc, 'touchend', this.handleMouseUp);
};
/**
* Handle `mouseup` or `touchend` events on the `VolumeControl`.
*
* @param {EventTarget~Event} event
* `mouseup` or `touchend` event that triggered this function.
*
* @listens touchend
* @listens mouseup
*/
VolumeControl.prototype.handleMouseUp = function handleMouseUp(event) {
var doc = this.el_.ownerDocument;
this.off(doc, 'mousemove', this.throttledHandleMouseMove);
this.off(doc, 'touchmove', this.throttledHandleMouseMove);
this.off(doc, 'mouseup', this.handleMouseUp);
this.off(doc, 'touchend', this.handleMouseUp);
};
/**
* Handle `mousedown` or `touchstart` events on the `VolumeControl`.
*
* @param {EventTarget~Event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
*/
VolumeControl.prototype.handleMouseMove = function handleMouseMove(event) {
this.volumeBar.handleMouseMove(event);
};
return VolumeControl;
}(Component);
/**
* Default options for the `VolumeControl`
*
* @type {Object}
* @private
*/
VolumeControl.prototype.options_ = {
children: ['volumeBar']
};
Component.registerComponent('VolumeControl', VolumeControl);
/**
* Check if muting volume is supported and if it isn't hide the mute toggle
* button.
*
* @param {Component} self
* A reference to the mute toggle button
*
* @param {Player} player
* A reference to the player
*
* @private
*/
var checkMuteSupport = function checkMuteSupport(self, player) {
// hide mute toggle button if it's not supported by the current tech
if (player.tech_ && !player.tech_.featuresMuteControl) {
self.addClass('vjs-hidden');
}
self.on(player, 'loadstart', function () {
if (!player.tech_.featuresMuteControl) {
self.addClass('vjs-hidden');
} else {
self.removeClass('vjs-hidden');
}
});
};
/**
* @file mute-toggle.js
*/
/**
* A button component for muting the audio.
*
* @extends Button
*/
var MuteToggle = function (_Button) {
inherits(MuteToggle, _Button);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function MuteToggle(player, options) {
classCallCheck(this, MuteToggle);
// hide this control if volume support is missing
var _this = possibleConstructorReturn(this, _Button.call(this, player, options));
checkMuteSupport(_this, player);
_this.on(player, ['loadstart', 'volumechange'], _this.update);
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
MuteToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* This gets called when an `MuteToggle` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
MuteToggle.prototype.handleClick = function handleClick(event) {
var vol = this.player_.volume();
var lastVolume = this.player_.lastVolume_();
if (vol === 0) {
var volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
this.player_.volume(volumeToSet);
this.player_.muted(false);
} else {
this.player_.muted(this.player_.muted() ? false : true);
}
};
/**
* Update the `MuteToggle` button based on the state of `volume` and `muted`
* on the player.
*
* @param {EventTarget~Event} [event]
* The {@link Player#loadstart} event if this function was called
* through an event.
*
* @listens Player#loadstart
* @listens Player#volumechange
*/
MuteToggle.prototype.update = function update(event) {
this.updateIcon_();
this.updateControlText_();
};
/**
* Update the appearance of the `MuteToggle` icon.
*
* Possible states (given `level` variable below):
* - 0: crossed out
* - 1: zero bars of volume
* - 2: one bar of volume
* - 3: two bars of volume
*
* @private
*/
MuteToggle.prototype.updateIcon_ = function updateIcon_() {
var vol = this.player_.volume();
var level = 3;
// in iOS when a player is loaded with muted attribute
// and volume is changed with a native mute button
// we want to make sure muted state is updated
if (IS_IOS) {
this.player_.muted(this.player_.tech_.el_.muted);
}
if (vol === 0 || this.player_.muted()) {
level = 0;
} else if (vol < 0.33) {
level = 1;
} else if (vol < 0.67) {
level = 2;
}
// TODO improve muted icon classes
for (var i = 0; i < 4; i++) {
removeClass(this.el_, 'vjs-vol-' + i);
}
addClass(this.el_, 'vjs-vol-' + level);
};
/**
* If `muted` has changed on the player, update the control text
* (`title` attribute on `vjs-mute-control` element and content of
* `vjs-control-text` element).
*
* @private
*/
MuteToggle.prototype.updateControlText_ = function updateControlText_() {
var soundOff = this.player_.muted() || this.player_.volume() === 0;
var text = soundOff ? 'Unmute' : 'Mute';
if (this.controlText() !== text) {
this.controlText(text);
}
};
return MuteToggle;
}(Button);
/**
* The text that should display over the `MuteToggle`s controls. Added for localization.
*
* @type {string}
* @private
*/
MuteToggle.prototype.controlText_ = 'Mute';
Component.registerComponent('MuteToggle', MuteToggle);
/**
* @file volume-control.js
*/
// Required children
/**
* A Component to contain the MuteToggle and VolumeControl so that
* they can work together.
*
* @extends Component
*/
var VolumePanel = function (_Component) {
inherits(VolumePanel, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options={}]
* The key/value store of player options.
*/
function VolumePanel(player) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, VolumePanel);
if (typeof options.inline !== 'undefined') {
options.inline = options.inline;
} else {
options.inline = true;
}
// pass the inline option down to the VolumeControl as vertical if
// the VolumeControl is on.
if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
options.volumeControl = options.volumeControl || {};
options.volumeControl.vertical = !options.inline;
}
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.on(player, ['loadstart'], _this.volumePanelState_);
// while the slider is active (the mouse has been pressed down and
// is dragging) we do not want to hide the VolumeBar
_this.on(_this.volumeControl, ['slideractive'], _this.sliderActive_);
_this.on(_this.volumeControl, ['sliderinactive'], _this.sliderInactive_);
return _this;
}
/**
* Add vjs-slider-active class to the VolumePanel
*
* @listens VolumeControl#slideractive
* @private
*/
VolumePanel.prototype.sliderActive_ = function sliderActive_() {
this.addClass('vjs-slider-active');
};
/**
* Removes vjs-slider-active class to the VolumePanel
*
* @listens VolumeControl#sliderinactive
* @private
*/
VolumePanel.prototype.sliderInactive_ = function sliderInactive_() {
this.removeClass('vjs-slider-active');
};
/**
* Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
* depending on MuteToggle and VolumeControl state
*
* @listens Player#loadstart
* @private
*/
VolumePanel.prototype.volumePanelState_ = function volumePanelState_() {
// hide volume panel if neither volume control or mute toggle
// are displayed
if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
this.addClass('vjs-hidden');
}
// if only mute toggle is visible we don't want
// volume panel expanding when hovered or active
if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
this.addClass('vjs-mute-toggle-only');
}
};
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
VolumePanel.prototype.createEl = function createEl() {
var orientationClass = 'vjs-volume-panel-horizontal';
if (!this.options_.inline) {
orientationClass = 'vjs-volume-panel-vertical';
}
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-panel vjs-control ' + orientationClass
});
};
return VolumePanel;
}(Component);
/**
* Default options for the `VolumeControl`
*
* @type {Object}
* @private
*/
VolumePanel.prototype.options_ = {
children: ['muteToggle', 'volumeControl']
};
Component.registerComponent('VolumePanel', VolumePanel);
/**
* @file menu.js
*/
/**
* The Menu component is used to build popup menus, including subtitle and
* captions selection menus.
*
* @extends Component
*/
var Menu = function (_Component) {
inherits(Menu, _Component);
/**
* Create an instance of this class.
*
* @param {Player} player
* the player that this component should attach to
*
* @param {Object} [options]
* Object of option names and values
*
*/
function Menu(player, options) {
classCallCheck(this, Menu);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
if (options) {
_this.menuButton_ = options.menuButton;
}
_this.focusedChild_ = -1;
_this.on('keydown', _this.handleKeyPress);
return _this;
}
/**
* Add a {@link MenuItem} to the menu.
*
* @param {Object|string} component
* The name or instance of the `MenuItem` to add.
*
*/
Menu.prototype.addItem = function addItem(component) {
this.addChild(component);
component.on('click', bind(this, function (event) {
// Unpress the associated MenuButton, and move focus back to it
if (this.menuButton_) {
this.menuButton_.unpressButton();
// don't focus menu button if item is a caption settings item
// because focus will move elsewhere and it logs an error on IE8
if (component.name() !== 'CaptionSettingsMenuItem') {
this.menuButton_.focus();
}
}
}));
};
/**
* Create the `Menu`s DOM element.
*
* @return {Element}
* the element that was created
*/
Menu.prototype.createEl = function createEl$$1() {
var contentElType = this.options_.contentElType || 'ul';
this.contentEl_ = createEl(contentElType, {
className: 'vjs-menu-content'
});
this.contentEl_.setAttribute('role', 'menu');
var el = _Component.prototype.createEl.call(this, 'div', {
append: this.contentEl_,
className: 'vjs-menu'
});
el.appendChild(this.contentEl_);
// Prevent clicks from bubbling up. Needed for Menu Buttons,
// where a click on the parent is significant
on(el, 'click', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
return el;
};
Menu.prototype.dispose = function dispose() {
this.contentEl_ = null;
_Component.prototype.dispose.call(this);
};
/**
* Handle a `keydown` event on this menu. This listener is added in the constructor.
*
* @param {EventTarget~Event} event
* A `keydown` event that happened on the menu.
*
* @listens keydown
*/
Menu.prototype.handleKeyPress = function handleKeyPress(event) {
// Left and Down Arrows
if (event.which === 37 || event.which === 40) {
event.preventDefault();
this.stepForward();
// Up and Right Arrows
} else if (event.which === 38 || event.which === 39) {
event.preventDefault();
this.stepBack();
}
};
/**
* Move to next (lower) menu item for keyboard users.
*/
Menu.prototype.stepForward = function stepForward() {
var stepChild = 0;
if (this.focusedChild_ !== undefined) {
stepChild = this.focusedChild_ + 1;
}
this.focus(stepChild);
};
/**
* Move to previous (higher) menu item for keyboard users.
*/
Menu.prototype.stepBack = function stepBack() {
var stepChild = 0;
if (this.focusedChild_ !== undefined) {
stepChild = this.focusedChild_ - 1;
}
this.focus(stepChild);
};
/**
* Set focus on a {@link MenuItem} in the `Menu`.
*
* @param {Object|string} [item=0]
* Index of child item set focus on.
*/
Menu.prototype.focus = function focus() {
var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var children = this.children().slice();
var haveTitle = children.length && children[0].className && /vjs-menu-title/.test(children[0].className);
if (haveTitle) {
children.shift();
}
if (children.length > 0) {
if (item < 0) {
item = 0;
} else if (item >= children.length) {
item = children.length - 1;
}
this.focusedChild_ = item;
children[item].el_.focus();
}
};
return Menu;
}(Component);
Component.registerComponent('Menu', Menu);
/**
* @file menu-button.js
*/
/**
* A `MenuButton` class for any popup {@link Menu}.
*
* @extends Component
*/
var MenuButton = function (_Component) {
inherits(MenuButton, _Component);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options={}]
* The key/value store of player options.
*/
function MenuButton(player) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, MenuButton);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options));
_this.menuButton_ = new Button(player, options);
_this.menuButton_.controlText(_this.controlText_);
_this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
// Add buildCSSClass values to the button, not the wrapper
var buttonClass = Button.prototype.buildCSSClass();
_this.menuButton_.el_.className = _this.buildCSSClass() + ' ' + buttonClass;
_this.menuButton_.removeClass('vjs-control');
_this.addChild(_this.menuButton_);
_this.update();
_this.enabled_ = true;
_this.on(_this.menuButton_, 'tap', _this.handleClick);
_this.on(_this.menuButton_, 'click', _this.handleClick);
_this.on(_this.menuButton_, 'focus', _this.handleFocus);
_this.on(_this.menuButton_, 'blur', _this.handleBlur);
_this.on('keydown', _this.handleSubmenuKeyPress);
return _this;
}
/**
* Update the menu based on the current state of its items.
*/
MenuButton.prototype.update = function update() {
var menu = this.createMenu();
if (this.menu) {
this.menu.dispose();
this.removeChild(this.menu);
}
this.menu = menu;
this.addChild(menu);
/**
* Track the state of the menu button
*
* @type {Boolean}
* @private
*/
this.buttonPressed_ = false;
this.menuButton_.el_.setAttribute('aria-expanded', 'false');
if (this.items && this.items.length <= this.hideThreshold_) {
this.hide();
} else {
this.show();
}
};
/**
* Create the menu and add all items to it.
*
* @return {Menu}
* The constructed menu
*/
MenuButton.prototype.createMenu = function createMenu() {
var menu = new Menu(this.player_, { menuButton: this });
/**
* Hide the menu if the number of items is less than or equal to this threshold. This defaults
* to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
* it here because every time we run `createMenu` we need to reset the value.
*
* @protected
* @type {Number}
*/
this.hideThreshold_ = 0;
// Add a title list item to the top
if (this.options_.title) {
var title = createEl('li', {
className: 'vjs-menu-title',
innerHTML: toTitleCase(this.options_.title),
tabIndex: -1
});
this.hideThreshold_ += 1;
menu.children_.unshift(title);
prependTo(title, menu.contentEl());
}
this.items = this.createItems();
if (this.items) {
// Add menu items to the menu
for (var i = 0; i < this.items.length; i++) {
menu.addItem(this.items[i]);
}
}
return menu;
};
/**
* Create the list of menu items. Specific to each subclass.
*
* @abstract
*/
MenuButton.prototype.createItems = function createItems() {};
/**
* Create the `MenuButtons`s DOM element.
*
* @return {Element}
* The element that gets created.
*/
MenuButton.prototype.createEl = function createEl$$1() {
return _Component.prototype.createEl.call(this, 'div', {
className: this.buildWrapperCSSClass()
}, {});
};
/**
* Allow sub components to stack CSS class names for the wrapper element
*
* @return {string}
* The constructed wrapper DOM `className`
*/
MenuButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
var menuButtonClass = 'vjs-menu-button';
// If the inline option is passed, we want to use different styles altogether.
if (this.options_.inline === true) {
menuButtonClass += '-inline';
} else {
menuButtonClass += '-popup';
}
// TODO: Fix the CSS so that this isn't necessary
var buttonClass = Button.prototype.buildCSSClass();
return 'vjs-menu-button ' + menuButtonClass + ' ' + buttonClass + ' ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
MenuButton.prototype.buildCSSClass = function buildCSSClass() {
var menuButtonClass = 'vjs-menu-button';
// If the inline option is passed, we want to use different styles altogether.
if (this.options_.inline === true) {
menuButtonClass += '-inline';
} else {
menuButtonClass += '-popup';
}
return 'vjs-menu-button ' + menuButtonClass + ' ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Get or set the localized control text that will be used for accessibility.
*
* > NOTE: This will come from the internal `menuButton_` element.
*
* @param {string} [text]
* Control text for element.
*
* @param {Element} [el=this.menuButton_.el()]
* Element to set the title on.
*
* @return {string}
* - The control text when getting
*/
MenuButton.prototype.controlText = function controlText(text) {
var el = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.menuButton_.el();
return this.menuButton_.controlText(text, el);
};
/**
* Handle a click on a `MenuButton`.
* See {@link ClickableComponent#handleClick} for instances where this is called.
*
* @param {EventTarget~Event} event
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
MenuButton.prototype.handleClick = function handleClick(event) {
// When you click the button it adds focus, which will show the menu.
// So we'll remove focus when the mouse leaves the button. Focus is needed
// for tab navigation.
this.one(this.menu.contentEl(), 'mouseleave', bind(this, function (e) {
this.unpressButton();
this.el_.blur();
}));
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
};
/**
* Set the focus to the actual button, not to this element
*/
MenuButton.prototype.focus = function focus() {
this.menuButton_.focus();
};
/**
* Remove the focus from the actual button, not this element
*/
MenuButton.prototype.blur = function blur() {
this.menuButton_.blur();
};
/**
* This gets called when a `MenuButton` gains focus via a `focus` event.
* Turns on listening for `keydown` events. When they happen it
* calls `this.handleKeyPress`.
*
* @param {EventTarget~Event} event
* The `focus` event that caused this function to be called.
*
* @listens focus
*/
MenuButton.prototype.handleFocus = function handleFocus() {
on(document, 'keydown', bind(this, this.handleKeyPress));
};
/**
* Called when a `MenuButton` loses focus. Turns off the listener for
* `keydown` events. Which Stops `this.handleKeyPress` from getting called.
*
* @param {EventTarget~Event} event
* The `blur` event that caused this function to be called.
*
* @listens blur
*/
MenuButton.prototype.handleBlur = function handleBlur() {
off(document, 'keydown', bind(this, this.handleKeyPress));
};
/**
* Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
* {@link ClickableComponent#handleKeyPress} for instances where this is called.
*
* @param {EventTarget~Event} event
* The `keydown` event that caused this function to be called.
*
* @listens keydown
*/
MenuButton.prototype.handleKeyPress = function handleKeyPress(event) {
// Escape (27) key or Tab (9) key unpress the 'button'
if (event.which === 27 || event.which === 9) {
if (this.buttonPressed_) {
this.unpressButton();
}
// Don't preventDefault for Tab key - we still want to lose focus
if (event.which !== 9) {
event.preventDefault();
// Set focus back to the menu button's button
this.menuButton_.el_.focus();
}
// Up (38) key or Down (40) key press the 'button'
} else if (event.which === 38 || event.which === 40) {
if (!this.buttonPressed_) {
this.pressButton();
event.preventDefault();
}
}
};
/**
* Handle a `keydown` event on a sub-menu. The listener for this is added in
* the constructor.
*
* @param {EventTarget~Event} event
* Key press event
*
* @listens keydown
*/
MenuButton.prototype.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) {
// Escape (27) key or Tab (9) key unpress the 'button'
if (event.which === 27 || event.which === 9) {
if (this.buttonPressed_) {
this.unpressButton();
}
// Don't preventDefault for Tab key - we still want to lose focus
if (event.which !== 9) {
event.preventDefault();
// Set focus back to the menu button's button
this.menuButton_.el_.focus();
}
}
};
/**
* Put the current `MenuButton` into a pressed state.
*/
MenuButton.prototype.pressButton = function pressButton() {
if (this.enabled_) {
this.buttonPressed_ = true;
this.menu.lockShowing();
this.menuButton_.el_.setAttribute('aria-expanded', 'true');
// set the focus into the submenu, except on iOS where it is resulting in
// undesired scrolling behavior when the player is in an iframe
if (IS_IOS && isInFrame()) {
// Return early so that the menu isn't focused
return;
}
this.menu.focus();
}
};
/**
* Take the current `MenuButton` out of a pressed state.
*/
MenuButton.prototype.unpressButton = function unpressButton() {
if (this.enabled_) {
this.buttonPressed_ = false;
this.menu.unlockShowing();
this.menuButton_.el_.setAttribute('aria-expanded', 'false');
}
};
/**
* Disable the `MenuButton`. Don't allow it to be clicked.
*/
MenuButton.prototype.disable = function disable() {
this.unpressButton();
this.enabled_ = false;
this.addClass('vjs-disabled');
this.menuButton_.disable();
};
/**
* Enable the `MenuButton`. Allow it to be clicked.
*/
MenuButton.prototype.enable = function enable() {
this.enabled_ = true;
this.removeClass('vjs-disabled');
this.menuButton_.enable();
};
return MenuButton;
}(Component);
Component.registerComponent('MenuButton', MenuButton);
/**
* @file track-button.js
*/
/**
* The base class for buttons that toggle specific track types (e.g. subtitles).
*
* @extends MenuButton
*/
var TrackButton = function (_MenuButton) {
inherits(TrackButton, _MenuButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function TrackButton(player, options) {
classCallCheck(this, TrackButton);
var tracks = options.tracks;
var _this = possibleConstructorReturn(this, _MenuButton.call(this, player, options));
if (_this.items.length <= 1) {
_this.hide();
}
if (!tracks) {
return possibleConstructorReturn(_this);
}
var updateHandler = bind(_this, _this.update);
tracks.addEventListener('removetrack', updateHandler);
tracks.addEventListener('addtrack', updateHandler);
_this.player_.on('ready', updateHandler);
_this.player_.on('dispose', function () {
tracks.removeEventListener('removetrack', updateHandler);
tracks.removeEventListener('addtrack', updateHandler);
});
return _this;
}
return TrackButton;
}(MenuButton);
Component.registerComponent('TrackButton', TrackButton);
/**
* @file menu-item.js
*/
/**
* The component for a menu item. `<li>`
*
* @extends ClickableComponent
*/
var MenuItem = function (_ClickableComponent) {
inherits(MenuItem, _ClickableComponent);
/**
* Creates an instance of the this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options={}]
* The key/value store of player options.
*
*/
function MenuItem(player, options) {
classCallCheck(this, MenuItem);
var _this = possibleConstructorReturn(this, _ClickableComponent.call(this, player, options));
_this.selectable = options.selectable;
_this.isSelected_ = options.selected || false;
_this.multiSelectable = options.multiSelectable;
_this.selected(_this.isSelected_);
if (_this.selectable) {
if (_this.multiSelectable) {
_this.el_.setAttribute('role', 'menuitemcheckbox');
} else {
_this.el_.setAttribute('role', 'menuitemradio');
}
} else {
_this.el_.setAttribute('role', 'menuitem');
}
return _this;
}
/**
* Create the `MenuItem's DOM element
*
* @param {string} [type=li]
* Element's node type, not actually used, always set to `li`.
*
* @param {Object} [props={}]
* An object of properties that should be set on the element
*
* @param {Object} [attrs={}]
* An object of attributes that should be set on the element
*
* @return {Element}
* The element that gets created.
*/
MenuItem.prototype.createEl = function createEl(type, props, attrs) {
// The control is textual, not just an icon
this.nonIconControl = true;
return _ClickableComponent.prototype.createEl.call(this, 'li', assign({
className: 'vjs-menu-item',
innerHTML: '<span class="vjs-menu-item-text">' + this.localize(this.options_.label) + '</span>',
tabIndex: -1
}, props), attrs);
};
/**
* Any click on a `MenuItem` puts it into the selected state.
* See {@link ClickableComponent#handleClick} for instances where this is called.
*
* @param {EventTarget~Event} event
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
MenuItem.prototype.handleClick = function handleClick(event) {
this.selected(true);
};
/**
* Set the state for this menu item as selected or not.
*
* @param {boolean} selected
* if the menu item is selected or not
*/
MenuItem.prototype.selected = function selected(_selected) {
if (this.selectable) {
if (_selected) {
this.addClass('vjs-selected');
this.el_.setAttribute('aria-checked', 'true');
// aria-checked isn't fully supported by browsers/screen readers,
// so indicate selected state to screen reader in the control text.
this.controlText(', selected');
this.isSelected_ = true;
} else {
this.removeClass('vjs-selected');
this.el_.setAttribute('aria-checked', 'false');
// Indicate un-selected state to screen reader
this.controlText('');
this.isSelected_ = false;
}
}
};
return MenuItem;
}(ClickableComponent);
Component.registerComponent('MenuItem', MenuItem);
/**
* @file text-track-menu-item.js
*/
/**
* The specific menu item type for selecting a language within a text track kind
*
* @extends MenuItem
*/
var TextTrackMenuItem = function (_MenuItem) {
inherits(TextTrackMenuItem, _MenuItem);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function TextTrackMenuItem(player, options) {
classCallCheck(this, TextTrackMenuItem);
var track = options.track;
var tracks = player.textTracks();
// Modify options for parent MenuItem class's init.
options.label = track.label || track.language || 'Unknown';
options.selected = track.mode === 'showing';
var _this = possibleConstructorReturn(this, _MenuItem.call(this, player, options));
_this.track = track;
var changeHandler = function changeHandler() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.handleTracksChange.apply(_this, args);
};
var selectedLanguageChangeHandler = function selectedLanguageChangeHandler() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this.handleSelectedLanguageChange.apply(_this, args);
};
player.on(['loadstart', 'texttrackchange'], changeHandler);
tracks.addEventListener('change', changeHandler);
tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
_this.on('dispose', function () {
player.off(['loadstart', 'texttrackchange'], changeHandler);
tracks.removeEventListener('change', changeHandler);
tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
});
// iOS7 doesn't dispatch change events to TextTrackLists when an
// associated track's mode changes. Without something like
// Object.observe() (also not present on iOS7), it's not
// possible to detect changes to the mode attribute and polyfill
// the change event. As a poor substitute, we manually dispatch
// change events whenever the controls modify the mode.
if (tracks.onchange === undefined) {
var event = void 0;
_this.on(['tap', 'click'], function () {
if (_typeof(window.Event) !== 'object') {
// Android 2.3 throws an Illegal Constructor error for window.Event
try {
event = new window.Event('change');
} catch (err) {
// continue regardless of error
}
}
if (!event) {
event = document.createEvent('Event');
event.initEvent('change', true, true);
}
tracks.dispatchEvent(event);
});
}
// set the default state based on current tracks
_this.handleTracksChange();
return _this;
}
/**
* This gets called when an `TextTrackMenuItem` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} event
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
TextTrackMenuItem.prototype.handleClick = function handleClick(event) {
var kind = this.track.kind;
var kinds = this.track.kinds;
var tracks = this.player_.textTracks();
if (!kinds) {
kinds = [kind];
}
_MenuItem.prototype.handleClick.call(this, event);
if (!tracks) {
return;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track === this.track && kinds.indexOf(track.kind) > -1) {
if (track.mode !== 'showing') {
track.mode = 'showing';
}
} else if (track.mode !== 'disabled') {
track.mode = 'disabled';
}
}
};
/**
* Handle text track list change
*
* @param {EventTarget~Event} event
* The `change` event that caused this function to be called.
*
* @listens TextTrackList#change
*/
TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
var shouldBeSelected = this.track.mode === 'showing';
// Prevent redundant selected() calls because they may cause
// screen readers to read the appended control text unnecessarily
if (shouldBeSelected !== this.isSelected_) {
this.selected(shouldBeSelected);
}
};
TextTrackMenuItem.prototype.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
if (this.track.mode === 'showing') {
var selectedLanguage = this.player_.cache_.selectedLanguage;
// Don't replace the kind of track across the same language
if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
return;
}
this.player_.cache_.selectedLanguage = {
enabled: true,
language: this.track.language,
kind: this.track.kind
};
}
};
TextTrackMenuItem.prototype.dispose = function dispose() {
// remove reference to track object on dispose
this.track = null;
_MenuItem.prototype.dispose.call(this);
};
return TextTrackMenuItem;
}(MenuItem);
Component.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
/**
* @file off-text-track-menu-item.js
*/
/**
* A special menu item for turning of a specific type of text track
*
* @extends TextTrackMenuItem
*/
var OffTextTrackMenuItem = function (_TextTrackMenuItem) {
inherits(OffTextTrackMenuItem, _TextTrackMenuItem);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function OffTextTrackMenuItem(player, options) {
classCallCheck(this, OffTextTrackMenuItem);
// Create pseudo track info
// Requires options['kind']
options.track = {
player: player,
kind: options.kind,
kinds: options.kinds,
'default': false,
mode: 'disabled'
};
if (!options.kinds) {
options.kinds = [options.kind];
}
if (options.label) {
options.track.label = options.label;
} else {
options.track.label = options.kinds.join(' and ') + ' off';
}
// MenuItem is selectable
options.selectable = true;
// MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
options.multiSelectable = false;
return possibleConstructorReturn(this, _TextTrackMenuItem.call(this, player, options));
}
/**
* Handle text track change
*
* @param {EventTarget~Event} event
* The event that caused this function to run
*/
OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
var tracks = this.player().textTracks();
var shouldBeSelected = true;
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
shouldBeSelected = false;
break;
}
}
// Prevent redundant selected() calls because they may cause
// screen readers to read the appended control text unnecessarily
if (shouldBeSelected !== this.isSelected_) {
this.selected(shouldBeSelected);
}
};
OffTextTrackMenuItem.prototype.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
var tracks = this.player().textTracks();
var allHidden = true;
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
allHidden = false;
break;
}
}
if (allHidden) {
this.player_.cache_.selectedLanguage = {
enabled: false
};
}
};
return OffTextTrackMenuItem;
}(TextTrackMenuItem);
Component.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
/**
* @file text-track-button.js
*/
/**
* The base class for buttons that toggle specific text track types (e.g. subtitles)
*
* @extends MenuButton
*/
var TextTrackButton = function (_TrackButton) {
inherits(TextTrackButton, _TrackButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options={}]
* The key/value store of player options.
*/
function TextTrackButton(player) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, TextTrackButton);
options.tracks = player.textTracks();
return possibleConstructorReturn(this, _TrackButton.call(this, player, options));
}
/**
* Create a menu item for each text track
*
* @param {TextTrackMenuItem[]} [items=[]]
* Existing array of items to use during creation
*
* @return {TextTrackMenuItem[]}
* Array of menu items that were created
*/
TextTrackButton.prototype.createItems = function createItems() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var TrackMenuItem = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : TextTrackMenuItem;
// Label is an overide for the [track] off label
// USed to localise captions/subtitles
var label = void 0;
if (this.label_) {
label = this.label_ + ' off';
}
// Add an OFF menu item to turn all tracks off
items.push(new OffTextTrackMenuItem(this.player_, {
kinds: this.kinds_,
kind: this.kind_,
label: label
}));
this.hideThreshold_ += 1;
var tracks = this.player_.textTracks();
if (!Array.isArray(this.kinds_)) {
this.kinds_ = [this.kind_];
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// only add tracks that are of an appropriate kind and have a label
if (this.kinds_.indexOf(track.kind) > -1) {
var item = new TrackMenuItem(this.player_, {
track: track,
// MenuItem is selectable
selectable: true,
// MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
multiSelectable: false
});
item.addClass('vjs-' + track.kind + '-menu-item');
items.push(item);
}
}
return items;
};
return TextTrackButton;
}(TrackButton);
Component.registerComponent('TextTrackButton', TextTrackButton);
/**
* @file chapters-track-menu-item.js
*/
/**
* The chapter track menu item
*
* @extends MenuItem
*/
var ChaptersTrackMenuItem = function (_MenuItem) {
inherits(ChaptersTrackMenuItem, _MenuItem);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function ChaptersTrackMenuItem(player, options) {
classCallCheck(this, ChaptersTrackMenuItem);
var track = options.track;
var cue = options.cue;
var currentTime = player.currentTime();
// Modify options for parent MenuItem class's init.
options.selectable = true;
options.multiSelectable = false;
options.label = cue.text;
options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
var _this = possibleConstructorReturn(this, _MenuItem.call(this, player, options));
_this.track = track;
_this.cue = cue;
track.addEventListener('cuechange', bind(_this, _this.update));
return _this;
}
/**
* This gets called when an `ChaptersTrackMenuItem` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
ChaptersTrackMenuItem.prototype.handleClick = function handleClick(event) {
_MenuItem.prototype.handleClick.call(this);
this.player_.currentTime(this.cue.startTime);
this.update(this.cue.startTime);
};
/**
* Update chapter menu item
*
* @param {EventTarget~Event} [event]
* The `cuechange` event that caused this function to run.
*
* @listens TextTrack#cuechange
*/
ChaptersTrackMenuItem.prototype.update = function update(event) {
var cue = this.cue;
var currentTime = this.player_.currentTime();
// vjs.log(currentTime, cue.startTime);
this.selected(cue.startTime <= currentTime && currentTime < cue.endTime);
};
return ChaptersTrackMenuItem;
}(MenuItem);
Component.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
/**
* @file chapters-button.js
*/
/**
* The button component for toggling and selecting chapters
* Chapters act much differently than other text tracks
* Cues are navigation vs. other tracks of alternative languages
*
* @extends TextTrackButton
*/
var ChaptersButton = function (_TextTrackButton) {
inherits(ChaptersButton, _TextTrackButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} [ready]
* The function to call when this function is ready.
*/
function ChaptersButton(player, options, ready) {
classCallCheck(this, ChaptersButton);
return possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready));
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
ChaptersButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
ChaptersButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
};
/**
* Update the menu based on the current state of its items.
*
* @param {EventTarget~Event} [event]
* An event that triggered this function to run.
*
* @listens TextTrackList#addtrack
* @listens TextTrackList#removetrack
* @listens TextTrackList#change
*/
ChaptersButton.prototype.update = function update(event) {
if (!this.track_ || event && (event.type === 'addtrack' || event.type === 'removetrack')) {
this.setTrack(this.findChaptersTrack());
}
_TextTrackButton.prototype.update.call(this);
};
/**
* Set the currently selected track for the chapters button.
*
* @param {TextTrack} track
* The new track to select. Nothing will change if this is the currently selected
* track.
*/
ChaptersButton.prototype.setTrack = function setTrack(track) {
if (this.track_ === track) {
return;
}
if (!this.updateHandler_) {
this.updateHandler_ = this.update.bind(this);
}
// here this.track_ refers to the old track instance
if (this.track_) {
var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
if (remoteTextTrackEl) {
remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
}
this.track_ = null;
}
this.track_ = track;
// here this.track_ refers to the new track instance
if (this.track_) {
this.track_.mode = 'hidden';
var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
if (_remoteTextTrackEl) {
_remoteTextTrackEl.addEventListener('load', this.updateHandler_);
}
}
};
/**
* Find the track object that is currently in use by this ChaptersButton
*
* @return {TextTrack|undefined}
* The current track or undefined if none was found.
*/
ChaptersButton.prototype.findChaptersTrack = function findChaptersTrack() {
var tracks = this.player_.textTracks() || [];
for (var i = tracks.length - 1; i >= 0; i--) {
// We will always choose the last track as our chaptersTrack
var track = tracks[i];
if (track.kind === this.kind_) {
return track;
}
}
};
/**
* Get the caption for the ChaptersButton based on the track label. This will also
* use the current tracks localized kind as a fallback if a label does not exist.
*
* @return {string}
* The tracks current label or the localized track kind.
*/
ChaptersButton.prototype.getMenuCaption = function getMenuCaption() {
if (this.track_ && this.track_.label) {
return this.track_.label;
}
return this.localize(toTitleCase(this.kind_));
};
/**
* Create menu from chapter track
*
* @return {Menu}
* New menu for the chapter buttons
*/
ChaptersButton.prototype.createMenu = function createMenu() {
this.options_.title = this.getMenuCaption();
return _TextTrackButton.prototype.createMenu.call(this);
};
/**
* Create a menu item for each text track
*
* @return {TextTrackMenuItem[]}
* Array of menu items
*/
ChaptersButton.prototype.createItems = function createItems() {
var items = [];
if (!this.track_) {
return items;
}
var cues = this.track_.cues;
if (!cues) {
return items;
}
for (var i = 0, l = cues.length; i < l; i++) {
var cue = cues[i];
var mi = new ChaptersTrackMenuItem(this.player_, { track: this.track_, cue: cue });
items.push(mi);
}
return items;
};
return ChaptersButton;
}(TextTrackButton);
/**
* `kind` of TextTrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
ChaptersButton.prototype.kind_ = 'chapters';
/**
* The text that should display over the `ChaptersButton`s controls. Added for localization.
*
* @type {string}
* @private
*/
ChaptersButton.prototype.controlText_ = 'Chapters';
Component.registerComponent('ChaptersButton', ChaptersButton);
/**
* @file descriptions-button.js
*/
/**
* The button component for toggling and selecting descriptions
*
* @extends TextTrackButton
*/
var DescriptionsButton = function (_TextTrackButton) {
inherits(DescriptionsButton, _TextTrackButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} [ready]
* The function to call when this component is ready.
*/
function DescriptionsButton(player, options, ready) {
classCallCheck(this, DescriptionsButton);
var _this = possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready));
var tracks = player.textTracks();
var changeHandler = bind(_this, _this.handleTracksChange);
tracks.addEventListener('change', changeHandler);
_this.on('dispose', function () {
tracks.removeEventListener('change', changeHandler);
});
return _this;
}
/**
* Handle text track change
*
* @param {EventTarget~Event} event
* The event that caused this function to run
*
* @listens TextTrackList#change
*/
DescriptionsButton.prototype.handleTracksChange = function handleTracksChange(event) {
var tracks = this.player().textTracks();
var disabled = false;
// Check whether a track of a different kind is showing
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (track.kind !== this.kind_ && track.mode === 'showing') {
disabled = true;
break;
}
}
// If another track is showing, disable this menu button
if (disabled) {
this.disable();
} else {
this.enable();
}
};
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
DescriptionsButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-descriptions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
DescriptionsButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
return 'vjs-descriptions-button ' + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
};
return DescriptionsButton;
}(TextTrackButton);
/**
* `kind` of TextTrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
DescriptionsButton.prototype.kind_ = 'descriptions';
/**
* The text that should display over the `DescriptionsButton`s controls. Added for localization.
*
* @type {string}
* @private
*/
DescriptionsButton.prototype.controlText_ = 'Descriptions';
Component.registerComponent('DescriptionsButton', DescriptionsButton);
/**
* @file subtitles-button.js
*/
/**
* The button component for toggling and selecting subtitles
*
* @extends TextTrackButton
*/
var SubtitlesButton = function (_TextTrackButton) {
inherits(SubtitlesButton, _TextTrackButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} [ready]
* The function to call when this component is ready.
*/
function SubtitlesButton(player, options, ready) {
classCallCheck(this, SubtitlesButton);
return possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready));
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
SubtitlesButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
};
return SubtitlesButton;
}(TextTrackButton);
/**
* `kind` of TextTrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
SubtitlesButton.prototype.kind_ = 'subtitles';
/**
* The text that should display over the `SubtitlesButton`s controls. Added for localization.
*
* @type {string}
* @private
*/
SubtitlesButton.prototype.controlText_ = 'Subtitles';
Component.registerComponent('SubtitlesButton', SubtitlesButton);
/**
* @file caption-settings-menu-item.js
*/
/**
* The menu item for caption track settings menu
*
* @extends TextTrackMenuItem
*/
var CaptionSettingsMenuItem = function (_TextTrackMenuItem) {
inherits(CaptionSettingsMenuItem, _TextTrackMenuItem);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function CaptionSettingsMenuItem(player, options) {
classCallCheck(this, CaptionSettingsMenuItem);
options.track = {
player: player,
kind: options.kind,
label: options.kind + ' settings',
selectable: false,
'default': false,
mode: 'disabled'
};
// CaptionSettingsMenuItem has no concept of 'selected'
options.selectable = false;
options.name = 'CaptionSettingsMenuItem';
var _this = possibleConstructorReturn(this, _TextTrackMenuItem.call(this, player, options));
_this.addClass('vjs-texttrack-settings');
_this.controlText(', opens ' + options.kind + ' settings dialog');
return _this;
}
/**
* This gets called when an `CaptionSettingsMenuItem` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
CaptionSettingsMenuItem.prototype.handleClick = function handleClick(event) {
this.player().getChild('textTrackSettings').open();
};
return CaptionSettingsMenuItem;
}(TextTrackMenuItem);
Component.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
/**
* @file captions-button.js
*/
/**
* The button component for toggling and selecting captions
*
* @extends TextTrackButton
*/
var CaptionsButton = function (_TextTrackButton) {
inherits(CaptionsButton, _TextTrackButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} [ready]
* The function to call when this component is ready.
*/
function CaptionsButton(player, options, ready) {
classCallCheck(this, CaptionsButton);
return possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready));
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
CaptionsButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
CaptionsButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
return 'vjs-captions-button ' + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
};
/**
* Create caption menu items
*
* @return {CaptionSettingsMenuItem[]}
* The array of current menu items.
*/
CaptionsButton.prototype.createItems = function createItems() {
var items = [];
if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
items.push(new CaptionSettingsMenuItem(this.player_, { kind: this.kind_ }));
this.hideThreshold_ += 1;
}
return _TextTrackButton.prototype.createItems.call(this, items);
};
return CaptionsButton;
}(TextTrackButton);
/**
* `kind` of TextTrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
CaptionsButton.prototype.kind_ = 'captions';
/**
* The text that should display over the `CaptionsButton`s controls. Added for localization.
*
* @type {string}
* @private
*/
CaptionsButton.prototype.controlText_ = 'Captions';
Component.registerComponent('CaptionsButton', CaptionsButton);
/**
* @file subs-caps-menu-item.js
*/
/**
* SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
* in the SubsCapsMenu.
*
* @extends TextTrackMenuItem
*/
var SubsCapsMenuItem = function (_TextTrackMenuItem) {
inherits(SubsCapsMenuItem, _TextTrackMenuItem);
function SubsCapsMenuItem() {
classCallCheck(this, SubsCapsMenuItem);
return possibleConstructorReturn(this, _TextTrackMenuItem.apply(this, arguments));
}
SubsCapsMenuItem.prototype.createEl = function createEl(type, props, attrs) {
var innerHTML = '<span class="vjs-menu-item-text">' + this.localize(this.options_.label);
if (this.options_.track.kind === 'captions') {
innerHTML += '\n <span aria-hidden="true" class="vjs-icon-placeholder"></span>\n <span class="vjs-control-text"> ' + this.localize('Captions') + '</span>\n ';
}
innerHTML += '</span>';
var el = _TextTrackMenuItem.prototype.createEl.call(this, type, assign({
innerHTML: innerHTML
}, props), attrs);
return el;
};
return SubsCapsMenuItem;
}(TextTrackMenuItem);
Component.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
/**
* @file sub-caps-button.js
*/
/**
* The button component for toggling and selecting captions and/or subtitles
*
* @extends TextTrackButton
*/
var SubsCapsButton = function (_TextTrackButton) {
inherits(SubsCapsButton, _TextTrackButton);
function SubsCapsButton(player) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, SubsCapsButton);
// Although North America uses "captions" in most cases for
// "captions and subtitles" other locales use "subtitles"
var _this = possibleConstructorReturn(this, _TextTrackButton.call(this, player, options));
_this.label_ = 'subtitles';
if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(_this.player_.language_) > -1) {
_this.label_ = 'captions';
}
_this.menuButton_.controlText(toTitleCase(_this.label_));
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
SubsCapsButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-subs-caps-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
SubsCapsButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
return 'vjs-subs-caps-button ' + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
};
/**
* Create caption/subtitles menu items
*
* @return {CaptionSettingsMenuItem[]}
* The array of current menu items.
*/
SubsCapsButton.prototype.createItems = function createItems() {
var items = [];
if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
items.push(new CaptionSettingsMenuItem(this.player_, { kind: this.label_ }));
this.hideThreshold_ += 1;
}
items = _TextTrackButton.prototype.createItems.call(this, items, SubsCapsMenuItem);
return items;
};
return SubsCapsButton;
}(TextTrackButton);
/**
* `kind`s of TextTrack to look for to associate it with this menu.
*
* @type {array}
* @private
*/
SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
/**
* The text that should display over the `SubsCapsButton`s controls.
*
*
* @type {string}
* @private
*/
SubsCapsButton.prototype.controlText_ = 'Subtitles';
Component.registerComponent('SubsCapsButton', SubsCapsButton);
/**
* @file audio-track-menu-item.js
*/
/**
* An {@link AudioTrack} {@link MenuItem}
*
* @extends MenuItem
*/
var AudioTrackMenuItem = function (_MenuItem) {
inherits(AudioTrackMenuItem, _MenuItem);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function AudioTrackMenuItem(player, options) {
classCallCheck(this, AudioTrackMenuItem);
var track = options.track;
var tracks = player.audioTracks();
// Modify options for parent MenuItem class's init.
options.label = track.label || track.language || 'Unknown';
options.selected = track.enabled;
var _this = possibleConstructorReturn(this, _MenuItem.call(this, player, options));
_this.track = track;
_this.addClass('vjs-' + track.kind + '-menu-item');
var changeHandler = function changeHandler() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.handleTracksChange.apply(_this, args);
};
tracks.addEventListener('change', changeHandler);
_this.on('dispose', function () {
tracks.removeEventListener('change', changeHandler);
});
return _this;
}
AudioTrackMenuItem.prototype.createEl = function createEl(type, props, attrs) {
var innerHTML = '<span class="vjs-menu-item-text">' + this.localize(this.options_.label);
if (this.options_.track.kind === 'main-desc') {
innerHTML += '\n <span aria-hidden="true" class="vjs-icon-placeholder"></span>\n <span class="vjs-control-text"> ' + this.localize('Descriptions') + '</span>\n ';
}
innerHTML += '</span>';
var el = _MenuItem.prototype.createEl.call(this, type, assign({
innerHTML: innerHTML
}, props), attrs);
return el;
};
/**
* This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
* for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
AudioTrackMenuItem.prototype.handleClick = function handleClick(event) {
var tracks = this.player_.audioTracks();
_MenuItem.prototype.handleClick.call(this, event);
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.enabled = track === this.track;
}
};
/**
* Handle any {@link AudioTrack} change.
*
* @param {EventTarget~Event} [event]
* The {@link AudioTrackList#change} event that caused this to run.
*
* @listens AudioTrackList#change
*/
AudioTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
this.selected(this.track.enabled);
};
return AudioTrackMenuItem;
}(MenuItem);
Component.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
/**
* @file audio-track-button.js
*/
/**
* The base class for buttons that toggle specific {@link AudioTrack} types.
*
* @extends TrackButton
*/
var AudioTrackButton = function (_TrackButton) {
inherits(AudioTrackButton, _TrackButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options={}]
* The key/value store of player options.
*/
function AudioTrackButton(player) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, AudioTrackButton);
options.tracks = player.audioTracks();
return possibleConstructorReturn(this, _TrackButton.call(this, player, options));
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
AudioTrackButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-audio-button ' + _TrackButton.prototype.buildCSSClass.call(this);
};
AudioTrackButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
return 'vjs-audio-button ' + _TrackButton.prototype.buildWrapperCSSClass.call(this);
};
/**
* Create a menu item for each audio track
*
* @param {AudioTrackMenuItem[]} [items=[]]
* An array of existing menu items to use.
*
* @return {AudioTrackMenuItem[]}
* An array of menu items
*/
AudioTrackButton.prototype.createItems = function createItems() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
// if there's only one audio track, there no point in showing it
this.hideThreshold_ = 1;
var tracks = this.player_.audioTracks();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
items.push(new AudioTrackMenuItem(this.player_, {
track: track,
// MenuItem is selectable
selectable: true,
// MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
multiSelectable: false
}));
}
return items;
};
return AudioTrackButton;
}(TrackButton);
/**
* The text that should display over the `AudioTrackButton`s controls. Added for localization.
*
* @type {string}
* @private
*/
AudioTrackButton.prototype.controlText_ = 'Audio Track';
Component.registerComponent('AudioTrackButton', AudioTrackButton);
/**
* @file playback-rate-menu-item.js
*/
/**
* The specific menu item type for selecting a playback rate.
*
* @extends MenuItem
*/
var PlaybackRateMenuItem = function (_MenuItem) {
inherits(PlaybackRateMenuItem, _MenuItem);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function PlaybackRateMenuItem(player, options) {
classCallCheck(this, PlaybackRateMenuItem);
var label = options.rate;
var rate = parseFloat(label, 10);
// Modify options for parent MenuItem class's init.
options.label = label;
options.selected = rate === 1;
options.selectable = true;
options.multiSelectable = false;
var _this = possibleConstructorReturn(this, _MenuItem.call(this, player, options));
_this.label = label;
_this.rate = rate;
_this.on(player, 'ratechange', _this.update);
return _this;
}
/**
* This gets called when an `PlaybackRateMenuItem` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
PlaybackRateMenuItem.prototype.handleClick = function handleClick(event) {
_MenuItem.prototype.handleClick.call(this);
this.player().playbackRate(this.rate);
};
/**
* Update the PlaybackRateMenuItem when the playbackrate changes.
*
* @param {EventTarget~Event} [event]
* The `ratechange` event that caused this function to run.
*
* @listens Player#ratechange
*/
PlaybackRateMenuItem.prototype.update = function update(event) {
this.selected(this.player().playbackRate() === this.rate);
};
return PlaybackRateMenuItem;
}(MenuItem);
/**
* The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
*
* @type {string}
* @private
*/
PlaybackRateMenuItem.prototype.contentElType = 'button';
Component.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
/**
* @file playback-rate-menu-button.js
*/
/**
* The component for controlling the playback rate.
*
* @extends MenuButton
*/
var PlaybackRateMenuButton = function (_MenuButton) {
inherits(PlaybackRateMenuButton, _MenuButton);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function PlaybackRateMenuButton(player, options) {
classCallCheck(this, PlaybackRateMenuButton);
var _this = possibleConstructorReturn(this, _MenuButton.call(this, player, options));
_this.updateVisibility();
_this.updateLabel();
_this.on(player, 'loadstart', _this.updateVisibility);
_this.on(player, 'ratechange', _this.updateLabel);
return _this;
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
PlaybackRateMenuButton.prototype.createEl = function createEl$$1() {
var el = _MenuButton.prototype.createEl.call(this);
this.labelEl_ = createEl('div', {
className: 'vjs-playback-rate-value',
innerHTML: '1x'
});
el.appendChild(this.labelEl_);
return el;
};
PlaybackRateMenuButton.prototype.dispose = function dispose() {
this.labelEl_ = null;
_MenuButton.prototype.dispose.call(this);
};
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this);
};
PlaybackRateMenuButton.prototype.buildWrapperCSSClass = function buildWrapperCSSClass() {
return 'vjs-playback-rate ' + _MenuButton.prototype.buildWrapperCSSClass.call(this);
};
/**
* Create the playback rate menu
*
* @return {Menu}
* Menu object populated with {@link PlaybackRateMenuItem}s
*/
PlaybackRateMenuButton.prototype.createMenu = function createMenu() {
var menu = new Menu(this.player());
var rates = this.playbackRates();
if (rates) {
for (var i = rates.length - 1; i >= 0; i--) {
menu.addChild(new PlaybackRateMenuItem(this.player(), { rate: rates[i] + 'x' }));
}
}
return menu;
};
/**
* Updates ARIA accessibility attributes
*/
PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Current playback rate
this.el().setAttribute('aria-valuenow', this.player().playbackRate());
};
/**
* This gets called when an `PlaybackRateMenuButton` is "clicked". See
* {@link ClickableComponent} for more detailed information on what a click can be.
*
* @param {EventTarget~Event} [event]
* The `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
PlaybackRateMenuButton.prototype.handleClick = function handleClick(event) {
// select next rate option
var currentRate = this.player().playbackRate();
var rates = this.playbackRates();
// this will select first one if the last one currently selected
var newRate = rates[0];
for (var i = 0; i < rates.length; i++) {
if (rates[i] > currentRate) {
newRate = rates[i];
break;
}
}
this.player().playbackRate(newRate);
};
/**
* Get possible playback rates
*
* @return {Array}
* All possible playback rates
*/
PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() {
return this.options_.playbackRates || this.options_.playerOptions && this.options_.playerOptions.playbackRates;
};
/**
* Get whether playback rates is supported by the tech
* and an array of playback rates exists
*
* @return {boolean}
* Whether changing playback rate is supported
*/
PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() {
return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
};
/**
* Hide playback rate controls when they're no playback rate options to select
*
* @param {EventTarget~Event} [event]
* The event that caused this function to run.
*
* @listens Player#loadstart
*/
PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility(event) {
if (this.playbackRateSupported()) {
this.removeClass('vjs-hidden');
} else {
this.addClass('vjs-hidden');
}
};
/**
* Update button label when rate changed
*
* @param {EventTarget~Event} [event]
* The event that caused this function to run.
*
* @listens Player#ratechange
*/
PlaybackRateMenuButton.prototype.updateLabel = function updateLabel(event) {
if (this.playbackRateSupported()) {
this.labelEl_.innerHTML = this.player().playbackRate() + 'x';
}
};
return PlaybackRateMenuButton;
}(MenuButton);
/**
* The text that should display over the `FullscreenToggle`s controls. Added for localization.
*
* @type {string}
* @private
*/
PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
Component.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
/**
* @file spacer.js
*/
/**
* Just an empty spacer element that can be used as an append point for plugins, etc.
* Also can be used to create space between elements when necessary.
*
* @extends Component
*/
var Spacer = function (_Component) {
inherits(Spacer, _Component);
function Spacer() {
classCallCheck(this, Spacer);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
Spacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
Spacer.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass()
});
};
return Spacer;
}(Component);
Component.registerComponent('Spacer', Spacer);
/**
* @file custom-control-spacer.js
*/
/**
* Spacer specifically meant to be used as an insertion point for new plugins, etc.
*
* @extends Spacer
*/
var CustomControlSpacer = function (_Spacer) {
inherits(CustomControlSpacer, _Spacer);
function CustomControlSpacer() {
classCallCheck(this, CustomControlSpacer);
return possibleConstructorReturn(this, _Spacer.apply(this, arguments));
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*/
CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this);
};
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
CustomControlSpacer.prototype.createEl = function createEl() {
var el = _Spacer.prototype.createEl.call(this, {
className: this.buildCSSClass()
});
// No-flex/table-cell mode requires there be some content
// in the cell to fill the remaining space of the table.
el.innerHTML = '\xA0';
return el;
};
return CustomControlSpacer;
}(Spacer);
Component.registerComponent('CustomControlSpacer', CustomControlSpacer);
/**
* @file control-bar.js
*/
// Required children
/**
* Container of main controls.
*
* @extends Component
*/
var ControlBar = function (_Component) {
inherits(ControlBar, _Component);
function ControlBar() {
classCallCheck(this, ControlBar);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
ControlBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-control-bar',
dir: 'ltr'
});
};
return ControlBar;
}(Component);
/**
* Default options for `ControlBar`
*
* @type {Object}
* @private
*/
ControlBar.prototype.options_ = {
children: ['playToggle', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
};
Component.registerComponent('ControlBar', ControlBar);
/**
* @file error-display.js
*/
/**
* A display that indicates an error has occurred. This means that the video
* is unplayable.
*
* @extends ModalDialog
*/
var ErrorDisplay = function (_ModalDialog) {
inherits(ErrorDisplay, _ModalDialog);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function ErrorDisplay(player, options) {
classCallCheck(this, ErrorDisplay);
var _this = possibleConstructorReturn(this, _ModalDialog.call(this, player, options));
_this.on(player, 'error', _this.open);
return _this;
}
/**
* Builds the default DOM `className`.
*
* @return {string}
* The DOM `className` for this object.
*
* @deprecated Since version 5.
*/
ErrorDisplay.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-error-display ' + _ModalDialog.prototype.buildCSSClass.call(this);
};
/**
* Gets the localized error message based on the `Player`s error.
*
* @return {string}
* The `Player`s error message localized or an empty string.
*/
ErrorDisplay.prototype.content = function content() {
var error = this.player().error();
return error ? this.localize(error.message) : '';
};
return ErrorDisplay;
}(ModalDialog);
/**
* The default options for an `ErrorDisplay`.
*
* @private
*/
ErrorDisplay.prototype.options_ = mergeOptions(ModalDialog.prototype.options_, {
pauseOnOpen: false,
fillAlways: true,
temporary: false,
uncloseable: true
});
Component.registerComponent('ErrorDisplay', ErrorDisplay);
/**
* @file text-track-settings.js
*/
var LOCAL_STORAGE_KEY = 'vjs-text-track-settings';
var COLOR_BLACK = ['#000', 'Black'];
var COLOR_BLUE = ['#00F', 'Blue'];
var COLOR_CYAN = ['#0FF', 'Cyan'];
var COLOR_GREEN = ['#0F0', 'Green'];
var COLOR_MAGENTA = ['#F0F', 'Magenta'];
var COLOR_RED = ['#F00', 'Red'];
var COLOR_WHITE = ['#FFF', 'White'];
var COLOR_YELLOW = ['#FF0', 'Yellow'];
var OPACITY_OPAQUE = ['1', 'Opaque'];
var OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
var OPACITY_TRANS = ['0', 'Transparent'];
// Configuration for the various <select> elements in the DOM of this component.
//
// Possible keys include:
//
// `default`:
// The default option index. Only needs to be provided if not zero.
// `parser`:
// A function which is used to parse the value from the selected option in
// a customized way.
// `selector`:
// The selector used to find the associated <select> element.
var selectConfigs = {
backgroundColor: {
selector: '.vjs-bg-color > select',
id: 'captions-background-color-%s',
label: 'Color',
options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
},
backgroundOpacity: {
selector: '.vjs-bg-opacity > select',
id: 'captions-background-opacity-%s',
label: 'Transparency',
options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
},
color: {
selector: '.vjs-fg-color > select',
id: 'captions-foreground-color-%s',
label: 'Color',
options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
},
edgeStyle: {
selector: '.vjs-edge-style > select',
id: '%s',
label: 'Text Edge Style',
options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
},
fontFamily: {
selector: '.vjs-font-family > select',
id: 'captions-font-family-%s',
label: 'Font Family',
options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
},
fontPercent: {
selector: '.vjs-font-percent > select',
id: 'captions-font-size-%s',
label: 'Font Size',
options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']],
'default': 2,
parser: function parser(v) {
return v === '1.00' ? null : Number(v);
}
},
textOpacity: {
selector: '.vjs-text-opacity > select',
id: 'captions-foreground-opacity-%s',
label: 'Transparency',
options: [OPACITY_OPAQUE, OPACITY_SEMI]
},
// Options for this object are defined below.
windowColor: {
selector: '.vjs-window-color > select',
id: 'captions-window-color-%s',
label: 'Color'
},
// Options for this object are defined below.
windowOpacity: {
selector: '.vjs-window-opacity > select',
id: 'captions-window-opacity-%s',
label: 'Transparency',
options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
}
};
selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
/**
* Get the actual value of an option.
*
* @param {string} value
* The value to get
*
* @param {Function} [parser]
* Optional function to adjust the value.
*
* @return {Mixed}
* - Will be `undefined` if no value exists
* - Will be `undefined` if the given value is "none".
* - Will be the actual value otherwise.
*
* @private
*/
function parseOptionValue(value, parser) {
if (parser) {
value = parser(value);
}
if (value && value !== 'none') {
return value;
}
}
/**
* Gets the value of the selected <option> element within a <select> element.
*
* @param {Element} el
* the element to look in
*
* @param {Function} [parser]
* Optional function to adjust the value.
*
* @return {Mixed}
* - Will be `undefined` if no value exists
* - Will be `undefined` if the given value is "none".
* - Will be the actual value otherwise.
*
* @private
*/
function getSelectedOptionValue(el, parser) {
var value = el.options[el.options.selectedIndex].value;
return parseOptionValue(value, parser);
}
/**
* Sets the selected <option> element within a <select> element based on a
* given value.
*
* @param {Element} el
* The element to look in.
*
* @param {string} value
* the property to look on.
*
* @param {Function} [parser]
* Optional function to adjust the value before comparing.
*
* @private
*/
function setSelectedOption(el, value, parser) {
if (!value) {
return;
}
for (var i = 0; i < el.options.length; i++) {
if (parseOptionValue(el.options[i].value, parser) === value) {
el.selectedIndex = i;
break;
}
}
}
/**
* Manipulate Text Tracks settings.
*
* @extends ModalDialog
*/
var TextTrackSettings = function (_ModalDialog) {
inherits(TextTrackSettings, _ModalDialog);
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
function TextTrackSettings(player, options) {
classCallCheck(this, TextTrackSettings);
options.temporary = false;
var _this = possibleConstructorReturn(this, _ModalDialog.call(this, player, options));
_this.updateDisplay = bind(_this, _this.updateDisplay);
// fill the modal and pretend we have opened it
_this.fill();
_this.hasBeenOpened_ = _this.hasBeenFilled_ = true;
_this.endDialog = createEl('p', {
className: 'vjs-control-text',
textContent: _this.localize('End of dialog window.')
});
_this.el().appendChild(_this.endDialog);
_this.setDefaults();
// Grab `persistTextTrackSettings` from the player options if not passed in child options
if (options.persistTextTrackSettings === undefined) {
_this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings;
}
_this.on(_this.$('.vjs-done-button'), 'click', function () {
_this.saveSettings();
_this.close();
});
_this.on(_this.$('.vjs-default-button'), 'click', function () {
_this.setDefaults();
_this.updateDisplay();
});
each(selectConfigs, function (config) {
_this.on(_this.$(config.selector), 'change', _this.updateDisplay);
});
if (_this.options_.persistTextTrackSettings) {
_this.restoreSettings();
}
return _this;
}
TextTrackSettings.prototype.dispose = function dispose() {
this.endDialog = null;
_ModalDialog.prototype.dispose.call(this);
};
/**
* Create a <select> element with configured options.
*
* @param {string} key
* Configuration key to use during creation.
*
* @return {string}
* An HTML string.
*
* @private
*/
TextTrackSettings.prototype.createElSelect_ = function createElSelect_(key) {
var _this2 = this;
var legendId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'label';
var config = selectConfigs[key];
var id = config.id.replace('%s', this.id_);
var selectLabelledbyIds = [legendId, id].join(' ').trim();
return ['<' + type + ' id="' + id + '" class="' + (type === 'label' ? 'vjs-label' : '') + '">', this.localize(config.label), '</' + type + '>', '<select aria-labelledby="' + selectLabelledbyIds + '">'].concat(config.options.map(function (o) {
var optionId = id + '-' + o[1].replace(/\W+/g, '');
return ['<option id="' + optionId + '" value="' + o[0] + '" ', 'aria-labelledby="' + selectLabelledbyIds + ' ' + optionId + '">', _this2.localize(o[1]), '</option>'].join('');
})).concat('</select>').join('');
};
/**
* Create foreground color element for the component
*
* @return {string}
* An HTML string.
*
* @private
*/
TextTrackSettings.prototype.createElFgColor_ = function createElFgColor_() {
var legendId = 'captions-text-legend-' + this.id_;
return ['<fieldset class="vjs-fg-color vjs-track-setting">', '<legend id="' + legendId + '">', this.localize('Text'), '</legend>', this.createElSelect_('color', legendId), '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_('textOpacity', legendId), '</span>', '</fieldset>'].join('');
};
/**
* Create background color element for the component
*
* @return {string}
* An HTML string.
*
* @private
*/
TextTrackSettings.prototype.createElBgColor_ = function createElBgColor_() {
var legendId = 'captions-background-' + this.id_;
return ['<fieldset class="vjs-bg-color vjs-track-setting">', '<legend id="' + legendId + '">', this.localize('Background'), '</legend>', this.createElSelect_('backgroundColor', legendId), '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_('backgroundOpacity', legendId), '</span>', '</fieldset>'].join('');
};
/**
* Create window color element for the component
*
* @return {string}
* An HTML string.
*
* @private
*/
TextTrackSettings.prototype.createElWinColor_ = function createElWinColor_() {
var legendId = 'captions-window-' + this.id_;
return ['<fieldset class="vjs-window-color vjs-track-setting">', '<legend id="' + legendId + '">', this.localize('Window'), '</legend>', this.createElSelect_('windowColor', legendId), '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_('windowOpacity', legendId), '</span>', '</fieldset>'].join('');
};
/**
* Create color elements for the component
*
* @return {Element}
* The element that was created
*
* @private
*/
TextTrackSettings.prototype.createElColors_ = function createElColors_() {
return createEl('div', {
className: 'vjs-track-settings-colors',
innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
});
};
/**
* Create font elements for the component
*
* @return {Element}
* The element that was created.
*
* @private
*/
TextTrackSettings.prototype.createElFont_ = function createElFont_() {
return createEl('div', {
className: 'vjs-track-settings-font',
innerHTML: ['<fieldset class="vjs-font-percent vjs-track-setting">', this.createElSelect_('fontPercent', '', 'legend'), '</fieldset>', '<fieldset class="vjs-edge-style vjs-track-setting">', this.createElSelect_('edgeStyle', '', 'legend'), '</fieldset>', '<fieldset class="vjs-font-family vjs-track-setting">', this.createElSelect_('fontFamily', '', 'legend'), '</fieldset>'].join('')
});
};
/**
* Create controls for the component
*
* @return {Element}
* The element that was created.
*
* @private
*/
TextTrackSettings.prototype.createElControls_ = function createElControls_() {
var defaultsDescription = this.localize('restore all settings to the default values');
return createEl('div', {
className: 'vjs-track-settings-controls',
innerHTML: ['<button type="button" class="vjs-default-button" title="' + defaultsDescription + '">', this.localize('Reset'), '<span class="vjs-control-text"> ' + defaultsDescription + '</span>', '</button>', '<button type="button" class="vjs-done-button">' + this.localize('Done') + '</button>'].join('')
});
};
TextTrackSettings.prototype.content = function content() {
return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
};
TextTrackSettings.prototype.label = function label() {
return this.localize('Caption Settings Dialog');
};
TextTrackSettings.prototype.description = function description() {
return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
};
TextTrackSettings.prototype.buildCSSClass = function buildCSSClass() {
return _ModalDialog.prototype.buildCSSClass.call(this) + ' vjs-text-track-settings';
};
/**
* Gets an object of text track settings (or null).
*
* @return {Object}
* An object with config values parsed from the DOM or localStorage.
*/
TextTrackSettings.prototype.getValues = function getValues() {
var _this3 = this;
return reduce(selectConfigs, function (accum, config, key) {
var value = getSelectedOptionValue(_this3.$(config.selector), config.parser);
if (value !== undefined) {
accum[key] = value;
}
return accum;
}, {});
};
/**
* Sets text track settings from an object of values.
*
* @param {Object} values
* An object with config values parsed from the DOM or localStorage.
*/
TextTrackSettings.prototype.setValues = function setValues(values) {
var _this4 = this;
each(selectConfigs, function (config, key) {
setSelectedOption(_this4.$(config.selector), values[key], config.parser);
});
};
/**
* Sets all `<select>` elements to their default values.
*/
TextTrackSettings.prototype.setDefaults = function setDefaults() {
var _this5 = this;
each(selectConfigs, function (config) {
var index = config.hasOwnProperty('default') ? config['default'] : 0;
_this5.$(config.selector).selectedIndex = index;
});
};
/**
* Restore texttrack settings from localStorage
*/
TextTrackSettings.prototype.restoreSettings = function restoreSettings() {
var values = void 0;
try {
values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY));
} catch (err) {
log.warn(err);
}
if (values) {
this.setValues(values);
}
};
/**
* Save text track settings to localStorage
*/
TextTrackSettings.prototype.saveSettings = function saveSettings() {
if (!this.options_.persistTextTrackSettings) {
return;
}
var values = this.getValues();
try {
if (Object.keys(values).length) {
window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values));
} else {
window.localStorage.removeItem(LOCAL_STORAGE_KEY);
}
} catch (err) {
log.warn(err);
}
};
/**
* Update display of text track settings
*/
TextTrackSettings.prototype.updateDisplay = function updateDisplay() {
var ttDisplay = this.player_.getChild('textTrackDisplay');
if (ttDisplay) {
ttDisplay.updateDisplay();
}
};
/**
* conditionally blur the element and refocus the captions button
*
* @private
*/
TextTrackSettings.prototype.conditionalBlur_ = function conditionalBlur_() {
this.previouslyActiveEl_ = null;
this.off(document, 'keydown', this.handleKeyDown);
var cb = this.player_.controlBar;
var subsCapsBtn = cb && cb.subsCapsButton;
var ccBtn = cb && cb.captionsButton;
if (subsCapsBtn) {
subsCapsBtn.focus();
} else if (ccBtn) {
ccBtn.focus();
}
};
return TextTrackSettings;
}(ModalDialog);
Component.registerComponent('TextTrackSettings', TextTrackSettings);
/**
* @file resize-manager.js
*/
/**
* A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
*
* It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}.
*
* If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
* If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
* @example <caption>How to disable the resize manager</caption>
* const player = videojs('#vid', {
* resizeManager: false
* });
*
* @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
*
* @extends Component
*/
var ResizeManager = function (_Component) {
inherits(ResizeManager, _Component);
/**
* Create the ResizeManager.
*
* @param {Object} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of ResizeManager options.
*
* @param {Object} [options.ResizeObserver]
* A polyfill for ResizeObserver can be passed in here.
* If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
*/
function ResizeManager(player, options) {
classCallCheck(this, ResizeManager);
var RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;
// if `null` was passed, we want to disable the ResizeObserver
if (options.ResizeObserver === null) {
RESIZE_OBSERVER_AVAILABLE = false;
}
// Only create an element when ResizeObserver isn't available
var options_ = mergeOptions({ createEl: !RESIZE_OBSERVER_AVAILABLE }, options);
var _this = possibleConstructorReturn(this, _Component.call(this, player, options_));
_this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
_this.loadListener_ = null;
_this.resizeObserver_ = null;
_this.debouncedHandler_ = debounce(function () {
_this.resizeHandler();
}, 100, false, _this);
if (RESIZE_OBSERVER_AVAILABLE) {
_this.resizeObserver_ = new _this.ResizeObserver(_this.debouncedHandler_);
_this.resizeObserver_.observe(player.el());
} else {
_this.loadListener_ = function () {
if (!_this.el_ || !_this.el_.contentWindow) {
return;
}
on(_this.el_.contentWindow, 'resize', _this.debouncedHandler_);
};
_this.one('load', _this.loadListener_);
}
return _this;
}
ResizeManager.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'iframe', {
className: 'vjs-resize-manager'
});
};
/**
* Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
*
* @fires Player#playerresize
*/
ResizeManager.prototype.resizeHandler = function resizeHandler() {
/**
* Called when the player size has changed
*
* @event Player#playerresize
* @type {EventTarget~Event}
*/
// make sure player is still around to trigger
// prevents this from causing an error after dispose
if (!this.player_ || !this.player_.trigger) {
return;
}
this.player_.trigger('playerresize');
};
ResizeManager.prototype.dispose = function dispose() {
if (this.debouncedHandler_) {
this.debouncedHandler_.cancel();
}
if (this.resizeObserver_) {
if (this.player_.el()) {
this.resizeObserver_.unobserve(this.player_.el());
}
this.resizeObserver_.disconnect();
}
if (this.el_ && this.el_.contentWindow) {
off(this.el_.contentWindow, 'resize', this.debouncedHandler_);
}
if (this.loadListener_) {
this.off('load', this.loadListener_);
}
this.ResizeObserver = null;
this.resizeObserver = null;
this.debouncedHandler_ = null;
this.loadListener_ = null;
};
return ResizeManager;
}(Component);
Component.registerComponent('ResizeManager', ResizeManager);
/**
* This function is used to fire a sourceset when there is something
* similar to `mediaEl.load()` being called. It will try to find the source via
* the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
* with the source that was found or empty string if we cannot know. If it cannot
* find a source then `sourceset` will not be fired.
*
* @param {Html5} tech
* The tech object that sourceset was setup on
*
* @return {boolean}
* returns false if the sourceset was not fired and true otherwise.
*/
var sourcesetLoad = function sourcesetLoad(tech) {
var el = tech.el();
// if `el.src` is set, that source will be loaded.
if (el.hasAttribute('src')) {
tech.triggerSourceset(el.src);
return true;
}
/**
* Since there isn't a src property on the media element, source elements will be used for
* implementing the source selection algorithm. This happens asynchronously and
* for most cases were there is more than one source we cannot tell what source will
* be loaded, without re-implementing the source selection algorithm. At this time we are not
* going to do that. There are three special cases that we do handle here though:
*
* 1. If there are no sources, do not fire `sourceset`.
* 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
* 3. If there is more than one `<source>` but all of them have the same `src` url.
* That will be our src.
*/
var sources = tech.$$('source');
var srcUrls = [];
var src = '';
// if there are no sources, do not fire sourceset
if (!sources.length) {
return false;
}
// only count valid/non-duplicate source elements
for (var i = 0; i < sources.length; i++) {
var url = sources[i].src;
if (url && srcUrls.indexOf(url) === -1) {
srcUrls.push(url);
}
}
// there were no valid sources
if (!srcUrls.length) {
return false;
}
// there is only one valid source element url
// use that
if (srcUrls.length === 1) {
src = srcUrls[0];
}
tech.triggerSourceset(src);
return true;
};
/**
* our implementation of an `innerHTML` descriptor for browsers
* that do not have one.
*/
var innerHTMLDescriptorPolyfill = {};
if (!IS_IE8) {
innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
get: function get() {
return this.cloneNode(true).innerHTML;
},
set: function set(v) {
// make a dummy node to use innerHTML on
var dummy = document.createElement(this.nodeName.toLowerCase());
// set innerHTML to the value provided
dummy.innerHTML = v;
// make a document fragment to hold the nodes from dummy
var docFrag = document.createDocumentFragment();
// copy all of the nodes created by the innerHTML on dummy
// to the document fragment
while (dummy.childNodes.length) {
docFrag.appendChild(dummy.childNodes[0]);
}
// remove content
this.innerText = '';
// now we add all of that html in one by appending the
// document fragment. This is how innerHTML does it.
window.Element.prototype.appendChild.call(this, docFrag);
// then return the result that innerHTML's setter would
return this.innerHTML;
}
});
}
/**
* Get a property descriptor given a list of priorities and the
* property to get.
*/
var getDescriptor = function getDescriptor(priority, prop) {
var descriptor = {};
for (var i = 0; i < priority.length; i++) {
descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
if (descriptor && descriptor.set && descriptor.get) {
break;
}
}
descriptor.enumerable = true;
descriptor.configurable = true;
return descriptor;
};
var getInnerHTMLDescriptor = function getInnerHTMLDescriptor(tech) {
return getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
};
/**
* Patches browser internal functions so that we can tell syncronously
* if a `<source>` was appended to the media element. For some reason this
* causes a `sourceset` if the the media element is ready and has no source.
* This happens when:
* - The page has just loaded and the media element does not have a source.
* - The media element was emptied of all sources, then `load()` was called.
*
* It does this by patching the following functions/properties when they are supported:
*
* - `append()` - can be used to add a `<source>` element to the media element
* - `appendChild()` - can be used to add a `<source>` element to the media element
* - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
* - `innerHTML` - can be used to add a `<source>` element to the media element
*
* @param {Html5} tech
* The tech object that sourceset is being setup on.
*/
var firstSourceWatch = function firstSourceWatch(tech) {
var el = tech.el();
// make sure firstSourceWatch isn't setup twice.
if (el.resetSourceWatch_) {
return;
}
var old = {};
var innerDescriptor = getInnerHTMLDescriptor(tech);
var appendWrapper = function appendWrapper(appendFn) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var retval = appendFn.apply(el, args);
sourcesetLoad(tech);
return retval;
};
};
['append', 'appendChild', 'insertAdjacentHTML'].forEach(function (k) {
if (!el[k]) {
return;
}
// store the old function
old[k] = el[k];
// call the old function with a sourceset if a source
// was loaded
el[k] = appendWrapper(old[k]);
});
Object.defineProperty(el, 'innerHTML', mergeOptions(innerDescriptor, {
set: appendWrapper(innerDescriptor.set)
}));
el.resetSourceWatch_ = function () {
el.resetSourceWatch_ = null;
Object.keys(old).forEach(function (k) {
el[k] = old[k];
});
Object.defineProperty(el, 'innerHTML', innerDescriptor);
};
// on the first sourceset, we need to revert our changes
tech.one('sourceset', el.resetSourceWatch_);
};
/**
* our implementation of a `src` descriptor for browsers
* that do not have one.
*/
var srcDescriptorPolyfill = {};
if (!IS_IE8) {
srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
get: function get() {
if (this.hasAttribute('src')) {
return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
}
return '';
},
set: function set(v) {
window.Element.prototype.setAttribute.call(this, 'src', v);
return v;
}
});
}
var getSrcDescriptor = function getSrcDescriptor(tech) {
return getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
};
/**
* setup `sourceset` handling on the `Html5` tech. This function
* patches the following element properties/functions:
*
* - `src` - to determine when `src` is set
* - `setAttribute()` - to determine when `src` is set
* - `load()` - this re-triggers the source selection algorithm, and can
* cause a sourceset.
*
* If there is no source when we are adding `sourceset` support or during a `load()`
* we also patch the functions listed in `firstSourceWatch`.
*
* @param {Html5} tech
* The tech to patch
*/
var setupSourceset = function setupSourceset(tech) {
if (!tech.featuresSourceset) {
return;
}
var el = tech.el();
// make sure sourceset isn't setup twice.
if (el.resetSourceset_) {
return;
}
var srcDescriptor = getSrcDescriptor(tech);
var oldSetAttribute = el.setAttribute;
var oldLoad = el.load;
Object.defineProperty(el, 'src', mergeOptions(srcDescriptor, {
set: function set(v) {
var retval = srcDescriptor.set.call(el, v);
// we use the getter here to get the actual value set on src
tech.triggerSourceset(el.src);
return retval;
}
}));
el.setAttribute = function (n, v) {
var retval = oldSetAttribute.call(el, n, v);
if (/src/i.test(n)) {
tech.triggerSourceset(el.src);
}
return retval;
};
el.load = function () {
var retval = oldLoad.call(el);
// if load was called, but there was no source to fire
// sourceset on. We have to watch for a source append
// as that can trigger a `sourceset` when the media element
// has no source
if (!sourcesetLoad(tech)) {
tech.triggerSourceset('');
firstSourceWatch(tech);
}
return retval;
};
if (el.currentSrc) {
tech.triggerSourceset(el.currentSrc);
} else if (!sourcesetLoad(tech)) {
firstSourceWatch(tech);
}
el.resetSourceset_ = function () {
el.resetSourceset_ = null;
el.load = oldLoad;
el.setAttribute = oldSetAttribute;
Object.defineProperty(el, 'src', srcDescriptor);
if (el.resetSourceWatch_) {
el.resetSourceWatch_();
}
};
};
var _templateObject$2 = taggedTemplateLiteralLoose(['Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n This may prevent text tracks from loading.'], ['Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n This may prevent text tracks from loading.']);
/**
* @file html5.js
*/
/**
* HTML5 Media Controller - Wrapper for HTML5 Media API
*
* @mixes Tech~SouceHandlerAdditions
* @extends Tech
*/
var Html5 = function (_Tech) {
inherits(Html5, _Tech);
/**
* Create an instance of this Tech.
*
* @param {Object} [options]
* The key/value store of player options.
*
* @param {Component~ReadyCallback} ready
* Callback function to call when the `HTML5` Tech is ready.
*/
function Html5(options, ready) {
classCallCheck(this, Html5);
var _this = possibleConstructorReturn(this, _Tech.call(this, options, ready));
var source = options.source;
var crossoriginTracks = false;
// Set the source if one is provided
// 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
// 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
// anyway so the error gets fired.
if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
_this.setSource(source);
} else {
_this.handleLateInit_(_this.el_);
}
// setup sourceset after late sourceset/init
if (options.enableSourceset) {
_this.setupSourcesetHandling_();
}
if (_this.el_.hasChildNodes()) {
var nodes = _this.el_.childNodes;
var nodesLength = nodes.length;
var removeNodes = [];
while (nodesLength--) {
var node = nodes[nodesLength];
var nodeName = node.nodeName.toLowerCase();
if (nodeName === 'track') {
if (!_this.featuresNativeTextTracks) {
// Empty video tag tracks so the built-in player doesn't use them also.
// This may not be fast enough to stop HTML5 browsers from reading the tags
// so we'll need to turn off any default tracks if we're manually doing
// captions and subtitles. videoElement.textTracks
removeNodes.push(node);
} else {
// store HTMLTrackElement and TextTrack to remote list
_this.remoteTextTrackEls().addTrackElement_(node);
_this.remoteTextTracks().addTrack(node.track);
_this.textTracks().addTrack(node.track);
if (!crossoriginTracks && !_this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
crossoriginTracks = true;
}
}
}
}
for (var i = 0; i < removeNodes.length; i++) {
_this.el_.removeChild(removeNodes[i]);
}
}
_this.proxyNativeTracks_();
if (_this.featuresNativeTextTracks && crossoriginTracks) {
log.warn(tsml(_templateObject$2));
}
// prevent iOS Safari from disabling metadata text tracks during native playback
_this.restoreMetadataTracksInIOSNativePlayer_();
// Determine if native controls should be used
// Our goal should be to get the custom controls on mobile solid everywhere
// so we can remove this all together. Right now this will block custom
// controls on touch enabled laptops like the Chrome Pixel
if ((TOUCH_ENABLED || IS_IPHONE || IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) {
_this.setControls(true);
}
// on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
// into a `fullscreenchange` event
_this.proxyWebkitFullscreen_();
_this.triggerReady();
return _this;
}
/**
* Dispose of `HTML5` media element and remove all tracks.
*/
Html5.prototype.dispose = function dispose() {
if (this.el_ && this.el_.resetSourceset_) {
this.el_.resetSourceset_();
}
Html5.disposeMediaElement(this.el_);
this.options_ = null;
// tech will handle clearing of the emulated track list
_Tech.prototype.dispose.call(this);
};
/**
* Modify the media element so that we can detect when
* the source is changed. Fires `sourceset` just after the source has changed
*/
Html5.prototype.setupSourcesetHandling_ = function setupSourcesetHandling_() {
setupSourceset(this);
};
/**
* When a captions track is enabled in the iOS Safari native player, all other
* tracks are disabled (including metadata tracks), which nulls all of their
* associated cue points. This will restore metadata tracks to their pre-fullscreen
* state in those cases so that cue points are not needlessly lost.
*
* @private
*/
Html5.prototype.restoreMetadataTracksInIOSNativePlayer_ = function restoreMetadataTracksInIOSNativePlayer_() {
var textTracks = this.textTracks();
var metadataTracksPreFullscreenState = void 0;
// captures a snapshot of every metadata track's current state
var takeMetadataTrackSnapshot = function takeMetadataTrackSnapshot() {
metadataTracksPreFullscreenState = [];
for (var i = 0; i < textTracks.length; i++) {
var track = textTracks[i];
if (track.kind === 'metadata') {
metadataTracksPreFullscreenState.push({
track: track,
storedMode: track.mode
});
}
}
};
// snapshot each metadata track's initial state, and update the snapshot
// each time there is a track 'change' event
takeMetadataTrackSnapshot();
textTracks.addEventListener('change', takeMetadataTrackSnapshot);
this.on('dispose', function () {
return textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
});
var restoreTrackMode = function restoreTrackMode() {
for (var i = 0; i < metadataTracksPreFullscreenState.length; i++) {
var storedTrack = metadataTracksPreFullscreenState[i];
if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
storedTrack.track.mode = storedTrack.storedMode;
}
}
// we only want this handler to be executed on the first 'change' event
textTracks.removeEventListener('change', restoreTrackMode);
};
// when we enter fullscreen playback, stop updating the snapshot and
// restore all track modes to their pre-fullscreen state
this.on('webkitbeginfullscreen', function () {
textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
// remove the listener before adding it just in case it wasn't previously removed
textTracks.removeEventListener('change', restoreTrackMode);
textTracks.addEventListener('change', restoreTrackMode);
});
// start updating the snapshot again after leaving fullscreen
this.on('webkitendfullscreen', function () {
// remove the listener before adding it just in case it wasn't previously removed
textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
textTracks.addEventListener('change', takeMetadataTrackSnapshot);
// remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
textTracks.removeEventListener('change', restoreTrackMode);
});
};
/**
* Proxy all native track list events to our track lists if the browser we are playing
* in supports that type of track list.
*
* @private
*/
Html5.prototype.proxyNativeTracks_ = function proxyNativeTracks_() {
var _this2 = this;
NORMAL.names.forEach(function (name) {
var props = NORMAL[name];
var elTracks = _this2.el()[props.getterName];
var techTracks = _this2[props.getterName]();
if (!_this2['featuresNative' + props.capitalName + 'Tracks'] || !elTracks || !elTracks.addEventListener) {
return;
}
var listeners = {
change: function change(e) {
techTracks.trigger({
type: 'change',
target: techTracks,
currentTarget: techTracks,
srcElement: techTracks
});
},
addtrack: function addtrack(e) {
techTracks.addTrack(e.track);
},
removetrack: function removetrack(e) {
techTracks.removeTrack(e.track);
}
};
var removeOldTracks = function removeOldTracks() {
var removeTracks = [];
for (var i = 0; i < techTracks.length; i++) {
var found = false;
for (var j = 0; j < elTracks.length; j++) {
if (elTracks[j] === techTracks[i]) {
found = true;
break;
}
}
if (!found) {
removeTracks.push(techTracks[i]);
}
}
while (removeTracks.length) {
techTracks.removeTrack(removeTracks.shift());
}
};
Object.keys(listeners).forEach(function (eventName) {
var listener = listeners[eventName];
elTracks.addEventListener(eventName, listener);
_this2.on('dispose', function (e) {
return elTracks.removeEventListener(eventName, listener);
});
});
// Remove (native) tracks that are not used anymore
_this2.on('loadstart', removeOldTracks);
_this2.on('dispose', function (e) {
return _this2.off('loadstart', removeOldTracks);
});
});
};
/**
* Create the `Html5` Tech's DOM element.
*
* @return {Element}
* The element that gets created.
*/
Html5.prototype.createEl = function createEl$$1() {
var el = this.options_.tag;
// Check if this browser supports moving the element into the box.
// On the iPhone video will break if you move the element,
// So we have to create a brand new element.
// If we ingested the player div, we do not need to move the media element.
if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
// If the original tag is still there, clone and remove it.
if (el) {
var clone = el.cloneNode(true);
if (el.parentNode) {
el.parentNode.insertBefore(clone, el);
}
Html5.disposeMediaElement(el);
el = clone;
} else {
el = document.createElement('video');
// determine if native controls should be used
var tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
var attributes = mergeOptions({}, tagAttributes);
if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
delete attributes.controls;
}
setAttributes(el, assign(attributes, {
id: this.options_.techId,
'class': 'vjs-tech'
}));
}
el.playerId = this.options_.playerId;
}
if (typeof this.options_.preload !== 'undefined') {
setAttribute(el, 'preload', this.options_.preload);
}
// Update specific tag settings, in case they were overridden
// `autoplay` has to be *last* so that `muted` and `playsinline` are present
// when iOS/Safari or other browsers attempt to autoplay.
var settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
for (var i = 0; i < settingsAttrs.length; i++) {
var attr = settingsAttrs[i];
var value = this.options_[attr];
if (typeof value !== 'undefined') {
if (value) {
setAttribute(el, attr, attr);
} else {
removeAttribute(el, attr);
}
el[attr] = value;
}
}
return el;
};
/**
* This will be triggered if the loadstart event has already fired, before videojs was
* ready. Two known examples of when this can happen are:
* 1. If we're loading the playback object after it has started loading
* 2. The media is already playing the (often with autoplay on) then
*
* This function will fire another loadstart so that videojs can catchup.
*
* @fires Tech#loadstart
*
* @return {undefined}
* returns nothing.
*/
Html5.prototype.handleLateInit_ = function handleLateInit_(el) {
if (el.networkState === 0 || el.networkState === 3) {
// The video element hasn't started loading the source yet
// or didn't find a source
return;
}
if (el.readyState === 0) {
// NetworkState is set synchronously BUT loadstart is fired at the
// end of the current stack, usually before setInterval(fn, 0).
// So at this point we know loadstart may have already fired or is
// about to fire, and either way the player hasn't seen it yet.
// We don't want to fire loadstart prematurely here and cause a
// double loadstart so we'll wait and see if it happens between now
// and the next loop, and fire it if not.
// HOWEVER, we also want to make sure it fires before loadedmetadata
// which could also happen between now and the next loop, so we'll
// watch for that also.
var loadstartFired = false;
var setLoadstartFired = function setLoadstartFired() {
loadstartFired = true;
};
this.on('loadstart', setLoadstartFired);
var triggerLoadstart = function triggerLoadstart() {
// We did miss the original loadstart. Make sure the player
// sees loadstart before loadedmetadata
if (!loadstartFired) {
this.trigger('loadstart');
}
};
this.on('loadedmetadata', triggerLoadstart);
this.ready(function () {
this.off('loadstart', setLoadstartFired);
this.off('loadedmetadata', triggerLoadstart);
if (!loadstartFired) {
// We did miss the original native loadstart. Fire it now.
this.trigger('loadstart');
}
});
return;
}
// From here on we know that loadstart already fired and we missed it.
// The other readyState events aren't as much of a problem if we double
// them, so not going to go to as much trouble as loadstart to prevent
// that unless we find reason to.
var eventsToTrigger = ['loadstart'];
// loadedmetadata: newly equal to HAVE_METADATA (1) or greater
eventsToTrigger.push('loadedmetadata');
// loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
if (el.readyState >= 2) {
eventsToTrigger.push('loadeddata');
}
// canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
if (el.readyState >= 3) {
eventsToTrigger.push('canplay');
}
// canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
if (el.readyState >= 4) {
eventsToTrigger.push('canplaythrough');
}
// We still need to give the player time to add event listeners
this.ready(function () {
eventsToTrigger.forEach(function (type) {
this.trigger(type);
}, this);
});
};
/**
* Set current time for the `HTML5` tech.
*
* @param {number} seconds
* Set the current time of the media to this.
*/
Html5.prototype.setCurrentTime = function setCurrentTime(seconds) {
try {
this.el_.currentTime = seconds;
} catch (e) {
log(e, 'Video is not ready. (Video.js)');
// this.warning(VideoJS.warnings.videoNotReady);
}
};
/**
* Get the current duration of the HTML5 media element.
*
* @return {number}
* The duration of the media or 0 if there is no duration.
*/
Html5.prototype.duration = function duration() {
var _this3 = this;
// Android Chrome will report duration as Infinity for VOD HLS until after
// playback has started, which triggers the live display erroneously.
// Return NaN if playback has not started and trigger a durationupdate once
// the duration can be reliably known.
if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
// Wait for the first `timeupdate` with currentTime > 0 - there may be
// several with 0
var checkProgress = function checkProgress() {
if (_this3.el_.currentTime > 0) {
// Trigger durationchange for genuinely live video
if (_this3.el_.duration === Infinity) {
_this3.trigger('durationchange');
}
_this3.off('timeupdate', checkProgress);
}
};
this.on('timeupdate', checkProgress);
return NaN;
}
return this.el_.duration || NaN;
};
/**
* Get the current width of the HTML5 media element.
*
* @return {number}
* The width of the HTML5 media element.
*/
Html5.prototype.width = function width() {
return this.el_.offsetWidth;
};
/**
* Get the current height of the HTML5 media element.
*
* @return {number}
* The heigth of the HTML5 media element.
*/
Html5.prototype.height = function height() {
return this.el_.offsetHeight;
};
/**
* Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
* `fullscreenchange` event.
*
* @private
* @fires fullscreenchange
* @listens webkitendfullscreen
* @listens webkitbeginfullscreen
* @listens webkitbeginfullscreen
*/
Html5.prototype.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() {
var _this4 = this;
if (!('webkitDisplayingFullscreen' in this.el_)) {
return;
}
var endFn = function endFn() {
this.trigger('fullscreenchange', { isFullscreen: false });
};
var beginFn = function beginFn() {
if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
this.one('webkitendfullscreen', endFn);
this.trigger('fullscreenchange', { isFullscreen: true });
}
};
this.on('webkitbeginfullscreen', beginFn);
this.on('dispose', function () {
_this4.off('webkitbeginfullscreen', beginFn);
_this4.off('webkitendfullscreen', endFn);
});
};
/**
* Check if fullscreen is supported on the current playback device.
*
* @return {boolean}
* - True if fullscreen is supported.
* - False if fullscreen is not supported.
*/
Html5.prototype.supportsFullScreen = function supportsFullScreen() {
if (typeof this.el_.webkitEnterFullScreen === 'function') {
var userAgent = window.navigator && window.navigator.userAgent || '';
// Seems to be broken in Chromium/Chrome && Safari in Leopard
if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
return true;
}
}
return false;
};
/**
* Request that the `HTML5` Tech enter fullscreen.
*/
Html5.prototype.enterFullScreen = function enterFullScreen() {
var video = this.el_;
if (video.paused && video.networkState <= video.HAVE_METADATA) {
// attempt to prime the video element for programmatic access
// this isn't necessary on the desktop but shouldn't hurt
this.el_.play();
// playing and pausing synchronously during the transition to fullscreen
// can get iOS ~6.1 devices into a play/pause loop
this.setTimeout(function () {
video.pause();
video.webkitEnterFullScreen();
}, 0);
} else {
video.webkitEnterFullScreen();
}
};
/**
* Request that the `HTML5` Tech exit fullscreen.
*/
Html5.prototype.exitFullScreen = function exitFullScreen() {
this.el_.webkitExitFullScreen();
};
/**
* A getter/setter for the `Html5` Tech's source object.
* > Note: Please use {@link Html5#setSource}
*
* @param {Tech~SourceObject} [src]
* The source object you want to set on the `HTML5` techs element.
*
* @return {Tech~SourceObject|undefined}
* - The current source object when a source is not passed in.
* - undefined when setting
*
* @deprecated Since version 5.
*/
Html5.prototype.src = function src(_src) {
if (_src === undefined) {
return this.el_.src;
}
// Setting src through `src` instead of `setSrc` will be deprecated
this.setSrc(_src);
};
/**
* Reset the tech by removing all sources and then calling
* {@link Html5.resetMediaElement}.
*/
Html5.prototype.reset = function reset() {
Html5.resetMediaElement(this.el_);
};
/**
* Get the current source on the `HTML5` Tech. Falls back to returning the source from
* the HTML5 media element.
*
* @return {Tech~SourceObject}
* The current source object from the HTML5 tech. With a fallback to the
* elements source.
*/
Html5.prototype.currentSrc = function currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
}
return this.el_.currentSrc;
};
/**
* Set controls attribute for the HTML5 media Element.
*
* @param {string} val
* Value to set the controls attribute to
*/
Html5.prototype.setControls = function setControls(val) {
this.el_.controls = !!val;
};
/**
* Create and returns a remote {@link TextTrack} object.
*
* @param {string} kind
* `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
*
* @param {string} [label]
* Label to identify the text track
*
* @param {string} [language]
* Two letter language abbreviation
*
* @return {TextTrack}
* The TextTrack that gets created.
*/
Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!this.featuresNativeTextTracks) {
return _Tech.prototype.addTextTrack.call(this, kind, label, language);
}
return this.el_.addTextTrack(kind, label, language);
};
/**
* Creates either native TextTrack or an emulated TextTrack depending
* on the value of `featuresNativeTextTracks`
*
* @param {Object} options
* The object should contain the options to intialize the TextTrack with.
*
* @param {string} [options.kind]
* `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
*
* @param {string} [options.label].
* Label to identify the text track
*
* @param {string} [options.language]
* Two letter language abbreviation.
*
* @param {boolean} [options.default]
* Default this track to on.
*
* @param {string} [options.id]
* The internal id to assign this track.
*
* @param {string} [options.src]
* A source url for the track.
*
* @return {HTMLTrackElement}
* The track element that gets created.
*/
Html5.prototype.createRemoteTextTrack = function createRemoteTextTrack(options) {
if (!this.featuresNativeTextTracks) {
return _Tech.prototype.createRemoteTextTrack.call(this, options);
}
var htmlTrackElement = document.createElement('track');
if (options.kind) {
htmlTrackElement.kind = options.kind;
}
if (options.label) {
htmlTrackElement.label = options.label;
}
if (options.language || options.srclang) {
htmlTrackElement.srclang = options.language || options.srclang;
}
if (options['default']) {
htmlTrackElement['default'] = options['default'];
}
if (options.id) {
htmlTrackElement.id = options.id;
}
if (options.src) {
htmlTrackElement.src = options.src;
}
return htmlTrackElement;
};
/**
* Creates a remote text track object and returns an html track element.
*
* @param {Object} options The object should contain values for
* kind, language, label, and src (location of the WebVTT file)
* @param {Boolean} [manualCleanup=true] if set to false, the TextTrack will be
* automatically removed from the video element whenever the source changes
* @return {HTMLTrackElement} An Html Track Element.
* This can be an emulated {@link HTMLTrackElement} or a native one.
* @deprecated The default value of the "manualCleanup" parameter will default
* to "false" in upcoming versions of Video.js
*/
Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup);
if (this.featuresNativeTextTracks) {
this.el().appendChild(htmlTrackElement);
}
return htmlTrackElement;
};
/**
* Remove remote `TextTrack` from `TextTrackList` object
*
* @param {TextTrack} track
* `TextTrack` object to remove
*/
Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
_Tech.prototype.removeRemoteTextTrack.call(this, track);
if (this.featuresNativeTextTracks) {
var tracks = this.$$('track');
var i = tracks.length;
while (i--) {
if (track === tracks[i] || track === tracks[i].track) {
this.el().removeChild(tracks[i]);
}
}
}
};
/**
* Gets available media playback quality metrics as specified by the W3C's Media
* Playback Quality API.
*
* @see [Spec]{@link https://wicg.github.io/media-playback-quality}
*
* @return {Object}
* An object with supported media playback quality metrics
*/
Html5.prototype.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
if (typeof this.el().getVideoPlaybackQuality === 'function') {
return this.el().getVideoPlaybackQuality();
}
var videoPlaybackQuality = {};
if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
}
if (window.performance && typeof window.performance.now === 'function') {
videoPlaybackQuality.creationTime = window.performance.now();
} else if (window.performance && window.performance.timing && typeof window.performance.timing.navigationStart === 'number') {
videoPlaybackQuality.creationTime = window.Date.now() - window.performance.timing.navigationStart;
}
return videoPlaybackQuality;
};
return Html5;
}(Tech);
/* HTML5 Support Testing ---------------------------------------------------- */
if (isReal()) {
/**
* Element for testing browser HTML5 media capabilities
*
* @type {Element}
* @constant
* @private
*/
Html5.TEST_VID = document.createElement('video');
var track = document.createElement('track');
track.kind = 'captions';
track.srclang = 'en';
track.label = 'English';
Html5.TEST_VID.appendChild(track);
}
/**
* Check if HTML5 media is supported by this browser/device.
*
* @return {boolean}
* - True if HTML5 media is supported.
* - False if HTML5 media is not supported.
*/
Html5.isSupported = function () {
// IE9 with no Media Player is a LIAR! (#984)
try {
Html5.TEST_VID.volume = 0.5;
} catch (e) {
return false;
}
return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
};
/**
* Check if the tech can support the given type
*
* @param {string} type
* The mimetype to check
* @return {string} 'probably', 'maybe', or '' (empty string)
*/
Html5.canPlayType = function (type) {
return Html5.TEST_VID.canPlayType(type);
};
/**
* Check if the tech can support the given source
* @param {Object} srcObj
* The source object
* @param {Object} options
* The options passed to the tech
* @return {string} 'probably', 'maybe', or '' (empty string)
*/
Html5.canPlaySource = function (srcObj, options) {
return Html5.canPlayType(srcObj.type);
};
/**
* Check if the volume can be changed in this browser/device.
* Volume cannot be changed in a lot of mobile devices.
* Specifically, it can't be changed from 1 on iOS.
*
* @return {boolean}
* - True if volume can be controlled
* - False otherwise
*/
Html5.canControlVolume = function () {
// IE will error if Windows Media Player not installed #3315
try {
var volume = Html5.TEST_VID.volume;
Html5.TEST_VID.volume = volume / 2 + 0.1;
return volume !== Html5.TEST_VID.volume;
} catch (e) {
return false;
}
};
/**
* Check if the volume can be muted in this browser/device.
* Some devices, e.g. iOS, don't allow changing volume
* but permits muting/unmuting.
*
* @return {bolean}
* - True if volume can be muted
* - False otherwise
*/
Html5.canMuteVolume = function () {
try {
var muted = Html5.TEST_VID.muted;
// in some versions of iOS muted property doesn't always
// work, so we want to set both property and attribute
Html5.TEST_VID.muted = !muted;
if (Html5.TEST_VID.muted) {
setAttribute(Html5.TEST_VID, 'muted', 'muted');
} else {
removeAttribute(Html5.TEST_VID, 'muted', 'muted');
}
return muted !== Html5.TEST_VID.muted;
} catch (e) {
return false;
}
};
/**
* Check if the playback rate can be changed in this browser/device.
*
* @return {boolean}
* - True if playback rate can be controlled
* - False otherwise
*/
Html5.canControlPlaybackRate = function () {
// Playback rate API is implemented in Android Chrome, but doesn't do anything
// https://github.com/videojs/video.js/issues/3180
if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
return false;
}
// IE will error if Windows Media Player not installed #3315
try {
var playbackRate = Html5.TEST_VID.playbackRate;
Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
return playbackRate !== Html5.TEST_VID.playbackRate;
} catch (e) {
return false;
}
};
/**
* Check if we can override a video/audio elements attributes, with
* Object.defineProperty.
*
* @return {boolean}
* - True if builtin attributes can be overriden
* - False otherwise
*/
Html5.canOverrideAttributes = function () {
if (IS_IE8) {
return false;
}
// if we cannot overwrite the src/innerHTML property, there is no support
// iOS 7 safari for instance cannot do this.
try {
var noop = function noop() {};
Object.defineProperty(document.createElement('video'), 'src', { get: noop, set: noop });
Object.defineProperty(document.createElement('audio'), 'src', { get: noop, set: noop });
Object.defineProperty(document.createElement('video'), 'innerHTML', { get: noop, set: noop });
Object.defineProperty(document.createElement('audio'), 'innerHTML', { get: noop, set: noop });
} catch (e) {
return false;
}
return true;
};
/**
* Check to see if native `TextTrack`s are supported by this browser/device.
*
* @return {boolean}
* - True if native `TextTrack`s are supported.
* - False otherwise
*/
Html5.supportsNativeTextTracks = function () {
return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
};
/**
* Check to see if native `VideoTrack`s are supported by this browser/device
*
* @return {boolean}
* - True if native `VideoTrack`s are supported.
* - False otherwise
*/
Html5.supportsNativeVideoTracks = function () {
return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
};
/**
* Check to see if native `AudioTrack`s are supported by this browser/device
*
* @return {boolean}
* - True if native `AudioTrack`s are supported.
* - False otherwise
*/
Html5.supportsNativeAudioTracks = function () {
return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
};
/**
* An array of events available on the Html5 tech.
*
* @private
* @type {Array}
*/
Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange'];
/**
* Boolean indicating whether the `Tech` supports volume control.
*
* @type {boolean}
* @default {@link Html5.canControlVolume}
*/
Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
/**
* Boolean indicating whether the `Tech` supports muting volume.
*
* @type {bolean}
* @default {@link Html5.canMuteVolume}
*/
Html5.prototype.featuresMuteControl = Html5.canMuteVolume();
/**
* Boolean indicating whether the `Tech` supports changing the speed at which the media
* plays. Examples:
* - Set player to play 2x (twice) as fast
* - Set player to play 0.5x (half) as fast
*
* @type {boolean}
* @default {@link Html5.canControlPlaybackRate}
*/
Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate();
/**
* Boolean indicating wether the `Tech` supports the `sourceset` event.
*
* @type {boolean}
* @default
*/
Html5.prototype.featuresSourceset = Html5.canOverrideAttributes();
/**
* Boolean indicating whether the `HTML5` tech currently supports the media element
* moving in the DOM. iOS breaks if you move the media element, so this is set this to
* false there. Everywhere else this should be true.
*
* @type {boolean}
* @default
*/
Html5.prototype.movingMediaElementInDOM = !IS_IOS;
// TODO: Previous comment: No longer appears to be used. Can probably be removed.
// Is this true?
/**
* Boolean indicating whether the `HTML5` tech currently supports automatic media resize
* when going into fullscreen.
*
* @type {boolean}
* @default
*/
Html5.prototype.featuresFullscreenResize = true;
/**
* Boolean indicating whether the `HTML5` tech currently supports the progress event.
* If this is false, manual `progress` events will be triggred instead.
*
* @type {boolean}
* @default
*/
Html5.prototype.featuresProgressEvents = true;
/**
* Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
* If this is false, manual `timeupdate` events will be triggred instead.
*
* @default
*/
Html5.prototype.featuresTimeupdateEvents = true;
/**
* Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
*
* @type {boolean}
* @default {@link Html5.supportsNativeTextTracks}
*/
Html5.prototype.featuresNativeTextTracks = Html5.supportsNativeTextTracks();
/**
* Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
*
* @type {boolean}
* @default {@link Html5.supportsNativeVideoTracks}
*/
Html5.prototype.featuresNativeVideoTracks = Html5.supportsNativeVideoTracks();
/**
* Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
*
* @type {boolean}
* @default {@link Html5.supportsNativeAudioTracks}
*/
Html5.prototype.featuresNativeAudioTracks = Html5.supportsNativeAudioTracks();
// HTML5 Feature detection and Device Fixes --------------------------------- //
var canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType;
var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
var mp4RE = /^video\/mp4/i;
Html5.patchCanPlayType = function () {
// Android 4.0 and above can play HLS to some extent but it reports being unable to do so
// Firefox and Chrome report correctly
if (ANDROID_VERSION >= 4.0 && !IS_FIREFOX && !IS_CHROME) {
Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mpegurlRE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
// Override Android 2.2 and less canPlayType method which is broken
} else if (IS_OLD_ANDROID) {
Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mp4RE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
};
Html5.unpatchCanPlayType = function () {
var r = Html5.TEST_VID.constructor.prototype.canPlayType;
Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
return r;
};
// by default, patch the media element
Html5.patchCanPlayType();
Html5.disposeMediaElement = function (el) {
if (!el) {
return;
}
if (el.parentNode) {
el.parentNode.removeChild(el);
}
// remove any child track or source nodes to prevent their loading
while (el.hasChildNodes()) {
el.removeChild(el.firstChild);
}
// remove any src reference. not setting `src=''` because that causes a warning
// in firefox
el.removeAttribute('src');
// force the media element to update its loading state by calling load()
// however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function () {
try {
el.load();
} catch (e) {
// not supported
}
})();
}
};
Html5.resetMediaElement = function (el) {
if (!el) {
return;
}
var sources = el.querySelectorAll('source');
var i = sources.length;
while (i--) {
el.removeChild(sources[i]);
}
// remove any src reference.
// not setting `src=''` because that throws an error
el.removeAttribute('src');
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function () {
try {
el.load();
} catch (e) {
// satisfy linter
}
})();
}
};
/* Native HTML5 element property wrapping ----------------------------------- */
// Wrap native boolean attributes with getters that check both property and attribute
// The list is as followed:
// muted, defaultMuted, autoplay, controls, loop, playsinline
[
/**
* Get the value of `muted` from the media element. `muted` indicates
* that the volume for the media should be set to silent. This does not actually change
* the `volume` attribute.
*
* @method Html5#muted
* @return {boolean}
* - True if the value of `volume` should be ignored and the audio set to silent.
* - False if the value of `volume` should be used.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
*/
'muted',
/**
* Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
* whether the media should start muted or not. Only changes the default state of the
* media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
* current state.
*
* @method Html5#defaultMuted
* @return {boolean}
* - The value of `defaultMuted` from the media element.
* - True indicates that the media should start muted.
* - False indicates that the media should not start muted
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
*/
'defaultMuted',
/**
* Get the value of `autoplay` from the media element. `autoplay` indicates
* that the media should start to play as soon as the page is ready.
*
* @method Html5#autoplay
* @return {boolean}
* - The value of `autoplay` from the media element.
* - True indicates that the media should start as soon as the page loads.
* - False indicates that the media should not start as soon as the page loads.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
*/
'autoplay',
/**
* Get the value of `controls` from the media element. `controls` indicates
* whether the native media controls should be shown or hidden.
*
* @method Html5#controls
* @return {boolean}
* - The value of `controls` from the media element.
* - True indicates that native controls should be showing.
* - False indicates that native controls should be hidden.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
*/
'controls',
/**
* Get the value of `loop` from the media element. `loop` indicates
* that the media should return to the start of the media and continue playing once
* it reaches the end.
*
* @method Html5#loop
* @return {boolean}
* - The value of `loop` from the media element.
* - True indicates that playback should seek back to start once
* the end of a media is reached.
* - False indicates that playback should not loop back to the start when the
* end of the media is reached.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
*/
'loop',
/**
* Get the value of `playsinline` from the media element. `playsinline` indicates
* to the browser that non-fullscreen playback is preferred when fullscreen
* playback is the native default, such as in iOS Safari.
*
* @method Html5#playsinline
* @return {boolean}
* - The value of `playsinline` from the media element.
* - True indicates that the media should play inline.
* - False indicates that the media should not play inline.
*
* @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
*/
'playsinline'].forEach(function (prop) {
Html5.prototype[prop] = function () {
return this.el_[prop] || this.el_.hasAttribute(prop);
};
});
// Wrap native boolean attributes with setters that set both property and attribute
// The list is as followed:
// setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
// setControls is special-cased above
[
/**
* Set the value of `muted` on the media element. `muted` indicates that the current
* audio level should be silent.
*
* @method Html5#setMuted
* @param {boolean} muted
* - True if the audio should be set to silent
* - False otherwise
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
*/
'muted',
/**
* Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
* audio level should be silent, but will only effect the muted level on intial playback..
*
* @method Html5.prototype.setDefaultMuted
* @param {boolean} defaultMuted
* - True if the audio should be set to silent
* - False otherwise
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
*/
'defaultMuted',
/**
* Set the value of `autoplay` on the media element. `autoplay` indicates
* that the media should start to play as soon as the page is ready.
*
* @method Html5#setAutoplay
* @param {boolean} autoplay
* - True indicates that the media should start as soon as the page loads.
* - False indicates that the media should not start as soon as the page loads.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
*/
'autoplay',
/**
* Set the value of `loop` on the media element. `loop` indicates
* that the media should return to the start of the media and continue playing once
* it reaches the end.
*
* @method Html5#setLoop
* @param {boolean} loop
* - True indicates that playback should seek back to start once
* the end of a media is reached.
* - False indicates that playback should not loop back to the start when the
* end of the media is reached.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
*/
'loop',
/**
* Set the value of `playsinline` from the media element. `playsinline` indicates
* to the browser that non-fullscreen playback is preferred when fullscreen
* playback is the native default, such as in iOS Safari.
*
* @method Html5#setPlaysinline
* @param {boolean} playsinline
* - True indicates that the media should play inline.
* - False indicates that the media should not play inline.
*
* @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
*/
'playsinline'].forEach(function (prop) {
Html5.prototype['set' + toTitleCase(prop)] = function (v) {
this.el_[prop] = v;
if (v) {
this.el_.setAttribute(prop, prop);
} else {
this.el_.removeAttribute(prop);
}
};
});
// Wrap native properties with a getter
// The list is as followed
// paused, currentTime, buffered, volume, poster, preload, error, seeking
// seekable, ended, playbackRate, defaultPlaybackRate, played, networkState
// readyState, videoWidth, videoHeight
[
/**
* Get the value of `paused` from the media element. `paused` indicates whether the media element
* is currently paused or not.
*
* @method Html5#paused
* @return {boolean}
* The value of `paused` from the media element.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
*/
'paused',
/**
* Get the value of `currentTime` from the media element. `currentTime` indicates
* the current second that the media is at in playback.
*
* @method Html5#currentTime
* @return {number}
* The value of `currentTime` from the media element.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
*/
'currentTime',
/**
* Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
* object that represents the parts of the media that are already downloaded and
* available for playback.
*
* @method Html5#buffered
* @return {TimeRange}
* The value of `buffered` from the media element.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
*/
'buffered',
/**
* Get the value of `volume` from the media element. `volume` indicates
* the current playback volume of audio for a media. `volume` will be a value from 0
* (silent) to 1 (loudest and default).
*
* @method Html5#volume
* @return {number}
* The value of `volume` from the media element. Value will be between 0-1.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
*/
'volume',
/**
* Get the value of `poster` from the media element. `poster` indicates
* that the url of an image file that can/will be shown when no media data is available.
*
* @method Html5#poster
* @return {string}
* The value of `poster` from the media element. Value will be a url to an
* image.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
*/
'poster',
/**
* Get the value of `preload` from the media element. `preload` indicates
* what should download before the media is interacted with. It can have the following
* values:
* - none: nothing should be downloaded
* - metadata: poster and the first few frames of the media may be downloaded to get
* media dimensions and other metadata
* - auto: allow the media and metadata for the media to be downloaded before
* interaction
*
* @method Html5#preload
* @return {string}
* The value of `preload` from the media element. Will be 'none', 'metadata',
* or 'auto'.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
*/
'preload',
/**
* Get the value of the `error` from the media element. `error` indicates any
* MediaError that may have occured during playback. If error returns null there is no
* current error.
*
* @method Html5#error
* @return {MediaError|null}
* The value of `error` from the media element. Will be `MediaError` if there
* is a current error and null otherwise.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
*/
'error',
/**
* Get the value of `seeking` from the media element. `seeking` indicates whether the
* media is currently seeking to a new position or not.
*
* @method Html5#seeking
* @return {boolean}
* - The value of `seeking` from the media element.
* - True indicates that the media is currently seeking to a new position.
* - Flase indicates that the media is not seeking to a new position at this time.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
*/
'seeking',
/**
* Get the value of `seekable` from the media element. `seekable` returns a
* `TimeRange` object indicating ranges of time that can currently be `seeked` to.
*
* @method Html5#seekable
* @return {TimeRange}
* The value of `seekable` from the media element. A `TimeRange` object
* indicating the current ranges of time that can be seeked to.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
*/
'seekable',
/**
* Get the value of `ended` from the media element. `ended` indicates whether
* the media has reached the end or not.
*
* @method Html5#ended
* @return {boolean}
* - The value of `ended` from the media element.
* - True indicates that the media has ended.
* - False indicates that the media has not ended.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
*/
'ended',
/**
* Get the value of `playbackRate` from the media element. `playbackRate` indicates
* the rate at which the media is currently playing back. Examples:
* - if playbackRate is set to 2, media will play twice as fast.
* - if playbackRate is set to 0.5, media will play half as fast.
*
* @method Html5#playbackRate
* @return {number}
* The value of `playbackRate` from the media element. A number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
*/
'playbackRate',
/**
* Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
* the rate at which the media is currently playing back. This value will not indicate the current
* `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
*
* Examples:
* - if defaultPlaybackRate is set to 2, media will play twice as fast.
* - if defaultPlaybackRate is set to 0.5, media will play half as fast.
*
* @method Html5.prototype.defaultPlaybackRate
* @return {number}
* The value of `defaultPlaybackRate` from the media element. A number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
*/
'defaultPlaybackRate',
/**
* Get the value of `played` from the media element. `played` returns a `TimeRange`
* object representing points in the media timeline that have been played.
*
* @method Html5#played
* @return {TimeRange}
* The value of `played` from the media element. A `TimeRange` object indicating
* the ranges of time that have been played.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
*/
'played',
/**
* Get the value of `networkState` from the media element. `networkState` indicates
* the current network state. It returns an enumeration from the following list:
* - 0: NETWORK_EMPTY
* - 1: NEWORK_IDLE
* - 2: NETWORK_LOADING
* - 3: NETWORK_NO_SOURCE
*
* @method Html5#networkState
* @return {number}
* The value of `networkState` from the media element. This will be a number
* from the list in the description.
*
* @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
*/
'networkState',
/**
* Get the value of `readyState` from the media element. `readyState` indicates
* the current state of the media element. It returns an enumeration from the
* following list:
* - 0: HAVE_NOTHING
* - 1: HAVE_METADATA
* - 2: HAVE_CURRENT_DATA
* - 3: HAVE_FUTURE_DATA
* - 4: HAVE_ENOUGH_DATA
*
* @method Html5#readyState
* @return {number}
* The value of `readyState` from the media element. This will be a number
* from the list in the description.
*
* @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
*/
'readyState',
/**
* Get the value of `videoWidth` from the video element. `videoWidth` indicates
* the current width of the video in css pixels.
*
* @method Html5#videoWidth
* @return {number}
* The value of `videoWidth` from the video element. This will be a number
* in css pixels.
*
* @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
*/
'videoWidth',
/**
* Get the value of `videoHeight` from the video element. `videoHeigth` indicates
* the current height of the video in css pixels.
*
* @method Html5#videoHeight
* @return {number}
* The value of `videoHeight` from the video element. This will be a number
* in css pixels.
*
* @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
*/
'videoHeight'].forEach(function (prop) {
Html5.prototype[prop] = function () {
return this.el_[prop];
};
});
// Wrap native properties with a setter in this format:
// set + toTitleCase(name)
// The list is as follows:
// setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate
[
/**
* Set the value of `volume` on the media element. `volume` indicates the current
* audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
* so on.
*
* @method Html5#setVolume
* @param {number} percentAsDecimal
* The volume percent as a decimal. Valid range is from 0-1.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
*/
'volume',
/**
* Set the value of `src` on the media element. `src` indicates the current
* {@link Tech~SourceObject} for the media.
*
* @method Html5#setSrc
* @param {Tech~SourceObject} src
* The source object to set as the current source.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
*/
'src',
/**
* Set the value of `poster` on the media element. `poster` is the url to
* an image file that can/will be shown when no media data is available.
*
* @method Html5#setPoster
* @param {string} poster
* The url to an image that should be used as the `poster` for the media
* element.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
*/
'poster',
/**
* Set the value of `preload` on the media element. `preload` indicates
* what should download before the media is interacted with. It can have the following
* values:
* - none: nothing should be downloaded
* - metadata: poster and the first few frames of the media may be downloaded to get
* media dimensions and other metadata
* - auto: allow the media and metadata for the media to be downloaded before
* interaction
*
* @method Html5#setPreload
* @param {string} preload
* The value of `preload` to set on the media element. Must be 'none', 'metadata',
* or 'auto'.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
*/
'preload',
/**
* Set the value of `playbackRate` on the media element. `playbackRate` indicates
* the rate at which the media should play back. Examples:
* - if playbackRate is set to 2, media will play twice as fast.
* - if playbackRate is set to 0.5, media will play half as fast.
*
* @method Html5#setPlaybackRate
* @return {number}
* The value of `playbackRate` from the media element. A number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
*/
'playbackRate',
/**
* Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
* the rate at which the media should play back upon initial startup. Changing this value
* after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
*
* Example Values:
* - if playbackRate is set to 2, media will play twice as fast.
* - if playbackRate is set to 0.5, media will play half as fast.
*
* @method Html5.prototype.setDefaultPlaybackRate
* @return {number}
* The value of `defaultPlaybackRate` from the media element. A number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
*/
'defaultPlaybackRate'].forEach(function (prop) {
Html5.prototype['set' + toTitleCase(prop)] = function (v) {
this.el_[prop] = v;
};
});
// wrap native functions with a function
// The list is as follows:
// pause, load play
[
/**
* A wrapper around the media elements `pause` function. This will call the `HTML5`
* media elements `pause` function.
*
* @method Html5#pause
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
*/
'pause',
/**
* A wrapper around the media elements `load` function. This will call the `HTML5`s
* media element `load` function.
*
* @method Html5#load
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
*/
'load',
/**
* A wrapper around the media elements `play` function. This will call the `HTML5`s
* media element `play` function.
*
* @method Html5#play
* @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
*/
'play'].forEach(function (prop) {
Html5.prototype[prop] = function () {
return this.el_[prop]();
};
});
Tech.withSourceHandlers(Html5);
/**
* Native source handler for Html5, simply passes the source to the media element.
*
* @proprety {Tech~SourceObject} source
* The source object
*
* @proprety {Html5} tech
* The instance of the HTML5 tech.
*/
Html5.nativeSourceHandler = {};
/**
* Check if the media element can play the given mime type.
*
* @param {string} type
* The mimetype to check
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
Html5.nativeSourceHandler.canPlayType = function (type) {
// IE9 on Windows 7 without MediaPlayer throws an error here
// https://github.com/videojs/video.js/issues/519
try {
return Html5.TEST_VID.canPlayType(type);
} catch (e) {
return '';
}
};
/**
* Check if the media element can handle a source natively.
*
* @param {Tech~SourceObject} source
* The source object
*
* @param {Object} [options]
* Options to be passed to the tech.
*
* @return {string}
* 'probably', 'maybe', or '' (empty string).
*/
Html5.nativeSourceHandler.canHandleSource = function (source, options) {
// If a type was provided we should rely on that
if (source.type) {
return Html5.nativeSourceHandler.canPlayType(source.type);
// If no type, fall back to checking 'video/[EXTENSION]'
} else if (source.src) {
var ext = getFileExtension(source.src);
return Html5.nativeSourceHandler.canPlayType('video/' + ext);
}
return '';
};
/**
* Pass the source to the native media element.
*
* @param {Tech~SourceObject} source
* The source object
*
* @param {Html5} tech
* The instance of the Html5 tech
*
* @param {Object} [options]
* The options to pass to the source
*/
Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
tech.setSrc(source.src);
};
/**
* A noop for the native dispose function, as cleanup is not needed.
*/
Html5.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Html5.registerSourceHandler(Html5.nativeSourceHandler);
Tech.registerTech('Html5', Html5);
var _templateObject$1 = taggedTemplateLiteralLoose(['\n Using the tech directly can be dangerous. I hope you know what you\'re doing.\n See https://github.com/videojs/video.js/issues/2617 for more info.\n '], ['\n Using the tech directly can be dangerous. I hope you know what you\'re doing.\n See https://github.com/videojs/video.js/issues/2617 for more info.\n ']);
/**
* @file player.js
*/
// Subclasses Component
// The following imports are used only to ensure that the corresponding modules
// are always included in the video.js package. Importing the modules will
// execute them and they will register themselves with video.js.
// Import Html5 tech, at least for disposing the original video tag.
// The following tech events are simply re-triggered
// on the player when they happen
var TECH_EVENTS_RETRIGGER = [
/**
* Fired while the user agent is downloading media data.
*
* @event Player#progress
* @type {EventTarget~Event}
*/
/**
* Retrigger the `progress` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechProgress_
* @fires Player#progress
* @listens Tech#progress
*/
'progress',
/**
* Fires when the loading of an audio/video is aborted.
*
* @event Player#abort
* @type {EventTarget~Event}
*/
/**
* Retrigger the `abort` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechAbort_
* @fires Player#abort
* @listens Tech#abort
*/
'abort',
/**
* Fires when the browser is intentionally not getting media data.
*
* @event Player#suspend
* @type {EventTarget~Event}
*/
/**
* Retrigger the `suspend` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechSuspend_
* @fires Player#suspend
* @listens Tech#suspend
*/
'suspend',
/**
* Fires when the current playlist is empty.
*
* @event Player#emptied
* @type {EventTarget~Event}
*/
/**
* Retrigger the `emptied` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechEmptied_
* @fires Player#emptied
* @listens Tech#emptied
*/
'emptied',
/**
* Fires when the browser is trying to get media data, but data is not available.
*
* @event Player#stalled
* @type {EventTarget~Event}
*/
/**
* Retrigger the `stalled` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechStalled_
* @fires Player#stalled
* @listens Tech#stalled
*/
'stalled',
/**
* Fires when the browser has loaded meta data for the audio/video.
*
* @event Player#loadedmetadata
* @type {EventTarget~Event}
*/
/**
* Retrigger the `stalled` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechLoadedmetadata_
* @fires Player#loadedmetadata
* @listens Tech#loadedmetadata
*/
'loadedmetadata',
/**
* Fires when the browser has loaded the current frame of the audio/video.
*
* @event Player#loadeddata
* @type {event}
*/
/**
* Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechLoaddeddata_
* @fires Player#loadeddata
* @listens Tech#loadeddata
*/
'loadeddata',
/**
* Fires when the current playback position has changed.
*
* @event Player#timeupdate
* @type {event}
*/
/**
* Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechTimeUpdate_
* @fires Player#timeupdate
* @listens Tech#timeupdate
*/
'timeupdate',
/**
* Fires when the video's intrinsic dimensions change
*
* @event Player#resize
* @type {event}
*/
/**
* Retrigger the `resize` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechResize_
* @fires Player#resize
* @listens Tech#resize
*/
'resize',
/**
* Fires when the volume has been changed
*
* @event Player#volumechange
* @type {event}
*/
/**
* Retrigger the `volumechange` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechVolumechange_
* @fires Player#volumechange
* @listens Tech#volumechange
*/
'volumechange',
/**
* Fires when the text track has been changed
*
* @event Player#texttrackchange
* @type {event}
*/
/**
* Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechTexttrackchange_
* @fires Player#texttrackchange
* @listens Tech#texttrackchange
*/
'texttrackchange'];
// events to queue when playback rate is zero
// this is a hash for the sole purpose of mapping non-camel-cased event names
// to camel-cased function names
var TECH_EVENTS_QUEUE = {
canplay: 'CanPlay',
canplaythrough: 'CanPlayThrough',
playing: 'Playing',
seeked: 'Seeked'
};
var BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
var BREAKPOINT_CLASSES = {};
// grep: vjs-layout-tiny
// grep: vjs-layout-x-small
// grep: vjs-layout-small
// grep: vjs-layout-medium
// grep: vjs-layout-large
// grep: vjs-layout-x-large
// grep: vjs-layout-huge
BREAKPOINT_ORDER.forEach(function (k) {
var v = k.charAt(0) === 'x' ? 'x-' + k.substring(1) : k;
BREAKPOINT_CLASSES[k] = 'vjs-layout-' + v;
});
var DEFAULT_BREAKPOINTS = {
tiny: 210,
xsmall: 320,
small: 425,
medium: 768,
large: 1440,
xlarge: 2560,
huge: Infinity
};
/**
* An instance of the `Player` class is created when any of the Video.js setup methods
* are used to initialize a video.
*
* After an instance has been created it can be accessed globally in two ways:
* 1. By calling `videojs('example_video_1');`
* 2. By using it directly via `videojs.players.example_video_1;`
*
* @extends Component
*/
var Player = function (_Component) {
inherits(Player, _Component);
/**
* Create an instance of this class.
*
* @param {Element} tag
* The original video DOM element used for configuring options.
*
* @param {Object} [options]
* Object of option names and values.
*
* @param {Component~ReadyCallback} [ready]
* Ready callback function.
*/
function Player(tag, options, ready) {
classCallCheck(this, Player);
// Make sure tag ID exists
tag.id = tag.id || options.id || 'vjs_video_' + newGUID();
// Set Options
// The options argument overrides options set in the video tag
// which overrides globally set options.
// This latter part coincides with the load order
// (tag must exist before Player)
options = assign(Player.getTagSettings(tag), options);
// Delay the initialization of children because we need to set up
// player properties first, and can't use `this` before `super()`
options.initChildren = false;
// Same with creating the element
options.createEl = false;
// don't auto mixin the evented mixin
options.evented = false;
// we don't want the player to report touch activity on itself
// see enableTouchActivity in Component
options.reportTouchActivity = false;
// If language is not set, get the closest lang attribute
if (!options.language) {
if (typeof tag.closest === 'function') {
var closest = tag.closest('[lang]');
if (closest && closest.getAttribute) {
options.language = closest.getAttribute('lang');
}
} else {
var element = tag;
while (element && element.nodeType === 1) {
if (getAttributes(element).hasOwnProperty('lang')) {
options.language = element.getAttribute('lang');
break;
}
element = element.parentNode;
}
}
}
// Run base component initializing with new options
// create logger
var _this = possibleConstructorReturn(this, _Component.call(this, null, options, ready));
_this.log = createLogger(_this.id_);
// Tracks when a tech changes the poster
_this.isPosterFromTech_ = false;
// Holds callback info that gets queued when playback rate is zero
// and a seek is happening
_this.queuedCallbacks_ = [];
// Turn off API access because we're loading a new tech that might load asynchronously
_this.isReady_ = false;
// Init state hasStarted_
_this.hasStarted_ = false;
// Init state userActive_
_this.userActive_ = false;
// if the global option object was accidentally blown away by
// someone, bail early with an informative error
if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) {
throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
}
// Store the original tag used to set options
_this.tag = tag;
// Store the tag attributes used to restore html5 element
_this.tagAttributes = tag && getAttributes(tag);
// Update current language
_this.language(_this.options_.language);
// Update Supported Languages
if (options.languages) {
// Normalise player option languages to lowercase
var languagesToLower = {};
Object.getOwnPropertyNames(options.languages).forEach(function (name$$1) {
languagesToLower[name$$1.toLowerCase()] = options.languages[name$$1];
});
_this.languages_ = languagesToLower;
} else {
_this.languages_ = Player.prototype.options_.languages;
}
// Cache for video property values.
_this.cache_ = {};
// Set poster
_this.poster_ = options.poster || '';
// Set controls
_this.controls_ = !!options.controls;
// Set default values for lastVolume
_this.cache_.lastVolume = 1;
// Original tag settings stored in options
// now remove immediately so native controls don't flash.
// May be turned back on by HTML5 tech if nativeControlsForTouch is true
tag.controls = false;
tag.removeAttribute('controls');
// the attribute overrides the option
if (tag.hasAttribute('autoplay')) {
_this.options_.autoplay = true;
} else {
// otherwise use the setter to validate and
// set the correct value.
_this.autoplay(_this.options_.autoplay);
}
/*
* Store the internal state of scrubbing
*
* @private
* @return {Boolean} True if the user is scrubbing
*/
_this.scrubbing_ = false;
_this.el_ = _this.createEl();
// Set default value for lastPlaybackRate
_this.cache_.lastPlaybackRate = _this.defaultPlaybackRate();
// Make this an evented object and use `el_` as its event bus.
evented(_this, { eventBusKey: 'el_' });
// We also want to pass the original player options to each component and plugin
// as well so they don't need to reach back into the player for options later.
// We also need to do another copy of this.options_ so we don't end up with
// an infinite loop.
var playerOptionsCopy = mergeOptions(_this.options_);
// Load plugins
if (options.plugins) {
var plugins = options.plugins;
Object.keys(plugins).forEach(function (name$$1) {
if (typeof this[name$$1] === 'function') {
this[name$$1](plugins[name$$1]);
} else {
throw new Error('plugin "' + name$$1 + '" does not exist');
}
}, _this);
}
_this.options_.playerOptions = playerOptionsCopy;
_this.middleware_ = [];
_this.initChildren();
// Set isAudio based on whether or not an audio tag was used
_this.isAudio(tag.nodeName.toLowerCase() === 'audio');
// Update controls className. Can't do this when the controls are initially
// set because the element doesn't exist yet.
if (_this.controls()) {
_this.addClass('vjs-controls-enabled');
} else {
_this.addClass('vjs-controls-disabled');
}
// Set ARIA label and region role depending on player type
_this.el_.setAttribute('role', 'region');
if (_this.isAudio()) {
_this.el_.setAttribute('aria-label', _this.localize('Audio Player'));
} else {
_this.el_.setAttribute('aria-label', _this.localize('Video Player'));
}
if (_this.isAudio()) {
_this.addClass('vjs-audio');
}
if (_this.flexNotSupported_()) {
_this.addClass('vjs-no-flex');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// if (browser.TOUCH_ENABLED) {
// this.addClass('vjs-touch-enabled');
// }
// iOS Safari has broken hover handling
if (!IS_IOS) {
_this.addClass('vjs-workinghover');
}
// Make player easily findable by ID
Player.players[_this.id_] = _this;
// Add a major version class to aid css in plugins
var majorVersion = version.split('.')[0];
_this.addClass('vjs-v' + majorVersion);
// When the player is first initialized, trigger activity so components
// like the control bar show themselves if needed
_this.userActive(true);
_this.reportUserActivity();
_this.one('play', _this.listenForUserActivity_);
_this.on('fullscreenchange', _this.handleFullscreenChange_);
_this.on('stageclick', _this.handleStageClick_);
_this.breakpoints(_this.options_.breakpoints);
_this.responsive(_this.options_.responsive);
_this.changingSrc_ = false;
_this.playWaitingForReady_ = false;
_this.playOnLoadstart_ = null;
return _this;
}
/**
* Destroys the video player and does any necessary cleanup.
*
* This is especially helpful if you are dynamically adding and removing videos
* to/from the DOM.
*
* @fires Player#dispose
*/
Player.prototype.dispose = function dispose() {
/**
* Called when the player is being disposed of.
*
* @event Player#dispose
* @type {EventTarget~Event}
*/
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
if (this.styleEl_ && this.styleEl_.parentNode) {
this.styleEl_.parentNode.removeChild(this.styleEl_);
this.styleEl_ = null;
}
// Kill reference to this player
Player.players[this.id_] = null;
if (this.tag && this.tag.player) {
this.tag.player = null;
}
if (this.el_ && this.el_.player) {
this.el_.player = null;
}
if (this.tech_) {
this.tech_.dispose();
this.isPosterFromTech_ = false;
this.poster_ = '';
}
if (this.playerElIngest_) {
this.playerElIngest_ = null;
}
if (this.tag) {
this.tag = null;
}
clearCacheForPlayer(this);
// the actual .el_ is removed here
_Component.prototype.dispose.call(this);
};
/**
* Create the `Player`'s DOM element.
*
* @return {Element}
* The DOM element that gets created.
*/
Player.prototype.createEl = function createEl$$1() {
var tag = this.tag;
var el = void 0;
var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
var divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
if (playerElIngest) {
el = this.el_ = tag.parentNode;
} else if (!divEmbed) {
el = this.el_ = _Component.prototype.createEl.call(this, 'div');
}
// Copy over all the attributes from the tag, including ID and class
// ID will now reference player box, not the video tag
var attrs = getAttributes(tag);
if (divEmbed) {
el = this.el_ = tag;
tag = this.tag = document.createElement('video');
while (el.children.length) {
tag.appendChild(el.firstChild);
}
if (!hasClass(el, 'video-js')) {
addClass(el, 'video-js');
}
el.appendChild(tag);
playerElIngest = this.playerElIngest_ = el;
// copy over properties from the video-js element
// ie8 doesn't support Object.keys nor hasOwnProperty
// on dom elements so we have to specify properties individually
['autoplay', 'controls', 'crossOrigin', 'defaultMuted', 'defaultPlaybackRate', 'loop', 'muted', 'playbackRate', 'src', 'volume'].forEach(function (prop) {
if (typeof el[prop] !== 'undefined') {
tag[prop] = el[prop];
}
});
}
// set tabindex to -1 to remove the video element from the focus order
tag.setAttribute('tabindex', '-1');
attrs.tabindex = '-1';
// Workaround for #4583 (JAWS+IE doesn't announce BPB or play button)
// See https://github.com/FreedomScientific/VFO-standards-support/issues/78
// Note that we can't detect if JAWS is being used, but this ARIA attribute
// doesn't change behavior of IE11 if JAWS is not being used
if (IE_VERSION) {
tag.setAttribute('role', 'application');
attrs.role = 'application';
}
// Remove width/height attrs from tag so CSS can make it 100% width/height
tag.removeAttribute('width');
tag.removeAttribute('height');
if ('width' in attrs) {
delete attrs.width;
}
if ('height' in attrs) {
delete attrs.height;
}
Object.getOwnPropertyNames(attrs).forEach(function (attr) {
// workaround so we don't totally break IE7
// http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7
if (attr === 'class') {
el.className += ' ' + attrs[attr];
if (divEmbed) {
tag.className += ' ' + attrs[attr];
}
} else {
el.setAttribute(attr, attrs[attr]);
if (divEmbed) {
tag.setAttribute(attr, attrs[attr]);
}
}
});
// Update tag id/class for use as HTML5 playback tech
// Might think we should do this after embedding in container so .vjs-tech class
// doesn't flash 100% width/height, but class only applies with .video-js parent
tag.playerId = tag.id;
tag.id += '_html5_api';
tag.className = 'vjs-tech';
// Make player findable on elements
tag.player = el.player = this;
// Default state of video is paused
this.addClass('vjs-paused');
// Add a style element in the player that we'll use to set the width/height
// of the player in a way that's still overrideable by CSS, just like the
// video element
if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
this.styleEl_ = createStyleElement('vjs-styles-dimensions');
var defaultsStyleEl = $('.vjs-styles-defaults');
var head = $('head');
head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
}
this.fill_ = false;
this.fluid_ = false;
// Pass in the width/height/aspectRatio options which will update the style el
this.width(this.options_.width);
this.height(this.options_.height);
this.fill(this.options_.fill);
this.fluid(this.options_.fluid);
this.aspectRatio(this.options_.aspectRatio);
// Hide any links within the video/audio tag, because IE doesn't hide them completely.
var links = tag.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var linkEl = links.item(i);
addClass(linkEl, 'vjs-hidden');
linkEl.setAttribute('hidden', 'hidden');
}
// insertElFirst seems to cause the networkState to flicker from 3 to 2, so
// keep track of the original for later so we can know if the source originally failed
tag.initNetworkState_ = tag.networkState;
// Wrap video tag in div (el/box) container
if (tag.parentNode && !playerElIngest) {
tag.parentNode.insertBefore(el, tag);
}
// insert the tag as the first child of the player element
// then manually add it to the children array so that this.addChild
// will work properly for other components
//
// Breaks iPhone, fixed in HTML5 setup.
prependTo(tag, el);
this.children_.unshift(tag);
// Set lang attr on player to ensure CSS :lang() in consistent with player
// if it's been set to something different to the doc
this.el_.setAttribute('lang', this.language_);
this.el_ = el;
return el;
};
/**
* A getter/setter for the `Player`'s width. Returns the player's configured value.
* To get the current width use `currentWidth()`.
*
* @param {number} [value]
* The value to set the `Player`'s width to.
*
* @return {number}
* The current width of the `Player` when getting.
*/
Player.prototype.width = function width(value) {
return this.dimension('width', value);
};
/**
* A getter/setter for the `Player`'s height. Returns the player's configured value.
* To get the current height use `currentheight()`.
*
* @param {number} [value]
* The value to set the `Player`'s heigth to.
*
* @return {number}
* The current height of the `Player` when getting.
*/
Player.prototype.height = function height(value) {
return this.dimension('height', value);
};
/**
* A getter/setter for the `Player`'s width & height.
*
* @param {string} dimension
* This string can be:
* - 'width'
* - 'height'
*
* @param {number} [value]
* Value for dimension specified in the first argument.
*
* @return {number}
* The dimension arguments value when getting (width/height).
*/
Player.prototype.dimension = function dimension(_dimension, value) {
var privDimension = _dimension + '_';
if (value === undefined) {
return this[privDimension] || 0;
}
if (value === '') {
// If an empty string is given, reset the dimension to be automatic
this[privDimension] = undefined;
this.updateStyleEl_();
return;
}
var parsedVal = parseFloat(value);
if (isNaN(parsedVal)) {
log.error('Improper value "' + value + '" supplied for for ' + _dimension);
return;
}
this[privDimension] = parsedVal;
this.updateStyleEl_();
};
/**
* A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
*
* Turning this on will turn off fill mode.
*
* @param {boolean} [bool]
* - A value of true adds the class.
* - A value of false removes the class.
* - No value will be a getter.
*
* @return {boolean|undefined}
* - The value of fluid when getting.
* - `undefined` when setting.
*/
Player.prototype.fluid = function fluid(bool) {
if (bool === undefined) {
return !!this.fluid_;
}
this.fluid_ = !!bool;
if (bool) {
this.addClass('vjs-fluid');
this.fill(false);
} else {
this.removeClass('vjs-fluid');
}
this.updateStyleEl_();
};
/**
* A getter/setter/toggler for the vjs-fill `className` on the `Player`.
*
* Turning this on will turn off fluid mode.
*
* @param {boolean} [bool]
* - A value of true adds the class.
* - A value of false removes the class.
* - No value will be a getter.
*
* @return {boolean|undefined}
* - The value of fluid when getting.
* - `undefined` when setting.
*/
Player.prototype.fill = function fill(bool) {
if (bool === undefined) {
return !!this.fill_;
}
this.fill_ = !!bool;
if (bool) {
this.addClass('vjs-fill');
this.fluid(false);
} else {
this.removeClass('vjs-fill');
}
};
/**
* Get/Set the aspect ratio
*
* @param {string} [ratio]
* Aspect ratio for player
*
* @return {string|undefined}
* returns the current aspect ratio when getting
*/
/**
* A getter/setter for the `Player`'s aspect ratio.
*
* @param {string} [ratio]
* The value to set the `Player's aspect ratio to.
*
* @return {string|undefined}
* - The current aspect ratio of the `Player` when getting.
* - undefined when setting
*/
Player.prototype.aspectRatio = function aspectRatio(ratio) {
if (ratio === undefined) {
return this.aspectRatio_;
}
// Check for width:height format
if (!/^\d+\:\d+$/.test(ratio)) {
throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
}
this.aspectRatio_ = ratio;
// We're assuming if you set an aspect ratio you want fluid mode,
// because in fixed mode you could calculate width and height yourself.
this.fluid(true);
this.updateStyleEl_();
};
/**
* Update styles of the `Player` element (height, width and aspect ratio).
*
* @private
* @listens Tech#loadedmetadata
*/
Player.prototype.updateStyleEl_ = function updateStyleEl_() {
if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
var techEl = this.tech_ && this.tech_.el();
if (techEl) {
if (_width >= 0) {
techEl.width = _width;
}
if (_height >= 0) {
techEl.height = _height;
}
}
return;
}
var width = void 0;
var height = void 0;
var aspectRatio = void 0;
var idClass = void 0;
// The aspect ratio is either used directly or to calculate width and height.
if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
// Use any aspectRatio that's been specifically set
aspectRatio = this.aspectRatio_;
} else if (this.videoWidth() > 0) {
// Otherwise try to get the aspect ratio from the video metadata
aspectRatio = this.videoWidth() + ':' + this.videoHeight();
} else {
// Or use a default. The video element's is 2:1, but 16:9 is more common.
aspectRatio = '16:9';
}
// Get the ratio as a decimal we can use to calculate dimensions
var ratioParts = aspectRatio.split(':');
var ratioMultiplier = ratioParts[1] / ratioParts[0];
if (this.width_ !== undefined) {
// Use any width that's been specifically set
width = this.width_;
} else if (this.height_ !== undefined) {
// Or calulate the width from the aspect ratio if a height has been set
width = this.height_ / ratioMultiplier;
} else {
// Or use the video's metadata, or use the video el's default of 300
width = this.videoWidth() || 300;
}
if (this.height_ !== undefined) {
// Use any height that's been specifically set
height = this.height_;
} else {
// Otherwise calculate the height from the ratio and the width
height = width * ratioMultiplier;
}
// Ensure the CSS class is valid by starting with an alpha character
if (/^[^a-zA-Z]/.test(this.id())) {
idClass = 'dimensions-' + this.id();
} else {
idClass = this.id() + '-dimensions';
}
// Ensure the right class is still on the player for the style element
this.addClass(idClass);
setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n ');
};
/**
* Load/Create an instance of playback {@link Tech} including element
* and API methods. Then append the `Tech` element in `Player` as a child.
*
* @param {string} techName
* name of the playback technology
*
* @param {string} source
* video source
*
* @private
*/
Player.prototype.loadTech_ = function loadTech_(techName, source) {
var _this2 = this;
// Pause and remove current playback technology
if (this.tech_) {
this.unloadTech_();
}
var titleTechName = toTitleCase(techName);
var camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
// get rid of the HTML5 video tag as soon as we are using another tech
if (titleTechName !== 'Html5' && this.tag) {
Tech.getTech('Html5').disposeMediaElement(this.tag);
this.tag.player = null;
this.tag = null;
}
this.techName_ = titleTechName;
// Turn off API access because we're loading a new tech that might load asynchronously
this.isReady_ = false;
// if autoplay is a string we pass false to the tech
// because the player is going to handle autoplay on `loadstart`
var autoplay = typeof this.autoplay() === 'string' ? false : this.autoplay();
// Grab tech-specific options from player options and add source and parent element to use.
var techOptions = {
source: source,
autoplay: autoplay,
'nativeControlsForTouch': this.options_.nativeControlsForTouch,
'playerId': this.id(),
'techId': this.id() + '_' + camelTechName + '_api',
'playsinline': this.options_.playsinline,
'preload': this.options_.preload,
'loop': this.options_.loop,
'muted': this.options_.muted,
'poster': this.poster(),
'language': this.language(),
'playerElIngest': this.playerElIngest_ || false,
'vtt.js': this.options_['vtt.js'],
'canOverridePoster': !!this.options_.techCanOverridePoster,
'enableSourceset': this.options_.enableSourceset
};
ALL.names.forEach(function (name$$1) {
var props = ALL[name$$1];
techOptions[props.getterName] = _this2[props.privateName];
});
assign(techOptions, this.options_[titleTechName]);
assign(techOptions, this.options_[camelTechName]);
assign(techOptions, this.options_[techName.toLowerCase()]);
if (this.tag) {
techOptions.tag = this.tag;
}
if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
techOptions.startTime = this.cache_.currentTime;
}
// Initialize tech instance
var TechClass = Tech.getTech(techName);
if (!TechClass) {
throw new Error('No Tech named \'' + titleTechName + '\' exists! \'' + titleTechName + '\' should be registered using videojs.registerTech()\'');
}
this.tech_ = new TechClass(techOptions);
// player.triggerReady is always async, so don't need this to be async
this.tech_.ready(bind(this, this.handleTechReady_), true);
textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
// Listen to all HTML5-defined events and trigger them on the player
TECH_EVENTS_RETRIGGER.forEach(function (event) {
_this2.on(_this2.tech_, event, _this2['handleTech' + toTitleCase(event) + '_']);
});
Object.keys(TECH_EVENTS_QUEUE).forEach(function (event) {
_this2.on(_this2.tech_, event, function (eventObj) {
if (_this2.tech_.playbackRate() === 0 && _this2.tech_.seeking()) {
_this2.queuedCallbacks_.push({
callback: _this2['handleTech' + TECH_EVENTS_QUEUE[event] + '_'].bind(_this2),
event: eventObj
});
return;
}
_this2['handleTech' + TECH_EVENTS_QUEUE[event] + '_'](eventObj);
});
});
this.on(this.tech_, 'loadstart', this.handleTechLoadStart_);
this.on(this.tech_, 'sourceset', this.handleTechSourceset_);
this.on(this.tech_, 'waiting', this.handleTechWaiting_);
this.on(this.tech_, 'ended', this.handleTechEnded_);
this.on(this.tech_, 'seeking', this.handleTechSeeking_);
this.on(this.tech_, 'play', this.handleTechPlay_);
this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_);
this.on(this.tech_, 'pause', this.handleTechPause_);
this.on(this.tech_, 'durationchange', this.handleTechDurationChange_);
this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_);
this.on(this.tech_, 'error', this.handleTechError_);
this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_);
this.on(this.tech_, 'posterchange', this.handleTechPosterChange_);
this.on(this.tech_, 'textdata', this.handleTechTextData_);
this.on(this.tech_, 'ratechange', this.handleTechRateChange_);
this.usingNativeControls(this.techGet_('controls'));
if (this.controls() && !this.usingNativeControls()) {
this.addTechControlsListeners_();
}
// Add the tech element in the DOM if it was not already there
// Make sure to not insert the original video element if using Html5
if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
prependTo(this.tech_.el(), this.el());
}
// Get rid of the original video tag reference after the first tech is loaded
if (this.tag) {
this.tag.player = null;
this.tag = null;
}
};
/**
* Unload and dispose of the current playback {@link Tech}.
*
* @private
*/
Player.prototype.unloadTech_ = function unloadTech_() {
var _this3 = this;
// Save the current text tracks so that we can reuse the same text tracks with the next tech
ALL.names.forEach(function (name$$1) {
var props = ALL[name$$1];
_this3[props.privateName] = _this3[props.getterName]();
});
this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
this.isReady_ = false;
this.tech_.dispose();
this.tech_ = false;
if (this.isPosterFromTech_) {
this.poster_ = '';
this.trigger('posterchange');
}
this.isPosterFromTech_ = false;
};
/**
* Return a reference to the current {@link Tech}.
* It will print a warning by default about the danger of using the tech directly
* but any argument that is passed in will silence the warning.
*
* @param {*} [safety]
* Anything passed in to silence the warning
*
* @return {Tech}
* The Tech
*/
Player.prototype.tech = function tech(safety) {
if (safety === undefined) {
log.warn(tsml(_templateObject$1));
}
return this.tech_;
};
/**
* Set up click and touch listeners for the playback element
*
* - On desktops: a click on the video itself will toggle playback
* - On mobile devices: a click on the video toggles controls
* which is done by toggling the user state between active and
* inactive
* - A tap can signal that a user has become active or has become inactive
* e.g. a quick tap on an iPhone movie should reveal the controls. Another
* quick tap should hide them again (signaling the user is in an inactive
* viewing state)
* - In addition to this, we still want the user to be considered inactive after
* a few seconds of inactivity.
*
* > Note: the only part of iOS interaction we can't mimic with this setup
* is a touch and hold on the video element counting as activity in order to
* keep the controls showing, but that shouldn't be an issue. A touch and hold
* on any controls will still keep the user active
*
* @private
*/
Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() {
// Make sure to remove all the previous listeners in case we are called multiple times.
this.removeTechControlsListeners_();
// Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do
// trigger mousedown/up.
// http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object
// Any touch events are set to block the mousedown event from happening
this.on(this.tech_, 'mousedown', this.handleTechClick_);
// If the controls were hidden we don't want that to change without a tap event
// so we'll check if the controls were already showing before reporting user
// activity
this.on(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.on(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.on(this.tech_, 'touchend', this.handleTechTouchEnd_);
// The tap listener needs to come after the touchend listener because the tap
// listener cancels out any reportedUserActivity when setting userActive(false)
this.on(this.tech_, 'tap', this.handleTechTap_);
};
/**
* Remove the listeners used for click and tap controls. This is needed for
* toggling to controls disabled, where a tap/touch should do nothing.
*
* @private
*/
Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() {
// We don't want to just use `this.off()` because there might be other needed
// listeners added by techs that extend this.
this.off(this.tech_, 'tap', this.handleTechTap_);
this.off(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.off(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.off(this.tech_, 'touchend', this.handleTechTouchEnd_);
this.off(this.tech_, 'mousedown', this.handleTechClick_);
};
/**
* Player waits for the tech to be ready
*
* @private
*/
Player.prototype.handleTechReady_ = function handleTechReady_() {
this.triggerReady();
// Keep the same volume as before
if (this.cache_.volume) {
this.techCall_('setVolume', this.cache_.volume);
}
// Look if the tech found a higher resolution poster while loading
this.handleTechPosterChange_();
// Update the duration if available
this.handleTechDurationChange_();
// Chrome and Safari both have issues with autoplay.
// In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work.
// In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays)
// This fixes both issues. Need to wait for API, so it updates displays correctly
if ((this.src() || this.currentSrc()) && this.tag && this.options_.autoplay && this.paused()) {
try {
// Chrome Fix. Fixed in Chrome v16.
delete this.tag.poster;
} catch (e) {
log('deleting tag.poster throws in some browsers', e);
}
}
};
/**
* Retrigger the `loadstart` event that was triggered by the {@link Tech}. This
* function will also trigger {@link Player#firstplay} if it is the first loadstart
* for a video.
*
* @fires Player#loadstart
* @fires Player#firstplay
* @listens Tech#loadstart
* @private
*/
Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() {
// TODO: Update to use `emptied` event instead. See #1277.
this.removeClass('vjs-ended');
this.removeClass('vjs-seeking');
// reset the error state
this.error(null);
// If it's already playing we want to trigger a firstplay event now.
// The firstplay event relies on both the play and loadstart events
// which can happen in any order for a new source
if (!this.paused()) {
/**
* Fired when the user agent begins looking for media data
*
* @event Player#loadstart
* @type {EventTarget~Event}
*/
this.trigger('loadstart');
this.trigger('firstplay');
} else {
// reset the hasStarted state
this.hasStarted(false);
this.trigger('loadstart');
}
// autoplay happens after loadstart for the browser,
// so we mimic that behavior
this.manualAutoplay_(this.autoplay());
};
/**
* Handle autoplay string values, rather than the typical boolean
* values that should be handled by the tech. Note that this is not
* part of any specification. Valid values and what they do can be
* found on the autoplay getter at Player#autoplay()
*/
Player.prototype.manualAutoplay_ = function manualAutoplay_(type) {
var _this4 = this;
if (!this.tech_ || typeof type !== 'string') {
return;
}
var muted = function muted() {
var previouslyMuted = _this4.muted();
_this4.muted(true);
var playPromise = _this4.play();
if (!playPromise || !playPromise.then || !playPromise['catch']) {
return;
}
return playPromise['catch'](function (e) {
// restore old value of muted on failure
_this4.muted(previouslyMuted);
});
};
var promise = void 0;
if (type === 'any') {
promise = this.play();
if (promise && promise.then && promise['catch']) {
promise['catch'](function () {
return muted();
});
}
} else if (type === 'muted') {
promise = muted();
} else {
promise = this.play();
}
if (!promise || !promise.then || !promise['catch']) {
return;
}
return promise.then(function () {
_this4.trigger({ type: 'autoplay-success', autoplay: type });
})['catch'](function (e) {
_this4.trigger({ type: 'autoplay-failure', autoplay: type });
});
};
/**
* Update the internal source caches so that we return the correct source from
* `src()`, `currentSource()`, and `currentSources()`.
*
* > Note: `currentSources` will not be updated if the source that is passed in exists
* in the current `currentSources` cache.
*
*
* @param {Tech~SourceObject} srcObj
* A string or object source to update our caches to.
*/
Player.prototype.updateSourceCaches_ = function updateSourceCaches_() {
var srcObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var src = srcObj;
var type = '';
if (typeof src !== 'string') {
src = srcObj.src;
type = srcObj.type;
}
// make sure all the caches are set to default values
// to prevent null checking
this.cache_.source = this.cache_.source || {};
this.cache_.sources = this.cache_.sources || [];
// try to get the type of the src that was passed in
if (src && !type) {
type = findMimetype(this, src);
}
// update `currentSource` cache always
this.cache_.source = mergeOptions({}, srcObj, { src: src, type: type });
var matchingSources = this.cache_.sources.filter(function (s) {
return s.src && s.src === src;
});
var sourceElSources = [];
var sourceEls = this.$$('source');
var matchingSourceEls = [];
for (var i = 0; i < sourceEls.length; i++) {
var sourceObj = getAttributes(sourceEls[i]);
sourceElSources.push(sourceObj);
if (sourceObj.src && sourceObj.src === src) {
matchingSourceEls.push(sourceObj.src);
}
}
// if we have matching source els but not matching sources
// the current source cache is not up to date
if (matchingSourceEls.length && !matchingSources.length) {
this.cache_.sources = sourceElSources;
// if we don't have matching source or source els set the
// sources cache to the `currentSource` cache
} else if (!matchingSources.length) {
this.cache_.sources = [this.cache_.source];
}
// update the tech `src` cache
this.cache_.src = src;
};
/**
* *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
* causing the media element to reload.
*
* It will fire for the initial source and each subsequent source.
* This event is a custom event from Video.js and is triggered by the {@link Tech}.
*
* The event object for this event contains a `src` property that will contain the source
* that was available when the event was triggered. This is generally only necessary if Video.js
* is switching techs while the source was being changed.
*
* It is also fired when `load` is called on the player (or media element)
* because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
* says that the resource selection algorithm needs to be aborted and restarted.
* In this case, it is very likely that the `src` property will be set to the
* empty string `""` to indicate we do not know what the source will be but
* that it is changing.
*
* *This event is currently still experimental and may change in minor releases.*
* __To use this, pass `enableSourceset` option to the player.__
*
* @event Player#sourceset
* @type {EventTarget~Event}
* @prop {string} src
* The source url available when the `sourceset` was triggered.
* It will be an empty string if we cannot know what the source is
* but know that the source will change.
*/
/**
* Retrigger the `sourceset` event that was triggered by the {@link Tech}.
*
* @fires Player#sourceset
* @listens Tech#sourceset
* @private
*/
Player.prototype.handleTechSourceset_ = function handleTechSourceset_(event) {
var _this5 = this;
// only update the source cache when the source
// was not updated using the player api
if (!this.changingSrc_) {
var updateSourceCaches = function updateSourceCaches(src) {
return _this5.updateSourceCaches_(src);
};
var playerSrc = this.currentSource().src;
var eventSrc = event.src;
// if we have a playerSrc that is not a blob, and a tech src that is a blob
if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
// if both the tech source and the player source were updated we assume
// something like @videojs/http-streaming did the sourceset and skip updating the source cache.
if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
updateSourceCaches = function updateSourceCaches() {};
}
}
// update the source to the intial source right away
// in some cases this will be empty string
updateSourceCaches(eventSrc);
// if the `sourceset` `src` was an empty string
// wait for a `loadstart` to update the cache to `currentSrc`.
// If a sourceset happens before a `loadstart`, we reset the state
// as this function will be called again.
if (!event.src) {
var updateCache = function updateCache(e) {
if (e.type !== 'sourceset') {
var techSrc = _this5.techGet('currentSrc');
_this5.lastSource_.tech = techSrc;
_this5.updateSourceCaches_(techSrc);
}
_this5.tech_.off(['sourceset', 'loadstart'], updateCache);
};
this.tech_.one(['sourceset', 'loadstart'], updateCache);
}
}
this.lastSource_ = { player: this.currentSource().src, tech: event.src };
this.trigger({
src: event.src,
type: 'sourceset'
});
};
/**
* Add/remove the vjs-has-started class
*
* @fires Player#firstplay
*
* @param {boolean} request
* - true: adds the class
* - false: remove the class
*
* @return {boolean}
* the boolean value of hasStarted_
*/
Player.prototype.hasStarted = function hasStarted(request) {
if (request === undefined) {
// act as getter, if we have no request to change
return this.hasStarted_;
}
if (request === this.hasStarted_) {
return;
}
this.hasStarted_ = request;
if (this.hasStarted_) {
this.addClass('vjs-has-started');
this.trigger('firstplay');
} else {
this.removeClass('vjs-has-started');
}
};
/**
* Fired whenever the media begins or resumes playback
*
* @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
* @fires Player#play
* @listens Tech#play
* @private
*/
Player.prototype.handleTechPlay_ = function handleTechPlay_() {
this.removeClass('vjs-ended');
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
// hide the poster when the user hits play
this.hasStarted(true);
/**
* Triggered whenever an {@link Tech#play} event happens. Indicates that
* playback has started or resumed.
*
* @event Player#play
* @type {EventTarget~Event}
*/
this.trigger('play');
};
/**
* Retrigger the `ratechange` event that was triggered by the {@link Tech}.
*
* If there were any events queued while the playback rate was zero, fire
* those events now.
*
* @private
* @method Player#handleTechRateChange_
* @fires Player#ratechange
* @listens Tech#ratechange
*/
Player.prototype.handleTechRateChange_ = function handleTechRateChange_() {
if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
this.queuedCallbacks_.forEach(function (queued) {
return queued.callback(queued.event);
});
this.queuedCallbacks_ = [];
}
this.cache_.lastPlaybackRate = this.tech_.playbackRate();
/**
* Fires when the playing speed of the audio/video is changed
*
* @event Player#ratechange
* @type {event}
*/
this.trigger('ratechange');
};
/**
* Retrigger the `waiting` event that was triggered by the {@link Tech}.
*
* @fires Player#waiting
* @listens Tech#waiting
* @private
*/
Player.prototype.handleTechWaiting_ = function handleTechWaiting_() {
var _this6 = this;
this.addClass('vjs-waiting');
/**
* A readyState change on the DOM element has caused playback to stop.
*
* @event Player#waiting
* @type {EventTarget~Event}
*/
this.trigger('waiting');
this.one('timeupdate', function () {
return _this6.removeClass('vjs-waiting');
});
};
/**
* Retrigger the `canplay` event that was triggered by the {@link Tech}.
* > Note: This is not consistent between browsers. See #1351
*
* @fires Player#canplay
* @listens Tech#canplay
* @private
*/
Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() {
this.removeClass('vjs-waiting');
/**
* The media has a readyState of HAVE_FUTURE_DATA or greater.
*
* @event Player#canplay
* @type {EventTarget~Event}
*/
this.trigger('canplay');
};
/**
* Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
*
* @fires Player#canplaythrough
* @listens Tech#canplaythrough
* @private
*/
Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
this.removeClass('vjs-waiting');
/**
* The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
* entire media file can be played without buffering.
*
* @event Player#canplaythrough
* @type {EventTarget~Event}
*/
this.trigger('canplaythrough');
};
/**
* Retrigger the `playing` event that was triggered by the {@link Tech}.
*
* @fires Player#playing
* @listens Tech#playing
* @private
*/
Player.prototype.handleTechPlaying_ = function handleTechPlaying_() {
this.removeClass('vjs-waiting');
/**
* The media is no longer blocked from playback, and has started playing.
*
* @event Player#playing
* @type {EventTarget~Event}
*/
this.trigger('playing');
};
/**
* Retrigger the `seeking` event that was triggered by the {@link Tech}.
*
* @fires Player#seeking
* @listens Tech#seeking
* @private
*/
Player.prototype.handleTechSeeking_ = function handleTechSeeking_() {
this.addClass('vjs-seeking');
/**
* Fired whenever the player is jumping to a new time
*
* @event Player#seeking
* @type {EventTarget~Event}
*/
this.trigger('seeking');
};
/**
* Retrigger the `seeked` event that was triggered by the {@link Tech}.
*
* @fires Player#seeked
* @listens Tech#seeked
* @private
*/
Player.prototype.handleTechSeeked_ = function handleTechSeeked_() {
this.removeClass('vjs-seeking');
/**
* Fired when the player has finished jumping to a new time
*
* @event Player#seeked
* @type {EventTarget~Event}
*/
this.trigger('seeked');
};
/**
* Retrigger the `firstplay` event that was triggered by the {@link Tech}.
*
* @fires Player#firstplay
* @listens Tech#firstplay
* @deprecated As of 6.0 firstplay event is deprecated.
* As of 6.0 passing the `starttime` option to the player and the firstplay event are deprecated.
* @private
*/
Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() {
// If the first starttime attribute is specified
// then we will start at the given offset in seconds
if (this.options_.starttime) {
log.warn('Passing the `starttime` option to the player will be deprecated in 6.0');
this.currentTime(this.options_.starttime);
}
this.addClass('vjs-has-started');
/**
* Fired the first time a video is played. Not part of the HLS spec, and this is
* probably not the best implementation yet, so use sparingly. If you don't have a
* reason to prevent playback, use `myPlayer.one('play');` instead.
*
* @event Player#firstplay
* @deprecated As of 6.0 firstplay event is deprecated.
* @type {EventTarget~Event}
*/
this.trigger('firstplay');
};
/**
* Retrigger the `pause` event that was triggered by the {@link Tech}.
*
* @fires Player#pause
* @listens Tech#pause
* @private
*/
Player.prototype.handleTechPause_ = function handleTechPause_() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
/**
* Fired whenever the media has been paused
*
* @event Player#pause
* @type {EventTarget~Event}
*/
this.trigger('pause');
};
/**
* Retrigger the `ended` event that was triggered by the {@link Tech}.
*
* @fires Player#ended
* @listens Tech#ended
* @private
*/
Player.prototype.handleTechEnded_ = function handleTechEnded_() {
this.addClass('vjs-ended');
if (this.options_.loop) {
this.currentTime(0);
this.play();
} else if (!this.paused()) {
this.pause();
}
/**
* Fired when the end of the media resource is reached (currentTime == duration)
*
* @event Player#ended
* @type {EventTarget~Event}
*/
this.trigger('ended');
};
/**
* Fired when the duration of the media resource is first known or changed
*
* @listens Tech#durationchange
* @private
*/
Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() {
this.duration(this.techGet_('duration'));
};
/**
* Handle a click on the media element to play/pause
*
* @param {EventTarget~Event} event
* the event that caused this function to trigger
*
* @listens Tech#mousedown
* @private
*/
Player.prototype.handleTechClick_ = function handleTechClick_(event) {
if (!isSingleLeftClick(event)) {
return;
}
// When controls are disabled a click should not toggle playback because
// the click is considered a control
if (!this.controls_) {
return;
}
if (this.paused()) {
silencePromise(this.play());
} else {
this.pause();
}
};
/**
* Handle a tap on the media element. It will toggle the user
* activity state, which hides and shows the controls.
*
* @listens Tech#tap
* @private
*/
Player.prototype.handleTechTap_ = function handleTechTap_() {
this.userActive(!this.userActive());
};
/**
* Handle touch to start
*
* @listens Tech#touchstart
* @private
*/
Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() {
this.userWasActive = this.userActive();
};
/**
* Handle touch to move
*
* @listens Tech#touchmove
* @private
*/
Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() {
if (this.userWasActive) {
this.reportUserActivity();
}
};
/**
* Handle touch to end
*
* @param {EventTarget~Event} event
* the touchend event that triggered
* this function
*
* @listens Tech#touchend
* @private
*/
Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
// Stop the mouse events from also happening
event.preventDefault();
};
/**
* Fired when the player switches in or out of fullscreen mode
*
* @private
* @listens Player#fullscreenchange
*/
Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() {
if (this.isFullscreen()) {
this.addClass('vjs-fullscreen');
} else {
this.removeClass('vjs-fullscreen');
}
};
/**
* native click events on the SWF aren't triggered on IE11, Win8.1RT
* use stageclick events triggered from inside the SWF instead
*
* @private
* @listens stageclick
*/
Player.prototype.handleStageClick_ = function handleStageClick_() {
this.reportUserActivity();
};
/**
* Handle Tech Fullscreen Change
*
* @param {EventTarget~Event} event
* the fullscreenchange event that triggered this function
*
* @param {Object} data
* the data that was sent with the event
*
* @private
* @listens Tech#fullscreenchange
* @fires Player#fullscreenchange
*/
Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
if (data) {
this.isFullscreen(data.isFullscreen);
}
/**
* Fired when going in and out of fullscreen.
*
* @event Player#fullscreenchange
* @type {EventTarget~Event}
*/
this.trigger('fullscreenchange');
};
/**
* Fires when an error occurred during the loading of an audio/video.
*
* @private
* @listens Tech#error
*/
Player.prototype.handleTechError_ = function handleTechError_() {
var error = this.tech_.error();
this.error(error);
};
/**
* Retrigger the `textdata` event that was triggered by the {@link Tech}.
*
* @fires Player#textdata
* @listens Tech#textdata
* @private
*/
Player.prototype.handleTechTextData_ = function handleTechTextData_() {
var data = null;
if (arguments.length > 1) {
data = arguments[1];
}
/**
* Fires when we get a textdata event from tech
*
* @event Player#textdata
* @type {EventTarget~Event}
*/
this.trigger('textdata', data);
};
/**
* Get object for cached values.
*
* @return {Object}
* get the current object cache
*/
Player.prototype.getCache = function getCache() {
return this.cache_;
};
/**
* Pass values to the playback tech
*
* @param {string} [method]
* the method to call
*
* @param {Object} arg
* the argument to pass
*
* @private
*/
Player.prototype.techCall_ = function techCall_(method, arg) {
// If it's not ready yet, call method when it is
this.ready(function () {
if (method in allowedSetters) {
return set$1(this.middleware_, this.tech_, method, arg);
} else if (method in allowedMediators) {
return mediate(this.middleware_, this.tech_, method, arg);
}
try {
if (this.tech_) {
this.tech_[method](arg);
}
} catch (e) {
log(e);
throw e;
}
}, true);
};
/**
* Get calls can't wait for the tech, and sometimes don't need to.
*
* @param {string} method
* Tech method
*
* @return {Function|undefined}
* the method or undefined
*
* @private
*/
Player.prototype.techGet_ = function techGet_(method) {
if (!this.tech_ || !this.tech_.isReady_) {
return;
}
if (method in allowedGetters) {
return get$1(this.middleware_, this.tech_, method);
} else if (method in allowedMediators) {
return mediate(this.middleware_, this.tech_, method);
}
// Flash likes to die and reload when you hide or reposition it.
// In these cases the object methods go away and we get errors.
// When that happens we'll catch the errors and inform tech that it's not ready any more.
try {
return this.tech_[method]();
} catch (e) {
// When building additional tech libs, an expected method may not be defined yet
if (this.tech_[method] === undefined) {
log('Video.js: ' + method + ' method not defined for ' + this.techName_ + ' playback technology.', e);
throw e;
}
// When a method isn't available on the object it throws a TypeError
if (e.name === 'TypeError') {
log('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e);
this.tech_.isReady_ = false;
throw e;
}
// If error unknown, just log and throw
log(e);
throw e;
}
};
/**
* Attempt to begin playback at the first opportunity.
*
* @return {Promise|undefined}
* Returns a promise if the browser supports Promises (or one
* was passed in as an option). This promise will be resolved on
* the return value of play. If this is undefined it will fulfill the
* promise chain otherwise the promise chain will be fulfilled when
* the promise from play is fulfilled.
*/
Player.prototype.play = function play() {
var _this7 = this;
var PromiseClass = this.options_.Promise || window.Promise;
if (PromiseClass) {
return new PromiseClass(function (resolve) {
_this7.play_(resolve);
});
}
return this.play_();
};
/**
* The actual logic for play, takes a callback that will be resolved on the
* return value of play. This allows us to resolve to the play promise if there
* is one on modern browsers.
*
* @private
* @param {Function} [callback]
* The callback that should be called when the techs play is actually called
*/
Player.prototype.play_ = function play_() {
var _this8 = this;
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : silencePromise;
// If this is called while we have a play queued up on a loadstart, remove
// that listener to avoid getting in a potentially bad state.
if (this.playOnLoadstart_) {
this.off('loadstart', this.playOnLoadstart_);
}
// If the player/tech is not ready, queue up another call to `play()` for
// when it is. This will loop back into this method for another attempt at
// playback when the tech is ready.
if (!this.isReady_) {
// Bail out if we're already waiting for `ready`!
if (this.playWaitingForReady_) {
return;
}
this.playWaitingForReady_ = true;
this.ready(function () {
_this8.playWaitingForReady_ = false;
callback(_this8.play());
});
// If the player/tech is ready and we have a source, we can attempt playback.
} else if (!this.changingSrc_ && (this.src() || this.currentSrc())) {
callback(this.techGet_('play'));
return;
// If the tech is ready, but we do not have a source, we'll need to wait
// for both the `ready` and a `loadstart` when the source is finally
// resolved by middleware and set on the player.
//
// This can happen if `play()` is called while changing sources or before
// one has been set on the player.
} else {
this.playOnLoadstart_ = function () {
_this8.playOnLoadstart_ = null;
callback(_this8.play());
};
this.one('loadstart', this.playOnLoadstart_);
}
};
/**
* Pause the video playback
*
* @return {Player}
* A reference to the player object this function was called on
*/
Player.prototype.pause = function pause() {
this.techCall_('pause');
};
/**
* Check if the player is paused or has yet to play
*
* @return {boolean}
* - false: if the media is currently playing
* - true: if media is not currently playing
*/
Player.prototype.paused = function paused() {
// The initial state of paused should be true (in Safari it's actually false)
return this.techGet_('paused') === false ? false : true;
};
/**
* Get a TimeRange object representing the current ranges of time that the user
* has played.
*
* @return {TimeRange}
* A time range object that represents all the increments of time that have
* been played.
*/
Player.prototype.played = function played() {
return this.techGet_('played') || createTimeRanges(0, 0);
};
/**
* Returns whether or not the user is "scrubbing". Scrubbing is
* when the user has clicked the progress bar handle and is
* dragging it along the progress bar.
*
* @param {boolean} [isScrubbing]
* wether the user is or is not scrubbing
*
* @return {boolean}
* The value of scrubbing when getting
*/
Player.prototype.scrubbing = function scrubbing(isScrubbing) {
if (typeof isScrubbing === 'undefined') {
return this.scrubbing_;
}
this.scrubbing_ = !!isScrubbing;
if (isScrubbing) {
this.addClass('vjs-scrubbing');
} else {
this.removeClass('vjs-scrubbing');
}
};
/**
* Get or set the current time (in seconds)
*
* @param {number|string} [seconds]
* The time to seek to in seconds
*
* @return {number}
* - the current time in seconds when getting
*/
Player.prototype.currentTime = function currentTime(seconds) {
if (typeof seconds !== 'undefined') {
if (seconds < 0) {
seconds = 0;
}
this.techCall_('setCurrentTime', seconds);
return;
}
// cache last currentTime and return. default to 0 seconds
//
// Caching the currentTime is meant to prevent a massive amount of reads on the tech's
// currentTime when scrubbing, but may not provide much performance benefit afterall.
// Should be tested. Also something has to read the actual current time or the cache will
// never get updated.
this.cache_.currentTime = this.techGet_('currentTime') || 0;
return this.cache_.currentTime;
};
/**
* Normally gets the length in time of the video in seconds;
* in all but the rarest use cases an argument will NOT be passed to the method
*
* > **NOTE**: The video must have started loading before the duration can be
* known, and in the case of Flash, may not be known until the video starts
* playing.
*
* @fires Player#durationchange
*
* @param {number} [seconds]
* The duration of the video to set in seconds
*
* @return {number}
* - The duration of the video in seconds when getting
*/
Player.prototype.duration = function duration(seconds) {
if (seconds === undefined) {
// return NaN if the duration is not known
return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
}
seconds = parseFloat(seconds);
// Standardize on Inifity for signaling video is live
if (seconds < 0) {
seconds = Infinity;
}
if (seconds !== this.cache_.duration) {
// Cache the last set value for optimized scrubbing (esp. Flash)
this.cache_.duration = seconds;
if (seconds === Infinity) {
this.addClass('vjs-live');
} else {
this.removeClass('vjs-live');
}
/**
* @event Player#durationchange
* @type {EventTarget~Event}
*/
this.trigger('durationchange');
}
};
/**
* Calculates how much time is left in the video. Not part
* of the native video API.
*
* @return {number}
* The time remaining in seconds
*/
Player.prototype.remainingTime = function remainingTime() {
return this.duration() - this.currentTime();
};
/**
* A remaining time function that is intented to be used when
* the time is to be displayed directly to the user.
*
* @return {number}
* The rounded time remaining in seconds
*/
Player.prototype.remainingTimeDisplay = function remainingTimeDisplay() {
return Math.floor(this.duration()) - Math.floor(this.currentTime());
};
//
// Kind of like an array of portions of the video that have been downloaded.
/**
* Get a TimeRange object with an array of the times of the video
* that have been downloaded. If you just want the percent of the
* video that's been downloaded, use bufferedPercent.
*
* @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
*
* @return {TimeRange}
* A mock TimeRange object (following HTML spec)
*/
Player.prototype.buffered = function buffered() {
var buffered = this.techGet_('buffered');
if (!buffered || !buffered.length) {
buffered = createTimeRanges(0, 0);
}
return buffered;
};
/**
* Get the percent (as a decimal) of the video that's been downloaded.
* This method is not a part of the native HTML video API.
*
* @return {number}
* A decimal between 0 and 1 representing the percent
* that is bufferred 0 being 0% and 1 being 100%
*/
Player.prototype.bufferedPercent = function bufferedPercent$$1() {
return bufferedPercent(this.buffered(), this.duration());
};
/**
* Get the ending time of the last buffered time range
* This is used in the progress bar to encapsulate all time ranges.
*
* @return {number}
* The end of the last buffered time range
*/
Player.prototype.bufferedEnd = function bufferedEnd() {
var buffered = this.buffered();
var duration = this.duration();
var end = buffered.end(buffered.length - 1);
if (end > duration) {
end = duration;
}
return end;
};
/**
* Get or set the current volume of the media
*
* @param {number} [percentAsDecimal]
* The new volume as a decimal percent:
* - 0 is muted/0%/off
* - 1.0 is 100%/full
* - 0.5 is half volume or 50%
*
* @return {number}
* The current volume as a percent when getting
*/
Player.prototype.volume = function volume(percentAsDecimal) {
var vol = void 0;
if (percentAsDecimal !== undefined) {
// Force value to between 0 and 1
vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
this.cache_.volume = vol;
this.techCall_('setVolume', vol);
if (vol > 0) {
this.lastVolume_(vol);
}
return;
}
// Default to 1 when returning current volume.
vol = parseFloat(this.techGet_('volume'));
return isNaN(vol) ? 1 : vol;
};
/**
* Get the current muted state, or turn mute on or off
*
* @param {boolean} [muted]
* - true to mute
* - false to unmute
*
* @return {boolean}
* - true if mute is on and getting
* - false if mute is off and getting
*/
Player.prototype.muted = function muted(_muted) {
if (_muted !== undefined) {
this.techCall_('setMuted', _muted);
return;
}
return this.techGet_('muted') || false;
};
/**
* Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
* indicates the state of muted on intial playback.
*
* ```js
* var myPlayer = videojs('some-player-id');
*
* myPlayer.src("http://www.example.com/path/to/video.mp4");
*
* // get, should be false
* console.log(myPlayer.defaultMuted());
* // set to true
* myPlayer.defaultMuted(true);
* // get should be true
* console.log(myPlayer.defaultMuted());
* ```
*
* @param {boolean} [defaultMuted]
* - true to mute
* - false to unmute
*
* @return {boolean|Player}
* - true if defaultMuted is on and getting
* - false if defaultMuted is off and getting
* - A reference to the current player when setting
*/
Player.prototype.defaultMuted = function defaultMuted(_defaultMuted) {
if (_defaultMuted !== undefined) {
return this.techCall_('setDefaultMuted', _defaultMuted);
}
return this.techGet_('defaultMuted') || false;
};
/**
* Get the last volume, or set it
*
* @param {number} [percentAsDecimal]
* The new last volume as a decimal percent:
* - 0 is muted/0%/off
* - 1.0 is 100%/full
* - 0.5 is half volume or 50%
*
* @return {number}
* the current value of lastVolume as a percent when getting
*
* @private
*/
Player.prototype.lastVolume_ = function lastVolume_(percentAsDecimal) {
if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
this.cache_.lastVolume = percentAsDecimal;
return;
}
return this.cache_.lastVolume;
};
/**
* Check if current tech can support native fullscreen
* (e.g. with built in controls like iOS, so not our flash swf)
*
* @return {boolean}
* if native fullscreen is supported
*/
Player.prototype.supportsFullScreen = function supportsFullScreen() {
return this.techGet_('supportsFullScreen') || false;
};
/**
* Check if the player is in fullscreen mode or tell the player that it
* is or is not in fullscreen mode.
*
* > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
* property and instead document.fullscreenElement is used. But isFullscreen is
* still a valuable property for internal player workings.
*
* @param {boolean} [isFS]
* Set the players current fullscreen state
*
* @return {boolean}
* - true if fullscreen is on and getting
* - false if fullscreen is off and getting
*/
Player.prototype.isFullscreen = function isFullscreen(isFS) {
if (isFS !== undefined) {
this.isFullscreen_ = !!isFS;
return;
}
return !!this.isFullscreen_;
};
/**
* Increase the size of the video to full screen
* In some browsers, full screen is not supported natively, so it enters
* "full window mode", where the video fills the browser window.
* In browsers and devices that support native full screen, sometimes the
* browser's default controls will be shown, and not the Video.js custom skin.
* This includes most mobile devices (iOS, Android) and older versions of
* Safari.
*
* @fires Player#fullscreenchange
*/
Player.prototype.requestFullscreen = function requestFullscreen() {
var fsApi = FullscreenApi;
this.isFullscreen(true);
if (fsApi.requestFullscreen) {
// the browser supports going fullscreen at the element level so we can
// take the controls fullscreen as well as the video
// Trigger fullscreenchange event after change
// We have to specifically add this each time, and remove
// when canceling fullscreen. Otherwise if there's multiple
// players on a page, they would all be reacting to the same fullscreen
// events
on(document, fsApi.fullscreenchange, bind(this, function documentFullscreenChange(e) {
this.isFullscreen(document[fsApi.fullscreenElement]);
// If cancelling fullscreen, remove event listener.
if (this.isFullscreen() === false) {
off(document, fsApi.fullscreenchange, documentFullscreenChange);
}
/**
* @event Player#fullscreenchange
* @type {EventTarget~Event}
*/
this.trigger('fullscreenchange');
}));
this.el_[fsApi.requestFullscreen]();
} else if (this.tech_.supportsFullScreen()) {
// we can't take the video.js controls fullscreen but we can go fullscreen
// with native controls
this.techCall_('enterFullScreen');
} else {
// fullscreen isn't supported so we'll just stretch the video element to
// fill the viewport
this.enterFullWindow();
/**
* @event Player#fullscreenchange
* @type {EventTarget~Event}
*/
this.trigger('fullscreenchange');
}
};
/**
* Return the video to its normal size after having been in full screen mode
*
* @fires Player#fullscreenchange
*/
Player.prototype.exitFullscreen = function exitFullscreen() {
var fsApi = FullscreenApi;
this.isFullscreen(false);
// Check for browser element fullscreen support
if (fsApi.requestFullscreen) {
document[fsApi.exitFullscreen]();
} else if (this.tech_.supportsFullScreen()) {
this.techCall_('exitFullScreen');
} else {
this.exitFullWindow();
/**
* @event Player#fullscreenchange
* @type {EventTarget~Event}
*/
this.trigger('fullscreenchange');
}
};
/**
* When fullscreen isn't supported we can stretch the
* video container to as wide as the browser will let us.
*
* @fires Player#enterFullWindow
*/
Player.prototype.enterFullWindow = function enterFullWindow() {
this.isFullWindow = true;
// Storing original doc overflow value to return to when fullscreen is off
this.docOrigOverflow = document.documentElement.style.overflow;
// Add listener for esc key to exit fullscreen
on(document, 'keydown', bind(this, this.fullWindowOnEscKey));
// Hide any scroll bars
document.documentElement.style.overflow = 'hidden';
// Apply fullscreen styles
addClass(document.body, 'vjs-full-window');
/**
* @event Player#enterFullWindow
* @type {EventTarget~Event}
*/
this.trigger('enterFullWindow');
};
/**
* Check for call to either exit full window or
* full screen on ESC key
*
* @param {string} event
* Event to check for key press
*/
Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
if (event.keyCode === 27) {
if (this.isFullscreen() === true) {
this.exitFullscreen();
} else {
this.exitFullWindow();
}
}
};
/**
* Exit full window
*
* @fires Player#exitFullWindow
*/
Player.prototype.exitFullWindow = function exitFullWindow() {
this.isFullWindow = false;
off(document, 'keydown', this.fullWindowOnEscKey);
// Unhide scroll bars.
document.documentElement.style.overflow = this.docOrigOverflow;
// Remove fullscreen styles
removeClass(document.body, 'vjs-full-window');
// Resize the box, controller, and poster to original sizes
// this.positionAll();
/**
* @event Player#exitFullWindow
* @type {EventTarget~Event}
*/
this.trigger('exitFullWindow');
};
/**
* Check whether the player can play a given mimetype
*
* @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
*
* @param {string} type
* The mimetype to check
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
Player.prototype.canPlayType = function canPlayType(type) {
var can = void 0;
// Loop through each playback technology in the options order
for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
var techName = j[i];
var tech = Tech.getTech(techName);
// Support old behavior of techs being registered as components.
// Remove once that deprecated behavior is removed.
if (!tech) {
tech = Component.getComponent(techName);
}
// Check if the current tech is defined before continuing
if (!tech) {
log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
continue;
}
// Check if the browser supports this technology
if (tech.isSupported()) {
can = tech.canPlayType(type);
if (can) {
return can;
}
}
}
return '';
};
/**
* Select source based on tech-order or source-order
* Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
* defaults to tech-order selection
*
* @param {Array} sources
* The sources for a media asset
*
* @return {Object|boolean}
* Object of source and tech order or false
*/
Player.prototype.selectSource = function selectSource(sources) {
var _this9 = this;
// Get only the techs specified in `techOrder` that exist and are supported by the
// current platform
var techs = this.options_.techOrder.map(function (techName) {
return [techName, Tech.getTech(techName)];
}).filter(function (_ref) {
var techName = _ref[0],
tech = _ref[1];
// Check if the current tech is defined before continuing
if (tech) {
// Check if the browser supports this technology
return tech.isSupported();
}
log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
return false;
});
// Iterate over each `innerArray` element once per `outerArray` element and execute
// `tester` with both. If `tester` returns a non-falsy value, exit early and return
// that value.
var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) {
var found = void 0;
outerArray.some(function (outerChoice) {
return innerArray.some(function (innerChoice) {
found = tester(outerChoice, innerChoice);
if (found) {
return true;
}
});
});
return found;
};
var foundSourceAndTech = void 0;
var flip = function flip(fn) {
return function (a, b) {
return fn(b, a);
};
};
var finder = function finder(_ref2, source) {
var techName = _ref2[0],
tech = _ref2[1];
if (tech.canPlaySource(source, _this9.options_[techName.toLowerCase()])) {
return { source: source, tech: techName };
}
};
// Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
// to select from them based on their priority.
if (this.options_.sourceOrder) {
// Source-first ordering
foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
} else {
// Tech-first ordering
foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
}
return foundSourceAndTech || false;
};
/**
* Get or set the video source.
*
* @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
* A SourceObject, an array of SourceObjects, or a string referencing
* a URL to a media source. It is _highly recommended_ that an object
* or array of objects is used here, so that source selection
* algorithms can take the `type` into account.
*
* If not provided, this method acts as a getter.
*
* @return {string|undefined}
* If the `source` argument is missing, returns the current source
* URL. Otherwise, returns nothing/undefined.
*/
Player.prototype.src = function src(source) {
var _this10 = this;
// getter usage
if (typeof source === 'undefined') {
return this.cache_.src || '';
}
// filter out invalid sources and turn our source into
// an array of source objects
var sources = filterSource(source);
// if a source was passed in then it is invalid because
// it was filtered to a zero length Array. So we have to
// show an error
if (!sources.length) {
this.setTimeout(function () {
this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) });
}, 0);
return;
}
// intial sources
this.changingSrc_ = true;
this.cache_.sources = sources;
this.updateSourceCaches_(sources[0]);
// middlewareSource is the source after it has been changed by middleware
setSource(this, sources[0], function (middlewareSource, mws) {
_this10.middleware_ = mws;
// since sourceSet is async we have to update the cache again after we select a source since
// the source that is selected could be out of order from the cache update above this callback.
_this10.cache_.sources = sources;
_this10.updateSourceCaches_(middlewareSource);
var err = _this10.src_(middlewareSource);
if (err) {
if (sources.length > 1) {
return _this10.src(sources.slice(1));
}
_this10.changingSrc_ = false;
// We need to wrap this in a timeout to give folks a chance to add error event handlers
_this10.setTimeout(function () {
this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) });
}, 0);
// we could not find an appropriate tech, but let's still notify the delegate that this is it
// this needs a better comment about why this is needed
_this10.triggerReady();
return;
}
setTech(mws, _this10.tech_);
});
};
/**
* Set the source object on the tech, returns a boolean that indicates wether
* there is a tech that can play the source or not
*
* @param {Tech~SourceObject} source
* The source object to set on the Tech
*
* @return {Boolean}
* - True if there is no Tech to playback this source
* - False otherwise
*
* @private
*/
Player.prototype.src_ = function src_(source) {
var _this11 = this;
var sourceTech = this.selectSource([source]);
if (!sourceTech) {
return true;
}
if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
this.changingSrc_ = true;
// load this technology with the chosen source
this.loadTech_(sourceTech.tech, sourceTech.source);
this.tech_.ready(function () {
_this11.changingSrc_ = false;
});
return false;
}
// wait until the tech is ready to set the source
// and set it synchronously if possible (#2326)
this.ready(function () {
// The setSource tech method was added with source handlers
// so older techs won't support it
// We need to check the direct prototype for the case where subclasses
// of the tech do not support source handlers
if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
this.techCall_('setSource', source);
} else {
this.techCall_('src', source.src);
}
this.changingSrc_ = false;
}, true);
return false;
};
/**
* Begin loading the src data.
*/
Player.prototype.load = function load() {
this.techCall_('load');
};
/**
* Reset the player. Loads the first tech in the techOrder,
* removes all the text tracks in the existing `tech`,
* and calls `reset` on the `tech`.
*/
Player.prototype.reset = function reset() {
if (this.tech_) {
this.tech_.clearTracks('text');
}
this.loadTech_(this.options_.techOrder[0], null);
this.techCall_('reset');
};
/**
* Returns all of the current source objects.
*
* @return {Tech~SourceObject[]}
* The current source objects
*/
Player.prototype.currentSources = function currentSources() {
var source = this.currentSource();
var sources = [];
// assume `{}` or `{ src }`
if (Object.keys(source).length !== 0) {
sources.push(source);
}
return this.cache_.sources || sources;
};
/**
* Returns the current source object.
*
* @return {Tech~SourceObject}
* The current source object
*/
Player.prototype.currentSource = function currentSource() {
return this.cache_.source || {};
};
/**
* Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
* Can be used in conjuction with `currentType` to assist in rebuilding the current source object.
*
* @return {string}
* The current source
*/
Player.prototype.currentSrc = function currentSrc() {
return this.currentSource() && this.currentSource().src || '';
};
/**
* Get the current source type e.g. video/mp4
* This can allow you rebuild the current source object so that you could load the same
* source and tech later
*
* @return {string}
* The source MIME type
*/
Player.prototype.currentType = function currentType() {
return this.currentSource() && this.currentSource().type || '';
};
/**
* Get or set the preload attribute
*
* @param {boolean} [value]
* - true means that we should preload
* - false maens that we should not preload
*
* @return {string}
* The preload attribute value when getting
*/
Player.prototype.preload = function preload(value) {
if (value !== undefined) {
this.techCall_('setPreload', value);
this.options_.preload = value;
return;
}
return this.techGet_('preload');
};
/**
* Get or set the autoplay option. When this is a boolean it will
* modify the attribute on the tech. When this is a string the attribute on
* the tech will be removed and `Player` will handle autoplay on loadstarts.
*
* @param {boolean|string} [value]
* - true: autoplay using the browser behavior
* - false: do not autoplay
* - 'play': call play() on every loadstart
* - 'muted': call muted() then play() on every loadstart
* - 'any': call play() on every loadstart. if that fails call muted() then play().
* - *: values other than those listed here will be set `autoplay` to true
*
* @return {boolean|string}
* The current value of autoplay when getting
*/
Player.prototype.autoplay = function autoplay(value) {
// getter usage
if (value === undefined) {
return this.options_.autoplay || false;
}
var techAutoplay = void 0;
// if the value is a valid string set it to that
if (typeof value === 'string' && /(any|play|muted)/.test(value)) {
this.options_.autoplay = value;
this.manualAutoplay_(value);
techAutoplay = false;
// any falsy value sets autoplay to false in the browser,
// lets do the same
} else if (!value) {
this.options_.autoplay = false;
// any other value (ie truthy) sets autoplay to true
} else {
this.options_.autoplay = true;
}
techAutoplay = techAutoplay || this.options_.autoplay;
// if we don't have a tech then we do not queue up
// a setAutoplay call on tech ready. We do this because the
// autoplay option will be passed in the constructor and we
// do not need to set it twice
if (this.tech_) {
this.techCall_('setAutoplay', techAutoplay);
}
};
/**
* Set or unset the playsinline attribute.
* Playsinline tells the browser that non-fullscreen playback is preferred.
*
* @param {boolean} [value]
* - true means that we should try to play inline by default
* - false means that we should use the browser's default playback mode,
* which in most cases is inline. iOS Safari is a notable exception
* and plays fullscreen by default.
*
* @return {string|Player}
* - the current value of playsinline
* - the player when setting
*
* @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
*/
Player.prototype.playsinline = function playsinline(value) {
if (value !== undefined) {
this.techCall_('setPlaysinline', value);
this.options_.playsinline = value;
return this;
}
return this.techGet_('playsinline');
};
/**
* Get or set the loop attribute on the video element.
*
* @param {boolean} [value]
* - true means that we should loop the video
* - false means that we should not loop the video
*
* @return {string}
* The current value of loop when getting
*/
Player.prototype.loop = function loop(value) {
if (value !== undefined) {
this.techCall_('setLoop', value);
this.options_.loop = value;
return;
}
return this.techGet_('loop');
};
/**
* Get or set the poster image source url
*
* @fires Player#posterchange
*
* @param {string} [src]
* Poster image source URL
*
* @return {string}
* The current value of poster when getting
*/
Player.prototype.poster = function poster(src) {
if (src === undefined) {
return this.poster_;
}
// The correct way to remove a poster is to set as an empty string
// other falsey values will throw errors
if (!src) {
src = '';
}
if (src === this.poster_) {
return;
}
// update the internal poster variable
this.poster_ = src;
// update the tech's poster
this.techCall_('setPoster', src);
this.isPosterFromTech_ = false;
// alert components that the poster has been set
/**
* This event fires when the poster image is changed on the player.
*
* @event Player#posterchange
* @type {EventTarget~Event}
*/
this.trigger('posterchange');
};
/**
* Some techs (e.g. YouTube) can provide a poster source in an
* asynchronous way. We want the poster component to use this
* poster source so that it covers up the tech's controls.
* (YouTube's play button). However we only want to use this
* source if the player user hasn't set a poster through
* the normal APIs.
*
* @fires Player#posterchange
* @listens Tech#posterchange
* @private
*/
Player.prototype.handleTechPosterChange_ = function handleTechPosterChange_() {
if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
var newPoster = this.tech_.poster() || '';
if (newPoster !== this.poster_) {
this.poster_ = newPoster;
this.isPosterFromTech_ = true;
// Let components know the poster has changed
this.trigger('posterchange');
}
}
};
/**
* Get or set whether or not the controls are showing.
*
* @fires Player#controlsenabled
*
* @param {boolean} [bool]
* - true to turn controls on
* - false to turn controls off
*
* @return {boolean}
* The current value of controls when getting
*/
Player.prototype.controls = function controls(bool) {
if (bool === undefined) {
return !!this.controls_;
}
bool = !!bool;
// Don't trigger a change event unless it actually changed
if (this.controls_ === bool) {
return;
}
this.controls_ = bool;
if (this.usingNativeControls()) {
this.techCall_('setControls', bool);
}
if (this.controls_) {
this.removeClass('vjs-controls-disabled');
this.addClass('vjs-controls-enabled');
/**
* @event Player#controlsenabled
* @type {EventTarget~Event}
*/
this.trigger('controlsenabled');
if (!this.usingNativeControls()) {
this.addTechControlsListeners_();
}
} else {
this.removeClass('vjs-controls-enabled');
this.addClass('vjs-controls-disabled');
/**
* @event Player#controlsdisabled
* @type {EventTarget~Event}
*/
this.trigger('controlsdisabled');
if (!this.usingNativeControls()) {
this.removeTechControlsListeners_();
}
}
};
/**
* Toggle native controls on/off. Native controls are the controls built into
* devices (e.g. default iPhone controls), Flash, or other techs
* (e.g. Vimeo Controls)
* **This should only be set by the current tech, because only the tech knows
* if it can support native controls**
*
* @fires Player#usingnativecontrols
* @fires Player#usingcustomcontrols
*
* @param {boolean} [bool]
* - true to turn native controls on
* - false to turn native controls off
*
* @return {boolean}
* The current value of native controls when getting
*/
Player.prototype.usingNativeControls = function usingNativeControls(bool) {
if (bool === undefined) {
return !!this.usingNativeControls_;
}
bool = !!bool;
// Don't trigger a change event unless it actually changed
if (this.usingNativeControls_ === bool) {
return;
}
this.usingNativeControls_ = bool;
if (this.usingNativeControls_) {
this.addClass('vjs-using-native-controls');
/**
* player is using the native device controls
*
* @event Player#usingnativecontrols
* @type {EventTarget~Event}
*/
this.trigger('usingnativecontrols');
} else {
this.removeClass('vjs-using-native-controls');
/**
* player is using the custom HTML controls
*
* @event Player#usingcustomcontrols
* @type {EventTarget~Event}
*/
this.trigger('usingcustomcontrols');
}
};
/**
* Set or get the current MediaError
*
* @fires Player#error
*
* @param {MediaError|string|number} [err]
* A MediaError or a string/number to be turned
* into a MediaError
*
* @return {MediaError|null}
* The current MediaError when getting (or null)
*/
Player.prototype.error = function error(err) {
if (err === undefined) {
return this.error_ || null;
}
// restoring to default
if (err === null) {
this.error_ = err;
this.removeClass('vjs-error');
if (this.errorDisplay) {
this.errorDisplay.close();
}
return;
}
this.error_ = new MediaError(err);
// add the vjs-error classname to the player
this.addClass('vjs-error');
// log the name of the error type and any message
// ie8 just logs "[object object]" if you just log the error object
log.error('(CODE:' + this.error_.code + ' ' + MediaError.errorTypes[this.error_.code] + ')', this.error_.message, this.error_);
/**
* @event Player#error
* @type {EventTarget~Event}
*/
this.trigger('error');
return;
};
/**
* Report user activity
*
* @param {Object} event
* Event object
*/
Player.prototype.reportUserActivity = function reportUserActivity(event) {
this.userActivity_ = true;
};
/**
* Get/set if user is active
*
* @fires Player#useractive
* @fires Player#userinactive
*
* @param {boolean} [bool]
* - true if the user is active
* - false if the user is inactive
*
* @return {boolean}
* The current value of userActive when getting
*/
Player.prototype.userActive = function userActive(bool) {
if (bool === undefined) {
return this.userActive_;
}
bool = !!bool;
if (bool === this.userActive_) {
return;
}
this.userActive_ = bool;
if (this.userActive_) {
this.userActivity_ = true;
this.removeClass('vjs-user-inactive');
this.addClass('vjs-user-active');
/**
* @event Player#useractive
* @type {EventTarget~Event}
*/
this.trigger('useractive');
return;
}
// Chrome/Safari/IE have bugs where when you change the cursor it can
// trigger a mousemove event. This causes an issue when you're hiding
// the cursor when the user is inactive, and a mousemove signals user
// activity. Making it impossible to go into inactive mode. Specifically
// this happens in fullscreen when we really need to hide the cursor.
//
// When this gets resolved in ALL browsers it can be removed
// https://code.google.com/p/chromium/issues/detail?id=103041
if (this.tech_) {
this.tech_.one('mousemove', function (e) {
e.stopPropagation();
e.preventDefault();
});
}
this.userActivity_ = false;
this.removeClass('vjs-user-active');
this.addClass('vjs-user-inactive');
/**
* @event Player#userinactive
* @type {EventTarget~Event}
*/
this.trigger('userinactive');
};
/**
* Listen for user activity based on timeout value
*
* @private
*/
Player.prototype.listenForUserActivity_ = function listenForUserActivity_() {
var mouseInProgress = void 0;
var lastMoveX = void 0;
var lastMoveY = void 0;
var handleActivity = bind(this, this.reportUserActivity);
var handleMouseMove = function handleMouseMove(e) {
// #1068 - Prevent mousemove spamming
// Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
lastMoveX = e.screenX;
lastMoveY = e.screenY;
handleActivity();
}
};
var handleMouseDown = function handleMouseDown() {
handleActivity();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
this.clearInterval(mouseInProgress);
// Setting userActivity=true now and setting the interval to the same time
// as the activityCheck interval (250) should ensure we never miss the
// next activityCheck
mouseInProgress = this.setInterval(handleActivity, 250);
};
var handleMouseUp = function handleMouseUp(event) {
handleActivity();
// Stop the interval that maintains activity if the mouse/touch is down
this.clearInterval(mouseInProgress);
};
// Any mouse movement will be considered user activity
this.on('mousedown', handleMouseDown);
this.on('mousemove', handleMouseMove);
this.on('mouseup', handleMouseUp);
// Listen for keyboard navigation
// Shouldn't need to use inProgress interval because of key repeat
this.on('keydown', handleActivity);
this.on('keyup', handleActivity);
// Run an interval every 250 milliseconds instead of stuffing everything into
// the mousemove/touchmove function itself, to prevent performance degradation.
// `this.reportUserActivity` simply sets this.userActivity_ to true, which
// then gets picked up by this loop
// http://ejohn.org/blog/learning-from-twitter/
var inactivityTimeout = void 0;
this.setInterval(function () {
// Check to see if mouse/touch activity has happened
if (!this.userActivity_) {
return;
}
// Reset the activity tracker
this.userActivity_ = false;
// If the user state was inactive, set the state to active
this.userActive(true);
// Clear any existing inactivity timeout to start the timer over
this.clearTimeout(inactivityTimeout);
var timeout = this.options_.inactivityTimeout;
if (timeout <= 0) {
return;
}
// In <timeout> milliseconds, if no more activity has occurred the
// user will be considered inactive
inactivityTimeout = this.setTimeout(function () {
// Protect against the case where the inactivityTimeout can trigger just
// before the next user activity is picked up by the activity check loop
// causing a flicker
if (!this.userActivity_) {
this.userActive(false);
}
}, timeout);
}, 250);
};
/**
* Gets or sets the current playback rate. A playback rate of
* 1.0 represents normal speed and 0.5 would indicate half-speed
* playback, for instance.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
*
* @param {number} [rate]
* New playback rate to set.
*
* @return {number}
* The current playback rate when getting or 1.0
*/
Player.prototype.playbackRate = function playbackRate(rate) {
if (rate !== undefined) {
// NOTE: this.cache_.lastPlaybackRate is set from the tech handler
// that is registered above
this.techCall_('setPlaybackRate', rate);
return;
}
if (this.tech_ && this.tech_.featuresPlaybackRate) {
return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
}
return 1.0;
};
/**
* Gets or sets the current default playback rate. A default playback rate of
* 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
* defaultPlaybackRate will only represent what the intial playbackRate of a video was, not
* not the current playbackRate.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
*
* @param {number} [rate]
* New default playback rate to set.
*
* @return {number|Player}
* - The default playback rate when getting or 1.0
* - the player when setting
*/
Player.prototype.defaultPlaybackRate = function defaultPlaybackRate(rate) {
if (rate !== undefined) {
return this.techCall_('setDefaultPlaybackRate', rate);
}
if (this.tech_ && this.tech_.featuresPlaybackRate) {
return this.techGet_('defaultPlaybackRate');
}
return 1.0;
};
/**
* Gets or sets the audio flag
*
* @param {boolean} bool
* - true signals that this is an audio player
* - false signals that this is not an audio player
*
* @return {boolean}
* The current value of isAudio when getting
*/
Player.prototype.isAudio = function isAudio(bool) {
if (bool !== undefined) {
this.isAudio_ = !!bool;
return;
}
return !!this.isAudio_;
};
/**
* A helper method for adding a {@link TextTrack} to our
* {@link TextTrackList}.
*
* In addition to the W3C settings we allow adding additional info through options.
*
* @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
*
* @param {string} [kind]
* the kind of TextTrack you are adding
*
* @param {string} [label]
* the label to give the TextTrack label
*
* @param {string} [language]
* the language to set on the TextTrack
*
* @return {TextTrack|undefined}
* the TextTrack that was added or undefined
* if there is no tech
*/
Player.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (this.tech_) {
return this.tech_.addTextTrack(kind, label, language);
}
};
/**
* Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will
* automatically removed from the video element whenever the source changes, unless
* manualCleanup is set to false.
*
* @param {Object} options
* Options to pass to {@link HTMLTrackElement} during creation. See
* {@link HTMLTrackElement} for object properties that you should use.
*
* @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be
*
* @return {HtmlTrackElement}
* the HTMLTrackElement that was created and added
* to the HtmlTrackElementList and the remote
* TextTrackList
*
* @deprecated The default value of the "manualCleanup" parameter will default
* to "false" in upcoming versions of Video.js
*/
Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
if (this.tech_) {
return this.tech_.addRemoteTextTrack(options, manualCleanup);
}
};
/**
* Remove a remote {@link TextTrack} from the respective
* {@link TextTrackList} and {@link HtmlTrackElementList}.
*
* @param {Object} track
* Remote {@link TextTrack} to remove
*
* @return {undefined}
* does not return anything
*/
Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack() {
var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref3$track = _ref3.track,
track = _ref3$track === undefined ? arguments[0] : _ref3$track;
// destructure the input into an object with a track argument, defaulting to arguments[0]
// default the whole argument to an empty object if nothing was passed in
if (this.tech_) {
return this.tech_.removeRemoteTextTrack(track);
}
};
/**
* Gets available media playback quality metrics as specified by the W3C's Media
* Playback Quality API.
*
* @see [Spec]{@link https://wicg.github.io/media-playback-quality}
*
* @return {Object|undefined}
* An object with supported media playback quality metrics or undefined if there
* is no tech or the tech does not support it.
*/
Player.prototype.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
return this.techGet_('getVideoPlaybackQuality');
};
/**
* Get video width
*
* @return {number}
* current video width
*/
Player.prototype.videoWidth = function videoWidth() {
return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
};
/**
* Get video height
*
* @return {number}
* current video height
*/
Player.prototype.videoHeight = function videoHeight() {
return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
};
/**
* The player's language code
* NOTE: The language should be set in the player options if you want the
* the controls to be built with a specific language. Changing the lanugage
* later will not update controls text.
*
* @param {string} [code]
* the language code to set the player to
*
* @return {string}
* The current language code when getting
*/
Player.prototype.language = function language(code) {
if (code === undefined) {
return this.language_;
}
this.language_ = String(code).toLowerCase();
};
/**
* Get the player's language dictionary
* Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
* Languages specified directly in the player options have precedence
*
* @return {Array}
* An array of of supported languages
*/
Player.prototype.languages = function languages() {
return mergeOptions(Player.prototype.options_.languages, this.languages_);
};
/**
* returns a JavaScript object reperesenting the current track
* information. **DOES not return it as JSON**
*
* @return {Object}
* Object representing the current of track info
*/
Player.prototype.toJSON = function toJSON() {
var options = mergeOptions(this.options_);
var tracks = options.tracks;
options.tracks = [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// deep merge tracks and null out player so no circular references
track = mergeOptions(track);
track.player = undefined;
options.tracks[i] = track;
}
return options;
};
/**
* Creates a simple modal dialog (an instance of the {@link ModalDialog}
* component) that immediately overlays the player with arbitrary
* content and removes itself when closed.
*
* @param {string|Function|Element|Array|null} content
* Same as {@link ModalDialog#content}'s param of the same name.
* The most straight-forward usage is to provide a string or DOM
* element.
*
* @param {Object} [options]
* Extra options which will be passed on to the {@link ModalDialog}.
*
* @return {ModalDialog}
* the {@link ModalDialog} that was created
*/
Player.prototype.createModal = function createModal(content, options) {
var _this12 = this;
options = options || {};
options.content = content || '';
var modal = new ModalDialog(this, options);
this.addChild(modal);
modal.on('dispose', function () {
_this12.removeChild(modal);
});
modal.open();
return modal;
};
/**
* Change breakpoint classes when the player resizes.
*
* @private
*/
Player.prototype.updateCurrentBreakpoint_ = function updateCurrentBreakpoint_() {
if (!this.responsive()) {
return;
}
var currentBreakpoint = this.currentBreakpoint();
var currentWidth = this.currentWidth();
for (var i = 0; i < BREAKPOINT_ORDER.length; i++) {
var candidateBreakpoint = BREAKPOINT_ORDER[i];
var maxWidth = this.breakpoints_[candidateBreakpoint];
if (currentWidth <= maxWidth) {
// The current breakpoint did not change, nothing to do.
if (currentBreakpoint === candidateBreakpoint) {
return;
}
// Only remove a class if there is a current breakpoint.
if (currentBreakpoint) {
this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
}
this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
this.breakpoint_ = candidateBreakpoint;
break;
}
}
};
/**
* Removes the current breakpoint.
*
* @private
*/
Player.prototype.removeCurrentBreakpoint_ = function removeCurrentBreakpoint_() {
var className = this.currentBreakpointClass();
this.breakpoint_ = '';
if (className) {
this.removeClass(className);
}
};
/**
* Get or set breakpoints on the player.
*
* Calling this method with an object or `true` will remove any previous
* custom breakpoints and start from the defaults again.
*
* @param {Object|boolean} [breakpoints]
* If an object is given, it can be used to provide custom
* breakpoints. If `true` is given, will set default breakpoints.
* If this argument is not given, will simply return the current
* breakpoints.
*
* @param {number} [breakpoints.tiny]
* The maximum width for the "vjs-layout-tiny" class.
*
* @param {number} [breakpoints.xsmall]
* The maximum width for the "vjs-layout-x-small" class.
*
* @param {number} [breakpoints.small]
* The maximum width for the "vjs-layout-small" class.
*
* @param {number} [breakpoints.medium]
* The maximum width for the "vjs-layout-medium" class.
*
* @param {number} [breakpoints.large]
* The maximum width for the "vjs-layout-large" class.
*
* @param {number} [breakpoints.xlarge]
* The maximum width for the "vjs-layout-x-large" class.
*
* @param {number} [breakpoints.huge]
* The maximum width for the "vjs-layout-huge" class.
*
* @return {Object}
* An object mapping breakpoint names to maximum width values.
*/
Player.prototype.breakpoints = function breakpoints(_breakpoints) {
// Used as a getter.
if (_breakpoints === undefined) {
return assign(this.breakpoints_);
}
this.breakpoint_ = '';
this.breakpoints_ = assign({}, DEFAULT_BREAKPOINTS, _breakpoints);
// When breakpoint definitions change, we need to update the currently
// selected breakpoint.
this.updateCurrentBreakpoint_();
// Clone the breakpoints before returning.
return assign(this.breakpoints_);
};
/**
* Get or set a flag indicating whether or not this player should adjust
* its UI based on its dimensions.
*
* @param {boolean} value
* Should be `true` if the player should adjust its UI based on its
* dimensions; otherwise, should be `false`.
*
* @return {boolean}
* Will be `true` if this player should adjust its UI based on its
* dimensions; otherwise, will be `false`.
*/
Player.prototype.responsive = function responsive(value) {
// Used as a getter.
if (value === undefined) {
return this.responsive_;
}
value = Boolean(value);
var current = this.responsive_;
// Nothing changed.
if (value === current) {
return;
}
// The value actually changed, set it.
this.responsive_ = value;
// Start listening for breakpoints and set the initial breakpoint if the
// player is now responsive.
if (value) {
this.on('playerresize', this.updateCurrentBreakpoint_);
this.updateCurrentBreakpoint_();
// Stop listening for breakpoints if the player is no longer responsive.
} else {
this.off('playerresize', this.updateCurrentBreakpoint_);
this.removeCurrentBreakpoint_();
}
return value;
};
/**
* Get current breakpoint name, if any.
*
* @return {string}
* If there is currently a breakpoint set, returns a the key from the
* breakpoints object matching it. Otherwise, returns an empty string.
*/
Player.prototype.currentBreakpoint = function currentBreakpoint() {
return this.breakpoint_;
};
/**
* Get the current breakpoint class name.
*
* @return {string}
* The matching class name (e.g. `"vjs-layout-tiny"` or
* `"vjs-layout-large"`) for the current breakpoint. Empty string if
* there is no current breakpoint.
*/
Player.prototype.currentBreakpointClass = function currentBreakpointClass() {
return BREAKPOINT_CLASSES[this.breakpoint_] || '';
};
/**
* Gets tag settings
*
* @param {Element} tag
* The player tag
*
* @return {Object}
* An object containing all of the settings
* for a player tag
*/
Player.getTagSettings = function getTagSettings(tag) {
var baseOptions = {
sources: [],
tracks: []
};
var tagOptions = getAttributes(tag);
var dataSetup = tagOptions['data-setup'];
if (hasClass(tag, 'vjs-fill')) {
tagOptions.fill = true;
}
if (hasClass(tag, 'vjs-fluid')) {
tagOptions.fluid = true;
}
// Check if data-setup attr exists.
if (dataSetup !== null) {
// Parse options JSON
// If empty string, make it a parsable json object.
var _safeParseTuple = safeParseTuple(dataSetup || '{}'),
err = _safeParseTuple[0],
data = _safeParseTuple[1];
if (err) {
log.error(err);
}
assign(tagOptions, data);
}
assign(baseOptions, tagOptions);
// Get tag children settings
if (tag.hasChildNodes()) {
var children = tag.childNodes;
for (var i = 0, j = children.length; i < j; i++) {
var child = children[i];
// Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
var childName = child.nodeName.toLowerCase();
if (childName === 'source') {
baseOptions.sources.push(getAttributes(child));
} else if (childName === 'track') {
baseOptions.tracks.push(getAttributes(child));
}
}
}
return baseOptions;
};
/**
* Determine wether or not flexbox is supported
*
* @return {boolean}
* - true if flexbox is supported
* - false if flexbox is not supported
*/
Player.prototype.flexNotSupported_ = function flexNotSupported_() {
var elem = document.createElement('i');
// Note: We don't actually use flexBasis (or flexOrder), but it's one of the more
// common flex features that we can rely on when checking for flex support.
return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style ||
// IE10-specific (2012 flex spec)
'msFlexOrder' in elem.style);
};
return Player;
}(Component);
/**
* Get the {@link VideoTrackList}
* @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
*
* @return {VideoTrackList}
* the current video track list
*
* @method Player.prototype.videoTracks
*/
/**
* Get the {@link AudioTrackList}
* @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
*
* @return {AudioTrackList}
* the current audio track list
*
* @method Player.prototype.audioTracks
*/
/**
* Get the {@link TextTrackList}
*
* @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
*
* @return {TextTrackList}
* the current text track list
*
* @method Player.prototype.textTracks
*/
/**
* Get the remote {@link TextTrackList}
*
* @return {TextTrackList}
* The current remote text track list
*
* @method Player.prototype.remoteTextTracks
*/
/**
* Get the remote {@link HtmlTrackElementList} tracks.
*
* @return {HtmlTrackElementList}
* The current remote text track element list
*
* @method Player.prototype.remoteTextTrackEls
*/
ALL.names.forEach(function (name$$1) {
var props = ALL[name$$1];
Player.prototype[props.getterName] = function () {
if (this.tech_) {
return this.tech_[props.getterName]();
}
// if we have not yet loadTech_, we create {video,audio,text}Tracks_
// these will be passed to the tech during loading
this[props.privateName] = this[props.privateName] || new props.ListClass();
return this[props.privateName];
};
});
/**
* Global player list
*
* @type {Object}
*/
Player.players = {};
var navigator = window.navigator;
/*
* Player instance options, surfaced using options
* options = Player.prototype.options_
* Make changes in options, not here.
*
* @type {Object}
* @private
*/
Player.prototype.options_ = {
// Default order of fallback technology
techOrder: Tech.defaultTechOrder_,
html5: {},
flash: {},
// default inactivity timeout
inactivityTimeout: 2000,
// default playback rates
playbackRates: [],
// Add playback rate selection by adding rates
// 'playbackRates': [0.5, 1, 1.5, 2],
// Included control sets
children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'controlBar', 'errorDisplay', 'textTrackSettings'],
language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
// locales and their language translations
languages: {},
// Default message to show when a video cannot be played.
notSupportedMessage: 'No compatible source was found for this media.',
breakpoints: {},
responsive: false
};
if (!IS_IE8) {
Player.prototype.options_.children.push('resizeManager');
}
[
/**
* Returns whether or not the player is in the "ended" state.
*
* @return {Boolean} True if the player is in the ended state, false if not.
* @method Player#ended
*/
'ended',
/**
* Returns whether or not the player is in the "seeking" state.
*
* @return {Boolean} True if the player is in the seeking state, false if not.
* @method Player#seeking
*/
'seeking',
/**
* Returns the TimeRanges of the media that are currently available
* for seeking to.
*
* @return {TimeRanges} the seekable intervals of the media timeline
* @method Player#seekable
*/
'seekable',
/**
* Returns the current state of network activity for the element, from
* the codes in the list below.
* - NETWORK_EMPTY (numeric value 0)
* The element has not yet been initialised. All attributes are in
* their initial states.
* - NETWORK_IDLE (numeric value 1)
* The element's resource selection algorithm is active and has
* selected a resource, but it is not actually using the network at
* this time.
* - NETWORK_LOADING (numeric value 2)
* The user agent is actively trying to download data.
* - NETWORK_NO_SOURCE (numeric value 3)
* The element's resource selection algorithm is active, but it has
* not yet found a resource to use.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
* @return {number} the current network activity state
* @method Player#networkState
*/
'networkState',
/**
* Returns a value that expresses the current state of the element
* with respect to rendering the current playback position, from the
* codes in the list below.
* - HAVE_NOTHING (numeric value 0)
* No information regarding the media resource is available.
* - HAVE_METADATA (numeric value 1)
* Enough of the resource has been obtained that the duration of the
* resource is available.
* - HAVE_CURRENT_DATA (numeric value 2)
* Data for the immediate current playback position is available.
* - HAVE_FUTURE_DATA (numeric value 3)
* Data for the immediate current playback position is available, as
* well as enough data for the user agent to advance the current
* playback position in the direction of playback.
* - HAVE_ENOUGH_DATA (numeric value 4)
* The user agent estimates that enough data is available for
* playback to proceed uninterrupted.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
* @return {number} the current playback rendering state
* @method Player#readyState
*/
'readyState'].forEach(function (fn) {
Player.prototype[fn] = function () {
return this.techGet_(fn);
};
});
TECH_EVENTS_RETRIGGER.forEach(function (event) {
Player.prototype['handleTech' + toTitleCase(event) + '_'] = function () {
return this.trigger(event);
};
});
/**
* Fired when the player has initial duration and dimension information
*
* @event Player#loadedmetadata
* @type {EventTarget~Event}
*/
/**
* Fired when the player has downloaded data at the current playback position
*
* @event Player#loadeddata
* @type {EventTarget~Event}
*/
/**
* Fired when the current playback position has changed *
* During playback this is fired every 15-250 milliseconds, depending on the
* playback technology in use.
*
* @event Player#timeupdate
* @type {EventTarget~Event}
*/
/**
* Fired when the volume changes
*
* @event Player#volumechange
* @type {EventTarget~Event}
*/
/**
* Reports whether or not a player has a plugin available.
*
* This does not report whether or not the plugin has ever been initialized
* on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
*
* @method Player#hasPlugin
* @param {string} name
* The name of a plugin.
*
* @return {boolean}
* Whether or not this player has the requested plugin available.
*/
/**
* Reports whether or not a player is using a plugin by name.
*
* For basic plugins, this only reports whether the plugin has _ever_ been
* initialized on this player.
*
* @method Player#usingPlugin
* @param {string} name
* The name of a plugin.
*
* @return {boolean}
* Whether or not this player is using the requested plugin.
*/
Component.registerComponent('Player', Player);
/**
* @file plugin.js
*/
/**
* The base plugin name.
*
* @private
* @constant
* @type {string}
*/
var BASE_PLUGIN_NAME = 'plugin';
/**
* The key on which a player's active plugins cache is stored.
*
* @private
* @constant
* @type {string}
*/
var PLUGIN_CACHE_KEY = 'activePlugins_';
/**
* Stores registered plugins in a private space.
*
* @private
* @type {Object}
*/
var pluginStorage = {};
/**
* Reports whether or not a plugin has been registered.
*
* @private
* @param {string} name
* The name of a plugin.
*
* @returns {boolean}
* Whether or not the plugin has been registered.
*/
var pluginExists = function pluginExists(name) {
return pluginStorage.hasOwnProperty(name);
};
/**
* Get a single registered plugin by name.
*
* @private
* @param {string} name
* The name of a plugin.
*
* @returns {Function|undefined}
* The plugin (or undefined).
*/
var getPlugin = function getPlugin(name) {
return pluginExists(name) ? pluginStorage[name] : undefined;
};
/**
* Marks a plugin as "active" on a player.
*
* Also, ensures that the player has an object for tracking active plugins.
*
* @private
* @param {Player} player
* A Video.js player instance.
*
* @param {string} name
* The name of a plugin.
*/
var markPluginAsActive = function markPluginAsActive(player, name) {
player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
player[PLUGIN_CACHE_KEY][name] = true;
};
/**
* Triggers a pair of plugin setup events.
*
* @private
* @param {Player} player
* A Video.js player instance.
*
* @param {Plugin~PluginEventHash} hash
* A plugin event hash.
*
* @param {Boolean} [before]
* If true, prefixes the event name with "before". In other words,
* use this to trigger "beforepluginsetup" instead of "pluginsetup".
*/
var triggerSetupEvent = function triggerSetupEvent(player, hash, before) {
var eventName = (before ? 'before' : '') + 'pluginsetup';
player.trigger(eventName, hash);
player.trigger(eventName + ':' + hash.name, hash);
};
/**
* Takes a basic plugin function and returns a wrapper function which marks
* on the player that the plugin has been activated.
*
* @private
* @param {string} name
* The name of the plugin.
*
* @param {Function} plugin
* The basic plugin.
*
* @returns {Function}
* A wrapper function for the given plugin.
*/
var createBasicPlugin = function createBasicPlugin(name, plugin) {
var basicPluginWrapper = function basicPluginWrapper() {
// We trigger the "beforepluginsetup" and "pluginsetup" events on the player
// regardless, but we want the hash to be consistent with the hash provided
// for advanced plugins.
//
// The only potentially counter-intuitive thing here is the `instance` in
// the "pluginsetup" event is the value returned by the `plugin` function.
triggerSetupEvent(this, { name: name, plugin: plugin, instance: null }, true);
var instance = plugin.apply(this, arguments);
markPluginAsActive(this, name);
triggerSetupEvent(this, { name: name, plugin: plugin, instance: instance });
return instance;
};
Object.keys(plugin).forEach(function (prop) {
basicPluginWrapper[prop] = plugin[prop];
});
return basicPluginWrapper;
};
/**
* Takes a plugin sub-class and returns a factory function for generating
* instances of it.
*
* This factory function will replace itself with an instance of the requested
* sub-class of Plugin.
*
* @private
* @param {string} name
* The name of the plugin.
*
* @param {Plugin} PluginSubClass
* The advanced plugin.
*
* @returns {Function}
*/
var createPluginFactory = function createPluginFactory(name, PluginSubClass) {
// Add a `name` property to the plugin prototype so that each plugin can
// refer to itself by name.
PluginSubClass.prototype.name = name;
return function () {
triggerSetupEvent(this, { name: name, plugin: PluginSubClass, instance: null }, true);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var instance = new (Function.prototype.bind.apply(PluginSubClass, [null].concat([this].concat(args))))();
// The plugin is replaced by a function that returns the current instance.
this[name] = function () {
return instance;
};
triggerSetupEvent(this, instance.getEventHash());
return instance;
};
};
/**
* Parent class for all advanced plugins.
*
* @mixes module:evented~EventedMixin
* @mixes module:stateful~StatefulMixin
* @fires Player#beforepluginsetup
* @fires Player#beforepluginsetup:$name
* @fires Player#pluginsetup
* @fires Player#pluginsetup:$name
* @listens Player#dispose
* @throws {Error}
* If attempting to instantiate the base {@link Plugin} class
* directly instead of via a sub-class.
*/
var Plugin = function () {
/**
* Creates an instance of this class.
*
* Sub-classes should call `super` to ensure plugins are properly initialized.
*
* @param {Player} player
* A Video.js player instance.
*/
function Plugin(player) {
classCallCheck(this, Plugin);
if (this.constructor === Plugin) {
throw new Error('Plugin must be sub-classed; not directly instantiated.');
}
this.player = player;
// Make this object evented, but remove the added `trigger` method so we
// use the prototype version instead.
evented(this);
delete this.trigger;
stateful(this, this.constructor.defaultState);
markPluginAsActive(player, this.name);
// Auto-bind the dispose method so we can use it as a listener and unbind
// it later easily.
this.dispose = bind(this, this.dispose);
// If the player is disposed, dispose the plugin.
player.on('dispose', this.dispose);
}
/**
* Get the version of the plugin that was set on <pluginName>.VERSION
*/
Plugin.prototype.version = function version() {
return this.constructor.VERSION;
};
/**
* Each event triggered by plugins includes a hash of additional data with
* conventional properties.
*
* This returns that object or mutates an existing hash.
*
* @param {Object} [hash={}]
* An object to be used as event an event hash.
*
* @returns {Plugin~PluginEventHash}
* An event hash object with provided properties mixed-in.
*/
Plugin.prototype.getEventHash = function getEventHash() {
var hash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
hash.name = this.name;
hash.plugin = this.constructor;
hash.instance = this;
return hash;
};
/**
* Triggers an event on the plugin object and overrides
* {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
*
* @param {string|Object} event
* An event type or an object with a type property.
*
* @param {Object} [hash={}]
* Additional data hash to merge with a
* {@link Plugin~PluginEventHash|PluginEventHash}.
*
* @returns {boolean}
* Whether or not default was prevented.
*/
Plugin.prototype.trigger = function trigger$$1(event) {
var hash = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return trigger(this.eventBusEl_, event, this.getEventHash(hash));
};
/**
* Handles "statechanged" events on the plugin. No-op by default, override by
* subclassing.
*
* @abstract
* @param {Event} e
* An event object provided by a "statechanged" event.
*
* @param {Object} e.changes
* An object describing changes that occurred with the "statechanged"
* event.
*/
Plugin.prototype.handleStateChanged = function handleStateChanged(e) {};
/**
* Disposes a plugin.
*
* Subclasses can override this if they want, but for the sake of safety,
* it's probably best to subscribe the "dispose" event.
*
* @fires Plugin#dispose
*/
Plugin.prototype.dispose = function dispose() {
var name = this.name,
player = this.player;
/**
* Signals that a advanced plugin is about to be disposed.
*
* @event Plugin#dispose
* @type {EventTarget~Event}
*/
this.trigger('dispose');
this.off();
player.off('dispose', this.dispose);
// Eliminate any possible sources of leaking memory by clearing up
// references between the player and the plugin instance and nulling out
// the plugin's state and replacing methods with a function that throws.
player[PLUGIN_CACHE_KEY][name] = false;
this.player = this.state = null;
// Finally, replace the plugin name on the player with a new factory
// function, so that the plugin is ready to be set up again.
player[name] = createPluginFactory(name, pluginStorage[name]);
};
/**
* Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
*
* @param {string|Function} plugin
* If a string, matches the name of a plugin. If a function, will be
* tested directly.
*
* @returns {boolean}
* Whether or not a plugin is a basic plugin.
*/
Plugin.isBasic = function isBasic(plugin) {
var p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
};
/**
* Register a Video.js plugin.
*
* @param {string} name
* The name of the plugin to be registered. Must be a string and
* must not match an existing plugin or a method on the `Player`
* prototype.
*
* @param {Function} plugin
* A sub-class of `Plugin` or a function for basic plugins.
*
* @returns {Function}
* For advanced plugins, a factory function for that plugin. For
* basic plugins, a wrapper function that initializes the plugin.
*/
Plugin.registerPlugin = function registerPlugin(name, plugin) {
if (typeof name !== 'string') {
throw new Error('Illegal plugin name, "' + name + '", must be a string, was ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name)) + '.');
}
if (pluginExists(name)) {
log.warn('A plugin named "' + name + '" already exists. You may want to avoid re-registering plugins!');
} else if (Player.prototype.hasOwnProperty(name)) {
throw new Error('Illegal plugin name, "' + name + '", cannot share a name with an existing player method!');
}
if (typeof plugin !== 'function') {
throw new Error('Illegal plugin for "' + name + '", must be a function, was ' + (typeof plugin === 'undefined' ? 'undefined' : _typeof(plugin)) + '.');
}
pluginStorage[name] = plugin;
// Add a player prototype method for all sub-classed plugins (but not for
// the base Plugin class).
if (name !== BASE_PLUGIN_NAME) {
if (Plugin.isBasic(plugin)) {
Player.prototype[name] = createBasicPlugin(name, plugin);
} else {
Player.prototype[name] = createPluginFactory(name, plugin);
}
}
return plugin;
};
/**
* De-register a Video.js plugin.
*
* @param {string} name
* The name of the plugin to be deregistered.
*/
Plugin.deregisterPlugin = function deregisterPlugin(name) {
if (name === BASE_PLUGIN_NAME) {
throw new Error('Cannot de-register base plugin.');
}
if (pluginExists(name)) {
delete pluginStorage[name];
delete Player.prototype[name];
}
};
/**
* Gets an object containing multiple Video.js plugins.
*
* @param {Array} [names]
* If provided, should be an array of plugin names. Defaults to _all_
* plugin names.
*
* @returns {Object|undefined}
* An object containing plugin(s) associated with their name(s) or
* `undefined` if no matching plugins exist).
*/
Plugin.getPlugins = function getPlugins() {
var names = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Object.keys(pluginStorage);
var result = void 0;
names.forEach(function (name) {
var plugin = getPlugin(name);
if (plugin) {
result = result || {};
result[name] = plugin;
}
});
return result;
};
/**
* Gets a plugin's version, if available
*
* @param {string} name
* The name of a plugin.
*
* @returns {string}
* The plugin's version or an empty string.
*/
Plugin.getPluginVersion = function getPluginVersion(name) {
var plugin = getPlugin(name);
return plugin && plugin.VERSION || '';
};
return Plugin;
}();
/**
* Gets a plugin by name if it exists.
*
* @static
* @method getPlugin
* @memberOf Plugin
* @param {string} name
* The name of a plugin.
*
* @returns {Function|undefined}
* The plugin (or `undefined`).
*/
Plugin.getPlugin = getPlugin;
/**
* The name of the base plugin class as it is registered.
*
* @type {string}
*/
Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
/**
* Documented in player.js
*
* @ignore
*/
Player.prototype.usingPlugin = function (name) {
return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
};
/**
* Documented in player.js
*
* @ignore
*/
Player.prototype.hasPlugin = function (name) {
return !!pluginExists(name);
};
/**
* Signals that a plugin is about to be set up on a player.
*
* @event Player#beforepluginsetup
* @type {Plugin~PluginEventHash}
*/
/**
* Signals that a plugin is about to be set up on a player - by name. The name
* is the name of the plugin.
*
* @event Player#beforepluginsetup:$name
* @type {Plugin~PluginEventHash}
*/
/**
* Signals that a plugin has just been set up on a player.
*
* @event Player#pluginsetup
* @type {Plugin~PluginEventHash}
*/
/**
* Signals that a plugin has just been set up on a player - by name. The name
* is the name of the plugin.
*
* @event Player#pluginsetup:$name
* @type {Plugin~PluginEventHash}
*/
/**
* @typedef {Object} Plugin~PluginEventHash
*
* @property {string} instance
* For basic plugins, the return value of the plugin function. For
* advanced plugins, the plugin instance on which the event is fired.
*
* @property {string} name
* The name of the plugin.
*
* @property {string} plugin
* For basic plugins, the plugin function. For advanced plugins, the
* plugin class/constructor.
*/
/**
* @file extend.js
* @module extend
*/
/**
* A combination of node inherits and babel's inherits (after transpile).
* Both work the same but node adds `super_` to the subClass
* and Bable adds the superClass as __proto__. Both seem useful.
*
* @param {Object} subClass
* The class to inherit to
*
* @param {Object} superClass
* The class to inherit from
*
* @private
*/
var _inherits = 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 === 'undefined' ? 'undefined' : _typeof(superClass)));
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) {
// node
subClass.super_ = superClass;
}
};
/**
* Function for subclassing using the same inheritance that
* videojs uses internally
*
* @static
* @const
*
* @param {Object} superClass
* The class to inherit from
*
* @param {Object} [subClassMethods={}]
* The class to inherit to
*
* @return {Object}
* The new object with subClassMethods that inherited superClass.
*/
var extendFn = function extendFn(superClass) {
var subClassMethods = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var subClass = function subClass() {
superClass.apply(this, arguments);
};
var methods = {};
if ((typeof subClassMethods === 'undefined' ? 'undefined' : _typeof(subClassMethods)) === 'object') {
if (subClassMethods.constructor !== Object.prototype.constructor) {
subClass = subClassMethods.constructor;
}
methods = subClassMethods;
} else if (typeof subClassMethods === 'function') {
subClass = subClassMethods;
}
_inherits(subClass, superClass);
// Extend subObj's prototype with functions and other properties from props
for (var name in methods) {
if (methods.hasOwnProperty(name)) {
subClass.prototype[name] = methods[name];
}
}
return subClass;
};
/**
* @file video.js
* @module videojs
*/
// Include the built-in techs
// HTML5 Element Shim for IE8
if (typeof HTMLVideoElement === 'undefined' && isReal()) {
document.createElement('video');
document.createElement('audio');
document.createElement('track');
document.createElement('video-js');
}
/**
* Normalize an `id` value by trimming off a leading `#`
*
* @param {string} id
* A string, maybe with a leading `#`.
*
* @returns {string}
* The string, without any leading `#`.
*/
var normalizeId = function normalizeId(id) {
return id.indexOf('#') === 0 ? id.slice(1) : id;
};
/**
* Doubles as the main function for users to create a player instance and also
* the main library object.
* The `videojs` function can be used to initialize or retrieve a player.
*
* @param {string|Element} id
* Video element or video element ID
*
* @param {Object} [options]
* Optional options object for config/settings
*
* @param {Component~ReadyCallback} [ready]
* Optional ready callback
*
* @return {Player}
* A player instance
*/
function videojs(id, options, ready) {
var player = videojs.getPlayer(id);
if (player) {
if (options) {
log.warn('Player "' + id + '" is already initialised. Options will not be applied.');
}
if (ready) {
player.ready(ready);
}
return player;
}
var el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
if (!isEl(el)) {
throw new TypeError('The element or ID supplied is not valid. (videojs)');
}
if (!document.body.contains(el)) {
log.warn('The element supplied is not included in the DOM');
}
options = options || {};
videojs.hooks('beforesetup').forEach(function (hookFunction) {
var opts = hookFunction(el, mergeOptions(options));
if (!isObject(opts) || Array.isArray(opts)) {
log.error('please return an object in beforesetup hooks');
return;
}
options = mergeOptions(options, opts);
});
// We get the current "Player" component here in case an integration has
// replaced it with a custom player.
var PlayerComponent = Component.getComponent('Player');
player = new PlayerComponent(el, options, ready);
videojs.hooks('setup').forEach(function (hookFunction) {
return hookFunction(player);
});
return player;
}
/**
* An Object that contains lifecycle hooks as keys which point to an array
* of functions that are run when a lifecycle is triggered
*/
videojs.hooks_ = {};
/**
* Get a list of hooks for a specific lifecycle
* @function videojs.hooks
*
* @param {string} type
* the lifecyle to get hooks from
*
* @param {Function|Function[]} [fn]
* Optionally add a hook (or hooks) to the lifecycle that your are getting.
*
* @return {Array}
* an array of hooks, or an empty array if there are none.
*/
videojs.hooks = function (type, fn) {
videojs.hooks_[type] = videojs.hooks_[type] || [];
if (fn) {
videojs.hooks_[type] = videojs.hooks_[type].concat(fn);
}
return videojs.hooks_[type];
};
/**
* Add a function hook to a specific videojs lifecycle.
*
* @param {string} type
* the lifecycle to hook the function to.
*
* @param {Function|Function[]}
* The function or array of functions to attach.
*/
videojs.hook = function (type, fn) {
videojs.hooks(type, fn);
};
/**
* Add a function hook that will only run once to a specific videojs lifecycle.
*
* @param {string} type
* the lifecycle to hook the function to.
*
* @param {Function|Function[]}
* The function or array of functions to attach.
*/
videojs.hookOnce = function (type, fn) {
videojs.hooks(type, [].concat(fn).map(function (original) {
var wrapper = function wrapper() {
videojs.removeHook(type, wrapper);
return original.apply(undefined, arguments);
};
return wrapper;
}));
};
/**
* Remove a hook from a specific videojs lifecycle.
*
* @param {string} type
* the lifecycle that the function hooked to
*
* @param {Function} fn
* The hooked function to remove
*
* @return {boolean}
* The function that was removed or undef
*/
videojs.removeHook = function (type, fn) {
var index = videojs.hooks(type).indexOf(fn);
if (index <= -1) {
return false;
}
videojs.hooks_[type] = videojs.hooks_[type].slice();
videojs.hooks_[type].splice(index, 1);
return true;
};
// Add default styles
if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
var style = $('.vjs-styles-defaults');
if (!style) {
style = createStyleElement('vjs-styles-defaults');
var head = $('head');
if (head) {
head.insertBefore(style, head.firstChild);
}
setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n ');
}
}
// Run Auto-load players
// You have to wait at least once in case this script is loaded after your
// video in the DOM (weird behavior only with minified version)
autoSetupTimeout(1, videojs);
/**
* Current software version. Follows semver.
*
* @type {string}
*/
videojs.VERSION = version;
/**
* The global options object. These are the settings that take effect
* if no overrides are specified when the player is created.
*
* @type {Object}
*/
videojs.options = Player.prototype.options_;
/**
* Get an object with the currently created players, keyed by player ID
*
* @return {Object}
* The created players
*/
videojs.getPlayers = function () {
return Player.players;
};
/**
* Get a single player based on an ID or DOM element.
*
* This is useful if you want to check if an element or ID has an associated
* Video.js player, but not create one if it doesn't.
*
* @param {string|Element} id
* An HTML element - `<video>`, `<audio>`, or `<video-js>` -
* or a string matching the `id` of such an element.
*
* @returns {Player|undefined}
* A player instance or `undefined` if there is no player instance
* matching the argument.
*/
videojs.getPlayer = function (id) {
var players = Player.players;
var tag = void 0;
if (typeof id === 'string') {
var nId = normalizeId(id);
var player = players[nId];
if (player) {
return player;
}
tag = $('#' + nId);
} else {
tag = id;
}
if (isEl(tag)) {
var _tag = tag,
_player = _tag.player,
playerId = _tag.playerId;
// Element may have a `player` property referring to an already created
// player instance. If so, return that.
if (_player || players[playerId]) {
return _player || players[playerId];
}
}
};
/**
* Returns an array of all current players.
*
* @return {Array}
* An array of all players. The array will be in the order that
* `Object.keys` provides, which could potentially vary between
* JavaScript engines.
*
*/
videojs.getAllPlayers = function () {
return (
// Disposed players leave a key with a `null` value, so we need to make sure
// we filter those out.
Object.keys(Player.players).map(function (k) {
return Player.players[k];
}).filter(Boolean)
);
};
/**
* Expose players object.
*
* @memberOf videojs
* @property {Object} players
*/
videojs.players = Player.players;
/**
* Get a component class object by name
*
* @borrows Component.getComponent as videojs.getComponent
*/
videojs.getComponent = Component.getComponent;
/**
* Register a component so it can referred to by name. Used when adding to other
* components, either through addChild `component.addChild('myComponent')` or through
* default children options `{ children: ['myComponent'] }`.
*
* > NOTE: You could also just initialize the component before adding.
* `component.addChild(new MyComponent());`
*
* @param {string} name
* The class name of the component
*
* @param {Component} comp
* The component class
*
* @return {Component}
* The newly registered component
*/
videojs.registerComponent = function (name$$1, comp) {
if (Tech.isTech(comp)) {
log.warn('The ' + name$$1 + ' tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)');
}
Component.registerComponent.call(Component, name$$1, comp);
};
/**
* Get a Tech class object by name
*
* @borrows Tech.getTech as videojs.getTech
*/
videojs.getTech = Tech.getTech;
/**
* Register a Tech so it can referred to by name.
* This is used in the tech order for the player.
*
* @borrows Tech.registerTech as videojs.registerTech
*/
videojs.registerTech = Tech.registerTech;
/**
* Register a middleware to a source type.
*
* @param {String} type A string representing a MIME type.
* @param {function(player):object} middleware A middleware factory that takes a player.
*/
videojs.use = use;
/**
* An object that can be returned by a middleware to signify
* that the middleware is being terminated.
*
* @type {object}
* @memberOf {videojs}
* @property {object} middleware.TERMINATOR
*/
// Object.defineProperty is not available in IE8
if (!IS_IE8 && Object.defineProperty) {
Object.defineProperty(videojs, 'middleware', {
value: {},
writeable: false,
enumerable: true
});
Object.defineProperty(videojs.middleware, 'TERMINATOR', {
value: TERMINATOR,
writeable: false,
enumerable: true
});
} else {
videojs.middleware = { TERMINATOR: TERMINATOR };
}
/**
* A suite of browser and device tests from {@link browser}.
*
* @type {Object}
* @private
*/
videojs.browser = browser;
/**
* Whether or not the browser supports touch events. Included for backward
* compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED`
* instead going forward.
*
* @deprecated since version 5.0
* @type {boolean}
*/
videojs.TOUCH_ENABLED = TOUCH_ENABLED;
/**
* Subclass an existing class
* Mimics ES6 subclassing with the `extend` keyword
*
* @borrows extend:extendFn as videojs.extend
*/
videojs.extend = extendFn;
/**
* Merge two options objects recursively
* Performs a deep merge like lodash.merge but **only merges plain objects**
* (not arrays, elements, anything else)
* Other values will be copied directly from the second object.
*
* @borrows merge-options:mergeOptions as videojs.mergeOptions
*/
videojs.mergeOptions = mergeOptions;
/**
* Change the context (this) of a function
*
* > NOTE: as of v5.0 we require an ES5 shim, so you should use the native
* `function() {}.bind(newContext);` instead of this.
*
* @borrows fn:bind as videojs.bind
*/
videojs.bind = bind;
/**
* Register a Video.js plugin.
*
* @borrows plugin:registerPlugin as videojs.registerPlugin
* @method registerPlugin
*
* @param {string} name
* The name of the plugin to be registered. Must be a string and
* must not match an existing plugin or a method on the `Player`
* prototype.
*
* @param {Function} plugin
* A sub-class of `Plugin` or a function for basic plugins.
*
* @return {Function}
* For advanced plugins, a factory function for that plugin. For
* basic plugins, a wrapper function that initializes the plugin.
*/
videojs.registerPlugin = Plugin.registerPlugin;
/**
* Deregister a Video.js plugin.
*
* @borrows plugin:deregisterPlugin as videojs.deregisterPlugin
* @method deregisterPlugin
*
* @param {string} name
* The name of the plugin to be deregistered. Must be a string and
* must match an existing plugin or a method on the `Player`
* prototype.
*
*/
videojs.deregisterPlugin = Plugin.deregisterPlugin;
/**
* Deprecated method to register a plugin with Video.js
*
* @deprecated
* videojs.plugin() is deprecated; use videojs.registerPlugin() instead
*
* @param {string} name
* The plugin name
*
* @param {Plugin|Function} plugin
* The plugin sub-class or function
*/
videojs.plugin = function (name$$1, plugin) {
log.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
return Plugin.registerPlugin(name$$1, plugin);
};
/**
* Gets an object containing multiple Video.js plugins.
*
* @param {Array} [names]
* If provided, should be an array of plugin names. Defaults to _all_
* plugin names.
*
* @return {Object|undefined}
* An object containing plugin(s) associated with their name(s) or
* `undefined` if no matching plugins exist).
*/
videojs.getPlugins = Plugin.getPlugins;
/**
* Gets a plugin by name if it exists.
*
* @param {string} name
* The name of a plugin.
*
* @return {Function|undefined}
* The plugin (or `undefined`).
*/
videojs.getPlugin = Plugin.getPlugin;
/**
* Gets a plugin's version, if available
*
* @param {string} name
* The name of a plugin.
*
* @return {string}
* The plugin's version or an empty string.
*/
videojs.getPluginVersion = Plugin.getPluginVersion;
/**
* Adding languages so that they're available to all players.
* Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
*
* @param {string} code
* The language code or dictionary property
*
* @param {Object} data
* The data values to be translated
*
* @return {Object}
* The resulting language dictionary object
*/
videojs.addLanguage = function (code, data) {
var _mergeOptions;
code = ('' + code).toLowerCase();
videojs.options.languages = mergeOptions(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions));
return videojs.options.languages[code];
};
/**
* Log messages
*
* @borrows log:log as videojs.log
*/
videojs.log = log;
videojs.createLogger = createLogger;
/**
* Creates an emulated TimeRange object.
*
* @borrows time-ranges:createTimeRanges as videojs.createTimeRange
*/
/**
* @borrows time-ranges:createTimeRanges as videojs.createTimeRanges
*/
videojs.createTimeRange = videojs.createTimeRanges = createTimeRanges;
/**
* Format seconds as a time string, H:MM:SS or M:SS
* Supplying a guide (in seconds) will force a number of leading zeros
* to cover the length of the guide
*
* @borrows format-time:formatTime as videojs.formatTime
*/
videojs.formatTime = formatTime;
/**
* Replaces format-time with a custom implementation, to be used in place of the default.
*
* @borrows format-time:setFormatTime as videojs.setFormatTime
*
* @method setFormatTime
*
* @param {Function} customFn
* A custom format-time function which will be called with the current time and guide (in seconds) as arguments.
* Passed fn should return a string.
*/
videojs.setFormatTime = setFormatTime;
/**
* Resets format-time to the default implementation.
*
* @borrows format-time:resetFormatTime as videojs.resetFormatTime
*
* @method resetFormatTime
*/
videojs.resetFormatTime = resetFormatTime;
/**
* Resolve and parse the elements of a URL
*
* @borrows url:parseUrl as videojs.parseUrl
*
*/
videojs.parseUrl = parseUrl;
/**
* Returns whether the url passed is a cross domain request or not.
*
* @borrows url:isCrossOrigin as videojs.isCrossOrigin
*/
videojs.isCrossOrigin = isCrossOrigin;
/**
* Event target class.
*
* @borrows EventTarget as videojs.EventTarget
*/
videojs.EventTarget = EventTarget;
/**
* Add an event listener to element
* It stores the handler function in a separate cache object
* and adds a generic handler to the element's event,
* along with a unique id (guid) to the element.
*
* @borrows events:on as videojs.on
*/
videojs.on = on;
/**
* Trigger a listener only once for an event
*
* @borrows events:one as videojs.one
*/
videojs.one = one;
/**
* Removes event listeners from an element
*
* @borrows events:off as videojs.off
*/
videojs.off = off;
/**
* Trigger an event for an element
*
* @borrows events:trigger as videojs.trigger
*/
videojs.trigger = trigger;
/**
* A cross-browser XMLHttpRequest wrapper. Here's a simple example:
*
* @param {Object} options
* settings for the request.
*
* @return {XMLHttpRequest|XDomainRequest}
* The request object.
*
* @see https://github.com/Raynos/xhr
*/
videojs.xhr = xhr;
/**
* TextTrack class
*
* @borrows TextTrack as videojs.TextTrack
*/
videojs.TextTrack = TextTrack;
/**
* export the AudioTrack class so that source handlers can create
* AudioTracks and then add them to the players AudioTrackList
*
* @borrows AudioTrack as videojs.AudioTrack
*/
videojs.AudioTrack = AudioTrack;
/**
* export the VideoTrack class so that source handlers can create
* VideoTracks and then add them to the players VideoTrackList
*
* @borrows VideoTrack as videojs.VideoTrack
*/
videojs.VideoTrack = VideoTrack;
/**
* Determines, via duck typing, whether or not a value is a DOM element.
*
* @borrows dom:isEl as videojs.isEl
* @deprecated Use videojs.dom.isEl() instead
*/
/**
* Determines, via duck typing, whether or not a value is a text node.
*
* @borrows dom:isTextNode as videojs.isTextNode
* @deprecated Use videojs.dom.isTextNode() instead
*/
/**
* Creates an element and applies properties.
*
* @borrows dom:createEl as videojs.createEl
* @deprecated Use videojs.dom.createEl() instead
*/
/**
* Check if an element has a CSS class
*
* @borrows dom:hasElClass as videojs.hasClass
* @deprecated Use videojs.dom.hasClass() instead
*/
/**
* Add a CSS class name to an element
*
* @borrows dom:addElClass as videojs.addClass
* @deprecated Use videojs.dom.addClass() instead
*/
/**
* Remove a CSS class name from an element
*
* @borrows dom:removeElClass as videojs.removeClass
* @deprecated Use videojs.dom.removeClass() instead
*/
/**
* Adds or removes a CSS class name on an element depending on an optional
* condition or the presence/absence of the class name.
*
* @borrows dom:toggleElClass as videojs.toggleClass
* @deprecated Use videojs.dom.toggleClass() instead
*/
/**
* Apply attributes to an HTML element.
*
* @borrows dom:setElAttributes as videojs.setAttribute
* @deprecated Use videojs.dom.setAttributes() instead
*/
/**
* Get an element's attribute values, as defined on the HTML tag
* Attributes are not the same as properties. They're defined on the tag
* or with setAttribute (which shouldn't be used with HTML)
* This will return true or false for boolean attributes.
*
* @borrows dom:getElAttributes as videojs.getAttributes
* @deprecated Use videojs.dom.getAttributes() instead
*/
/**
* Empties the contents of an element.
*
* @borrows dom:emptyEl as videojs.emptyEl
* @deprecated Use videojs.dom.emptyEl() instead
*/
/**
* Normalizes and appends content to an element.
*
* The content for an element can be passed in multiple types and
* combinations, whose behavior is as follows:
*
* - String
* Normalized into a text node.
*
* - Element, TextNode
* Passed through.
*
* - Array
* A one-dimensional array of strings, elements, nodes, or functions (which
* return single strings, elements, or nodes).
*
* - Function
* If the sole argument, is expected to produce a string, element,
* node, or array.
*
* @borrows dom:appendContents as videojs.appendContet
* @deprecated Use videojs.dom.appendContent() instead
*/
/**
* Normalizes and inserts content into an element; this is identical to
* `appendContent()`, except it empties the element first.
*
* The content for an element can be passed in multiple types and
* combinations, whose behavior is as follows:
*
* - String
* Normalized into a text node.
*
* - Element, TextNode
* Passed through.
*
* - Array
* A one-dimensional array of strings, elements, nodes, or functions (which
* return single strings, elements, or nodes).
*
* - Function
* If the sole argument, is expected to produce a string, element,
* node, or array.
*
* @borrows dom:insertContent as videojs.insertContent
* @deprecated Use videojs.dom.insertContent() instead
*/
['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(function (k) {
videojs[k] = function () {
log.warn('videojs.' + k + '() is deprecated; use videojs.dom.' + k + '() instead');
return Dom[k].apply(null, arguments);
};
});
/**
* A safe getComputedStyle with an IE8 fallback.
*
* This is because in Firefox, if the player is loaded in an iframe with `display:none`,
* then `getComputedStyle` returns `null`, so, we do a null-check to make sure
* that the player doesn't break in these cases.
* See https://bugzilla.mozilla.org/show_bug.cgi?id=548397 for more details.
*
* @borrows computed-style:computedStyle as videojs.computedStyle
*/
videojs.computedStyle = computedStyle;
/**
* Export the Dom utilities for use in external plugins
* and Tech's
*/
videojs.dom = Dom;
/**
* Export the Url utilities for use in external plugins
* and Tech's
*/
videojs.url = Url;
module.exports = videojs;
/***/ }),
/* 119 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 120 */
/***/ (function(module, exports) {
module.exports = isFunction
var toString = Object.prototype.toString
function isFunction (fn) {
var string = toString.call(fn)
return string === '[object Function]' ||
(typeof fn === 'function' && string !== '[object RegExp]') ||
(typeof window !== 'undefined' &&
// IE8 and below
(fn === window.setTimeout ||
fn === window.alert ||
fn === window.confirm ||
fn === window.prompt))
};
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
var trim = __webpack_require__(122)
, forEach = __webpack_require__(136)
, isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
}
module.exports = function (headers) {
if (!headers)
return {}
var result = {}
forEach(
trim(headers).split('\n')
, function (row) {
var index = row.indexOf(':')
, key = trim(row.slice(0, index)).toLowerCase()
, value = trim(row.slice(index + 1))
if (typeof(result[key]) === 'undefined') {
result[key] = value
} else if (isArray(result[key])) {
result[key].push(value)
} else {
result[key] = [ result[key], value ]
}
}
)
return result
}
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(48);
var define = __webpack_require__(63);
var implementation = __webpack_require__(64);
var getPolyfill = __webpack_require__(65);
var shim = __webpack_require__(135);
var boundTrim = bind.call(Function.call, getPolyfill());
define(boundTrim, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = boundTrim;
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.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;
};
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = __webpack_require__(125);
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,
$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.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;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.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.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.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.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
module.exports = 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;
};
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(127);
var $Object = GetIntrinsic('%Object%');
var $TypeError = GetIntrinsic('%TypeError%');
var $String = GetIntrinsic('%String%');
var $isNaN = __webpack_require__(128);
var $isFinite = __webpack_require__(129);
var sign = __webpack_require__(130);
var mod = __webpack_require__(131);
var IsCallable = __webpack_require__(49);
var toPrimitive = __webpack_require__(132);
var has = __webpack_require__(134);
// https://es5.github.io/#x9
var ES5 = {
ToPrimitive: toPrimitive,
ToBoolean: function ToBoolean(value) {
return !!value;
},
ToNumber: function ToNumber(value) {
return +value; // eslint-disable-line no-implicit-coercion
},
ToInteger: function ToInteger(value) {
var number = this.ToNumber(value);
if ($isNaN(number)) { return 0; }
if (number === 0 || !$isFinite(number)) { return number; }
return sign(number) * Math.floor(Math.abs(number));
},
ToInt32: function ToInt32(x) {
return this.ToNumber(x) >> 0;
},
ToUint32: function ToUint32(x) {
return this.ToNumber(x) >>> 0;
},
ToUint16: function ToUint16(value) {
var number = this.ToNumber(value);
if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
var posInt = sign(number) * Math.floor(Math.abs(number));
return mod(posInt, 0x10000);
},
ToString: function ToString(value) {
return $String(value);
},
ToObject: function ToObject(value) {
this.CheckObjectCoercible(value);
return $Object(value);
},
CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) {
/* jshint eqnull:true */
if (value == null) {
throw new $TypeError(optMessage || 'Cannot call method on ' + value);
}
return value;
},
IsCallable: IsCallable,
SameValue: function SameValue(x, y) {
if (x === y) { // 0 === -0, but they are not identical.
if (x === 0) { return 1 / x === 1 / y; }
return true;
}
return $isNaN(x) && $isNaN(y);
},
// https://www.ecma-international.org/ecma-262/5.1/#sec-8
Type: function Type(x) {
if (x === null) {
return 'Null';
}
if (typeof x === 'undefined') {
return 'Undefined';
}
if (typeof x === 'function' || typeof x === 'object') {
return 'Object';
}
if (typeof x === 'number') {
return 'Number';
}
if (typeof x === 'boolean') {
return 'Boolean';
}
if (typeof x === 'string') {
return 'String';
}
},
// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
IsPropertyDescriptor: function IsPropertyDescriptor(Desc) {
if (this.Type(Desc) !== 'Object') {
return false;
}
var allowed = {
'[[Configurable]]': true,
'[[Enumerable]]': true,
'[[Get]]': true,
'[[Set]]': true,
'[[Value]]': true,
'[[Writable]]': true
};
// jscs:disable
for (var key in Desc) { // eslint-disable-line
if (has(Desc, key) && !allowed[key]) {
return false;
}
}
// jscs:enable
var isData = has(Desc, '[[Value]]');
var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
if (isData && IsAccessor) {
throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
}
return true;
},
// https://ecma-international.org/ecma-262/5.1/#sec-8.10.1
IsAccessorDescriptor: function IsAccessorDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return false;
}
if (!this.IsPropertyDescriptor(Desc)) {
throw new $TypeError('Desc must be a Property Descriptor');
}
if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) {
return false;
}
return true;
},
// https://ecma-international.org/ecma-262/5.1/#sec-8.10.2
IsDataDescriptor: function IsDataDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return false;
}
if (!this.IsPropertyDescriptor(Desc)) {
throw new $TypeError('Desc must be a Property Descriptor');
}
if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {
return false;
}
return true;
},
// https://ecma-international.org/ecma-262/5.1/#sec-8.10.3
IsGenericDescriptor: function IsGenericDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return false;
}
if (!this.IsPropertyDescriptor(Desc)) {
throw new $TypeError('Desc must be a Property Descriptor');
}
if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) {
return true;
}
return false;
},
// https://ecma-international.org/ecma-262/5.1/#sec-8.10.4
FromPropertyDescriptor: function FromPropertyDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return Desc;
}
if (!this.IsPropertyDescriptor(Desc)) {
throw new $TypeError('Desc must be a Property Descriptor');
}
if (this.IsDataDescriptor(Desc)) {
return {
value: Desc['[[Value]]'],
writable: !!Desc['[[Writable]]'],
enumerable: !!Desc['[[Enumerable]]'],
configurable: !!Desc['[[Configurable]]']
};
} else if (this.IsAccessorDescriptor(Desc)) {
return {
get: Desc['[[Get]]'],
set: Desc['[[Set]]'],
enumerable: !!Desc['[[Enumerable]]'],
configurable: !!Desc['[[Configurable]]']
};
} else {
throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor');
}
},
// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5
ToPropertyDescriptor: function ToPropertyDescriptor(Obj) {
if (this.Type(Obj) !== 'Object') {
throw new $TypeError('ToPropertyDescriptor requires an object');
}
var desc = {};
if (has(Obj, 'enumerable')) {
desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable);
}
if (has(Obj, 'configurable')) {
desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable);
}
if (has(Obj, 'value')) {
desc['[[Value]]'] = Obj.value;
}
if (has(Obj, 'writable')) {
desc['[[Writable]]'] = this.ToBoolean(Obj.writable);
}
if (has(Obj, 'get')) {
var getter = Obj.get;
if (typeof getter !== 'undefined' && !this.IsCallable(getter)) {
throw new TypeError('getter must be a function');
}
desc['[[Get]]'] = getter;
}
if (has(Obj, 'set')) {
var setter = Obj.set;
if (typeof setter !== 'undefined' && !this.IsCallable(setter)) {
throw new $TypeError('setter must be a function');
}
desc['[[Set]]'] = setter;
}
if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
}
return desc;
}
};
module.exports = ES5;
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* globals
Set,
Map,
WeakSet,
WeakMap,
Promise,
Symbol,
Proxy,
Atomics,
SharedArrayBuffer,
ArrayBuffer,
DataView,
Uint8Array,
Float32Array,
Float64Array,
Int8Array,
Int16Array,
Int32Array,
Uint8ClampedArray,
Uint16Array,
Uint32Array,
*/
var undefined; // eslint-disable-line no-shadow-restricted-names
var ThrowTypeError = Object.getOwnPropertyDescriptor
? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }())
: function () { throw new TypeError(); };
var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var generator; // = function * () {};
var generatorFunction = generator ? getProto(generator) : undefined;
var asyncFn; // async function() {};
var asyncFunction = asyncFn ? asyncFn.constructor : undefined;
var asyncGen; // async function * () {};
var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;
var asyncGenIterator = asyncGen ? asyncGen() : undefined;
var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
var INTRINSICS = {
'$ %Array%': Array,
'$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,
'$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
'$ %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,
'$ %AsyncFunction%': asyncFunction,
'$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,
'$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,
'$ %AsyncGeneratorFunction%': asyncGenFunction,
'$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,
'$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,
'$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'$ %Boolean%': Boolean,
'$ %BooleanPrototype%': Boolean.prototype,
'$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : 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 : Float32Array,
'$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,
'$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,
'$ %Function%': Function,
'$ %FunctionPrototype%': Function.prototype,
'$ %Generator%': generator ? getProto(generator()) : undefined,
'$ %GeneratorFunction%': generatorFunction,
'$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,
'$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,
'$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,
'$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,
'$ %isFinite%': isFinite,
'$ %isNaN%': isNaN,
'$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
'$ %JSON%': JSON,
'$ %JSONParse%': JSON.parse,
'$ %Map%': typeof Map === 'undefined' ? undefined : Map,
'$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
'$ %MapPrototype%': typeof Map === 'undefined' ? undefined : 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 : Promise,
'$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,
'$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,
'$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,
'$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,
'$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,
'$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'$ %RangeError%': RangeError,
'$ %RangeErrorPrototype%': RangeError.prototype,
'$ %ReferenceError%': ReferenceError,
'$ %ReferenceErrorPrototype%': ReferenceError.prototype,
'$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'$ %RegExp%': RegExp,
'$ %RegExpPrototype%': RegExp.prototype,
'$ %Set%': typeof Set === 'undefined' ? undefined : Set,
'$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
'$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,
'$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,
'$ %String%': String,
'$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
'$ %StringPrototype%': String.prototype,
'$ %Symbol%': hasSymbols ? Symbol : undefined,
'$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,
'$ %SyntaxError%': SyntaxError,
'$ %SyntaxErrorPrototype%': SyntaxError.prototype,
'$ %ThrowTypeError%': ThrowTypeError,
'$ %TypedArray%': TypedArray,
'$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,
'$ %TypeError%': TypeError,
'$ %TypeErrorPrototype%': TypeError.prototype,
'$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,
'$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,
'$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,
'$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,
'$ %URIError%': URIError,
'$ %URIErrorPrototype%': URIError.prototype,
'$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,
'$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,
'$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new TypeError('"allowMissing" argument must be a boolean');
}
var key = '$ ' + name;
if (!(key in INTRINSICS)) {
throw new SyntaxError('intrinsic ' + name + ' does not exist!');
}
// istanbul ignore if // hopefully this is impossible to test :-)
if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) {
throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return INTRINSICS[key];
};
/***/ }),
/* 128 */
/***/ (function(module, exports) {
module.exports = Number.isNaN || function isNaN(a) {
return a !== a;
};
/***/ }),
/* 129 */
/***/ (function(module, exports) {
var $isNaN = Number.isNaN || function (a) { return a !== a; };
module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; };
/***/ }),
/* 130 */
/***/ (function(module, exports) {
module.exports = function sign(number) {
return number >= 0 ? 1 : -1;
};
/***/ }),
/* 131 */
/***/ (function(module, exports) {
module.exports = function mod(number, modulo) {
var remain = number % modulo;
return Math.floor(remain >= 0 ? remain : remain + modulo);
};
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
var isPrimitive = __webpack_require__(133);
var isCallable = __webpack_require__(49);
// https://es5.github.io/#x8.12
var ES5internalSlots = {
'[[DefaultValue]]': function (O, hint) {
var actualHint = hint || (toStr.call(O) === '[object Date]' ? String : Number);
if (actualHint === String || actualHint === Number) {
var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
var value, i;
for (i = 0; i < methods.length; ++i) {
if (isCallable(O[methods[i]])) {
value = O[methods[i]]();
if (isPrimitive(value)) {
return value;
}
}
}
throw new TypeError('No default value');
}
throw new TypeError('invalid [[DefaultValue]] hint supplied');
}
};
// https://es5.github.io/#x9
module.exports = function ToPrimitive(input, PreferredType) {
if (isPrimitive(input)) {
return input;
}
return ES5internalSlots['[[DefaultValue]]'](input, PreferredType);
};
/***/ }),
/* 133 */
/***/ (function(module, exports) {
module.exports = function isPrimitive(value) {
return value === null || (typeof value !== 'function' && typeof value !== 'object');
};
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(48);
module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(63);
var getPolyfill = __webpack_require__(65);
module.exports = function shimStringTrim() {
var polyfill = getPolyfill();
define(String.prototype, { trim: polyfill }, { trim: function () { return String.prototype.trim !== polyfill; } });
return polyfill;
};
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isCallable = __webpack_require__(49);
var toStr = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var forEachArray = function forEachArray(array, iterator, receiver) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty.call(array, i)) {
if (receiver == null) {
iterator(array[i], i, array);
} else {
iterator.call(receiver, array[i], i, array);
}
}
}
};
var forEachString = function forEachString(string, iterator, receiver) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
if (receiver == null) {
iterator(string.charAt(i), i, string);
} else {
iterator.call(receiver, string.charAt(i), i, string);
}
}
};
var forEachObject = function forEachObject(object, iterator, receiver) {
for (var k in object) {
if (hasOwnProperty.call(object, k)) {
if (receiver == null) {
iterator(object[k], k, object);
} else {
iterator.call(receiver, object[k], k, object);
}
}
}
};
var forEach = function forEach(list, iterator, thisArg) {
if (!isCallable(iterator)) {
throw new TypeError('iterator must be a function');
}
var receiver;
if (arguments.length >= 3) {
receiver = thisArg;
}
if (toStr.call(list) === '[object Array]') {
forEachArray(list, iterator, receiver);
} else if (typeof list === 'string') {
forEachString(list, iterator, receiver);
} else {
forEachObject(list, iterator, receiver);
}
};
module.exports = forEach;
/***/ }),
/* 137 */
/***/ (function(module, exports) {
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
/**
* 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.
*/
// Default exports for Node. Export the extended versions of VTTCue and
// VTTRegion in Node since we likely want the capability to convert back and
// forth between JSON. If we don't then it's not that big of a deal since we're
// off browser.
var window = __webpack_require__(43);
var vttjs = module.exports = {
WebVTT: __webpack_require__(139),
VTTCue: __webpack_require__(140),
VTTRegion: __webpack_require__(141)
};
window.vttjs = vttjs;
window.WebVTT = vttjs.WebVTT;
var cueShim = vttjs.VTTCue;
var regionShim = vttjs.VTTRegion;
var nativeVTTCue = window.VTTCue;
var nativeVTTRegion = window.VTTRegion;
vttjs.shim = function() {
window.VTTCue = cueShim;
window.VTTRegion = regionShim;
};
vttjs.restore = function() {
window.VTTCue = nativeVTTCue;
window.VTTRegion = nativeVTTRegion;
};
if (!window.VTTCue) {
vttjs.shim();
}
/***/ }),
/* 139 */
/***/ (function(module, 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.
*/
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
var _objCreate = Object.create || (function() {
function F() {}
return function(o) {
if (arguments.length !== 1) {
throw new Error('Object.create shim only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
// Creates a new ParserError object from an errorData object. The errorData
// object should have default code and message properties. The default message
// property can be overriden by passing in a message parameter.
// See ParsingError.Errors below for acceptable errors.
function ParsingError(errorData, message) {
this.name = "ParsingError";
this.code = errorData.code;
this.message = message || errorData.message;
}
ParsingError.prototype = _objCreate(Error.prototype);
ParsingError.prototype.constructor = ParsingError;
// ParsingError metadata for acceptable ParsingErrors.
ParsingError.Errors = {
BadSignature: {
code: 0,
message: "Malformed WebVTT signature."
},
BadTimeStamp: {
code: 1,
message: "Malformed time stamp."
}
};
// 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) + (f | 0) / 1000;
}
var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
if (!m) {
return null;
}
if (m[3]) {
// Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
} else if (m[1] > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[1], m[2], 0, m[4]);
} else {
// Timestamp takes the form of [minutes]:[seconds].[milliseconds]
return computeSeconds(0, m[1], m[2], m[4]);
}
}
// A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
function Settings() {
this.values = _objCreate(null);
}
Settings.prototype = {
// Only accept the first assignment to any key.
set: function(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.
get: function(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.
has: function(k) {
return k in this.values;
},
// Accept a setting if its one of the given alternatives.
alt: function(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.
integer: function(k, v) {
if (/^-?\d+$/.test(v)) { // integer
this.set(k, parseInt(v, 10));
}
},
// Accept a setting if its a valid percentage.
percent: function(k, v) {
var m;
if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
v = parseFloat(v);
if (v >= 0 && v <= 100) {
this.set(k, v);
return true;
}
}
return false;
}
};
// Helper function to parse input into groups separated by 'groupDelim', and
// interprete 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);
}
}
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 ParsingError(ParsingError.Errors.BadTimeStamp,
"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) {
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":
var vals = v.split(","),
vals0 = vals[0];
settings.integer(k, vals0);
settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
settings.alt(k, vals0, ["auto"]);
if (vals.length === 2) {
settings.alt("lineAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "position":
vals = v.split(",");
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt("positionAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "size":
settings.percent(k, v);
break;
case "align":
settings.alt(k, v, ["start", "middle", "end", "left", "right"]);
break;
}
}, /:/, /\s/);
// Apply default values for any missing fields.
cue.region = settings.get("region", null);
cue.vertical = settings.get("vertical", "");
cue.line = settings.get("line", "auto");
cue.lineAlign = settings.get("lineAlign", "start");
cue.snapToLines = settings.get("snapToLines", true);
cue.size = settings.get("size", 100);
cue.align = settings.get("align", "middle");
cue.position = settings.get("position", {
start: 0,
left: 0,
middle: 50,
end: 100,
right: 100
}, cue.align);
cue.positionAlign = settings.get("positionAlign", {
start: "start",
left: "start",
middle: "middle",
end: "end",
right: "end"
}, cue.align);
}
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 ParsingError(ParsingError.Errors.BadTimeStamp,
"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);
}
var ESCAPE = {
"&amp;": "&",
"&lt;": "<",
"&gt;": ">",
"&lrm;": "\u200e",
"&rlm;": "\u200f",
"&nbsp;": "\u00a0"
};
var TAG_NAME = {
c: "span",
i: "i",
b: "b",
u: "u",
ruby: "ruby",
rt: "rt",
v: "span",
lang: "span"
};
var TAG_ANNOTATION = {
v: "title",
lang: "lang"
};
var NEEDS_PARENT = {
rt: "ruby"
};
// Parse content into a document fragment.
function parseContent(window, input) {
function nextToken() {
// Check for end-of-string.
if (!input) {
return null;
}
// Consume 'n' characters from the input.
function consume(result) {
input = input.substr(result.length);
return result;
}
var m = input.match(/^([^<]*)(<[^>]*>?)?/);
// If there is some text before the next tag, return it, otherwise return
// the tag.
return consume(m[1] ? m[1] : m[2]);
}
// Unescape a string 's'.
function unescape1(e) {
return ESCAPE[e];
}
function unescape(s) {
while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {
s = s.replace(m[0], unescape1);
}
return s;
}
function shouldAdd(current, element) {
return !NEEDS_PARENT[element.localName] ||
NEEDS_PARENT[element.localName] === current.localName;
}
// Create an element for this tag.
function createElement(type, annotation) {
var tagName = TAG_NAME[type];
if (!tagName) {
return null;
}
var element = window.document.createElement(tagName);
element.localName = tagName;
var name = TAG_ANNOTATION[type];
if (name && annotation) {
element[name] = annotation.trim();
}
return element;
}
var rootDiv = window.document.createElement("div"),
current = rootDiv,
t,
tagStack = [];
while ((t = nextToken()) !== null) {
if (t[0] === '<') {
if (t[1] === "/") {
// If the closing tag matches, move back up to the parent node.
if (tagStack.length &&
tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
tagStack.pop();
current = current.parentNode;
}
// Otherwise just ignore the end tag.
continue;
}
var ts = parseTimeStamp(t.substr(1, t.length - 2));
var node;
if (ts) {
// Timestamps are lead nodes as well.
node = window.document.createProcessingInstruction("timestamp", ts);
current.appendChild(node);
continue;
}
var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
// If we can't parse the tag, skip to the next tag.
if (!m) {
continue;
}
// Try to construct an element, and ignore the tag if we couldn't.
node = createElement(m[1], m[3]);
if (!node) {
continue;
}
// Determine if the tag should be added based on the context of where it
// is placed in the cuetext.
if (!shouldAdd(current, node)) {
continue;
}
// Set the class list (as a list of classes, separated by space).
if (m[2]) {
node.className = m[2].substr(1).replace('.', ' ');
}
// Append the node to the current node, and enter the scope of the new
// node.
tagStack.push(m[1]);
current.appendChild(node);
current = node;
continue;
}
// Text nodes are leaf nodes.
current.appendChild(window.document.createTextNode(unescape(t)));
}
return rootDiv;
}
// This is a list of all the Unicode characters that have a strong
// right-to-left category. What this means is that these characters are
// written right-to-left for sure. It was generated by pulling all the strong
// right-to-left characters out of the Unicode data table. That table can
// found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6],
[0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d],
[0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6],
[0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5],
[0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815],
[0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858],
[0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f],
[0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c],
[0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1],
[0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc],
[0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808],
[0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855],
[0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f],
[0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13],
[0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58],
[0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72],
[0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f],
[0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32],
[0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42],
[0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f],
[0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59],
[0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62],
[0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77],
[0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b],
[0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
function isStrongRTLChar(charCode) {
for (var i = 0; i < strongRTLRanges.length; i++) {
var currentRange = strongRTLRanges[i];
if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
return true;
}
}
return false;
}
function determineBidi(cueDiv) {
var nodeStack = [],
text = "",
charCode;
if (!cueDiv || !cueDiv.childNodes) {
return "ltr";
}
function pushNodes(nodeStack, node) {
for (var i = node.childNodes.length - 1; i >= 0; i--) {
nodeStack.push(node.childNodes[i]);
}
}
function nextTextNode(nodeStack) {
if (!nodeStack || !nodeStack.length) {
return null;
}
var node = nodeStack.pop(),
text = node.textContent || node.innerText;
if (text) {
// TODO: This should match all unicode type B characters (paragraph
// separator characters). See issue #115.
var m = text.match(/^.*(\n|\r)/);
if (m) {
nodeStack.length = 0;
return m[0];
}
return text;
}
if (node.tagName === "ruby") {
return nextTextNode(nodeStack);
}
if (node.childNodes) {
pushNodes(nodeStack, node);
return nextTextNode(nodeStack);
}
}
pushNodes(nodeStack, cueDiv);
while ((text = nextTextNode(nodeStack))) {
for (var i = 0; i < text.length; i++) {
charCode = text.charCodeAt(i);
if (isStrongRTLChar(charCode)) {
return "rtl";
}
}
}
return "ltr";
}
function computeLinePos(cue) {
if (typeof cue.line === "number" &&
(cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {
return cue.line;
}
if (!cue.track || !cue.track.textTrackList ||
!cue.track.textTrackList.mediaElement) {
return -1;
}
var track = cue.track,
trackList = track.textTrackList,
count = 0;
for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
if (trackList[i].mode === "showing") {
count++;
}
}
return ++count * -1;
}
function StyleBox() {
}
// Apply styles to a div. If there is no div passed then it defaults to the
// div on 'this'.
StyleBox.prototype.applyStyles = function(styles, div) {
div = div || this.div;
for (var prop in styles) {
if (styles.hasOwnProperty(prop)) {
div.style[prop] = styles[prop];
}
}
};
StyleBox.prototype.formatStyle = function(val, unit) {
return val === 0 ? 0 : val + unit;
};
// Constructs the computed display state of the cue (a div). Places the div
// into the overlay which should be a block level element (usually a div).
function CueStyleBox(window, cue, styleOptions) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var color = "rgba(255, 255, 255, 1)";
var backgroundColor = "rgba(0, 0, 0, 0.8)";
if (isIE8) {
color = "rgb(255, 255, 255)";
backgroundColor = "rgb(0, 0, 0)";
}
StyleBox.call(this);
this.cue = cue;
// Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
// have inline positioning and will function as the cue background box.
this.cueDiv = parseContent(window, cue.text);
var styles = {
color: color,
backgroundColor: backgroundColor,
position: "relative",
left: 0,
right: 0,
top: 0,
bottom: 0,
display: "inline"
};
if (!isIE8) {
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl";
styles.unicodeBidi = "plaintext";
}
this.applyStyles(styles, this.cueDiv);
// Create an absolutely positioned div that will be used to position the cue
// div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
// mirrors of them except "middle" which is "center" in CSS.
this.div = window.document.createElement("div");
styles = {
textAlign: cue.align === "middle" ? "center" : cue.align,
font: styleOptions.font,
whiteSpace: "pre-line",
position: "absolute"
};
if (!isIE8) {
styles.direction = determineBidi(this.cueDiv);
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl".
stylesunicodeBidi = "plaintext";
}
this.applyStyles(styles);
this.div.appendChild(this.cueDiv);
// Calculate the distance from the reference edge of the viewport to the text
// position of the cue box. The reference edge will be resolved later when
// the box orientation styles are applied.
var textPos = 0;
switch (cue.positionAlign) {
case "start":
textPos = cue.position;
break;
case "middle":
textPos = cue.position - (cue.size / 2);
break;
case "end":
textPos = cue.position - cue.size;
break;
}
// Horizontal box orientation; textPos is the distance from the left edge of the
// area to the left edge of the box and cue.size is the distance extending to
// the right from there.
if (cue.vertical === "") {
this.applyStyles({
left: this.formatStyle(textPos, "%"),
width: this.formatStyle(cue.size, "%")
});
// Vertical box orientation; textPos is the distance from the top edge of the
// area to the top edge of the box and cue.size is the height extending
// downwards from there.
} else {
this.applyStyles({
top: this.formatStyle(textPos, "%"),
height: this.formatStyle(cue.size, "%")
});
}
this.move = function(box) {
this.applyStyles({
top: this.formatStyle(box.top, "px"),
bottom: this.formatStyle(box.bottom, "px"),
left: this.formatStyle(box.left, "px"),
right: this.formatStyle(box.right, "px"),
height: this.formatStyle(box.height, "px"),
width: this.formatStyle(box.width, "px")
});
};
}
CueStyleBox.prototype = _objCreate(StyleBox.prototype);
CueStyleBox.prototype.constructor = CueStyleBox;
// Represents the co-ordinates of an Element in a way that we can easily
// compute things with such as if it overlaps or intersects with another Element.
// Can initialize it with either a StyleBox or another BoxPosition.
function BoxPosition(obj) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
// Either a BoxPosition was passed in and we need to copy it, or a StyleBox
// was passed in and we need to copy the results of 'getBoundingClientRect'
// as the object returned is readonly. All co-ordinate values are in reference
// to the viewport origin (top left).
var lh, height, width, top;
if (obj.div) {
height = obj.div.offsetHeight;
width = obj.div.offsetWidth;
top = obj.div.offsetTop;
var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
rects.getClientRects && rects.getClientRects();
obj = obj.div.getBoundingClientRect();
// In certain cases the outter div will be slightly larger then the sum of
// the inner div's lines. This could be due to bold text, etc, on some platforms.
// In this case we should get the average line height and use that. This will
// result in the desired behaviour.
lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
: 0;
}
this.left = obj.left;
this.right = obj.right;
this.top = obj.top || top;
this.height = obj.height || height;
this.bottom = obj.bottom || (top + (obj.height || height));
this.width = obj.width || width;
this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
if (isIE8 && !this.lineHeight) {
this.lineHeight = 13;
}
}
// Move the box along a particular axis. Optionally pass in an amount to move
// the box. If no amount is passed then the default is the line height of the
// box.
BoxPosition.prototype.move = function(axis, toMove) {
toMove = toMove !== undefined ? toMove : this.lineHeight;
switch (axis) {
case "+x":
this.left += toMove;
this.right += toMove;
break;
case "-x":
this.left -= toMove;
this.right -= toMove;
break;
case "+y":
this.top += toMove;
this.bottom += toMove;
break;
case "-y":
this.top -= toMove;
this.bottom -= toMove;
break;
}
};
// Check if this box overlaps another box, b2.
BoxPosition.prototype.overlaps = function(b2) {
return this.left < b2.right &&
this.right > b2.left &&
this.top < b2.bottom &&
this.bottom > b2.top;
};
// Check if this box overlaps any other boxes in boxes.
BoxPosition.prototype.overlapsAny = function(boxes) {
for (var i = 0; i < boxes.length; i++) {
if (this.overlaps(boxes[i])) {
return true;
}
}
return false;
};
// Check if this box is within another box.
BoxPosition.prototype.within = function(container) {
return this.top >= container.top &&
this.bottom <= container.bottom &&
this.left >= container.left &&
this.right <= container.right;
};
// Check if this box is entirely within the container or it is overlapping
// on the edge opposite of the axis direction passed. For example, if "+x" is
// passed and the box is overlapping on the left edge of the container, then
// return true.
BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
switch (axis) {
case "+x":
return this.left < container.left;
case "-x":
return this.right > container.right;
case "+y":
return this.top < container.top;
case "-y":
return this.bottom > container.bottom;
}
};
// Find the percentage of the area that this box is overlapping with another
// box.
BoxPosition.prototype.intersectPercentage = function(b2) {
var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
intersectArea = x * y;
return intersectArea / (this.height * this.width);
};
// Convert the positions from this box to CSS compatible positions using
// the reference container's positions. This has to be done because this
// box's positions are in reference to the viewport origin, whereas, CSS
// values are in referecne to their respective edges.
BoxPosition.prototype.toCSSCompatValues = function(reference) {
return {
top: this.top - reference.top,
bottom: reference.bottom - this.bottom,
left: this.left - reference.left,
right: reference.right - this.right,
height: this.height,
width: this.width
};
};
// Get an object that represents the box's position without anything extra.
// Can pass a StyleBox, HTMLElement, or another BoxPositon.
BoxPosition.getSimpleBoxPosition = function(obj) {
var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
obj = obj.div ? obj.div.getBoundingClientRect() :
obj.tagName ? obj.getBoundingClientRect() : obj;
var ret = {
left: obj.left,
right: obj.right,
top: obj.top || top,
height: obj.height || height,
bottom: obj.bottom || (top + (obj.height || height)),
width: obj.width || width
};
return ret;
};
// Move a StyleBox to its specified, or next best, position. The containerBox
// is the box that contains the StyleBox, such as a div. boxPositions are
// a list of other boxes that the styleBox can't overlap with.
function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
// Find the best position for a cue box, b, on the video. The axis parameter
// is a list of axis, the order of which, it will move the box along. For example:
// Passing ["+x", "-x"] will move the box first along the x axis in the positive
// direction. If it doesn't find a good position for it there it will then move
// it along the x axis in the negative direction.
function findBestPosition(b, axis) {
var bestPosition,
specifiedPosition = new BoxPosition(b),
percentage = 1; // Highest possible so the first thing we get is better.
for (var i = 0; i < axis.length; i++) {
while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
(b.within(containerBox) && b.overlapsAny(boxPositions))) {
b.move(axis[i]);
}
// We found a spot where we aren't overlapping anything. This is our
// best position.
if (b.within(containerBox)) {
return b;
}
var p = b.intersectPercentage(containerBox);
// If we're outside the container box less then we were on our last try
// then remember this position as the best position.
if (percentage > p) {
bestPosition = new BoxPosition(b);
percentage = p;
}
// Reset the box position to the specified position.
b = new BoxPosition(specifiedPosition);
}
return bestPosition || specifiedPosition;
}
var boxPosition = new BoxPosition(styleBox),
cue = styleBox.cue,
linePos = computeLinePos(cue),
axis = [];
// If we have a line number to align the cue to.
if (cue.snapToLines) {
var size;
switch (cue.vertical) {
case "":
axis = [ "+y", "-y" ];
size = "height";
break;
case "rl":
axis = [ "+x", "-x" ];
size = "width";
break;
case "lr":
axis = [ "-x", "+x" ];
size = "width";
break;
}
var step = boxPosition.lineHeight,
position = step * Math.round(linePos),
maxPosition = containerBox[size] + step,
initialAxis = axis[0];
// If the specified intial position is greater then the max position then
// clamp the box to the amount of steps it would take for the box to
// reach the max position.
if (Math.abs(position) > maxPosition) {
position = position < 0 ? -1 : 1;
position *= Math.ceil(maxPosition / step) * step;
}
// If computed line position returns negative then line numbers are
// relative to the bottom of the video instead of the top. Therefore, we
// need to increase our initial position by the length or width of the
// video, depending on the writing direction, and reverse our axis directions.
if (linePos < 0) {
position += cue.vertical === "" ? containerBox.height : containerBox.width;
axis = axis.reverse();
}
// Move the box to the specified position. This may not be its best
// position.
boxPosition.move(initialAxis, position);
} else {
// If we have a percentage line value for the cue.
var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
switch (cue.lineAlign) {
case "middle":
linePos -= (calculatedPercentage / 2);
break;
case "end":
linePos -= calculatedPercentage;
break;
}
// Apply initial line position to the cue box.
switch (cue.vertical) {
case "":
styleBox.applyStyles({
top: styleBox.formatStyle(linePos, "%")
});
break;
case "rl":
styleBox.applyStyles({
left: styleBox.formatStyle(linePos, "%")
});
break;
case "lr":
styleBox.applyStyles({
right: styleBox.formatStyle(linePos, "%")
});
break;
}
axis = [ "+y", "-x", "+x", "-y" ];
// Get the box position again after we've applied the specified positioning
// to it.
boxPosition = new BoxPosition(styleBox);
}
var bestPosition = findBestPosition(boxPosition, axis);
styleBox.move(bestPosition.toCSSCompatValues(containerBox));
}
function WebVTT() {
// Nothing
}
// Helper to allow strings to be decoded instead of the default binary utf8 data.
WebVTT.StringDecoder = function() {
return {
decode: function(data) {
if (!data) {
return "";
}
if (typeof data !== "string") {
throw new Error("Error - expected string data.");
}
return decodeURIComponent(encodeURIComponent(data));
}
};
};
WebVTT.convertCueToDOMTree = function(window, cuetext) {
if (!window || !cuetext) {
return null;
}
return parseContent(window, cuetext);
};
var FONT_SIZE_PERCENT = 0.05;
var FONT_STYLE = "sans-serif";
var CUE_BACKGROUND_PADDING = "1.5%";
// Runs the processing model over the cues and regions passed to it.
// @param overlay A block level element (usually a div) that the computed cues
// and regions will be placed into.
WebVTT.processCues = function(window, cues, overlay) {
if (!window || !cues || !overlay) {
return null;
}
// Remove all previous children.
while (overlay.firstChild) {
overlay.removeChild(overlay.firstChild);
}
var paddedOverlay = window.document.createElement("div");
paddedOverlay.style.position = "absolute";
paddedOverlay.style.left = "0";
paddedOverlay.style.right = "0";
paddedOverlay.style.top = "0";
paddedOverlay.style.bottom = "0";
paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
overlay.appendChild(paddedOverlay);
// Determine if we need to compute the display states of the cues. This could
// be the case if a cue's state has been changed since the last computation or
// if it has not been computed yet.
function shouldCompute(cues) {
for (var i = 0; i < cues.length; i++) {
if (cues[i].hasBeenReset || !cues[i].displayState) {
return true;
}
}
return false;
}
// We don't need to recompute the cues' display states. Just reuse them.
if (!shouldCompute(cues)) {
for (var i = 0; i < cues.length; i++) {
paddedOverlay.appendChild(cues[i].displayState);
}
return;
}
var boxPositions = [],
containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
var styleOptions = {
font: fontSize + "px " + FONT_STYLE
};
(function() {
var styleBox, cue;
for (var i = 0; i < cues.length; i++) {
cue = cues[i];
// Compute the intial position and styles of the cue div.
styleBox = new CueStyleBox(window, cue, styleOptions);
paddedOverlay.appendChild(styleBox.div);
// Move the cue div to it's correct line position.
moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
// Remember the computed div so that we don't have to recompute it later
// if we don't have too.
cue.displayState = styleBox.div;
boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
}
})();
};
WebVTT.Parser = function(window, vttjs, decoder) {
if (!decoder) {
decoder = vttjs;
vttjs = {};
}
if (!vttjs) {
vttjs = {};
}
this.window = window;
this.vttjs = vttjs;
this.state = "INITIAL";
this.buffer = "";
this.decoder = decoder || new TextDecoder("utf8");
this.regionList = [];
};
WebVTT.Parser.prototype = {
// If the error is a ParsingError then report it to the consumer if
// possible. If it's not a ParsingError then throw it like normal.
reportOrThrowError: function(e) {
if (e instanceof ParsingError) {
this.onparsingerror && this.onparsingerror(e);
} else {
throw e;
}
},
parse: function (data) {
var self = 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.
self.buffer += self.decoder.decode(data, {stream: true});
}
function collectNextLine() {
var buffer = self.buffer;
var pos = 0;
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;
}
self.buffer = buffer.substr(pos);
return line;
}
// 3.4 WebVTT region and WebVTT region settings syntax
function parseRegion(input) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "id":
settings.set(k, v);
break;
case "width":
settings.percent(k, v);
break;
case "lines":
settings.integer(k, v);
break;
case "regionanchor":
case "viewportanchor":
var xy = v.split(',');
if (xy.length !== 2) {
break;
}
// We have to make sure both x and y parse, so use a temporary
// settings object here.
var anchor = new Settings();
anchor.percent("x", xy[0]);
anchor.percent("y", xy[1]);
if (!anchor.has("x") || !anchor.has("y")) {
break;
}
settings.set(k + "X", anchor.get("x"));
settings.set(k + "Y", anchor.get("y"));
break;
case "scroll":
settings.alt(k, v, ["up"]);
break;
}
}, /=/, /\s/);
// Create the region, using default values for any values that were not
// specified.
if (settings.has("id")) {
var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
region.width = settings.get("width", 100);
region.lines = settings.get("lines", 3);
region.regionAnchorX = settings.get("regionanchorX", 0);
region.regionAnchorY = settings.get("regionanchorY", 100);
region.viewportAnchorX = settings.get("viewportanchorX", 0);
region.viewportAnchorY = settings.get("viewportanchorY", 100);
region.scroll = settings.get("scroll", "");
// Register the region.
self.onregion && self.onregion(region);
// Remember the VTTRegion for later in case we parse any VTTCues that
// reference it.
self.regionList.push({
id: settings.get("id"),
region: region
});
}
}
// draft-pantos-http-live-streaming-20
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
// 3.5 WebVTT
function parseTimestampMap(input) {
var settings = new Settings();
parseOptions(input, function(k, v) {
switch(k) {
case "MPEGT":
settings.integer(k + 'S', v);
break;
case "LOCA":
settings.set(k + 'L', parseTimeStamp(v));
break;
}
}, /[^\d]:/, /,/);
self.ontimestampmap && self.ontimestampmap({
"MPEGTS": settings.get("MPEGTS"),
"LOCAL": settings.get("LOCAL")
});
}
// 3.2 WebVTT metadata header syntax
function parseHeader(input) {
if (input.match(/X-TIMESTAMP-MAP/)) {
// This line contains HLS X-TIMESTAMP-MAP metadata
parseOptions(input, function(k, v) {
switch(k) {
case "X-TIMESTAMP-MAP":
parseTimestampMap(v);
break;
}
}, /=/);
} else {
parseOptions(input, function (k, v) {
switch (k) {
case "Region":
// 3.3 WebVTT region metadata header syntax
parseRegion(v);
break;
}
}, /:/);
}
}
// 5.1 WebVTT file parsing.
try {
var line;
if (self.state === "INITIAL") {
// We can't start parsing until we have the first line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
line = collectNextLine();
var m = line.match(/^WEBVTT([ \t].*)?$/);
if (!m || !m[0]) {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
self.state = "HEADER";
}
var alreadyCollectedLine = false;
while (self.buffer) {
// We can't parse a line until we have the full line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
if (!alreadyCollectedLine) {
line = collectNextLine();
} else {
alreadyCollectedLine = false;
}
switch (self.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).
self.state = "ID";
}
continue;
case "NOTE":
// Ignore NOTE blocks.
if (!line) {
self.state = "ID";
}
continue;
case "ID":
// Check for the start of NOTE blocks.
if (/^NOTE($|[ \t])/.test(line)) {
self.state = "NOTE";
break;
}
// 19-29 - Allow any number of line terminators, then initialize new cue values.
if (!line) {
continue;
}
self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
self.state = "CUE";
// 30-39 - Check if self line contains an optional identifier or timing data.
if (line.indexOf("-->") === -1) {
self.cue.id = line;
continue;
}
// Process line as start of a cue.
/*falls through*/
case "CUE":
// 40 - Collect cue timings and settings.
try {
parseCue(line, self.cue, self.regionList);
} catch (e) {
self.reportOrThrowError(e);
// In case of an error ignore rest of the cue.
self.cue = null;
self.state = "BADCUE";
continue;
}
self.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.
self.oncue && self.oncue(self.cue);
self.cue = null;
self.state = "ID";
continue;
}
if (self.cue.text) {
self.cue.text += "\n";
}
self.cue.text += line;
continue;
case "BADCUE": // BADCUE
// 54-62 - Collect and discard the remaining cue.
if (!line) {
self.state = "ID";
}
continue;
}
}
} catch (e) {
self.reportOrThrowError(e);
// If we are currently parsing a cue, report what we have.
if (self.state === "CUETEXT" && self.cue && self.oncue) {
self.oncue(self.cue);
}
self.cue = null;
// Enter BADWEBVTT state if header was not parsed correctly otherwise
// another exception occurred so enter BADCUE state.
self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
}
return this;
},
flush: function () {
var self = this;
try {
// Finish decoding the stream.
self.buffer += self.decoder.decode();
// Synthesize the end of the current cue or region.
if (self.cue || self.state === "HEADER") {
self.buffer += "\n\n";
self.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 (self.state === "INITIAL") {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
} catch(e) {
self.reportOrThrowError(e);
}
self.onflush && self.onflush();
return this;
}
};
module.exports = WebVTT;
/***/ }),
/* 140 */
/***/ (function(module, 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.
*/
var autoKeyword = "auto";
var directionSetting = {
"": true,
"lr": true,
"rl": true
};
var alignSetting = {
"start": true,
"middle": true,
"end": true,
"left": true,
"right": true
};
function findDirectionSetting(value) {
if (typeof value !== "string") {
return false;
}
var dir = directionSetting[value.toLowerCase()];
return dir ? value.toLowerCase() : false;
}
function findAlignSetting(value) {
if (typeof value !== "string") {
return false;
}
var align = alignSetting[value.toLowerCase()];
return align ? value.toLowerCase() : false;
}
function extend(obj) {
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 isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var baseObj = {};
if (isIE8) {
cue = document.createElement('custom');
} else {
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() {
return _id;
},
set: function(value) {
_id = "" + value;
}
}));
Object.defineProperty(cue,
"pauseOnExit", extend({}, baseObj, {
get: function() {
return _pauseOnExit;
},
set: function(value) {
_pauseOnExit = !!value;
}
}));
Object.defineProperty(cue,
"startTime", extend({}, baseObj, {
get: function() {
return _startTime;
},
set: function(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() {
return _endTime;
},
set: function(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() {
return _text;
},
set: function(value) {
_text = "" + value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"region", extend({}, baseObj, {
get: function() {
return _region;
},
set: function(value) {
_region = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"vertical", extend({}, baseObj, {
get: function() {
return _vertical;
},
set: function(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() {
return _snapToLines;
},
set: function(value) {
_snapToLines = !!value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"line", extend({}, baseObj, {
get: function() {
return _line;
},
set: function(value) {
if (typeof value !== "number" && value !== autoKeyword) {
throw new SyntaxError("An invalid number or illegal string was specified.");
}
_line = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"lineAlign", extend({}, baseObj, {
get: function() {
return _lineAlign;
},
set: function(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() {
return _position;
},
set: function(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() {
return _positionAlign;
},
set: function(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() {
return _size;
},
set: function(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() {
return _align;
},
set: function(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;
if (isIE8) {
return cue;
}
}
/**
* VTTCue methods
*/
VTTCue.prototype.getCueAsHTML = function() {
// Assume WebVTT.convertCueToDOMTree is on the global.
return WebVTT.convertCueToDOMTree(window, this.text);
};
module.exports = VTTCue;
/***/ }),
/* 141 */
/***/ (function(module, 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.
*/
var scrollSetting = {
"": true,
"up": true
};
function findScrollSetting(value) {
if (typeof value !== "string") {
return false;
}
var scroll = scrollSetting[value.toLowerCase()];
return scroll ? value.toLowerCase() : false;
}
function isValidPercentValue(value) {
return typeof value === "number" && (value >= 0 && value <= 100);
}
// VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
function VTTRegion() {
var _width = 100;
var _lines = 3;
var _regionAnchorX = 0;
var _regionAnchorY = 100;
var _viewportAnchorX = 0;
var _viewportAnchorY = 100;
var _scroll = "";
Object.defineProperties(this, {
"width": {
enumerable: true,
get: function() {
return _width;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("Width must be between 0 and 100.");
}
_width = value;
}
},
"lines": {
enumerable: true,
get: function() {
return _lines;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("Lines must be set to a number.");
}
_lines = value;
}
},
"regionAnchorY": {
enumerable: true,
get: function() {
return _regionAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("RegionAnchorX must be between 0 and 100.");
}
_regionAnchorY = value;
}
},
"regionAnchorX": {
enumerable: true,
get: function() {
return _regionAnchorX;
},
set: function(value) {
if(!isValidPercentValue(value)) {
throw new Error("RegionAnchorY must be between 0 and 100.");
}
_regionAnchorX = value;
}
},
"viewportAnchorY": {
enumerable: true,
get: function() {
return _viewportAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorY must be between 0 and 100.");
}
_viewportAnchorY = value;
}
},
"viewportAnchorX": {
enumerable: true,
get: function() {
return _viewportAnchorX;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorX must be between 0 and 100.");
}
_viewportAnchorX = value;
}
},
"scroll": {
enumerable: true,
get: function() {
return _scroll;
},
set: function(value) {
var setting = findScrollSetting(value);
// Have to check for false as an empty string is a legal value.
if (setting === false) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_scroll = setting;
}
}
});
}
module.exports = VTTRegion;
/***/ }),
/* 142 */
/***/ (function(module, exports) {
module.exports = {"_args":[["videojs-swf@5.4.1","/home/esokia-6/work/work41/Phraseanet/Phraseanet-production-client"]],"_from":"videojs-swf@5.4.1","_id":"videojs-swf@5.4.1","_inBundle":false,"_integrity":"sha1-IHfvccdJ8seCPvSbq65N0qywj4c=","_location":"/videojs-swf","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"videojs-swf@5.4.1","name":"videojs-swf","escapedName":"videojs-swf","rawSpec":"5.4.1","saveSpec":null,"fetchSpec":"5.4.1"},"_requiredBy":["/videojs-flash"],"_resolved":"https://registry.npmjs.org/videojs-swf/-/videojs-swf-5.4.1.tgz","_spec":"5.4.1","_where":"/home/esokia-6/work/work41/Phraseanet/Phraseanet-production-client","author":{"name":"Brightcove"},"bugs":{"url":"https://github.com/videojs/video-js-swf/issues"},"copyright":"Copyright 2014 Brightcove, Inc. https://github.com/videojs/video-js-swf/blob/master/LICENSE","description":"The Flash-fallback video player for video.js (http://videojs.com)","devDependencies":{"async":"~0.2.9","chg":"^0.3.2","flex-sdk":"4.6.0-0","grunt":"~0.4.0","grunt-bumpup":"~0.5.0","grunt-cli":"~0.1.0","grunt-connect":"~0.2.0","grunt-contrib-jshint":"~0.4.3","grunt-contrib-qunit":"~0.2.1","grunt-contrib-watch":"~0.1.4","grunt-npm":"~0.0.2","grunt-prompt":"~0.1.2","grunt-shell":"~0.6.1","grunt-tagrelease":"~0.3.1","qunitjs":"~1.12.0","video.js":"^5.9.2"},"homepage":"http://videojs.com","keywords":["flash","video","player"],"name":"videojs-swf","repository":{"type":"git","url":"git+https://github.com/videojs/video-js-swf.git"},"scripts":{"version":"chg release -y && grunt dist && git add -f dist/ && git add CHANGELOG.md"},"version":"5.4.1"}
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var thesaurusDatasource = function thesaurusDatasource(services) {
var configService = services.configService,
localeService = services.localeService,
recordEditorEvents = services.recordEditorEvents;
var $container = null;
var parentOptions = {};
var ETHSeeker = null;
var $editTextArea = void 0;
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, parentOptions = _options.parentOptions, $editTextArea = _options.$editTextArea, _options);
var cclicks = 0;
var cDelay = 350;
var cTimer = null;
$container.on('click', '.edit-thesaurus-action', function (event) {
event.preventDefault();
cclicks++;
if (cclicks === 1) {
cTimer = setTimeout(function () {
onSelectBranch(event);
cclicks = 0;
}, cDelay);
} else {
clearTimeout(cTimer);
onSelectTerm(event);
cclicks = 0;
}
}).on('dblclick', '.thesaurus-branch-action', function (event) {
// dbl is handled by click event
event.preventDefault();
});
ETHSeeker = new ThesaurusSeeker(parentOptions.sbas_id);
return ETHSeeker;
};
var searchValue = function searchValue(params) {
var event = params.event,
value = params.value,
field = params.field;
// ok a thesaurus branch match
if (field.tbranch !== undefined) {
return ETHSeeker.search(value);
}
};
function ThesaurusSeeker(sbas_id) {
this.jq = null;
this.sbas_id = sbas_id;
var zid = ('' + sbas_id).replace(new RegExp('\\.', 'g'), '\\.') + '\\.T';
this.TH_P_node = (0, _jquery2.default)('#TH_P\\.' + zid, parentOptions.$container);
this.TH_K_node = (0, _jquery2.default)('#TH_K\\.' + zid, parentOptions.$container);
this._ctimer = null;
this.search = function (txt) {
if (this._ctimer) {
clearTimeout(this._ctimer);
}
this._ctimer = setTimeout(function () {
return ETHSeeker.search_delayed('"' + txt.replace("'", "\\'") + '"');
}, 125);
};
this.search_delayed = function (txt) {
if (this.jq && typeof this.jq.abort === 'function') {
this.jq.abort();
this.jq = null;
}
txt = txt.replace("'", "\\'");
var url = '/xmlhttp/openbranches_prod.h.php';
var parms = {
bid: this.sbas_id,
lng: localeService.getLocale(),
t: txt,
mod: 'TREE',
u: Math.random()
};
var me = this;
this.jq = _jquery2.default.ajax({
url: url,
data: parms,
type: 'POST',
success: function success(ret) {
me.TH_P_node.html('...');
me.TH_K_node.attr('class', 'h').html(ret);
me.jq = null;
}
});
};
this.openBranch = function (id, thid) {
if (this.jq) {
this.jq.abort();
this.jq = null;
}
var url = '/xmlhttp/getterm_prod.h.php';
var parms = {
bid: this.sbas_id,
lng: localeService.getLocale(),
sortsy: 1,
id: thid,
typ: 'TH'
};
var me = this;
this.jq = _jquery2.default.ajax({
url: url,
data: parms,
success: function success(ret) {
var zid = '#TH_K\\.' + id.replace(new RegExp('\\.', 'g'), '\\.'); // escape les '.' pour jquery
(0, _jquery2.default)(zid, parentOptions.$container).html(ret);
me.jq = null;
}
});
};
}
// onclick dans le thesaurus
function onSelectBranch(event) {
var e = void 0;
for (e = event.srcElement ? event.srcElement : event.target; e && (!e.tagName || !e.id); e = e.parentNode) {}
if (e) {
switch (e.id.substr(0, 4)) {
case 'TH_P':
// +/- de deploiement de mot
toggleBranch(e.id.substr(5));
break;
default:
}
}
return false;
}
// ondblclick dans le thesaurus
function onSelectTerm(event) {
var e = void 0;
for (e = event.srcElement ? event.srcElement : event.target; e && (!e.tagName || !e.id); e = e.parentNode) {}
if (e) {
switch (e.id.substr(0, 4)) {
case 'TH_W':
var currentFieldIndex = parentOptions.fieldCollection.getActiveFieldIndex();
if (currentFieldIndex >= 0) {
var w = (0, _jquery2.default)(e).text();
recordEditorEvents.emit('recordEditor.addValueFromDataSource', { value: w });
}
break;
default:
}
}
return false;
}
// on ouvre ou ferme une branche de thesaurus
function toggleBranch(id) {
var o = document.getElementById('TH_K.' + id);
if (o.className === 'o') {
// on ferme
o.className = 'c';
document.getElementById('TH_P.' + id).innerHTML = '+';
document.getElementById('TH_K.' + id).innerHTML = localeService.t('loading');
} else if (o.className === 'c' || o.className === 'h') {
// on ouvre
o.className = 'o';
document.getElementById('TH_P.' + id).innerHTML = '-';
var t_id = id.split('.');
var sbas_id = t_id[0];
t_id.shift();
var thid = t_id.join('.');
var url = '/xmlhttp/getterm_prod.x.php';
var parms = 'bid=' + sbas_id;
parms += '&lng=' + localeService.getLocale();
parms += '&sortsy=1';
parms += '&id=' + thid;
parms += '&typ=TH';
ETHSeeker.openBranch(id, thid);
}
return false;
}
recordEditorEvents.listenAll({
'recordEditor.userInputValue': searchValue
});
return { initialize: initialize };
};
exports.default = thesaurusDatasource;
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(38);
var geonameDatasource = function geonameDatasource(services) {
var configService = services.configService,
localeService = services.localeService,
recordEditorEvents = services.recordEditorEvents;
var tabContainerName = 'geonameTabContainer';
var autoActivateTabOnce = true;
var $container = null;
var parentOptions = {};
var $editTextArea = void 0;
var $tabContent = void 0;
var geonamesFieldMapping = false;
var cityFields = [];
var provinceFields = [];
var countryFields = [];
var latitudeFields = [];
var longitudeFields = [];
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, parentOptions = _options.parentOptions, $editTextArea = _options.$editTextArea, _options);
var geocodingProviders = configService.get('geocodingProviders');
_underscore2.default.each(geocodingProviders, function (provider) {
//geoname field mapping
if (provider['geonames-field-mapping'] == true) {
if (provider['cityfields']) {
cityFields = provider['cityfields'].split(',').map(function (item) {
return item.trim();
});
}
if (provider['provincefields']) {
provinceFields = provider['provincefields'].split(',').map(function (item) {
return item.trim();
});
}
if (provider['countryfields']) {
countryFields = provider['countryfields'].split(',').map(function (item) {
return item.trim();
});
}
if (provider['latitudefields']) {
latitudeFields = provider['latitudefields'].split(',').map(function (item) {
return item.trim();
});
}
if (provider['longitudefields']) {
longitudeFields = provider['longitudefields'].split(',').map(function (item) {
return item.trim();
});
}
}
});
recordEditorEvents.emit('appendTab', {
tabProperties: {
id: tabContainerName,
title: localeService.t('Geoname Datasource')
},
position: 1
});
// reset for each fields
autoActivateTabOnce = true;
};
var onTabAdded = function onTabAdded(params) {
var origParams = params.origParams;
if (origParams.tabProperties.id === tabContainerName) {
$tabContent = (0, _jquery2.default)('#' + tabContainerName, $container);
bindEvents();
}
};
var bindEvents = function bindEvents() {
var cclicks = 0;
var cDelay = 350;
var cTimer = null;
$tabContent.on('click', '.geoname-add-action', function (event) {
event.preventDefault();
cclicks++;
if (cclicks === 1) {
cTimer = setTimeout(function () {
cclicks = 0;
}, cDelay);
} else {
clearTimeout(cTimer);
onSelectValue(event);
cclicks = 0;
}
});
};
var onSelectValue = function onSelectValue(event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var value = $el.data('city');
// the field may have changed over time
var field = parentOptions.fieldCollection.getActiveField();
switch (field.name) {
case 'City':
value = $el.data('city');
break;
case 'Country':
value = $el.data('country');
break;
case 'Province':
value = $el.data('province');
break;
case 'Longitude':
value = $el.data('longitude');
break;
case 'Latitude':
value = $el.data('latitude');
break;
default:
break;
}
// send prefill instruction for related fields:
// send data for all geo fields (same as preset API)
var fields = {};
var presets = {};
_underscore2.default.each(cityFields, function (field) {
fields[field] = [$el.data('city')];
});
_underscore2.default.each(provinceFields, function (field) {
fields[field] = [$el.data('province')];
});
_underscore2.default.each(countryFields, function (field) {
fields[field] = [$el.data('country')];
});
(0, _jquery2.default)("#dialog-edit_lat_lon").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
confirmYes: function confirmYes() {
(0, _jquery2.default)(this).dialog("close");
_underscore2.default.each(latitudeFields, function (field) {
fields[field] = [String($el.data('latitude'))];
});
_underscore2.default.each(longitudeFields, function (field) {
fields[field] = [String($el.data('longitude'))];
});
presets.fields = fields;
recordEditorEvents.emit('recordEditor.addPresetValuesFromDataSource', { data: presets, mode: '' });
// force update on current field:
recordEditorEvents.emit('recordEditor.addValueFromDataSource', { value: value, field: field });
console.log('Lat & Lon updated');
},
confirmNo: function confirmNo() {
presets.fields = fields;
recordEditorEvents.emit('recordEditor.addPresetValuesFromDataSource', { data: presets, mode: '' });
// force update on current field:
recordEditorEvents.emit('recordEditor.addValueFromDataSource', { value: value, field: field });
(0, _jquery2.default)(this).dialog("close");
}
},
open: function open() {
(0, _jquery2.default)('.ui-button-text:contains(confirmYes)').html((0, _jquery2.default)('#dialog-edit-yes').val());
(0, _jquery2.default)('.ui-button-text:contains(confirmNo)').html((0, _jquery2.default)('#dialog-edit-no').val());
},
close: function close() {}
});
};
var highlight = function highlight(s, t) {
if (t === '') {
return s;
}
var matcher = new RegExp('(' + t + ')', 'ig');
return s.replace(matcher, '<span class="ui-state-highlight">$1</span>');
};
var searchValue = function searchValue(params) {
var event = params.event,
value = params.value,
field = params.field;
var datas = {
sort: '',
sortParams: '',
'client-ip': null,
country: '',
name: '',
limit: 20
};
var searchType = false;
var name = void 0;
var country = void 0;
var terms = value.split(',');
if (terms.length === 2) {
country = terms.pop();
}
name = terms.pop();
if (cityFields.filter(function (item) {
return item.toLowerCase() == field.name.toLowerCase();
}).length > 0) {
searchType = 'city';
datas.name = _jquery2.default.trim(name);
datas.country = _jquery2.default.trim(country);
} else if (provinceFields.filter(function (item) {
return item.toLowerCase() == field.name.toLowerCase();
}).length > 0) {
// @TODO - API can't search by region/province
searchType = 'city';
datas.province = _jquery2.default.trim(name);
// datas.country = $.trim(country);
} else if (countryFields.filter(function (item) {
return item.toLowerCase() == field.name.toLowerCase();
}).length > 0) {
searchType = 'city';
datas.country = _jquery2.default.trim(name);
// } else if (latitudeFields.filter(item => item.toLowerCase() == field.name.toLowerCase()).length > 0) {
// searchType = 'latitude';
// datas.latitude = $.trim(name);
}
if (searchType === false) {
return;
}
// switch tab only on the first search:
if (autoActivateTabOnce === true) {
recordEditorEvents.emit('recordEditor.activateToolTab', tabContainerName);
autoActivateTabOnce = false;
}
fetchGeoname(searchType, datas, function (jqXhr, status, error) {
if (jqXhr.status !== 0 && jqXhr.statusText !== 'abort') {
console.log('error occured', [jqXhr, status, error]);
}
}, function (data) {
return data;
});
};
var fetchGeoname = function fetchGeoname(resource, datas, errorCallback, parseresults) {
var url = configService.get('geonameServerUrl');
url = url.substr(url.length - 1) === '/' ? url : url + '/';
return _jquery2.default.ajax({
url: url + resource,
data: datas,
dataType: 'jsonp',
jsonpCallback: 'parseresults',
success: function success(data) {
var template = '';
_underscore2.default.map(data || [], function (item) {
var matchWith = datas.name !== '' ? datas.name : datas.country;
var labelName = highlight(item.name, matchWith);
var labelCountry = highlight(item.country ? item.country.name || '' : '', matchWith);
var regionName = item.region ? item.region.name || '' : '';
var labelRegion = highlight(regionName, name);
var location = {
value: labelName + (labelRegion !== '' ? ', <span class="region">' + labelRegion + '</span>' : ''),
label: labelCountry !== '' ? labelCountry : '',
geonameid: item.geonameid
};
template += '\n <li class="geoname-add-action" data-city="' + item.name + '" data-country="' + item.country.name + '" data-province="' + regionName + '" data-latitude="' + item.location.latitude + '" data-longitude="' + item.location.longitude + '"><p>\n <span>' + location.value + '</span>\n <br>\n <span>' + location.label + '</span></p>\n </li>';
});
$tabContent.empty().append('<ul class="geoname-results">' + template + '</ul>');
},
error: function error(xhr, status, _error) {
console.log(status + '; ' + _error);
}
});
};
recordEditorEvents.listenAll({
'appendTab.complete': onTabAdded,
'recordEditor.userInputValue': searchValue
});
return { initialize: initialize };
};
exports.default = geonameDatasource;
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var markerCollection = function markerCollection(services) {
var configService = services.configService,
localeService = services.localeService,
eventEmitter = services.eventEmitter;
var markerCollection = {};
var cachedGeoJson = void 0;
var featureLayer = void 0;
var map = void 0;
var geoJsonPoiCollection = void 0;
var editable = void 0;
var initialize = function initialize(params) {
var _params;
var initWith = (_params = params, map = _params.map, featureLayer = _params.featureLayer, geoJsonPoiCollection = _params.geoJsonPoiCollection, _params);
editable = params.editable || false;
setCollection(geoJsonPoiCollection);
};
var setCollection = function setCollection(geoJsonPoiCollection) {
featureLayer.setGeoJSON(geoJsonPoiCollection);
cachedGeoJson = featureLayer.getGeoJSON();
featureLayer.eachLayer(function (layer) {
setMarkerPopup(layer);
});
};
var triggerRefresh = function triggerRefresh() {
setCollection(cachedGeoJson);
cachedGeoJson = featureLayer.getGeoJSON();
};
var setMarkerPopup = function setMarkerPopup(marker) {
switch (marker.feature.geometry.type) {
case 'Polygon':
break;
case 'Point':
setPoint(marker);
break;
default:
}
};
var setPoint = function setPoint(marker) {
markerCollection[marker._leaflet_id] = marker;
var $content = (0, _jquery2.default)('<div style="min-width: 200px"/>');
var template = '<p>' + marker.feature.properties.title + '</p> ';
if (editable === true && marker.dragging !== undefined) {
template += '\n <div class="view-mode">\n <button class="edit-position btn btn-inverse btn-small btn-block" data-marker-id="' + marker._leaflet_id + '">' + localeService.t('mapMarkerEdit') + '</button>\n </div>\n <div class="edit-mode">\n <p class="help">' + localeService.t('mapMarkerMoveLabel') + '</p>\n <p><span class="updated-position"></span></p>\n <div>\n <button class="cancel-position btn btn-inverse btn-small btn-block" data-marker-id="' + marker._leaflet_id + '">' + localeService.t('mapMarkerEditCancel') + '</button>\n <button class="submit-position btn btn-inverse btn-small btn-block" data-marker-id="' + marker._leaflet_id + '">' + localeService.t('mapMarkerEditSubmit') + '</button>\n </div>\n </div>';
}
$content.append(template);
$content.find('.edit-mode').hide();
$content.on('click', '.edit-position', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var marker = getMarker($el.data('marker-id'));
marker._originalPosition = marker.getLatLng().wrap();
marker.dragging.enable();
$content.find('.view-mode').hide();
$content.find('.edit-mode').show();
$content.find('.help').show();
});
$content.on('click', '.submit-position', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var marker = getMarker($el.data('marker-id'));
marker.dragging.disable();
$content.find('.view-mode').show();
$content.find('.help').hide();
$content.find('.edit-mode').hide();
marker._originalPosition = marker.getLatLng().wrap();
eventEmitter.emit('markerChange', { marker: marker, position: marker.getLatLng().wrap() });
});
$content.on('click', '.cancel-position', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var marker = getMarker($el.data('marker-id'));
marker.dragging.disable();
$content.find('.view-mode').show();
marker.setLatLng(marker._originalPosition);
triggerRefresh();
});
marker.bindPopup($content.get(0));
marker.on('dragend', function () {
var position = marker.getLatLng().wrap();
$content.find('.updated-position').html(position.lat + '<br>' + position.lng);
$content.find('.edit-mode').show();
marker.bindPopup($content.get(0));
marker.openPopup();
});
};
var getMarker = function getMarker(markerId) {
return markerCollection[markerId];
};
return {
initialize: initialize, setCollection: setCollection
};
};
exports.default = markerCollection;
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mapboxgl = __webpack_require__(66);
var markerGLCollection = function markerGLCollection(services) {
var configService = services.configService,
localeService = services.localeService,
eventEmitter = services.eventEmitter;
var markerCollection = {};
var cachedGeoJson = void 0;
var map = void 0;
var geojson = void 0;
var editable = void 0;
var isDraggable = false;
var isCursorOverPoint = false;
var isDragging = false;
var popup = {};
var popupDialog = void 0;
var initialize = function initialize(params) {
var _params;
var initWith = (_params = params, map = _params.map, geojson = _params.geojson, _params);
editable = params.editable || false;
setCollection(geojson);
};
var setCollection = function setCollection(geojson) {
cachedGeoJson = geojson;
geojson.features.forEach(function (marker) {
setMarkerPopup(marker);
});
};
var setMarkerPopup = function setMarkerPopup(marker) {
switch (marker.geometry.type) {
case 'Polygon':
break;
case 'Point':
setPoint(marker);
break;
default:
}
};
var setPoint = function setPoint(marker) {
var $content = (0, _jquery2.default)('<div style="min-width: 200px"/>');
var template = '<p>' + marker.properties.title + '</p> ';
if (editable === true) {
template += '\n <div class="view-mode">\n <button class="edit-position btn btn-inverse btn-small btn-block" data-marker-id="' + marker.properties.recordIndex + '">' + localeService.t('mapMarkerEdit') + '</button>\n </div>\n <div class="edit-mode">\n <p class="help" style="font-size: 12px;font-style: italic;">' + localeService.t('mapMarkerMoveLabel') + '</p>\n <p><span class="updated-position" style="font-size: 12px;"></span></p>\n <div>\n <button class="cancel-position btn btn-inverse btn-small btn-block" data-marker-id="' + marker.properties.recordIndex + '">' + localeService.t('mapMarkerEditCancel') + '</button>\n <button class="submit-position btn btn-inverse btn-small btn-block" data-marker-id="' + marker.properties.recordIndex + '">' + localeService.t('mapMarkerEditSubmit') + '</button>\n </div>\n </div>';
}
$content.append(template);
$content.find('.edit-mode').hide();
//
$content.on('click', '.edit-position', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var marker = getMarker($el.data('marker-id'));
marker._originalPosition = marker.lngLat.wrap();
$content.find('.view-mode').hide();
$content.find('.edit-mode').show();
$content.find('.help').show();
isDraggable = true;
map.on('mousedown', mouseDown);
});
$content.on('click', '.submit-position', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var marker = getMarker($el.data('marker-id'));
isDraggable = false;
$content.find('.view-mode').show();
$content.find('.help').hide();
$content.find('.updated-position').html('');
$content.find('.edit-mode').hide();
var popup = document.getElementsByClassName('mapboxgl-popup');
if (popup[0]) popup[0].parentElement.removeChild(popup[0]);
marker.lngLat = {
lng: cachedGeoJson.features[0].geometry.coordinates[0],
lat: cachedGeoJson.features[0].geometry.coordinates[1]
};
marker.feature = marker.features[0];
eventEmitter.emit('markerChange', { marker: marker, position: marker.lngLat });
});
$content.on('click', '.cancel-position', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var marker = getMarker($el.data('marker-id'));
isDraggable = false;
$content.find('.view-mode').show();
$content.find('.updated-position').html('');
$content.find('.edit-mode').hide();
$content.find('.help').hide();
var popup = document.getElementsByClassName('mapboxgl-popup');
if (popup[0]) popup[0].parentElement.removeChild(popup[0]);
cachedGeoJson.features[0].geometry.coordinates = [marker._originalPosition.lng, marker._originalPosition.lat];
map.getSource('data').setData(cachedGeoJson);
});
// When the cursor enters a feature in the point layer, prepare for dragging.
map.on('mouseenter', 'points', function () {
if (!isDraggable) {
return;
}
map.getCanvas().style.cursor = 'move';
isCursorOverPoint = true;
map.dragPan.disable();
});
map.on('mouseleave', 'points', function () {
if (!isDraggable) {
return;
}
map.getCanvas().style.cursor = '';
isCursorOverPoint = false;
map.dragPan.enable();
});
map.on('click', 'points', function (e) {
markerCollection[e.features[0].properties.recordIndex] = e;
var coordinates = e.features[0].geometry.coordinates.slice();
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
var popup = document.getElementsByClassName('mapboxgl-popup');
// Check if there is already a popup on the map and if so, remove it
if (popup[0]) popup[0].parentElement.removeChild(popup[0]);
popupDialog = new mapboxgl.Popup({ closeOnClick: false }).setLngLat(coordinates).setDOMContent($content.get(0)).addTo(map);
popupDialog.on('close', function (event) {
if (editable) {
resetMarkerPosition($content);
}
});
});
function mouseDown() {
if (!isCursorOverPoint) return;
isDragging = true;
// Set a cursor indicator
map.getCanvas().style.cursor = 'grab';
// Mouse events
map.on('mousemove', onMove);
map.once('mouseup', onUp);
var popup = document.getElementsByClassName('mapboxgl-popup');
if (popup[0]) popup[0].parentElement.removeChild(popup[0]);
}
function onMove(e) {
if (!isDragging) return;
var coords = e.lngLat;
// Set a UI indicator for dragging.
map.getCanvas().style.cursor = 'grabbing';
// Update the Point feature in `geojson` coordinates
// and call setData to the source layer `point` on it.
cachedGeoJson.features[0].geometry.coordinates = [coords.lng, coords.lat];
map.getSource('data').setData(cachedGeoJson);
}
function onUp(e) {
if (!isDragging) return;
var position = e.lngLat;
map.getCanvas().style.cursor = '';
isDragging = false;
// Unbind mouse events
map.off('mousemove', onMove);
$content.find('.updated-position').html(position.lat + '<br>' + position.lng);
popupDialog = new mapboxgl.Popup({ closeOnClick: false }).setLngLat(position).setDOMContent($content.get(0)).addTo(map);
popupDialog.on('close', function (event) {
if (editable) {
resetMarkerPosition($content);
}
});
}
};
var resetMarkerPosition = function resetMarkerPosition($content) {
var marker = getMarker($content.find('.edit-position').data('marker-id'));
$content.find('.view-mode').show();
$content.find('.updated-position').html('');
$content.find('.edit-mode').hide();
$content.find('.help').hide();
isDraggable = false;
if (marker._originalPosition !== undefined) {
cachedGeoJson.features[0].geometry.coordinates = [marker._originalPosition.lng, marker._originalPosition.lat];
map.getSource('data').setData(cachedGeoJson);
}
};
var getMarker = function getMarker(markerId) {
return markerCollection[markerId];
};
return {
initialize: initialize, setCollection: setCollection
};
};
exports.default = markerGLCollection;
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Set a provider
*
*/
var provider = function provider(services) {
var configService = services.configService,
localeService = services.localeService,
eventEmitter = services.eventEmitter;
var accessToken = void 0;
var defaultPosition = void 0;
var defaultZoom = void 0;
var markerDefaultZoom = void 0;
var activeProvider = void 0;
var fieldPosition = void 0;
var defaultMapProvider = void 0;
var transitionOptions = Object.create(null);
var mapLayers = [{ name: 'streets', value: 'mapbox://styles/mapbox/streets-v9' }];
var initialize = function initialize() {
var isValid = false;
// select geocoding provider:
var geocodingProviders = configService.get('geocodingProviders');
_underscore2.default.each(geocodingProviders, function (provider) {
if (provider.enabled === true) {
activeProvider = provider;
accessToken = provider['public-key'];
var fieldMapping = provider['position-fields'] !== undefined ? provider['position-fields'] : [];
fieldPosition = {};
if (fieldMapping.length > 0) {
_underscore2.default.each(fieldMapping, function (mapping) {
// latitude and longitude are combined in a composite field
if (mapping.type === 'latlng') {
fieldPosition = {
latitude: function latitude(poi) {
return extractFromPosition('lat', poi[mapping.name]);
},
longitude: function longitude(poi) {
return extractFromPosition('lon', poi[mapping.name]);
}
};
} else if (mapping.type === 'lat') {
// if latitude field mapping is provided, fallback:
fieldPosition.latitude = function (poi) {
return isNaN(parseFloat(poi[mapping.name], 10)) ? false : parseFloat(poi[mapping.name], 10);
};
} else if (mapping.type === 'lon') {
// if longitude field mapping is provided, fallback:
fieldPosition.longitude = function (poi) {
return isNaN(parseFloat(poi[mapping.name], 10)) ? false : parseFloat(poi[mapping.name], 10);
};
}
});
if (fieldPosition.latitude !== undefined && fieldPosition.longitude !== undefined) {
isValid = true;
}
} else {
fieldPosition = {
latitude: function latitude(poi) {
return getCoordinatesFromTechnicalInfo(poi, 'lat');
},
longitude: function longitude(poi) {
return getCoordinatesFromTechnicalInfo(poi, 'lng');
}
};
isValid = true;
}
// set default values:
var defaultPositionValue = $('#map-position-from-setting').val();
if (defaultPositionValue != '') {
defaultPositionValue = defaultPositionValue.split('"');
var arr = [];
arr.push(defaultPositionValue[1]);
arr.push(defaultPositionValue[3]);
defaultPosition = arr;
} else {
defaultPosition = provider['default-position'];
}
defaultZoom = $('#map-zoom-from-setting').val() != '' ? $('#map-zoom-from-setting').val() : provider['default-zoom'] || 2;
markerDefaultZoom = provider['marker-default-zoom'] || 12;
defaultMapProvider = provider['map-provider'] || "mapboxWebGL";
if (provider['map-layers'] && provider['map-layers'].length > 0) {
//update map layer;
mapLayers = provider['map-layers'];
}
if (provider['transition-mapboxgl'] !== undefined) {
var options = provider['transition-mapboxgl'][0] || [];
transitionOptions.animate = options['animate'] !== undefined ? options['animate'] : true;
transitionOptions.speed = options['speed'] || 1.2;
transitionOptions.curve = options['curve'] || 1.42;
}
}
});
if (accessToken === undefined) {
isValid = false;
}
return isValid;
};
var getCoordinatesFromTechnicalInfo = function getCoordinatesFromTechnicalInfo(poi, fieldMapping) {
if (poi["technicalInfo"] !== undefined) {
if (fieldMapping == 'lat') {
return isNaN(parseFloat(poi["technicalInfo"].latitude, 10)) ? false : parseFloat(poi["technicalInfo"].latitude, 10);
} else {
return isNaN(parseFloat(poi["technicalInfo"].longitude, 10)) ? false : parseFloat(poi["technicalInfo"].longitude, 10);
}
}
return false;
};
/**
* extract latitude or longitude from a position
* @param name
* @param source
* @returns {*}
*/
var extractFromPosition = function extractFromPosition(name, source) {
if (source === undefined || source === null) {
return false;
}
var position = source.split(' ');
if (position.length !== 2) {
position = source.split(',');
}
// ok parse lat
if (position.length === 2) {
if (name === 'lat' || name === 'latitude') {
return parseFloat(position[0]);
}
return parseFloat(position[1]);
} else {
// invalid
return false;
}
};
var getConfiguration = function getConfiguration() {
return {
defaultPosition: defaultPosition,
defaultZoom: defaultZoom,
markerDefaultZoom: markerDefaultZoom,
fieldPosition: fieldPosition,
accessToken: accessToken,
defaultMapProvider: defaultMapProvider,
mapLayers: mapLayers,
provider: activeProvider,
transitionOptions: transitionOptions
};
};
return {
initialize: initialize, getConfiguration: getConfiguration
};
};
exports.default = provider;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var leafletLocaleFr = {
draw: {
toolbar: {
actions: {
title: 'Annulez le dessin',
text: 'Annuler'
},
finish: {
title: 'Terminer le dessin',
text: 'Terminer'
},
undo: {
title: 'Supprimer le dernier point',
text: 'Supprimer le dernier point'
},
buttons: {
polyline: 'Dessiner une polyligne',
polygon: 'Dessiner un polygone',
rectangle: 'Dessiner un rectangle',
circle: 'Dessiner un cercle',
marker: 'Dessiner un marqueur'
}
},
handlers: {
circle: {
tooltip: {
start: 'Cliquez et déplacez pour dessiner un cercle.'
}
},
marker: {
tooltip: {
start: 'Cliquez sur la carte pour placer un marqueur.'
}
},
polygon: {
tooltip: {
start: 'Cliquez pour commencer à dessiner une forme.',
cont: 'Cliquez pour continuer à dessiner une forme.',
end: 'Cliquez sur le dernier point pour fermer cette forme.'
}
},
polyline: {
error: '<strong>Erreur:</strong> Les arrêtes de la forme ne doivent pas se croiser!',
tooltip: {
start: 'Cliquez pour commencer à dessiner d\'une ligne.',
cont: 'Cliquez pour continuer à dessiner une ligne.',
end: 'Cliquez sur le dernier point pour terminer la ligne.'
}
},
rectangle: {
tooltip: {
start: 'Cliquez et déplacez pour dessiner un rectangle.'
}
},
simpleshape: {
tooltip: {
end: 'Relachez la souris pour finir de dessiner.'
}
}
}
},
edit: {
toolbar: {
actions: {
save: {
title: 'Sauvegardez les changements.',
text: 'Sauver'
},
cancel: {
title: 'Annulez l\'édition, ignorer tous les changements.',
text: 'Annuler'
}
},
buttons: {
edit: 'Editer les couches.',
editDisabled: 'Pas de couches à éditer.',
remove: 'Supprimer les couches.',
removeDisabled: 'Pas de couches à supprimer.'
}
},
handlers: {
edit: {
tooltip: {
text: 'Déplacez les ancres, ou le marqueur pour éditer l\'objet.',
subtext: 'Cliquez sur Annuler pour revenir sur les changements.'
}
},
remove: {
tooltip: {
text: 'Cliquez sur l\'objet à enlever'
}
}
}
}
};
exports.default = leafletLocaleFr;
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(150);
if(typeof content === 'string') content = [[module.i, content, '']];
// Prepare cssTransformation
var transform;
var options = {}
options.transform = transform
// add the styles to the DOM
var update = __webpack_require__(41)(content, options);
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!../../css-loader/index.js!./style.css", function() {
var newContent = require("!!../../css-loader/index.js!./style.css");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
var escape = __webpack_require__(67);
exports = module.exports = __webpack_require__(40)(false);
// imports
// module
exports.push([module.i, "/* general typography */\n.leaflet-container {\n background:#fff;\n font:12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;\n color:#404040;\n color:rgba(0,0,0,0.75);\n outline:0;\n overflow:hidden;\n -ms-touch-action:none;\n }\n\n.leaflet-container *,\n.leaflet-container *:after,\n.leaflet-container *:before {\n -webkit-box-sizing:border-box;\n -moz-box-sizing:border-box;\n box-sizing:border-box;\n }\n\n.leaflet-container h1,\n.leaflet-container h2,\n.leaflet-container h3,\n.leaflet-container h4,\n.leaflet-container h5,\n.leaflet-container h6,\n.leaflet-container p {\n font-size:15px;\n line-height:20px;\n margin:0 0 10px;\n }\n\n.leaflet-container .marker-description img {\n margin-bottom: 10px;\n }\n\n.leaflet-container a {\n color:#3887BE;\n font-weight:normal;\n text-decoration:none;\n }\n .leaflet-container a:hover { color:#63b6e5; }\n .leaflet-container.dark a { color:#63b6e5; }\n .leaflet-container.dark a:hover { color:#8fcaec; }\n\n.leaflet-container.dark .mapbox-button,\n.leaflet-container .mapbox-button {\n background-color:#3887be;\n display:inline-block;\n height:40px;\n line-height:40px;\n text-decoration:none;\n color:#fff;\n font-size:12px;\n white-space:nowrap;\n text-overflow:ellipsis;\n }\n .leaflet-container.dark .mapbox-button:hover,\n .leaflet-container .mapbox-button:hover {\n color:#fff;\n background-color:#3bb2d0;\n }\n\n/* Base Leaflet\n------------------------------------------------------- */\n.leaflet-map-pane,\n.leaflet-tile,\n.leaflet-marker-icon,\n.leaflet-marker-shadow,\n.leaflet-tile-pane,\n.leaflet-tile-container,\n.leaflet-overlay-pane,\n.leaflet-shadow-pane,\n.leaflet-marker-pane,\n.leaflet-popup-pane,\n.leaflet-overlay-pane svg,\n.leaflet-zoom-box,\n.leaflet-image-layer,\n.leaflet-layer {\n position:absolute;\n left:0;\n top:0;\n }\n\n.leaflet-tile,\n.leaflet-marker-icon,\n.leaflet-marker-shadow {\n -webkit-user-drag:none;\n -webkit-user-select:none;\n -moz-user-select:none;\n user-select:none;\n }\n.leaflet-marker-icon,\n.leaflet-marker-shadow {\n display: block;\n }\n\n.leaflet-tile {\n filter:inherit;\n visibility:hidden;\n }\n.leaflet-tile-loaded {\n visibility:inherit;\n }\n.leaflet-zoom-box {\n width:0;\n height:0;\n }\n\n.leaflet-tile-pane { z-index:2; }\n.leaflet-objects-pane { z-index:3; }\n.leaflet-overlay-pane { z-index:4; }\n.leaflet-shadow-pane { z-index:5; }\n.leaflet-marker-pane { z-index:6; }\n.leaflet-popup-pane { z-index:7; }\n\n.leaflet-control {\n position:relative;\n z-index:7;\n pointer-events:auto;\n float:left;\n clear:both;\n }\n .leaflet-right .leaflet-control { float:right; }\n .leaflet-top .leaflet-control { margin-top:10px; }\n .leaflet-bottom .leaflet-control { margin-bottom:10px; }\n .leaflet-left .leaflet-control { margin-left:10px; }\n .leaflet-right .leaflet-control { margin-right:10px; }\n\n.leaflet-top,\n.leaflet-bottom {\n position:absolute;\n z-index:1000;\n pointer-events:none;\n }\n .leaflet-top { top:0; }\n .leaflet-right { right:0; }\n .leaflet-bottom { bottom:0; }\n .leaflet-left { left:0; }\n\n/* zoom and fade animations */\n.leaflet-fade-anim .leaflet-tile,\n.leaflet-fade-anim .leaflet-popup {\n opacity:0;\n -webkit-transition:opacity 0.2s linear;\n -moz-transition:opacity 0.2s linear;\n -o-transition:opacity 0.2s linear;\n transition:opacity 0.2s linear;\n }\n .leaflet-fade-anim .leaflet-tile-loaded,\n .leaflet-fade-anim .leaflet-map-pane .leaflet-popup {\n opacity:1;\n }\n\n.leaflet-zoom-anim .leaflet-zoom-animated {\n -webkit-transition:-webkit-transform 0.25s cubic-bezier(0,0,0.25,1);\n -moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);\n -o-transition: -o-transform 0.25s cubic-bezier(0,0,0.25,1);\n transition: transform 0.25s cubic-bezier(0,0,0.25,1);\n }\n.leaflet-zoom-anim .leaflet-tile,\n.leaflet-pan-anim .leaflet-tile,\n.leaflet-touching .leaflet-zoom-animated {\n -webkit-transition:none;\n -moz-transition:none;\n -o-transition:none;\n transition:none;\n }\n.leaflet-zoom-anim .leaflet-zoom-hide { visibility: hidden; }\n\n/* cursors */\n.leaflet-container {\n cursor:-webkit-grab;\n cursor: -moz-grab;\n }\n.leaflet-overlay-pane path,\n.leaflet-marker-icon,\n.leaflet-container.map-clickable,\n.leaflet-container.leaflet-clickable {\n cursor:pointer;\n }\n.leaflet-popup-pane,\n.leaflet-control {\n cursor:auto;\n }\n.leaflet-dragging,\n.leaflet-dragging .map-clickable,\n.leaflet-dragging .leaflet-clickable,\n.leaflet-dragging .leaflet-container {\n cursor:move;\n cursor:-webkit-grabbing;\n cursor: -moz-grabbing;\n }\n\n.leaflet-zoom-box {\n background:#fff;\n border:2px dotted #202020;\n opacity:0.5;\n }\n\n/* general toolbar styles */\n.leaflet-control-layers,\n.leaflet-bar {\n background-color:#fff;\n border:1px solid #999;\n border-color:rgba(0,0,0,0.4);\n border-radius:3px;\n box-shadow:none;\n }\n.leaflet-bar a,\n.leaflet-bar a:hover {\n color:#404040;\n color:rgba(0,0,0,0.75);\n border-bottom:1px solid #ddd;\n border-bottom-color:rgba(0,0,0,0.10);\n }\n .leaflet-bar a:hover,\n .leaflet-bar a:active {\n background-color:#f8f8f8;\n cursor:pointer;\n }\n .leaflet-bar a:hover:first-child {\n border-radius:3px 3px 0 0;\n }\n .leaflet-bar a:hover:last-child {\n border-bottom:none;\n border-radius:0 0 3px 3px;\n }\n .leaflet-bar a:hover:only-of-type {\n border-radius:3px;\n }\n\n.leaflet-bar .leaflet-disabled {\n cursor:default;\n opacity:0.75;\n }\n.leaflet-control-zoom-in,\n.leaflet-control-zoom-out {\n display:block;\n content:'';\n text-indent:-999em;\n }\n\n.leaflet-control-layers .leaflet-control-layers-list,\n.leaflet-control-layers-expanded .leaflet-control-layers-toggle {\n display:none;\n }\n .leaflet-control-layers-expanded .leaflet-control-layers-list {\n display:block;\n position:relative;\n }\n\n.leaflet-control-layers-expanded {\n background:#fff;\n padding:6px 10px 6px 6px;\n color:#404040;\n color:rgba(0,0,0,0.75);\n }\n.leaflet-control-layers-selector {\n margin-top:2px;\n position:relative;\n top:1px;\n }\n.leaflet-control-layers label {\n display: block;\n }\n.leaflet-control-layers-separator {\n height:0;\n border-top:1px solid #ddd;\n border-top-color:rgba(0,0,0,0.10);\n margin:5px -10px 5px -6px;\n }\n\n.leaflet-container .leaflet-control-attribution {\n background-color:rgba(255,255,255,0.5);\n margin:0;\n box-shadow:none;\n }\n .leaflet-container .leaflet-control-attribution a,\n .leaflet-container .map-info-container a {\n color:#404040;\n }\n .leaflet-control-attribution a:hover,\n .map-info-container a:hover {\n color:inherit;\n text-decoration:underline;\n }\n\n.leaflet-control-attribution,\n.leaflet-control-scale-line {\n padding:0 5px;\n }\n .leaflet-left .leaflet-control-scale { margin-left:5px; }\n .leaflet-bottom .leaflet-control-scale { margin-bottom:5px; }\n\n/* Used for smaller map containers & triggered by container size */\n.leaflet-container .leaflet-control-attribution.leaflet-compact-attribution { margin:10px; }\n.leaflet-container .leaflet-control-attribution.leaflet-compact-attribution {\n background:#fff;\n border-radius:3px 13px 13px 3px;\n padding:3px 31px 3px 3px;\n visibility:hidden;\n }\n .leaflet-control-attribution.leaflet-compact-attribution:hover {\n visibility:visible;\n }\n\n.leaflet-control-attribution.leaflet-compact-attribution:after {\n content:'';\n background-color:#fff;\n background-color:rgba(255,255,255,0.5);\n background-position:0 -78px;\n border-radius:50%;\n position:absolute;\n display:inline-block;\n width:26px;\n height:26px;\n vertical-align:middle;\n bottom:0;\n z-index:1;\n visibility:visible;\n cursor:pointer;\n }\n .leaflet-control-attribution.leaflet-compact-attribution:hover:after { background-color:#fff; }\n\n.leaflet-right .leaflet-control-attribution.leaflet-compact-attribution:after { right:0; }\n.leaflet-left .leaflet-control-attribution.leaflet-compact-attribution:after { left:0; }\n\n.leaflet-control-scale-line {\n background-color:rgba(255,255,255,0.5);\n border:1px solid #999;\n border-color:rgba(0,0,0,0.4);\n border-top:none;\n padding:2px 5px 1px;\n white-space:nowrap;\n overflow:hidden;\n }\n .leaflet-control-scale-line:not(:first-child) {\n border-top:2px solid #ddd;\n border-top-color:rgba(0,0,0,0.10);\n border-bottom:none;\n margin-top:-2px;\n }\n .leaflet-control-scale-line:not(:first-child):not(:last-child) {\n border-bottom:2px solid #777;\n }\n\n/* popup */\n.leaflet-popup {\n position:absolute;\n text-align:center;\n pointer-events:none;\n }\n.leaflet-popup-content-wrapper {\n padding:1px;\n text-align:left;\n pointer-events:all;\n }\n.leaflet-popup-content {\n padding:10px 10px 15px;\n margin:0;\n line-height:inherit;\n }\n .leaflet-popup-close-button + .leaflet-popup-content-wrapper .leaflet-popup-content {\n padding-top:15px;\n }\n\n.leaflet-popup-tip-container {\n width:20px;\n height:20px;\n margin:0 auto;\n position:relative;\n }\n.leaflet-popup-tip {\n width:0;\n\theight:0;\n margin:0;\n\tborder-left:10px solid transparent;\n\tborder-right:10px solid transparent;\n\tborder-top:10px solid #fff;\n box-shadow:none;\n }\n.leaflet-popup-close-button {\n text-indent:-999em;\n position:absolute;\n top:0;right:0;\n pointer-events:all;\n }\n .leaflet-popup-close-button:hover {\n background-color:#f8f8f8;\n }\n\n.leaflet-popup-scrolled {\n overflow:auto;\n border-bottom:1px solid #ddd;\n border-top:1px solid #ddd;\n }\n\n/* div icon */\n.leaflet-div-icon {\n background:#fff;\n border:1px solid #999;\n border-color:rgba(0,0,0,0.4);\n }\n.leaflet-editing-icon {\n border-radius:3px;\n }\n\n/* Leaflet + Mapbox\n------------------------------------------------------- */\n.leaflet-bar a,\n.mapbox-icon,\n.map-tooltip.closable .close,\n.leaflet-control-layers-toggle,\n.leaflet-popup-close-button,\n.mapbox-button-icon:before {\n content:'';\n display:inline-block;\n width:26px;\n height:26px;\n vertical-align:middle;\n background-repeat:no-repeat;\n }\n.leaflet-bar a {\n display:block;\n }\n\n.leaflet-control-attribution:after,\n.leaflet-control-zoom-in,\n.leaflet-control-zoom-out,\n.leaflet-popup-close-button,\n.leaflet-control-layers-toggle,\n.leaflet-container.dark .map-tooltip .close,\n.map-tooltip .close,\n.mapbox-icon {\n opacity: .75;\n background-image:url(" + escape(__webpack_require__(151)) + ");\n background-repeat:no-repeat;\n background-size:26px 260px;\n }\n .leaflet-container.dark .leaflet-control-attribution:after,\n .mapbox-button-icon:before,\n .leaflet-container.dark .leaflet-control-zoom-in,\n .leaflet-container.dark .leaflet-control-zoom-out,\n .leaflet-container.dark .leaflet-control-layers-toggle,\n .leaflet-container.dark .mapbox-icon {\n opacity: 1;\n background-image:url(" + escape(__webpack_require__(152)) + ");\n background-size:26px 260px;\n }\n .leaflet-bar .leaflet-control-zoom-in { background-position:0 0; }\n .leaflet-bar .leaflet-control-zoom-out { background-position:0 -26px; }\n .map-tooltip.closable .close,\n .leaflet-popup-close-button {\n background-position:-3px -55px;\n width:20px;\n height:20px;\n border-radius:0 3px 0 0;\n }\n .mapbox-icon-info { background-position:0 -78px; }\n .leaflet-control-layers-toggle { background-position:0 -104px; }\n .mapbox-icon.mapbox-icon-share:before, .mapbox-icon.mapbox-icon-share { background-position:0 -130px; }\n .mapbox-icon.mapbox-icon-geocoder:before, .mapbox-icon.mapbox-icon-geocoder { background-position:0 -156px; }\n .mapbox-icon-facebook:before, .mapbox-icon-facebook { background-position:0 -182px; }\n .mapbox-icon-twitter:before, .mapbox-icon-twitter { background-position:0 -208px; }\n .mapbox-icon-pinterest:before, .mapbox-icon-pinterest { background-position:0 -234px; }\n\n.leaflet-popup-content-wrapper,\n.map-legends,\n.map-tooltip {\n background:#fff;\n border-radius:3px;\n box-shadow:0 1px 2px rgba(0,0,0,0.10);\n }\n.map-legends,\n.map-tooltip {\n max-width:300px;\n }\n.map-legends .map-legend {\n padding:10px;\n }\n.map-tooltip {\n z-index:999999;\n padding:10px;\n min-width:180px;\n max-height:400px;\n overflow:auto;\n opacity:1;\n -webkit-transition:opacity 150ms;\n -moz-transition:opacity 150ms;\n -o-transition:opacity 150ms;\n transition:opacity 150ms;\n }\n\n.map-tooltip .close {\n text-indent:-999em;\n overflow:hidden;\n display:none;\n }\n .map-tooltip.closable .close {\n position:absolute;\n top:0;right:0;\n border-radius:3px;\n }\n .map-tooltip.closable .close:active {\n background-color:#f8f8f8;\n }\n\n.leaflet-control-interaction {\n position:absolute;\n top:10px;\n right:10px;\n width:300px;\n }\n.leaflet-popup-content .marker-title {\n font-weight:bold;\n }\n.leaflet-control .mapbox-button {\n background-color:#fff;\n border:1px solid #ddd;\n border-color:rgba(0,0,0,0.10);\n padding:5px 10px;\n border-radius:3px;\n }\n\n/* Share modal\n------------------------------------------------------- */\n.mapbox-modal > div {\n position:absolute;\n top:0;\n left:0;\n width:100%;\n height:100%;\n z-index:-1;\n overflow-y:auto;\n }\n .mapbox-modal.active > div {\n z-index:99999;\n transition:all .2s, z-index 0 0;\n }\n\n.mapbox-modal .mapbox-modal-mask {\n background:rgba(0,0,0,0.5);\n opacity:0;\n }\n .mapbox-modal.active .mapbox-modal-mask { opacity:1; }\n\n.mapbox-modal .mapbox-modal-content {\n -webkit-transform:translateY(-100%);\n -moz-transform:translateY(-100%);\n -ms-transform:translateY(-100%);\n transform:translateY(-100%);\n }\n .mapbox-modal.active .mapbox-modal-content {\n -webkit-transform:translateY(0);\n -moz-transform:translateY(0);\n -ms-transform:translateY(0);\n transform:translateY(0);\n }\n\n.mapbox-modal-body {\n position:relative;\n background:#fff;\n padding:20px;\n z-index:1000;\n width:50%;\n margin:20px 0 20px 25%;\n }\n.mapbox-share-buttons {\n margin:0 0 20px;\n }\n.mapbox-share-buttons a {\n width:33.3333%;\n border-left:1px solid #fff;\n text-align:center;\n border-radius:0;\n }\n .mapbox-share-buttons a:last-child { border-radius:0 3px 3px 0; }\n .mapbox-share-buttons a:first-child { border:none; border-radius:3px 0 0 3px; }\n\n.mapbox-modal input {\n width:100%;\n height:40px;\n padding:10px;\n border:1px solid #ddd;\n border-color:rgba(0,0,0,0.10);\n color:rgba(0,0,0,0.5);\n }\n\n/* Info Control\n------------------------------------------------------- */\n.leaflet-control.mapbox-control-info {\n margin:5px 30px 10px 10px;\n min-height:26px;\n }\n .leaflet-right .leaflet-control.mapbox-control-info {\n margin:5px 10px 10px 30px;\n }\n\n.mapbox-info-toggle {\n background-color:#fff;\n background-color:rgba(255,255,255,0.5);\n border-radius:50%;\n position:absolute;\n bottom:0;left:0;\n z-index:1;\n }\n .leaflet-right .mapbox-control-info .mapbox-info-toggle { left:auto; right:0; }\n .mapbox-info-toggle:hover { background-color:#fff; }\n\n.map-info-container {\n background:#fff;\n padding:3px 5px 3px 27px;\n display:none;\n position:relative;\n bottom:0;left:0;\n border-radius:13px 3px 3px 13px;\n }\n .leaflet-right .map-info-container {\n left:auto;\n right:0;\n padding:3px 27px 3px 5px;\n border-radius:3px 13px 13px 3px;\n }\n\n.mapbox-control-info.active .map-info-container { display:inline-block; }\n.leaflet-container .mapbox-improve-map { font-weight:bold; }\n\n/* Geocoder\n------------------------------------------------------- */\n.leaflet-control-mapbox-geocoder {\n position:relative;\n }\n.leaflet-control-mapbox-geocoder.searching {\n opacity:0.75;\n }\n.leaflet-control-mapbox-geocoder .leaflet-control-mapbox-geocoder-wrap {\n background:#fff;\n position:absolute;\n border:1px solid #999;\n border-color:rgba(0,0,0,0.4);\n overflow:hidden;\n left:26px;\n height:28px;\n width:0;\n top:-1px;\n border-radius:0 3px 3px 0;\n opacity:0;\n -webkit-transition:opacity 100ms;\n -moz-transition:opacity 100ms;\n -o-transition:opacity 100ms;\n transition:opacity 100ms;\n }\n.leaflet-control-mapbox-geocoder.active .leaflet-control-mapbox-geocoder-wrap {\n width:180px;\n opacity:1;\n }\n.leaflet-bar .leaflet-control-mapbox-geocoder-toggle,\n.leaflet-bar .leaflet-control-mapbox-geocoder-toggle:hover {\n border-bottom:none;\n }\n.leaflet-control-mapbox-geocoder-toggle {\n border-radius:3px;\n }\n.leaflet-control-mapbox-geocoder.active,\n.leaflet-control-mapbox-geocoder.active .leaflet-control-mapbox-geocoder-toggle {\n border-top-right-radius:0;\n border-bottom-right-radius:0;\n }\n.leaflet-control-mapbox-geocoder .leaflet-control-mapbox-geocoder-form input {\n background:transparent;\n border:0;\n width:180px;\n padding:0 0 0 10px;\n height:26px;\n outline:none;\n }\n.leaflet-control-mapbox-geocoder-results {\n width:180px;\n position:absolute;\n left:26px;\n top:25px;\n border-radius:0 0 3px 3px;\n }\n .leaflet-control-mapbox-geocoder.active .leaflet-control-mapbox-geocoder-results {\n background:#fff;\n border:1px solid #999;\n border-color:rgba(0,0,0,0.4);\n }\n.leaflet-control-mapbox-geocoder-results a,\n.leaflet-control-mapbox-geocoder-results span {\n padding:0 10px;\n text-overflow:ellipsis;\n white-space:nowrap;\n display:block;\n width:100%;\n font-size:12px;\n line-height:26px;\n text-align:left;\n overflow:hidden;\n }\n .leaflet-container.dark .leaflet-control .leaflet-control-mapbox-geocoder-results a:hover,\n .leaflet-control-mapbox-geocoder-results a:hover {\n background:#f8f8f8;\n opacity:1;\n }\n\n.leaflet-right .leaflet-control-mapbox-geocoder-wrap,\n.leaflet-right .leaflet-control-mapbox-geocoder-results {\n left:auto;\n right:26px;\n }\n.leaflet-right .leaflet-control-mapbox-geocoder-wrap {\n border-radius:3px 0 0 3px;\n }\n.leaflet-right .leaflet-control-mapbox-geocoder.active,\n.leaflet-right .leaflet-control-mapbox-geocoder.active .leaflet-control-mapbox-geocoder-toggle {\n border-radius:0 3px 3px 0;\n }\n\n.leaflet-bottom .leaflet-control-mapbox-geocoder-results {\n top:auto;\n bottom:25px;\n border-radius:3px 3px 0 0;\n }\n\n/* Mapbox Logo\n------------------------------------------------------- */\n.mapbox-logo-true:before {\n content:'';\n display:inline-block;\n width:61px;\n height:19px;\n vertical-align:middle;\n}\n.mapbox-logo-true {\n background-repeat:no-repeat;\n background-size:61px 19px;\n background-image:url('data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSI2NSIgaGVpZ2h0PSIyMCI+PGRlZnMvPjxtZXRhZGF0YT48cmRmOlJERj48Y2M6V29yayByZGY6YWJvdXQ9IiI+PGRjOmZvcm1hdD5pbWFnZS9zdmcreG1sPC9kYzpmb3JtYXQ+PGRjOnR5cGUgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIvPjxkYzp0aXRsZS8+PC9jYzpXb3JrPjwvcmRmOlJERj48L21ldGFkYXRhPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yNjEuODQ4MywtOTguNTAzOTUpIj48ZyB0cmFuc2Zvcm09Im1hdHJpeCgwLjE3NDQxODM2LDAsMCwwLjE3NDQxODM2LDIyMC41MjI4MiwyOS4yMjkzNDIpIiBzdHlsZT0ib3BhY2l0eTowLjI1O2ZpbGw6I2ZmZmZmZjtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MTcuMjAwMDIzNjU7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLW9wYWNpdHk6MTtzdHJva2UtZGFzaGFycmF5Om5vbmUiPjxwYXRoIGQ9Ik0gNS4yOCAxLjUgQyA0LjU0IDEuNTYgMy45IDIuMjUgMy45MSAzIGwgMCAxMS44OCBjIDAuMDIgMC43NyAwLjcyIDEuNDcgMS41IDEuNDcgbCAxLjc1IDAgYyAwLjc4IDAgMS40OCAtMC42OSAxLjUgLTEuNDcgbCAwIC00LjI4IDAuNzIgMS4xOSBjIDAuNTMgMC44NyAyLjAzIDAuODcgMi41NiAwIGwgMC43MiAtMS4xOSAwIDQuMjggYyAwLjAyIDAuNzYgMC43IDEuNDUgMS40NyAxLjQ3IGwgMS43NSAwIGMgMC43OCAwIDEuNDggLTAuNjkgMS41IC0xLjQ3IGwgMCAtMC4xNiBjIDEuMDIgMS4xMiAyLjQ2IDEuODEgNC4wOSAxLjgxIGwgNC4wOSAwIDAgMS40NyBjIC0wIDAuNzggMC42OSAxLjQ4IDEuNDcgMS41IGwgMS43NSAwIGMgMC43OSAtMCAxLjUgLTAuNzEgMS41IC0xLjUgbCAwLjAyIC0xLjQ3IGMgMS43MiAwIDMuMDggLTAuNjQgNC4xNCAtMS42OSBsIDAgMC4xOSBjIDAgMC4zOSAwLjE2IDAuNzkgMC40NCAxLjA2IDAuMjggMC4yOCAwLjY3IDAuNDQgMS4wNiAwLjQ0IGwgMy4zMSAwIGMgMi4wMyAwIDMuODUgLTEuMDYgNC45MSAtMi42OSAxLjA1IDEuNjEgMi44NCAyLjY5IDQuODggMi42OSAxLjAzIDAgMS45OCAtMC4yNyAyLjgxIC0wLjc1IDAuMjggMC4zNSAwLjczIDAuNTcgMS4xOSAwLjU2IGwgMi4xMiAwIGMgMC40OCAwLjAxIDAuOTcgLTAuMjMgMS4yNSAtMC42MiBsIDAuOTEgLTEuMjggMC45MSAxLjI4IGMgMC4yOCAwLjM5IDAuNzQgMC42MyAxLjIyIDAuNjIgbCAyLjE2IDAgQyA2Mi42NyAxNi4zMyA2My40MiAxNC44OSA2Mi44MSAxNCBMIDYwLjIyIDEwLjM4IDYyLjYyIDcgQyA2My4yNiA2LjExIDYyLjUgNC42MiA2MS40MSA0LjYyIGwgLTIuMTYgMCBDIDU4Ljc4IDQuNjIgNTguMzEgNC44NiA1OC4wMyA1LjI1IEwgNTcuMzEgNi4yOCA1Ni41NiA1LjI1IEMgNTYuMjkgNC44NiA1NS44MiA0LjYyIDU1LjM0IDQuNjIgbCAtMi4xNiAwIGMgLTAuNDkgLTAgLTAuOTcgMC4yNSAtMS4yNSAwLjY2IC0wLjg2IC0wLjUxIC0xLjg0IC0wLjgxIC0yLjkxIC0wLjgxIC0yLjAzIDAgLTMuODMgMS4wOCAtNC44OCAyLjY5IEMgNDMuMSA1LjUzIDQxLjI3IDQuNDcgMzkuMTkgNC40NyBMIDM5LjE5IDMgQyAzOS4xOSAyLjYxIDM5LjAzIDIuMjEgMzguNzUgMS45NCAzOC40NyAxLjY2IDM4LjA4IDEuNSAzNy42OSAxLjUgbCAtMS43NSAwIGMgLTAuNzEgMCAtMS41IDAuODMgLTEuNSAxLjUgbCAwIDMuMTYgQyAzMy4zOCA1LjEgMzEuOTYgNC40NyAzMC4zOCA0LjQ3IGwgLTMuMzQgMCBjIC0wLjc3IDAuMDIgLTEuNDcgMC43MiAtMS40NyAxLjUgbCAwIDAuMzEgYyAtMS4wMiAtMS4xMiAtMi40NiAtMS44MSAtNC4wOSAtMS44MSAtMS42MyAwIC0zLjA3IDAuNyAtNC4wOSAxLjgxIEwgMTcuMzggMyBjIC0wIC0wLjc5IC0wLjcxIC0xLjUgLTEuNSAtMS41IEwgMTQuNSAxLjUgQyAxMy41NSAxLjUgMTIuMjggMS44NyAxMS42NiAyLjk0IGwgLTEgMS42OSAtMSAtMS42OSBDIDkuMDMgMS44NyA3Ljc3IDEuNSA2LjgxIDEuNSBsIC0xLjQxIDAgQyA1LjM2IDEuNSA1LjMyIDEuNSA1LjI4IDEuNSB6IG0gMTYuMTkgNy43MiBjIDAuNTMgMCAwLjk0IDAuMzUgMC45NCAxLjI4IGwgMCAxLjI4IC0wLjk0IDAgYyAtMC41MiAwIC0wLjk0IC0wLjM4IC0wLjk0IC0xLjI4IC0wIC0wLjkgMC40MiAtMS4yOCAwLjk0IC0xLjI4IHogbSA4LjgxIDAgYyAwLjgzIDAgMS4xOCAwLjY4IDEuMTkgMS4yOCAwLjAxIDAuOTQgLTAuNjIgMS4yOCAtMS4xOSAxLjI4IHogbSA4LjcyIDAgYyAwLjcyIDAgMS4zNyAwLjYgMS4zNyAxLjI4IDAgMC43NyAtMC41MSAxLjI4IC0xLjM3IDEuMjggeiBtIDEwLjAzIDAgYyAwLjU4IDAgMS4wOSAwLjUgMS4wOSAxLjI4IDAgMC43OCAtMC41MSAxLjI4IC0xLjA5IDEuMjggLTAuNTggMCAtMS4xMiAtMC41IC0xLjEyIC0xLjI4IDAgLTAuNzggMC41NCAtMS4yOCAxLjEyIC0xLjI4IHoiIHRyYW5zZm9ybT0ibWF0cml4KDUuNzMzMzQxNCwwLDAsNS43MzMzNDE0LDIzNi45MzMwOCwzOTcuMTc0OTgpIiBzdHlsZT0iZm9udC1zaXplOm1lZGl1bTtmb250LXN0eWxlOm5vcm1hbDtmb250LXZhcmlhbnQ6bm9ybWFsO2ZvbnQtd2VpZ2h0Om5vcm1hbDtmb250LXN0cmV0Y2g6bm9ybWFsO3RleHQtaW5kZW50OjA7dGV4dC1hbGlnbjpzdGFydDt0ZXh0LWRlY29yYXRpb246bm9uZTtsaW5lLWhlaWdodDpub3JtYWw7bGV0dGVyLXNwYWNpbmc6bm9ybWFsO3dvcmQtc3BhY2luZzpub3JtYWw7dGV4dC10cmFuc2Zvcm06bm9uZTtkaXJlY3Rpb246bHRyO2Jsb2NrLXByb2dyZXNzaW9uOnRiO3dyaXRpbmctbW9kZTpsci10Yjt0ZXh0LWFuY2hvcjpzdGFydDtiYXNlbGluZS1zaGlmdDpiYXNlbGluZTtjb2xvcjojMDAwMDAwO2ZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTcuMjAwMDIzNjU7bWFya2VyOm5vbmU7dmlzaWJpbGl0eTp2aXNpYmxlO2Rpc3BsYXk6aW5saW5lO292ZXJmbG93OnZpc2libGU7ZW5hYmxlLWJhY2tncm91bmQ6YWNjdW11bGF0ZTtmb250LWZhbWlseTpTYW5zOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246U2FucyIvPjwvZz48ZyB0cmFuc2Zvcm09Im1hdHJpeCgwLjE3NDQxODM2LDAsMCwwLjE3NDQxODM2LDIyMC41MjI4MiwyOS4yMjkzNDIpIiBzdHlsZT0iZmlsbDojZmZmZmZmIj48cGF0aCBkPSJtIDUuNDEgMyAwIDEyIDEuNzUgMCAwIC05LjkxIDMuNSA1Ljk0IDMuNDcgLTUuOTQgMCA5LjkxIDEuNzUgMCAwIC0xMiBMIDE0LjUgMyBDIDEzLjggMyAxMy4yNSAzLjE2IDEyLjk0IDMuNjkgTCAxMC42NiA3LjU5IDguMzggMy42OSBDIDguMDcgMy4xNiA3LjUxIDMgNi44MSAzIHogTSAzNiAzIGwgMCAxMi4wMyAzLjI1IDAgYyAyLjQ0IDAgNC4zOCAtMS45MSA0LjM4IC00LjUzIDAgLTIuNjIgLTEuOTMgLTQuNDcgLTQuMzggLTQuNDcgQyAzOC43IDYuMDMgMzguMzIgNiAzNy43NSA2IGwgMCAtMyB6IE0gMjEuNDcgNS45NyBjIC0yLjQ0IDAgLTQuMTkgMS45MSAtNC4xOSA0LjUzIDAgMi42MiAxLjc1IDQuNTMgNC4xOSA0LjUzIGwgNC4xOSAwIDAgLTQuNTMgYyAwIC0yLjYyIC0xLjc1IC00LjUzIC00LjE5IC00LjUzIHogbSAyNy41NiAwIGMgLTIuNDEgMCAtNC4zOCAyLjAzIC00LjM4IDQuNTMgMCAyLjUgMS45NyA0LjUzIDQuMzggNC41MyAyLjQxIDAgNC4zNCAtMi4wMyA0LjM0IC00LjUzIDAgLTIuNSAtMS45NCAtNC41MyAtNC4zNCAtNC41MyB6IG0gLTIyIDAuMDMgMCAxMiAxLjc1IDAgMCAtMi45NyBjIDAuNTcgMCAxLjA0IC0wIDEuNTkgMCAyLjQ0IDAgNC4zNCAtMS45MSA0LjM0IC00LjUzIDAgLTIuNjIgLTEuOSAtNC41IC00LjM0IC00LjUgeiBtIDI2LjE2IDAgMy4wMyA0LjM4IC0zLjE5IDQuNjIgMi4xMiAwIEwgNTcuMzEgMTEuOTEgNTkuNDQgMTUgNjEuNTkgMTUgNTguMzggMTAuMzggNjEuNDEgNiA1OS4yNSA2IDU3LjMxIDguODEgNTUuMzQgNiB6IE0gMjEuNDcgNy43MiBjIDEuNCAwIDIuNDQgMS4xOSAyLjQ0IDIuNzggbCAwIDIuNzggLTIuNDQgMCBjIC0xLjQgMCAtMi40NCAtMS4yMSAtMi40NCAtMi43OCAtMCAtMS41NyAxLjA0IC0yLjc4IDIuNDQgLTIuNzggeiBtIDI3LjU2IDAgYyAxLjQ0IDAgMi41OSAxLjI0IDIuNTkgMi43OCAwIDEuNTQgLTEuMTUgMi43OCAtMi41OSAyLjc4IC0xLjQ0IDAgLTIuNjIgLTEuMjQgLTIuNjIgLTIuNzggMCAtMS41NCAxLjE4IC0yLjc4IDIuNjIgLTIuNzggeiBtIC0yMC4yNSAwLjAzIDEuNTkgMCBjIDEuNTkgMCAyLjU5IDEuMjggMi41OSAyLjc1IDAgMS40NyAtMS4xMyAyLjc4IC0yLjU5IDIuNzggbCAtMS41OSAwIHogbSA4Ljk3IDAgMS41IDAgYyAxLjQ3IDAgMi42MiAxLjI4IDIuNjIgMi43NSAwIDEuNDcgLTEuMDQgMi43OCAtMi42MiAyLjc4IGwgLTEuNSAwIHoiIHRyYW5zZm9ybT0ibWF0cml4KDUuNzMzMzQxNCwwLDAsNS43MzMzNDE0LDIzNi45MzMwOCwzOTcuMTc0OTgpIiBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIi8+PC9nPjwvZz48L3N2Zz4=');\n}\n\n/* Dark Theme\n------------------------------------------------------- */\n.leaflet-container.dark .leaflet-bar {\n background-color:#404040;\n border-color:#202020;\n border-color:rgba(0,0,0,0.75);\n }\n .leaflet-container.dark .leaflet-bar a {\n color:#404040;\n border-color:rgba(0,0,0,0.5);\n }\n .leaflet-container.dark .leaflet-bar a:active,\n .leaflet-container.dark .leaflet-bar a:hover {\n background-color:#505050;\n }\n\n.leaflet-container.dark .leaflet-control-attribution:after,\n.leaflet-container.dark .mapbox-info-toggle,\n.leaflet-container.dark .map-info-container,\n.leaflet-container.dark .leaflet-control-attribution {\n background-color:rgba(0,0,0,0.5);\n color:#f8f8f8;\n }\n .leaflet-container.dark .leaflet-control-attribution a,\n .leaflet-container.dark .leaflet-control-attribution a:hover,\n .leaflet-container.dark .map-info-container a,\n .leaflet-container.dark .map-info-container a:hover {\n color:#fff;\n }\n\n.leaflet-container.dark .leaflet-control-attribution:hover:after {\n background-color:#000;\n }\n.leaflet-container.dark .leaflet-control-layers-list span {\n color:#f8f8f8;\n }\n.leaflet-container.dark .leaflet-control-layers-separator {\n border-top-color:rgba(255,255,255,0.10);\n }\n.leaflet-container.dark .leaflet-bar a.leaflet-disabled,\n.leaflet-container.dark .leaflet-control .mapbox-button.disabled {\n background-color:#252525;\n color:#404040;\n }\n.leaflet-container.dark .leaflet-control-mapbox-geocoder > div {\n border-color:#202020;\n border-color:rgba(0,0,0,0.75);\n }\n .leaflet-container.dark .leaflet-control .leaflet-control-mapbox-geocoder-results a {\n border-color:#ddd #202020;\n border-color:rgba(0,0,0,0.10) rgba(0,0,0,0.75);\n }\n .leaflet-container.dark .leaflet-control .leaflet-control-mapbox-geocoder-results span {\n border-color:#202020;\n border-color:rgba(0,0,0,0.75);\n }\n\n/* Larger Screens\n------------------------------------------------------- */\n@media only screen and (max-width:800px) {\n.mapbox-modal-body {\n width:83.3333%;\n margin-left:8.3333%;\n }\n}\n\n/* Smaller Screens\n------------------------------------------------------- */\n@media only screen and (max-width:640px) {\n.mapbox-modal-body {\n width:100%;\n height:100%;\n margin:0;\n }\n}\n\n/* Print\n------------------------------------------------------- */\n@media print { .mapbox-improve-map { display:none; } }\n\n/* Browser Fixes\n------------------------------------------------------- */\n/* VML support for IE8 */\n.leaflet-vml-shape { width:1px; height:1px; }\n.lvml { behavior:url(#default#VML); display:inline-block; position:absolute; }\n/* Map is broken in FF if you have max-width: 100% on tiles */\n.leaflet-container img.leaflet-tile { max-width:none !important; }\n/* Markers are broken in FF/IE if you have max-width: 100% on marker images */\n.leaflet-container img.leaflet-marker-icon { max-width:none; }\n/* Stupid Android 2 doesn't understand \"max-width: none\" properly */\n.leaflet-container img.leaflet-image-layer { max-width:15000px !important; }\n/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */\n.leaflet-overlay-pane svg { -moz-user-select:none; }\n/* Older IEs don't support the translateY property for display animation */\n.leaflet-oldie .mapbox-modal .mapbox-modal-content { display:none; }\n.leaflet-oldie .mapbox-modal.active .mapbox-modal-content { display:block; }\n.map-tooltip { width:280px\\8; /* < IE9 */ }\n\n/* < IE8 */\n.leaflet-oldie .leaflet-control-zoom-in,\n.leaflet-oldie .leaflet-control-zoom-out,\n.leaflet-oldie .leaflet-popup-close-button,\n.leaflet-oldie .leaflet-control-layers-toggle,\n.leaflet-oldie .leaflet-container.dark .map-tooltip .close,\n.leaflet-oldie .map-tooltip .close,\n.leaflet-oldie .mapbox-icon {\n background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAEECAYAAAA24SSRAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAXnSURBVHic7ZxfiFVFGMB/33pRUQsKto002DY3McJ6yBYkESQxpYTypaB66KEXYRWLYOlhr9RTRGWRUkk9RyEU+Y9ClECJVTKlPybWBilqkYuWrqBOD/NdPV7PmTPn3NPtat/AcO6ZP9/vfN/Mmfl2Zs6Kc452hK62UAxkIANdEURkVERGC9crOjKIiANwzkmRep1lOjWXa2ijaU7jaGWgKsL110a1EnV+LQMqbLqyobO6t4EMZCADGchABrqmQUlPNSWOVgaqIpi7ZSADGchABjKQga49kIjURaQem14apGE4KVR/D0fXds5FRaAOOL1e+h1dP7ZgE6wQxDnXvs7QWaZLE1wUVmRNdY1zrp6wRF0kfqHYnHwDGchABjJQIETNRyIyFVgBzAPmavIIsAt4xzn3d66QiNl1PnCYy05JczwMzG9pKlfIhQCkES/kwUKQqRma9GpM02xqGXdrBdCXZm2NzaFP66SGUGeYl5E+WqJO0HRHSG+PXtJN54AjVbhbjQcbBSjiakH4hR0p+hChOiHQrhKg7Drt6t7//Qtb9RAU5XtXMaiak28gAxnIQO0Gicg0EXlMRDaIyFGNGzRtWhQpMA/1A6uAL4BzZM9H57TMKqC/8HyUPFhZJLiMI4sh0/UDK4FtwHig3LiWWal1UkPsDDsFWAgsBZZo8hZgM7DdOXcmV0igjQ4Ba4HFwORAuclaZi1wqNU2OgNsVw22aNoS1XAhMCXx4OkubOBJZwKDwFbgLNm97qyWGQRmtuoFWRsV0ujabCPzVA1kIAMZqBNAIjIgImPNRxUzK+SsmtRJn4Pqmj8AjCXzsmTlaTSck/8zcDRX/QiNMp8S6Ab2a5nvG5plyioDaoLs1/sBYKwyUBokkTdQJeiVZgi6UR+UVQI0QWHdoXKFvKDYz7RiynXctk7LPlmeRmsKyAqWNQfSQAYykIGuS5CI1ERkSET2ishpvQ6JSLE93ByfoQbsRHeNgfe4vOO8E6iF6hdxToZU6OqGUIWv1vShqkB7VYNaU3pN0/fGgvLa6C5gk3PufJO5zwObgDuraqM8jbZWpdEnwG3AYKOX6XVQ07+sSqNQr3P4QxS9LXeGBGxIzTiGXwR8QSHRsCj7ZjxAbxFYaVAKbMe/BkrAduRpZJ6qgQxkoP8DKDRY1sk/s5W6YFhoUG3nFnZeOIJfxLgXWB7zBFmmyzPT44my9zXSC098OZCTwCQttzOZVzVoX1a5LHmdtYyWDM29yjknItKF3xSelFWvKo1mhCClQLo1sC95T8T/ebr+xrqOABVZT82tY56qgQxkIAN1CkhEulsGiUi3iCzKyJsjIpuBYyLyo4isFpHXReTuTFLAr1sOnAeeT8nbzNW+3rfAM2UcyAcSQj4FngR68Ot0F1NA24CuMqBu4PMUgYdS0hzwYqlFJ+AeNV3s30aLSoEUtjEScoHE3nkZ0Ay1fR7o3ZCcGNAEYHcO5A/g5pZACpsMPEf6UexTwCN5MvI6w2zgaeBt4HQK5BsC57ubY+jPll/wHzn1Ayc07QD+u6MR4GPn3LlA/SuCOZAGMpCBDFRhiF50EpFl+PP49wOzgIPAHmCLc+6zXAERE18P+b7DRqAnJCfvfF0P/mTgLZr0l97vB27CL3HO0rwTwBzn3PHCGiU0uQisA6bhzT0T/T4ZeAr4s6FZmal8WcI0LwETgdfwHzY1XKz3teyjibLLioLWa8UDeG/oZbxD+QHwdULwg1r+K71fXxQ0ohXfAgS/Mvyh5i1MgNZp2qt6P5ImL/QezdbrSeAG4EbVJJkH8LteJ+p1FikhBPpNr3Odc6fUNHdo2oJEucbX8Y2zDQeLgr7T62IReRb4AX9mGGC6Xo8Bu0VkOvCQpu1JlRZoo6Vc/WL2ad4C4A28CWvAR5TtdU0dwqH/ewHvHi8HbgUexh+euDRCFH6PVOh0/FKzw3um4M8zpA1DxwkMQzFjXR9+d/9N1WI8BZI71kU56Aq8HXgC+Ak/5o3gX+rUNmmO5nsbqP2gfwCyvJzPNoKXiAAAAABJRU5ErkJggg==');\n}\n.leaflet-oldie .mapbox-button-icon:before,\n.leaflet-oldie .leaflet-container.dark .leaflet-control-zoom-in,\n.leaflet-oldie .leaflet-container.dark .leaflet-control-zoom-out,\n.leaflet-oldie .leaflet-container.dark .leaflet-control-layers-toggle,\n.leaflet-oldie .leaflet-container.dark .mapbox-icon {\n background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAEECAYAAAA24SSRAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAXYSURBVHic7ZxfiFVFHMc/a4uKWtDDtqJGZprYgwX5ByTdkkLbSgghCiKih14EBYtg6aEr9RRREKRUUs9hGEVtChKaYMkq2VqWmnUX2tKiNDNZY/Xbw/wue7x7zsw559626zY/GM6df7/P+c3MPfO7M3NumyTGQiaMCSWCIiiC6qVqoZC0lXgy1Cq0FanUck1XxVmSNL8WrzYT1LCMvz5qL1FnoAyoTNOVkpYb3hEUQREUQREUQRF0RYOqjHim9aHaTFDDEt2tCIqgCIqgCIqgCLoiQRULedNLgwCeq1NasbR8IilvqMhJpe5zrvpFQElYIYiksRsMLdd0aYoLwYqsqW5i9KjLLdHJj6AIiqAIiiCP5J2PpgLrgGXAYkvrA/YBrwF/BTXkmB2XSzqhbDlhZRqaypdLuuiB1ORiCOaDTM2wZLaFNMumZunzDYZ1wJy01ubyPfOazLE6qeIbDMsy0qsl6ngtWpyRfqOFInVKbWFXS9TxWtRXQl9mHR9oXwlQdp2xGt4t8YVt6iMor+/d8EM1OvkRFEERFEH/AWga8CCwFfjJwlZLm5ZHge/pPQ+4z8IKYGJGub+BT4GPLBwvCio7f6QeWfQ13TxgA7ATGPKUG7IyG6xOOj3nxDcFWAl0A/da2sdAL/AJcD6kwAc6bop6gT1kWzUZ6LKb6CbDqrx9dB535704S8BZ1o2zdEpSZ1HQ3MRddtmdp8kQzuKa9d8VBSUl9lEh0Pjro6ZKy00TERRBERRBLQZaCpxh9FHFUqBKiiJZ+n5gFfBHnrsKgUKb7t/j/PCwBNZwapKW1yGp3/KPSDrjKVsalIT0W3ypwZoGSoPU8pY2E/RCCqSiwJ55GdBVBusIlCu0Xpf3Na1guZbb1mnYJwtZtKmALm/Z6EBGUARFUASNV1A70AMcBP60aw9F93ADPkO7pD3mDwxKesOusvT2QP3czkmPKd2YUNpucVl+LlBo4jsITAduAIbrmnMAOAncnqflQn10M26JebgufdjSb8oDyQM6hlv3ru/4dkv/vFmgd4EZwPoErN3iM4BdeUGNjDpJqsrtmzc86mqwHkkH5X4t7JD0tEFyw3INzYwwuwisEVA9bPe/CarBdocsip5qBEVQBP3fQRWyX4jOCpUsZS2xhR2SQdwixq3A2lDhMkcTa7Ie2G6fwzfsmax8clrSJCu3py4vVV/ZphsALtjnFXkqtNwyWlLqR1Ub7obPA5OyKjXLolk+SFmQgEN18eD/PLXEI2j8gYqspwbrRE81giIogiKohUAdzQB1APdk5C3Ends6CXwLbAReBm7J1OZxINdKGpb0VEpeb4pT+aWkx8os0SxJKHlf0iOSOiXNkHQpBbRT0oQyoA5JH6YoPJ6SJknPeHR5+6gTWJ2SPjej/BceXV7QV8AHvsoJucTlvt5o8ZkraZa1fUheD+gJfo9+Bq4JlPkNt4Xgl9CdSJos6UlJF1IsOSvp/hw6vL8mFgCLgCXA44w+730IeIiM89314gP9ACzHHXD9xdIO49476gO2MfJjLCjRgYygCIqgCGqiFFl0WoM7j78ImA8cBQ7gzuaHp/wck1anpO2BqXy7lSu9I9YJ9APXWfycxfuBa4HbzDpwc9ZC4FQZi2qWXJK0WdI0ue3SuRp5P/lRSb8nLCvsQK5JNM2zkiZKeknSkKVdlPSmlX0gUXZNUdAWq3hY7tzj83K++FuS9icU32Hl91p8S1FQn1V8VVKb3Mrw25a3MgHabGkvWrwvTZ/ve7TArqeBq3H+3f66PIBf7VrzkuaTIj7Qj3ZdDJwF9jLy5wJdiXK1t+NrZxuOFgV9bddVwBPAN8ARS5tp15PAZxa/29IOpGrz9FG3Rsscy+uS9IqkBXLD/Z1GRl1yQEjuHANy7vFaSdMlrZa0K1Gm1PcISTMlDZiSbZa2I8VSSTolz2Mo9PQeBO7CvTE1iDtRc2dKuffwPX4CfVQfrpf0sKRjks5Zs27J6pP6EH3vCBp70D8db2VXFPfIagAAAABJRU5ErkJggg==');\n}\n\n.leaflet-oldie .mapbox-logo-true {\n background-image: none;\n}\n", ""]);
// exports
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "icons-000000@2x.4c2a02.png";
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "icons-ffffff@2x.f9d13b.png";
/***/ }),
/* 153 */
/***/ (function(module, exports) {
/**
* When source maps are enabled, `style-loader` uses a link element with a data-uri to
* embed the css on the page. This breaks all relative urls because now they are relative to a
* bundle instead of the current page.
*
* One solution is to only use full urls, but that may be impossible.
*
* Instead, this function "fixes" the relative urls to be absolute according to the current page location.
*
* A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command.
*
*/
module.exports = function (css) {
// get current location
var location = typeof window !== "undefined" && window.location;
if (!location) {
throw new Error("fixUrls requires window.location");
}
// blank or null?
if (!css || typeof css !== "string") {
return css;
}
var baseUrl = location.protocol + "//" + location.host;
var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/");
// convert each url(...)
/*
This regular expression is just a way to recursively match brackets within
a string.
/url\s*\( = Match on the word "url" with any whitespace after it and then a parens
( = Start a capturing group
(?: = Start a non-capturing group
[^)(] = Match anything that isn't a parentheses
| = OR
\( = Match a start parentheses
(?: = Start another non-capturing groups
[^)(]+ = Match anything that isn't a parentheses
| = OR
\( = Match a start parentheses
[^)(]* = Match anything that isn't a parentheses
\) = Match a end parentheses
) = End Group
*\) = Match anything and then a close parens
) = Close non-capturing group
* = Match anything
) = Close capturing group
\) = Match a close parens
/gi = Get all matches, not the first. Be case insensitive.
*/
var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) {
// strip quotes (if they exist)
var unquotedOrigUrl = origUrl
.trim()
.replace(/^"(.*)"$/, function(o, $1){ return $1; })
.replace(/^'(.*)'$/, function(o, $1){ return $1; });
// already a full url? no change
if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(unquotedOrigUrl)) {
return fullMatch;
}
// convert the url to a full url
var newUrl;
if (unquotedOrigUrl.indexOf("//") === 0) {
//TODO: should we add protocol?
newUrl = unquotedOrigUrl;
} else if (unquotedOrigUrl.indexOf("/") === 0) {
// path should be relative to the base url
newUrl = baseUrl + unquotedOrigUrl; // already starts with '/'
} else {
// path should be relative to current directory
newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './'
}
// send back the fixed url(...)
return "url(" + JSON.stringify(newUrl) + ")";
});
// send back the fixed css
return fixedCss;
};
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(155);
if(typeof content === 'string') content = [[module.i, content, '']];
// Prepare cssTransformation
var transform;
var options = {}
options.transform = transform
// add the styles to the DOM
var update = __webpack_require__(41)(content, options);
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!../../css-loader/index.js!./mapbox-gl.css", function() {
var newContent = require("!!../../css-loader/index.js!./mapbox-gl.css");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(40)(false);
// imports
// module
exports.push([module.i, ".mapboxgl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgba(0,0,0,0)}.mapboxgl-canvas{position:absolute;left:0;top:0}.mapboxgl-map:-webkit-full-screen{width:100%;height:100%}.mapboxgl-canary{background-color:salmon}.mapboxgl-canvas-container.mapboxgl-interactive,.mapboxgl-ctrl-group button.mapboxgl-ctrl-compass{cursor:-webkit-grab;cursor:-moz-grab;cursor:grab;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none}.mapboxgl-canvas-container.mapboxgl-interactive.mapboxgl-track-pointer{cursor:pointer}.mapboxgl-canvas-container.mapboxgl-interactive:active,.mapboxgl-ctrl-group button.mapboxgl-ctrl-compass:active{cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate,.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate .mapboxgl-canvas{touch-action:pan-x pan-y}.mapboxgl-canvas-container.mapboxgl-touch-drag-pan,.mapboxgl-canvas-container.mapboxgl-touch-drag-pan .mapboxgl-canvas{touch-action:pinch-zoom}.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate.mapboxgl-touch-drag-pan,.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate.mapboxgl-touch-drag-pan .mapboxgl-canvas{touch-action:none}.mapboxgl-ctrl-bottom-left,.mapboxgl-ctrl-bottom-right,.mapboxgl-ctrl-top-left,.mapboxgl-ctrl-top-right{position:absolute;pointer-events:none;z-index:2}.mapboxgl-ctrl-top-left{top:0;left:0}.mapboxgl-ctrl-top-right{top:0;right:0}.mapboxgl-ctrl-bottom-left{bottom:0;left:0}.mapboxgl-ctrl-bottom-right{right:0;bottom:0}.mapboxgl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.mapboxgl-ctrl-top-left .mapboxgl-ctrl{margin:10px 0 0 10px;float:left}.mapboxgl-ctrl-top-right .mapboxgl-ctrl{margin:10px 10px 0 0;float:right}.mapboxgl-ctrl-bottom-left .mapboxgl-ctrl{margin:0 0 10px 10px;float:left}.mapboxgl-ctrl-bottom-right .mapboxgl-ctrl{margin:0 10px 10px 0;float:right}.mapboxgl-ctrl-group{border-radius:4px;background:#fff}.mapboxgl-ctrl-group:not(:empty){-moz-box-shadow:0 0 2px rgba(0,0,0,.1);-webkit-box-shadow:0 0 2px rgba(0,0,0,.1);box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (-ms-high-contrast:active){.mapboxgl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.mapboxgl-ctrl-group button{width:29px;height:29px;display:block;padding:0;outline:none;border:0;box-sizing:border-box;background-color:transparent;cursor:pointer}.mapboxgl-ctrl-group button+button{border-top:1px solid #ddd}.mapboxgl-ctrl button .mapboxgl-ctrl-icon{display:block;width:100%;height:100%;background-repeat:no-repeat;background-position:50%}@media (-ms-high-contrast:active){.mapboxgl-ctrl-icon{background-color:transparent}.mapboxgl-ctrl-group button+button{border-top:1px solid ButtonText}}.mapboxgl-ctrl button::-moz-focus-inner{border:0;padding:0}.mapboxgl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.mapboxgl-ctrl button:disabled{cursor:not-allowed}.mapboxgl-ctrl button:disabled .mapboxgl-ctrl-icon{opacity:.25}.mapboxgl-ctrl button:not(:disabled):hover{background-color:rgba(0,0,0,.05)}.mapboxgl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.mapboxgl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.mapboxgl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.mapboxgl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.mapboxgl-ctrl-group button:focus:only-child{border-radius:inherit}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-out .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-9z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-in .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5z'/%3E%3C/svg%3E\")}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-out .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-9z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-in .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5z'/%3E%3C/svg%3E\")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-out .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-9z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-in .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5z'/%3E%3C/svg%3E\")}}.mapboxgl-ctrl button.mapboxgl-ctrl-fullscreen .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3h1zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16h1zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5H13zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1V7.5z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-shrink .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1h-5.5zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1v-5.5zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1v5.5zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1h5.5z'/%3E%3C/svg%3E\")}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-fullscreen .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3h1zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16h1zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5H13zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1V7.5z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-shrink .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1h-5.5zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1v-5.5zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1v5.5zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1h5.5z'/%3E%3C/svg%3E\")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-fullscreen .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3h1zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16h1zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5H13zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1V7.5z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-shrink .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1h-5.5zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1v-5.5zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1v5.5zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1h5.5z'/%3E%3C/svg%3E\")}}.mapboxgl-ctrl button.mapboxgl-ctrl-compass .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M10.5 14l4-8 4 8h-8z'/%3E%3Cpath d='M10.5 16l4 8 4-8h-8z' fill='%23ccc'/%3E%3C/svg%3E\")}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-compass .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M10.5 14l4-8 4 8h-8z'/%3E%3Cpath d='M10.5 16l4 8 4-8h-8z' fill='%23999'/%3E%3C/svg%3E\")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-compass .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M10.5 14l4-8 4 8h-8z'/%3E%3Cpath d='M10.5 16l4 8 4-8h-8z' fill='%23ccc'/%3E%3C/svg%3E\")}}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate:disabled .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23aaa'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath d='M14 5l1 1-9 9-1-1 9-9z' fill='red'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active-error .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e58978'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background-error .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e54e33'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-waiting .mapboxgl-ctrl-icon{-webkit-animation:mapboxgl-spin 2s linear infinite;-moz-animation:mapboxgl-spin 2s infinite linear;-o-animation:mapboxgl-spin 2s infinite linear;-ms-animation:mapboxgl-spin 2s infinite linear;animation:mapboxgl-spin 2s linear infinite}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate:disabled .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23999'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath d='M14 5l1 1-9 9-1-1 9-9z' fill='red'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active-error .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e58978'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background-error .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e54e33'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E\")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E\")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate:disabled .mapboxgl-ctrl-icon{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23666'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath d='M14 5l1 1-9 9-1-1 9-9z' fill='red'/%3E%3C/svg%3E\")}}@-webkit-keyframes mapboxgl-spin{0%{-webkit-transform:rotate(0deg)}to{-webkit-transform:rotate(1turn)}}@-moz-keyframes mapboxgl-spin{0%{-moz-transform:rotate(0deg)}to{-moz-transform:rotate(1turn)}}@-o-keyframes mapboxgl-spin{0%{-o-transform:rotate(0deg)}to{-o-transform:rotate(1turn)}}@-ms-keyframes mapboxgl-spin{0%{-ms-transform:rotate(0deg)}to{-ms-transform:rotate(1turn)}}@keyframes mapboxgl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.mapboxgl-ctrl-logo{width:88px;height:23px;margin:0 0 -4px -4px;display:block;background-repeat:no-repeat;cursor:pointer;overflow:hidden;background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='88' height='23' viewBox='0 0 88 23' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' fill-rule='evenodd'%3E%3Cdefs%3E%3Cpath id='a' d='M11.5 2.25c5.105 0 9.25 4.145 9.25 9.25s-4.145 9.25-9.25 9.25-9.25-4.145-9.25-9.25 4.145-9.25 9.25-9.25zM6.997 15.983c-.051-.338-.828-5.802 2.233-8.873a4.395 4.395 0 013.13-1.28c1.27 0 2.49.51 3.39 1.42.91.9 1.42 2.12 1.42 3.39 0 1.18-.449 2.301-1.28 3.13C12.72 16.93 7 16 7 16l-.003-.017zM15.3 10.5l-2 .8-.8 2-.8-2-2-.8 2-.8.8-2 .8 2 2 .8z'/%3E%3Cpath id='b' d='M50.63 8c.13 0 .23.1.23.23V9c.7-.76 1.7-1.18 2.73-1.18 2.17 0 3.95 1.85 3.95 4.17s-1.77 4.19-3.94 4.19c-1.04 0-2.03-.43-2.74-1.18v3.77c0 .13-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V8.23c0-.12.1-.23.23-.23h1.4zm-3.86.01c.01 0 .01 0 .01-.01.13 0 .22.1.22.22v7.55c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V15c-.7.76-1.69 1.19-2.73 1.19-2.17 0-3.94-1.87-3.94-4.19 0-2.32 1.77-4.19 3.94-4.19 1.03 0 2.02.43 2.73 1.18v-.75c0-.12.1-.23.23-.23h1.4zm26.375-.19a4.24 4.24 0 00-4.16 3.29c-.13.59-.13 1.19 0 1.77a4.233 4.233 0 004.17 3.3c2.35 0 4.26-1.87 4.26-4.19 0-2.32-1.9-4.17-4.27-4.17zM60.63 5c.13 0 .23.1.23.23v3.76c.7-.76 1.7-1.18 2.73-1.18 1.88 0 3.45 1.4 3.84 3.28.13.59.13 1.2 0 1.8-.39 1.88-1.96 3.29-3.84 3.29-1.03 0-2.02-.43-2.73-1.18v.77c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V5.23c0-.12.1-.23.23-.23h1.4zm-34 11h-1.4c-.13 0-.23-.11-.23-.23V8.22c.01-.13.1-.22.23-.22h1.4c.13 0 .22.11.23.22v.68c.5-.68 1.3-1.09 2.16-1.1h.03c1.09 0 2.09.6 2.6 1.55.45-.95 1.4-1.55 2.44-1.56 1.62 0 2.93 1.25 2.9 2.78l.03 5.2c0 .13-.1.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.8 0-1.46.7-1.59 1.62l.01 4.68c0 .13-.11.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.85 0-1.54.79-1.6 1.8v4.5c0 .13-.1.23-.23.23zm53.615 0h-1.61c-.04 0-.08-.01-.12-.03-.09-.06-.13-.19-.06-.28l2.43-3.71-2.39-3.65a.213.213 0 01-.03-.12c0-.12.09-.21.21-.21h1.61c.13 0 .24.06.3.17l1.41 2.37 1.4-2.37a.34.34 0 01.3-.17h1.6c.04 0 .08.01.12.03.09.06.13.19.06.28l-2.37 3.65 2.43 3.7c0 .05.01.09.01.13 0 .12-.09.21-.21.21h-1.61c-.13 0-.24-.06-.3-.17l-1.44-2.42-1.44 2.42a.34.34 0 01-.3.17zm-7.12-1.49c-1.33 0-2.42-1.12-2.42-2.51 0-1.39 1.08-2.52 2.42-2.52 1.33 0 2.42 1.12 2.42 2.51 0 1.39-1.08 2.51-2.42 2.52zm-19.865 0c-1.32 0-2.39-1.11-2.42-2.48v-.07c.02-1.38 1.09-2.49 2.4-2.49 1.32 0 2.41 1.12 2.41 2.51 0 1.39-1.07 2.52-2.39 2.53zm-8.11-2.48c-.01 1.37-1.09 2.47-2.41 2.47s-2.42-1.12-2.42-2.51c0-1.39 1.08-2.52 2.4-2.52 1.33 0 2.39 1.11 2.41 2.48l.02.08zm18.12 2.47c-1.32 0-2.39-1.11-2.41-2.48v-.06c.02-1.38 1.09-2.48 2.41-2.48s2.42 1.12 2.42 2.51c0 1.39-1.09 2.51-2.42 2.51z'/%3E%3C/defs%3E%3Cmask id='c'%3E%3Crect width='100%25' height='100%25' fill='%23fff'/%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/mask%3E%3Cg opacity='.3' stroke='%23000' stroke-width='3'%3E%3Ccircle mask='url(%23c)' cx='11.5' cy='11.5' r='9.25'/%3E%3Cuse xlink:href='%23b' mask='url(%23c)'/%3E%3C/g%3E%3Cg opacity='.9' fill='%23fff'%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/g%3E%3C/svg%3E\")}a.mapboxgl-ctrl-logo.mapboxgl-compact{width:23px}@media (-ms-high-contrast:active){a.mapboxgl-ctrl-logo{background-color:transparent;background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='88' height='23' viewBox='0 0 88 23' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' fill-rule='evenodd'%3E%3Cdefs%3E%3Cpath id='a' d='M11.5 2.25c5.105 0 9.25 4.145 9.25 9.25s-4.145 9.25-9.25 9.25-9.25-4.145-9.25-9.25 4.145-9.25 9.25-9.25zM6.997 15.983c-.051-.338-.828-5.802 2.233-8.873a4.395 4.395 0 013.13-1.28c1.27 0 2.49.51 3.39 1.42.91.9 1.42 2.12 1.42 3.39 0 1.18-.449 2.301-1.28 3.13C12.72 16.93 7 16 7 16l-.003-.017zM15.3 10.5l-2 .8-.8 2-.8-2-2-.8 2-.8.8-2 .8 2 2 .8z'/%3E%3Cpath id='b' d='M50.63 8c.13 0 .23.1.23.23V9c.7-.76 1.7-1.18 2.73-1.18 2.17 0 3.95 1.85 3.95 4.17s-1.77 4.19-3.94 4.19c-1.04 0-2.03-.43-2.74-1.18v3.77c0 .13-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V8.23c0-.12.1-.23.23-.23h1.4zm-3.86.01c.01 0 .01 0 .01-.01.13 0 .22.1.22.22v7.55c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V15c-.7.76-1.69 1.19-2.73 1.19-2.17 0-3.94-1.87-3.94-4.19 0-2.32 1.77-4.19 3.94-4.19 1.03 0 2.02.43 2.73 1.18v-.75c0-.12.1-.23.23-.23h1.4zm26.375-.19a4.24 4.24 0 00-4.16 3.29c-.13.59-.13 1.19 0 1.77a4.233 4.233 0 004.17 3.3c2.35 0 4.26-1.87 4.26-4.19 0-2.32-1.9-4.17-4.27-4.17zM60.63 5c.13 0 .23.1.23.23v3.76c.7-.76 1.7-1.18 2.73-1.18 1.88 0 3.45 1.4 3.84 3.28.13.59.13 1.2 0 1.8-.39 1.88-1.96 3.29-3.84 3.29-1.03 0-2.02-.43-2.73-1.18v.77c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V5.23c0-.12.1-.23.23-.23h1.4zm-34 11h-1.4c-.13 0-.23-.11-.23-.23V8.22c.01-.13.1-.22.23-.22h1.4c.13 0 .22.11.23.22v.68c.5-.68 1.3-1.09 2.16-1.1h.03c1.09 0 2.09.6 2.6 1.55.45-.95 1.4-1.55 2.44-1.56 1.62 0 2.93 1.25 2.9 2.78l.03 5.2c0 .13-.1.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.8 0-1.46.7-1.59 1.62l.01 4.68c0 .13-.11.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.85 0-1.54.79-1.6 1.8v4.5c0 .13-.1.23-.23.23zm53.615 0h-1.61c-.04 0-.08-.01-.12-.03-.09-.06-.13-.19-.06-.28l2.43-3.71-2.39-3.65a.213.213 0 01-.03-.12c0-.12.09-.21.21-.21h1.61c.13 0 .24.06.3.17l1.41 2.37 1.4-2.37a.34.34 0 01.3-.17h1.6c.04 0 .08.01.12.03.09.06.13.19.06.28l-2.37 3.65 2.43 3.7c0 .05.01.09.01.13 0 .12-.09.21-.21.21h-1.61c-.13 0-.24-.06-.3-.17l-1.44-2.42-1.44 2.42a.34.34 0 01-.3.17zm-7.12-1.49c-1.33 0-2.42-1.12-2.42-2.51 0-1.39 1.08-2.52 2.42-2.52 1.33 0 2.42 1.12 2.42 2.51 0 1.39-1.08 2.51-2.42 2.52zm-19.865 0c-1.32 0-2.39-1.11-2.42-2.48v-.07c.02-1.38 1.09-2.49 2.4-2.49 1.32 0 2.41 1.12 2.41 2.51 0 1.39-1.07 2.52-2.39 2.53zm-8.11-2.48c-.01 1.37-1.09 2.47-2.41 2.47s-2.42-1.12-2.42-2.51c0-1.39 1.08-2.52 2.4-2.52 1.33 0 2.39 1.11 2.41 2.48l.02.08zm18.12 2.47c-1.32 0-2.39-1.11-2.41-2.48v-.06c.02-1.38 1.09-2.48 2.41-2.48s2.42 1.12 2.42 2.51c0 1.39-1.09 2.51-2.42 2.51z'/%3E%3C/defs%3E%3Cmask id='c'%3E%3Crect width='100%25' height='100%25' fill='%23fff'/%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/mask%3E%3Cg stroke='%23000' stroke-width='3'%3E%3Ccircle mask='url(%23c)' cx='11.5' cy='11.5' r='9.25'/%3E%3Cuse xlink:href='%23b' mask='url(%23c)'/%3E%3C/g%3E%3Cg fill='%23fff'%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/g%3E%3C/svg%3E\")}}@media (-ms-high-contrast:black-on-white){a.mapboxgl-ctrl-logo{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='88' height='23' viewBox='0 0 88 23' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' fill-rule='evenodd'%3E%3Cdefs%3E%3Cpath id='a' d='M11.5 2.25c5.105 0 9.25 4.145 9.25 9.25s-4.145 9.25-9.25 9.25-9.25-4.145-9.25-9.25 4.145-9.25 9.25-9.25zM6.997 15.983c-.051-.338-.828-5.802 2.233-8.873a4.395 4.395 0 013.13-1.28c1.27 0 2.49.51 3.39 1.42.91.9 1.42 2.12 1.42 3.39 0 1.18-.449 2.301-1.28 3.13C12.72 16.93 7 16 7 16l-.003-.017zM15.3 10.5l-2 .8-.8 2-.8-2-2-.8 2-.8.8-2 .8 2 2 .8z'/%3E%3Cpath id='b' d='M50.63 8c.13 0 .23.1.23.23V9c.7-.76 1.7-1.18 2.73-1.18 2.17 0 3.95 1.85 3.95 4.17s-1.77 4.19-3.94 4.19c-1.04 0-2.03-.43-2.74-1.18v3.77c0 .13-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V8.23c0-.12.1-.23.23-.23h1.4zm-3.86.01c.01 0 .01 0 .01-.01.13 0 .22.1.22.22v7.55c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V15c-.7.76-1.69 1.19-2.73 1.19-2.17 0-3.94-1.87-3.94-4.19 0-2.32 1.77-4.19 3.94-4.19 1.03 0 2.02.43 2.73 1.18v-.75c0-.12.1-.23.23-.23h1.4zm26.375-.19a4.24 4.24 0 00-4.16 3.29c-.13.59-.13 1.19 0 1.77a4.233 4.233 0 004.17 3.3c2.35 0 4.26-1.87 4.26-4.19 0-2.32-1.9-4.17-4.27-4.17zM60.63 5c.13 0 .23.1.23.23v3.76c.7-.76 1.7-1.18 2.73-1.18 1.88 0 3.45 1.4 3.84 3.28.13.59.13 1.2 0 1.8-.39 1.88-1.96 3.29-3.84 3.29-1.03 0-2.02-.43-2.73-1.18v.77c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V5.23c0-.12.1-.23.23-.23h1.4zm-34 11h-1.4c-.13 0-.23-.11-.23-.23V8.22c.01-.13.1-.22.23-.22h1.4c.13 0 .22.11.23.22v.68c.5-.68 1.3-1.09 2.16-1.1h.03c1.09 0 2.09.6 2.6 1.55.45-.95 1.4-1.55 2.44-1.56 1.62 0 2.93 1.25 2.9 2.78l.03 5.2c0 .13-.1.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.8 0-1.46.7-1.59 1.62l.01 4.68c0 .13-.11.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.85 0-1.54.79-1.6 1.8v4.5c0 .13-.1.23-.23.23zm53.615 0h-1.61c-.04 0-.08-.01-.12-.03-.09-.06-.13-.19-.06-.28l2.43-3.71-2.39-3.65a.213.213 0 01-.03-.12c0-.12.09-.21.21-.21h1.61c.13 0 .24.06.3.17l1.41 2.37 1.4-2.37a.34.34 0 01.3-.17h1.6c.04 0 .08.01.12.03.09.06.13.19.06.28l-2.37 3.65 2.43 3.7c0 .05.01.09.01.13 0 .12-.09.21-.21.21h-1.61c-.13 0-.24-.06-.3-.17l-1.44-2.42-1.44 2.42a.34.34 0 01-.3.17zm-7.12-1.49c-1.33 0-2.42-1.12-2.42-2.51 0-1.39 1.08-2.52 2.42-2.52 1.33 0 2.42 1.12 2.42 2.51 0 1.39-1.08 2.51-2.42 2.52zm-19.865 0c-1.32 0-2.39-1.11-2.42-2.48v-.07c.02-1.38 1.09-2.49 2.4-2.49 1.32 0 2.41 1.12 2.41 2.51 0 1.39-1.07 2.52-2.39 2.53zm-8.11-2.48c-.01 1.37-1.09 2.47-2.41 2.47s-2.42-1.12-2.42-2.51c0-1.39 1.08-2.52 2.4-2.52 1.33 0 2.39 1.11 2.41 2.48l.02.08zm18.12 2.47c-1.32 0-2.39-1.11-2.41-2.48v-.06c.02-1.38 1.09-2.48 2.41-2.48s2.42 1.12 2.42 2.51c0 1.39-1.09 2.51-2.42 2.51z'/%3E%3C/defs%3E%3Cmask id='c'%3E%3Crect width='100%25' height='100%25' fill='%23fff'/%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/mask%3E%3Cg stroke='%23fff' stroke-width='3' fill='%23fff'%3E%3Ccircle mask='url(%23c)' cx='11.5' cy='11.5' r='9.25'/%3E%3Cuse xlink:href='%23b' mask='url(%23c)'/%3E%3C/g%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/svg%3E\")}}.mapboxgl-ctrl.mapboxgl-ctrl-attrib{padding:0 5px;background-color:hsla(0,0%,100%,.5);margin:0}@media screen{.mapboxgl-ctrl-attrib.mapboxgl-compact{min-height:20px;padding:0;margin:10px;position:relative;background-color:#fff;border-radius:3px 12px 12px 3px}.mapboxgl-ctrl-attrib.mapboxgl-compact:hover{padding:2px 24px 2px 4px;visibility:visible;margin-top:6px}.mapboxgl-ctrl-bottom-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:hover,.mapboxgl-ctrl-top-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:hover{padding:2px 4px 2px 24px;border-radius:12px 3px 3px 12px}.mapboxgl-ctrl-attrib.mapboxgl-compact .mapboxgl-ctrl-attrib-inner{display:none}.mapboxgl-ctrl-attrib.mapboxgl-compact:hover .mapboxgl-ctrl-attrib-inner{display:block}.mapboxgl-ctrl-attrib.mapboxgl-compact:after{content:\"\";cursor:pointer;position:absolute;background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='24' height='24' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill-rule='evenodd'%3E%3Cpath d='M4 10a6 6 0 1012 0 6 6 0 10-12 0m5-3a1 1 0 102 0 1 1 0 10-2 0m0 3a1 1 0 112 0v3a1 1 0 11-2 0'/%3E%3C/svg%3E\");background-color:hsla(0,0%,100%,.5);width:24px;height:24px;box-sizing:border-box;border-radius:12px}.mapboxgl-ctrl-bottom-right>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{bottom:0;right:0}.mapboxgl-ctrl-top-right>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{top:0;right:0}.mapboxgl-ctrl-top-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{top:0;left:0}.mapboxgl-ctrl-bottom-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{bottom:0;left:0}}@media screen and (-ms-high-contrast:active){.mapboxgl-ctrl-attrib.mapboxgl-compact:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='24' height='24' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill-rule='evenodd' fill='%23fff'%3E%3Cpath d='M4 10a6 6 0 1012 0 6 6 0 10-12 0m5-3a1 1 0 102 0 1 1 0 10-2 0m0 3a1 1 0 112 0v3a1 1 0 11-2 0'/%3E%3C/svg%3E\")}}@media screen and (-ms-high-contrast:black-on-white){.mapboxgl-ctrl-attrib.mapboxgl-compact:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='24' height='24' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill-rule='evenodd'%3E%3Cpath d='M4 10a6 6 0 1012 0 6 6 0 10-12 0m5-3a1 1 0 102 0 1 1 0 10-2 0m0 3a1 1 0 112 0v3a1 1 0 11-2 0'/%3E%3C/svg%3E\")}}.mapboxgl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.mapboxgl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.mapboxgl-ctrl-attrib .mapbox-improve-map{font-weight:700;margin-left:2px}.mapboxgl-attrib-empty{display:none}.mapboxgl-ctrl-scale{background-color:hsla(0,0%,100%,.75);font-size:10px;border:2px solid #333;border-top:#333;padding:0 5px;color:#333;box-sizing:border-box}.mapboxgl-popup{position:absolute;top:0;left:0;display:-webkit-flex;display:flex;will-change:transform;pointer-events:none}.mapboxgl-popup-anchor-top,.mapboxgl-popup-anchor-top-left,.mapboxgl-popup-anchor-top-right{-webkit-flex-direction:column;flex-direction:column}.mapboxgl-popup-anchor-bottom,.mapboxgl-popup-anchor-bottom-left,.mapboxgl-popup-anchor-bottom-right{-webkit-flex-direction:column-reverse;flex-direction:column-reverse}.mapboxgl-popup-anchor-left{-webkit-flex-direction:row;flex-direction:row}.mapboxgl-popup-anchor-right{-webkit-flex-direction:row-reverse;flex-direction:row-reverse}.mapboxgl-popup-tip{width:0;height:0;border:10px solid transparent;z-index:1}.mapboxgl-popup-anchor-top .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-top:none;border-bottom-color:#fff}.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip{-webkit-align-self:flex-start;align-self:flex-start;border-top:none;border-left:none;border-bottom-color:#fff}.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip{-webkit-align-self:flex-end;align-self:flex-end;border-top:none;border-right:none;border-bottom-color:#fff}.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-bottom:none;border-top-color:#fff}.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip{-webkit-align-self:flex-start;align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip{-webkit-align-self:flex-end;align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.mapboxgl-popup-anchor-left .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-left:none;border-right-color:#fff}.mapboxgl-popup-anchor-right .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-right:none;border-left-color:#fff}.mapboxgl-popup-close-button{position:absolute;right:0;top:0;border:0;border-radius:0 3px 0 0;cursor:pointer;background-color:transparent}.mapboxgl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.mapboxgl-popup-content{position:relative;background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:10px 10px 15px;pointer-events:auto}.mapboxgl-popup-anchor-top-left .mapboxgl-popup-content{border-top-left-radius:0}.mapboxgl-popup-anchor-top-right .mapboxgl-popup-content{border-top-right-radius:0}.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-content{border-bottom-left-radius:0}.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-content{border-bottom-right-radius:0}.mapboxgl-popup-track-pointer{display:none}.mapboxgl-popup-track-pointer *{pointer-events:none;user-select:none}.mapboxgl-map:hover .mapboxgl-popup-track-pointer{display:flex}.mapboxgl-map:active .mapboxgl-popup-track-pointer{display:none}.mapboxgl-marker{position:absolute;top:0;left:0;will-change:transform}.mapboxgl-user-location-dot,.mapboxgl-user-location-dot:before{background-color:#1da1f2;width:15px;height:15px;border-radius:50%}.mapboxgl-user-location-dot:before{content:\"\";position:absolute;-webkit-animation:mapboxgl-user-location-dot-pulse 2s infinite;-moz-animation:mapboxgl-user-location-dot-pulse 2s infinite;-ms-animation:mapboxgl-user-location-dot-pulse 2s infinite;animation:mapboxgl-user-location-dot-pulse 2s infinite}.mapboxgl-user-location-dot:after{border-radius:50%;border:2px solid #fff;content:\"\";height:19px;left:-2px;position:absolute;top:-2px;width:19px;box-sizing:border-box;box-shadow:0 0 3px rgba(0,0,0,.35)}@-webkit-keyframes mapboxgl-user-location-dot-pulse{0%{-webkit-transform:scale(1);opacity:1}70%{-webkit-transform:scale(3);opacity:0}to{-webkit-transform:scale(1);opacity:0}}@-ms-keyframes mapboxgl-user-location-dot-pulse{0%{-ms-transform:scale(1);opacity:1}70%{-ms-transform:scale(3);opacity:0}to{-ms-transform:scale(1);opacity:0}}@keyframes mapboxgl-user-location-dot-pulse{0%{transform:scale(1);opacity:1}70%{transform:scale(3);opacity:0}to{transform:scale(1);opacity:0}}.mapboxgl-user-location-dot-stale{background-color:#aaa}.mapboxgl-user-location-dot-stale:after{display:none}.mapboxgl-user-location-accuracy-circle{background-color:rgba(29,161,242,.2);width:1px;height:1px;border-radius:100%}.mapboxgl-crosshair,.mapboxgl-crosshair .mapboxgl-interactive,.mapboxgl-crosshair .mapboxgl-interactive:active{cursor:crosshair}.mapboxgl-boxzoom{position:absolute;top:0;left:0;width:0;height:0;background:#fff;border:2px dotted #202020;opacity:.5}@media print{.mapbox-improve-map{display:none}}", ""]);
// exports
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(157);
if(typeof content === 'string') content = [[module.i, content, '']];
// Prepare cssTransformation
var transform;
var options = {}
options.transform = transform
// add the styles to the DOM
var update = __webpack_require__(41)(content, options);
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!../../../../node_modules/css-loader/index.js!./mapbox.css", function() {
var newContent = require("!!../../../../node_modules/css-loader/index.js!./mapbox.css");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(40)(false);
// imports
// module
exports.push([module.i, ".ui-widget-content .leaflet-popup-content {\n color: #555555;\n}\n\n.mapbox-logo {\n display: none;\n}\n\n.phrasea-popup .leaflet-popup-content-wrapper {\n background: #3b3b3b;\n color: #fff;\n font-size: 16px;\n line-height: 24px;\n border-radius: 3px;\n}\n\n.phrasea-popup .leaflet-popup-content-wrapper a {\n color: rgba(255, 255, 255, 0.5);\n}\n\n.phrasea-popup .leaflet-popup-tip-container {\n width: 30px;\n height: 15px;\n}\n\n.phrasea-popup .leaflet-popup-content p {\n color: #FFF;\n\n}\n\n.phrasea-popup .leaflet-popup-content p.help {\n text-align: center;\n font-style: italic;\n}\n\n.phrasea-popup .leaflet-popup-tip {\n border-top: 10px solid #3b3b3b;\n}\n\n.updated-position {\n text-align: center;\n}\n\n.ui-widget-content .leaflet-container {\n color: #555555;\n}\n\n.ui-widget-content .leaflet-container label {\n color: #555555;\n display: block;\n font-size: 12px;\n padding: 0 15px;\n}\n\n.ui-widget-content .leaflet-container form {\n margin: 10px 0 0 0;\n}\n\n.ui-widget-content .leaflet-container input[type=\"radio\"] {\n margin: -4px 0 0 0;\n padding: 0;\n}\n\n.leaflet-control-layers-selector {\n margin-top: 2px;\n position: relative;\n top: 1px;\n}\n\n.leaflet-control-mapbox-geocoder .leaflet-control-mapbox-geocoder-form input {\n box-shadow: none;\n font-size: 12px;\n}\n\n.ui-widget-content .leaflet-container form {\n margin-top: 0;\n}\n\n.mapboxgl-popup-content {\n background: #555555;\n width: 200px;\n font-size: 15px;\n}\n\n.mapboxgl-popup-anchor-top .mapboxgl-popup-tip {\n border-bottom-color: #555555;\n}\n\n.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip {\n border-bottom-color: #555555;\n}\n\n.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip {\n\n border-bottom-color: #555555;\n}\n.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip {\n\n border-top-color: #555555;\n}\n\n.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip {\n\n border-top-color: #555555;\n}\n\n.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip {\n\n border-top-color: #555555;\n}\n\n.mapboxgl-popup-anchor-left .mapboxgl-popup-tip {\n\n border-right-color: #555555;\n}\n\n.mapboxgl-popup-anchor-right .mapboxgl-popup-tip {\n\n border-left-color: #555555;\n}\n\n.map-selection-container {\n position: absolute;\n width: 30px;\n height: 30px;\n top: 130px;\n right: 10px;\n border-radius: 5px;\n border: 2px solid #ccc;\n background-color: #fff;\n cursor: pointer;\n box-sizing: border-box;\n}\n\n.map-selection-container:hover {\n background-color: #eee;\n}\n\n.map-dropdown-content {\n display: none;\n min-width: 80px;\n position: absolute;\n right: 0;\n background: #FFF;\n padding: 10px;\n border: 1px solid #ccc;\n -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);\n -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);\n}\n\n.map-dropdown-content label {\n color: #555555;\n display: block;\n font-size: 13px;\n}\n\n.map-drop-btn {\n background: transparent;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n border: none;\n margin: 0;\n padding: 0;\n}\n\n.map-drop-btn i {\n padding: 6px;\n margin: 0;\n}\n\n.circle-control-container {\n position: absolute;\n top: 170px;\n right: 10px;\n}\n\n#map-notice-btn {\n position: absolute;\n top: 6px;\n left: 6px;\n background: transparent;\n cursor: pointer;\n border: none;\n width: 30px;\n height: 30px;\n margin: 0;\n padding: 0;\n display: none;\n}\n\n#map-notice-btn:focus {\n outline: 0;\n}\n\n#notice-box {\n display: block;\n position: absolute;\n top: 6px;\n left: 6px;\n width: 305px;\n border-radius: 6px;\n box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);\n background-color: #ffffff;\n border: solid 1px #8f8f8f;\n padding: 4px 5px 5px 6px;\n}\n\n.notice-header {\n display: block;\n}\n\n.notice-title {\n font-family: Roboto;\n font-size: 15px;\n font-weight: 500;\n letter-spacing: 0px;\n color: #3e3d3d;\n margin-left: 6px;\n line-height: 20px;\n vertical-align: middle;\n margin-right: 20px;\n}\n\n.notice-desc {\n display: block;\n font-family: Roboto;\n font-size: 12px;\n line-height: 1.17;\n letter-spacing: 0px;\n color: #3e3d3d;\n margin: 6px 10px 0px 10px;\n}\n\n.notice-close-btn {\n position: absolute;\n top: 0px;\n right: 2px;\n font-family: Roboto;\n font-size: 16px;\n color: #3e3d3d;\n cursor: pointer;\n padding: 4px;\n}\n\n.draw-icon {\n margin-bottom: 5px;\n padding: 0;\n position: relative;\n border-radius: 5px;\n border: 2px solid #ccc;\n background-color: #fff;\n cursor: pointer;\n box-sizing: border-box;\n display: block;\n}\n\n.draw-icon:hover {\n background-color: rgba(0, 0, 0, 0.05);\n}\n\n.draw-icon.selected {\n background-color: #aaa;\n}\n\n.draw-icon i {\n font-size: 20px;\n line-height: 26px;\n}\n\n.map-dropdown-content label input[type=\"radio\"] {\n margin: 0px 0 0 0;\n padding: 0;\n}\n\n.map-dropdown-content.show {\n display: block;\n}\n", ""]);
// exports
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(159);
if(typeof content === 'string') content = [[module.i, content, '']];
// Prepare cssTransformation
var transform;
var options = {}
options.transform = transform
// add the styles to the DOM
var update = __webpack_require__(41)(content, options);
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!../../css-loader/index.js!./leaflet.draw.css", function() {
var newContent = require("!!../../css-loader/index.js!./leaflet.draw.css");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
var escape = __webpack_require__(67);
exports = module.exports = __webpack_require__(40)(false);
// imports
// module
exports.push([module.i, "/* ================================================================== */\n/* Toolbars\n/* ================================================================== */\n\n.leaflet-draw-section {\n\tposition: relative;\n}\n\n.leaflet-draw-toolbar {\n\tmargin-top: 12px;\n}\n\n.leaflet-draw-toolbar-top {\n\tmargin-top: 0;\n}\n\n.leaflet-draw-toolbar-notop a:first-child {\n\tborder-top-right-radius: 0;\n}\n\n.leaflet-draw-toolbar-nobottom a:last-child {\n\tborder-bottom-right-radius: 0;\n}\n\n.leaflet-draw-toolbar a {\n\tbackground-image: url(" + escape(__webpack_require__(160)) + ");\n\tbackground-repeat: no-repeat;\n}\n\n.leaflet-retina .leaflet-draw-toolbar a {\n\tbackground-image: url(" + escape(__webpack_require__(161)) + ");\n\tbackground-size: 270px 30px;\n}\n\n.leaflet-draw a {\n\tdisplay: block;\n\ttext-align: center;\n\ttext-decoration: none;\n}\n\n/* ================================================================== */\n/* Toolbar actions menu\n/* ================================================================== */\n\n.leaflet-draw-actions {\n\tdisplay: none;\n\tlist-style: none;\n\tmargin: 0;\n\tpadding: 0;\n\tposition: absolute;\n\tleft: 26px; /* leaflet-draw-toolbar.left + leaflet-draw-toolbar.width */\n\ttop: 0;\n\twhite-space: nowrap;\n}\n\n.leaflet-touch .leaflet-draw-actions {\n\tleft: 32px;\n}\n\n.leaflet-right .leaflet-draw-actions {\n\tright:26px;\n\tleft:auto;\n}\n\n.leaflet-touch .leaflet-right .leaflet-draw-actions {\n\tright:32px;\n\tleft:auto;\n}\n\n.leaflet-draw-actions li {\n\tdisplay: inline-block;\n}\n\n.leaflet-draw-actions li:first-child a {\n\tborder-left: none;\n}\n\n.leaflet-draw-actions li:last-child a {\n\t-webkit-border-radius: 0 4px 4px 0;\n\t border-radius: 0 4px 4px 0;\n}\n\n.leaflet-right .leaflet-draw-actions li:last-child a {\n\t-webkit-border-radius: 0;\n\t border-radius: 0;\n}\n\n.leaflet-right .leaflet-draw-actions li:first-child a {\n\t-webkit-border-radius: 4px 0 0 4px;\n\t border-radius: 4px 0 0 4px;\n}\n\n.leaflet-draw-actions a {\n\tbackground-color: #919187;\n\tborder-left: 1px solid #AAA;\n\tcolor: #FFF;\n\tfont: 11px/19px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n\tline-height: 28px;\n\ttext-decoration: none;\n\tpadding-left: 10px;\n\tpadding-right: 10px;\n\theight: 28px;\n}\n\n.leaflet-touch .leaflet-draw-actions a {\n\tfont-size: 12px;\n\tline-height: 30px;\n\theight: 30px;\n}\n\n.leaflet-draw-actions-bottom {\n\tmargin-top: 0;\n}\n\n.leaflet-draw-actions-top {\n\tmargin-top: 1px;\n}\n\n.leaflet-draw-actions-top a,\n.leaflet-draw-actions-bottom a {\n\theight: 27px;\n\tline-height: 27px;\n}\n\n.leaflet-draw-actions a:hover {\n\tbackground-color: #A0A098;\n}\n\n.leaflet-draw-actions-top.leaflet-draw-actions-bottom a {\n\theight: 26px;\n\tline-height: 26px;\n}\n\n/* ================================================================== */\n/* Draw toolbar\n/* ================================================================== */\n\n.leaflet-draw-toolbar .leaflet-draw-draw-polyline {\n\tbackground-position: -2px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-polyline {\n\tbackground-position: 0 -1px;\n}\n\n.leaflet-draw-toolbar .leaflet-draw-draw-polygon {\n\tbackground-position: -31px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-polygon {\n\tbackground-position: -29px -1px;\n}\n\n.leaflet-draw-toolbar .leaflet-draw-draw-rectangle {\n\tbackground-position: -62px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-rectangle {\n\tbackground-position: -60px -1px;\n}\n\n.leaflet-draw-toolbar .leaflet-draw-draw-circle {\n\tbackground-position: -92px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-circle {\n\tbackground-position: -90px -1px;\n}\n\n.leaflet-draw-toolbar .leaflet-draw-draw-marker {\n\tbackground-position: -122px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-marker {\n\tbackground-position: -120px -1px;\n}\n\n/* ================================================================== */\n/* Edit toolbar\n/* ================================================================== */\n\n.leaflet-draw-toolbar .leaflet-draw-edit-edit {\n\tbackground-position: -152px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-edit {\n\tbackground-position: -150px -1px;\n}\n\n.leaflet-draw-toolbar .leaflet-draw-edit-remove {\n\tbackground-position: -182px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-remove {\n\tbackground-position: -180px -1px;\n}\n\n.leaflet-draw-toolbar .leaflet-draw-edit-edit.leaflet-disabled {\n\tbackground-position: -212px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-edit.leaflet-disabled {\n\tbackground-position: -210px -1px;\n}\n\n.leaflet-draw-toolbar .leaflet-draw-edit-remove.leaflet-disabled {\n\tbackground-position: -242px -2px;\n}\n\n.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-remove.leaflet-disabled {\n\tbackground-position: -240px -2px;\n}\n\n/* ================================================================== */\n/* Drawing styles\n/* ================================================================== */\n\n.leaflet-mouse-marker {\n\tbackground-color: #fff;\n\tcursor: crosshair;\n}\n\n.leaflet-draw-tooltip {\n\tbackground: rgb(54, 54, 54);\n\tbackground: rgba(0, 0, 0, 0.5);\n\tborder: 1px solid transparent;\n\t-webkit-border-radius: 4px;\n\t border-radius: 4px;\n\tcolor: #fff;\n\tfont: 12px/18px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n\tmargin-left: 20px;\n\tmargin-top: -21px;\n\tpadding: 4px 8px;\n\tposition: absolute;\n\tvisibility: hidden;\n\twhite-space: nowrap;\n\tz-index: 6;\n}\n\n.leaflet-draw-tooltip:before {\n\tborder-right: 6px solid black;\n\tborder-right-color: rgba(0, 0, 0, 0.5);\n\tborder-top: 6px solid transparent;\n\tborder-bottom: 6px solid transparent;\n\tcontent: \"\";\n\tposition: absolute;\n\ttop: 7px;\n\tleft: -7px;\n}\n\n.leaflet-error-draw-tooltip {\n\tbackground-color: #F2DEDE;\n\tborder: 1px solid #E6B6BD;\n\tcolor: #B94A48;\n}\n\n.leaflet-error-draw-tooltip:before {\n\tborder-right-color: #E6B6BD;\n}\n\n.leaflet-draw-tooltip-single {\n\tmargin-top: -12px\n}\n\n.leaflet-draw-tooltip-subtext {\n\tcolor: #f8d5e4;\n}\n\n.leaflet-draw-guide-dash {\n\tfont-size: 1%;\n\topacity: 0.6;\n\tposition: absolute;\n\twidth: 5px;\n\theight: 5px;\n}\n\n/* ================================================================== */\n/* Edit styles\n/* ================================================================== */\n\n.leaflet-edit-marker-selected {\n\tbackground: rgba(254, 87, 161, 0.1);\n\tborder: 4px dashed rgba(254, 87, 161, 0.6);\n\t-webkit-border-radius: 4px;\n\t border-radius: 4px;\n\tbox-sizing: content-box;\n}\n\n.leaflet-edit-move {\n\tcursor: move;\n}\n\n.leaflet-edit-resize {\n\tcursor: pointer;\n}\n\n/* ================================================================== */\n/* Old IE styles\n/* ================================================================== */\n\n.leaflet-oldie .leaflet-draw-toolbar {\n\tborder: 1px solid #999;\n}", ""]);
// exports
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "spritesheet.429614.png";
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "spritesheet-2x.2f19f5.png";
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(163);
if(typeof content === 'string') content = [[module.i, content, '']];
// Prepare cssTransformation
var transform;
var options = {}
options.transform = transform
// add the styles to the DOM
var update = __webpack_require__(41)(content, options);
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!../../css-loader/index.js!./leaflet.contextmenu.css", function() {
var newContent = require("!!../../css-loader/index.js!./leaflet.contextmenu.css");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(40)(false);
// imports
// module
exports.push([module.i, ".leaflet-contextmenu {\n display: none;\n\tbox-shadow: 0 1px 7px rgba(0,0,0,0.4);\n\t-webkit-border-radius: 4px;\n\tborder-radius: 4px;\n padding: 4px 0;\n background-color: #fff;\n cursor: default;\n\t-webkit-user-select: none;\n\t-moz-user-select: none;\n\tuser-select: none;\n}\n\n.leaflet-contextmenu a.leaflet-contextmenu-item {\n display: block;\n color: #222;\n font-size: 12px;\n line-height: 20px;\n text-decoration: none;\n padding: 0 12px;\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n cursor: default;\n outline: none;\n}\n\n.leaflet-contextmenu a.leaflet-contextmenu-item-disabled {\n opacity: 0.5;\n}\n\n.leaflet-contextmenu a.leaflet-contextmenu-item.over {\n background-color: #f4f4f4;\n border-top: 1px solid #f0f0f0;\n border-bottom: 1px solid #f0f0f0;\n}\n\n.leaflet-contextmenu a.leaflet-contextmenu-item-disabled.over {\n background-color: inherit;\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n}\n\n.leaflet-contextmenu-icon {\n margin: 2px 8px 0 0;\n width: 16px;\n height: 16px;\n float: left;\n border: 0;\n}\n\n.leaflet-contextmenu-separator {\n border-bottom: 1px solid #ccc;\n margin: 5px 0;\n}", ""]);
// exports
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
// Copyright (C) 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* Implements RFC 3986 for parsing/formatting URIs.
*
* @author mikesamuel@gmail.com
* \@provides URI
* \@overrides window
*/
var URI = (function () {
/**
* creates a uri from the string form. The parser is relaxed, so special
* characters that aren't escaped but don't cause ambiguities will not cause
* parse failures.
*
* @return {URI|null}
*/
function parse(uriStr) {
var m = ('' + uriStr).match(URI_RE_);
if (!m) { return null; }
return new URI(
nullIfAbsent(m[1]),
nullIfAbsent(m[2]),
nullIfAbsent(m[3]),
nullIfAbsent(m[4]),
nullIfAbsent(m[5]),
nullIfAbsent(m[6]),
nullIfAbsent(m[7]));
}
/**
* creates a uri from the given parts.
*
* @param scheme {string} an unencoded scheme such as "http" or null
* @param credentials {string} unencoded user credentials or null
* @param domain {string} an unencoded domain name or null
* @param port {number} a port number in [1, 32768].
* -1 indicates no port, as does null.
* @param path {string} an unencoded path
* @param query {Array.<string>|string|null} a list of unencoded cgi
* parameters where even values are keys and odds the corresponding values
* or an unencoded query.
* @param fragment {string} an unencoded fragment without the "#" or null.
* @return {URI}
*/
function create(scheme, credentials, domain, port, path, query, fragment) {
var uri = new URI(
encodeIfExists2(scheme, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_),
encodeIfExists2(
credentials, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_),
encodeIfExists(domain),
port > 0 ? port.toString() : null,
encodeIfExists2(path, URI_DISALLOWED_IN_PATH_),
null,
encodeIfExists(fragment));
if (query) {
if ('string' === typeof query) {
uri.setRawQuery(query.replace(/[^?&=0-9A-Za-z_\-~.%]/g, encodeOne));
} else {
uri.setAllParameters(query);
}
}
return uri;
}
function encodeIfExists(unescapedPart) {
if ('string' == typeof unescapedPart) {
return encodeURIComponent(unescapedPart);
}
return null;
};
/**
* if unescapedPart is non null, then escapes any characters in it that aren't
* valid characters in a url and also escapes any special characters that
* appear in extra.
*
* @param unescapedPart {string}
* @param extra {RegExp} a character set of characters in [\01-\177].
* @return {string|null} null iff unescapedPart == null.
*/
function encodeIfExists2(unescapedPart, extra) {
if ('string' == typeof unescapedPart) {
return encodeURI(unescapedPart).replace(extra, encodeOne);
}
return null;
};
/** converts a character in [\01-\177] to its url encoded equivalent. */
function encodeOne(ch) {
var n = ch.charCodeAt(0);
return '%' + '0123456789ABCDEF'.charAt((n >> 4) & 0xf) +
'0123456789ABCDEF'.charAt(n & 0xf);
}
/**
* {@updoc
* $ normPath('foo/./bar')
* # 'foo/bar'
* $ normPath('./foo')
* # 'foo'
* $ normPath('foo/.')
* # 'foo'
* $ normPath('foo//bar')
* # 'foo/bar'
* }
*/
function normPath(path) {
return path.replace(/(^|\/)\.(?:\/|$)/g, '$1').replace(/\/{2,}/g, '/');
}
var PARENT_DIRECTORY_HANDLER = new RegExp(
''
// A path break
+ '(/|^)'
// followed by a non .. path element
// (cannot be . because normPath is used prior to this RegExp)
+ '(?:[^./][^/]*|\\.{2,}(?:[^./][^/]*)|\\.{3,}[^/]*)'
// followed by .. followed by a path break.
+ '/\\.\\.(?:/|$)');
var PARENT_DIRECTORY_HANDLER_RE = new RegExp(PARENT_DIRECTORY_HANDLER);
var EXTRA_PARENT_PATHS_RE = /^(?:\.\.\/)*(?:\.\.$)?/;
/**
* Normalizes its input path and collapses all . and .. sequences except for
* .. sequences that would take it above the root of the current parent
* directory.
* {@updoc
* $ collapse_dots('foo/../bar')
* # 'bar'
* $ collapse_dots('foo/./bar')
* # 'foo/bar'
* $ collapse_dots('foo/../bar/./../../baz')
* # 'baz'
* $ collapse_dots('../foo')
* # '../foo'
* $ collapse_dots('../foo').replace(EXTRA_PARENT_PATHS_RE, '')
* # 'foo'
* }
*/
function collapse_dots(path) {
if (path === null) { return null; }
var p = normPath(path);
// Only /../ left to flatten
var r = PARENT_DIRECTORY_HANDLER_RE;
// We replace with $1 which matches a / before the .. because this
// guarantees that:
// (1) we have at most 1 / between the adjacent place,
// (2) always have a slash if there is a preceding path section, and
// (3) we never turn a relative path into an absolute path.
for (var q; (q = p.replace(r, '$1')) != p; p = q) {};
return p;
}
/**
* resolves a relative url string to a base uri.
* @return {URI}
*/
function resolve(baseUri, relativeUri) {
// there are several kinds of relative urls:
// 1. //foo - replaces everything from the domain on. foo is a domain name
// 2. foo - replaces the last part of the path, the whole query and fragment
// 3. /foo - replaces the the path, the query and fragment
// 4. ?foo - replace the query and fragment
// 5. #foo - replace the fragment only
var absoluteUri = baseUri.clone();
// we satisfy these conditions by looking for the first part of relativeUri
// that is not blank and applying defaults to the rest
var overridden = relativeUri.hasScheme();
if (overridden) {
absoluteUri.setRawScheme(relativeUri.getRawScheme());
} else {
overridden = relativeUri.hasCredentials();
}
if (overridden) {
absoluteUri.setRawCredentials(relativeUri.getRawCredentials());
} else {
overridden = relativeUri.hasDomain();
}
if (overridden) {
absoluteUri.setRawDomain(relativeUri.getRawDomain());
} else {
overridden = relativeUri.hasPort();
}
var rawPath = relativeUri.getRawPath();
var simplifiedPath = collapse_dots(rawPath);
if (overridden) {
absoluteUri.setPort(relativeUri.getPort());
simplifiedPath = simplifiedPath
&& simplifiedPath.replace(EXTRA_PARENT_PATHS_RE, '');
} else {
overridden = !!rawPath;
if (overridden) {
// resolve path properly
if (simplifiedPath.charCodeAt(0) !== 0x2f /* / */) { // path is relative
var absRawPath = collapse_dots(absoluteUri.getRawPath() || '')
.replace(EXTRA_PARENT_PATHS_RE, '');
var slash = absRawPath.lastIndexOf('/') + 1;
simplifiedPath = collapse_dots(
(slash ? absRawPath.substring(0, slash) : '')
+ collapse_dots(rawPath))
.replace(EXTRA_PARENT_PATHS_RE, '');
}
} else {
simplifiedPath = simplifiedPath
&& simplifiedPath.replace(EXTRA_PARENT_PATHS_RE, '');
if (simplifiedPath !== rawPath) {
absoluteUri.setRawPath(simplifiedPath);
}
}
}
if (overridden) {
absoluteUri.setRawPath(simplifiedPath);
} else {
overridden = relativeUri.hasQuery();
}
if (overridden) {
absoluteUri.setRawQuery(relativeUri.getRawQuery());
} else {
overridden = relativeUri.hasFragment();
}
if (overridden) {
absoluteUri.setRawFragment(relativeUri.getRawFragment());
}
return absoluteUri;
}
/**
* a mutable URI.
*
* This class contains setters and getters for the parts of the URI.
* The <tt>getXYZ</tt>/<tt>setXYZ</tt> methods return the decoded part -- so
* <code>uri.parse('/foo%20bar').getPath()</code> will return the decoded path,
* <tt>/foo bar</tt>.
*
* <p>The raw versions of fields are available too.
* <code>uri.parse('/foo%20bar').getRawPath()</code> will return the raw path,
* <tt>/foo%20bar</tt>. Use the raw setters with care, since
* <code>URI::toString</code> is not guaranteed to return a valid url if a
* raw setter was used.
*
* <p>All setters return <tt>this</tt> and so may be chained, a la
* <code>uri.parse('/foo').setFragment('part').toString()</code>.
*
* <p>You should not use this constructor directly -- please prefer the factory
* functions {@link uri.parse}, {@link uri.create}, {@link uri.resolve}
* instead.</p>
*
* <p>The parameters are all raw (assumed to be properly escaped) parts, and
* any (but not all) may be null. Undefined is not allowed.</p>
*
* @constructor
*/
function URI(
rawScheme,
rawCredentials, rawDomain, port,
rawPath, rawQuery, rawFragment) {
this.scheme_ = rawScheme;
this.credentials_ = rawCredentials;
this.domain_ = rawDomain;
this.port_ = port;
this.path_ = rawPath;
this.query_ = rawQuery;
this.fragment_ = rawFragment;
/**
* @type {Array|null}
*/
this.paramCache_ = null;
}
/** returns the string form of the url. */
URI.prototype.toString = function () {
var out = [];
if (null !== this.scheme_) { out.push(this.scheme_, ':'); }
if (null !== this.domain_) {
out.push('//');
if (null !== this.credentials_) { out.push(this.credentials_, '@'); }
out.push(this.domain_);
if (null !== this.port_) { out.push(':', this.port_.toString()); }
}
if (null !== this.path_) { out.push(this.path_); }
if (null !== this.query_) { out.push('?', this.query_); }
if (null !== this.fragment_) { out.push('#', this.fragment_); }
return out.join('');
};
URI.prototype.clone = function () {
return new URI(this.scheme_, this.credentials_, this.domain_, this.port_,
this.path_, this.query_, this.fragment_);
};
URI.prototype.getScheme = function () {
// HTML5 spec does not require the scheme to be lowercased but
// all common browsers except Safari lowercase the scheme.
return this.scheme_ && decodeURIComponent(this.scheme_).toLowerCase();
};
URI.prototype.getRawScheme = function () {
return this.scheme_;
};
URI.prototype.setScheme = function (newScheme) {
this.scheme_ = encodeIfExists2(
newScheme, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_);
return this;
};
URI.prototype.setRawScheme = function (newScheme) {
this.scheme_ = newScheme ? newScheme : null;
return this;
};
URI.prototype.hasScheme = function () {
return null !== this.scheme_;
};
URI.prototype.getCredentials = function () {
return this.credentials_ && decodeURIComponent(this.credentials_);
};
URI.prototype.getRawCredentials = function () {
return this.credentials_;
};
URI.prototype.setCredentials = function (newCredentials) {
this.credentials_ = encodeIfExists2(
newCredentials, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_);
return this;
};
URI.prototype.setRawCredentials = function (newCredentials) {
this.credentials_ = newCredentials ? newCredentials : null;
return this;
};
URI.prototype.hasCredentials = function () {
return null !== this.credentials_;
};
URI.prototype.getDomain = function () {
return this.domain_ && decodeURIComponent(this.domain_);
};
URI.prototype.getRawDomain = function () {
return this.domain_;
};
URI.prototype.setDomain = function (newDomain) {
return this.setRawDomain(newDomain && encodeURIComponent(newDomain));
};
URI.prototype.setRawDomain = function (newDomain) {
this.domain_ = newDomain ? newDomain : null;
// Maintain the invariant that paths must start with a slash when the URI
// is not path-relative.
return this.setRawPath(this.path_);
};
URI.prototype.hasDomain = function () {
return null !== this.domain_;
};
URI.prototype.getPort = function () {
return this.port_ && decodeURIComponent(this.port_);
};
URI.prototype.setPort = function (newPort) {
if (newPort) {
newPort = Number(newPort);
if (newPort !== (newPort & 0xffff)) {
throw new Error('Bad port number ' + newPort);
}
this.port_ = '' + newPort;
} else {
this.port_ = null;
}
return this;
};
URI.prototype.hasPort = function () {
return null !== this.port_;
};
URI.prototype.getPath = function () {
return this.path_ && decodeURIComponent(this.path_);
};
URI.prototype.getRawPath = function () {
return this.path_;
};
URI.prototype.setPath = function (newPath) {
return this.setRawPath(encodeIfExists2(newPath, URI_DISALLOWED_IN_PATH_));
};
URI.prototype.setRawPath = function (newPath) {
if (newPath) {
newPath = String(newPath);
this.path_ =
// Paths must start with '/' unless this is a path-relative URL.
(!this.domain_ || /^\//.test(newPath)) ? newPath : '/' + newPath;
} else {
this.path_ = null;
}
return this;
};
URI.prototype.hasPath = function () {
return null !== this.path_;
};
URI.prototype.getQuery = function () {
// From http://www.w3.org/Addressing/URL/4_URI_Recommentations.html
// Within the query string, the plus sign is reserved as shorthand notation
// for a space.
return this.query_ && decodeURIComponent(this.query_).replace(/\+/g, ' ');
};
URI.prototype.getRawQuery = function () {
return this.query_;
};
URI.prototype.setQuery = function (newQuery) {
this.paramCache_ = null;
this.query_ = encodeIfExists(newQuery);
return this;
};
URI.prototype.setRawQuery = function (newQuery) {
this.paramCache_ = null;
this.query_ = newQuery ? newQuery : null;
return this;
};
URI.prototype.hasQuery = function () {
return null !== this.query_;
};
/**
* sets the query given a list of strings of the form
* [ key0, value0, key1, value1, ... ].
*
* <p><code>uri.setAllParameters(['a', 'b', 'c', 'd']).getQuery()</code>
* will yield <code>'a=b&c=d'</code>.
*/
URI.prototype.setAllParameters = function (params) {
if (typeof params === 'object') {
if (!(params instanceof Array)
&& (params instanceof Object
|| Object.prototype.toString.call(params) !== '[object Array]')) {
var newParams = [];
var i = -1;
for (var k in params) {
var v = params[k];
if ('string' === typeof v) {
newParams[++i] = k;
newParams[++i] = v;
}
}
params = newParams;
}
}
this.paramCache_ = null;
var queryBuf = [];
var separator = '';
for (var j = 0; j < params.length;) {
var k = params[j++];
var v = params[j++];
queryBuf.push(separator, encodeURIComponent(k.toString()));
separator = '&';
if (v) {
queryBuf.push('=', encodeURIComponent(v.toString()));
}
}
this.query_ = queryBuf.join('');
return this;
};
URI.prototype.checkParameterCache_ = function () {
if (!this.paramCache_) {
var q = this.query_;
if (!q) {
this.paramCache_ = [];
} else {
var cgiParams = q.split(/[&\?]/);
var out = [];
var k = -1;
for (var i = 0; i < cgiParams.length; ++i) {
var m = cgiParams[i].match(/^([^=]*)(?:=(.*))?$/);
// From http://www.w3.org/Addressing/URL/4_URI_Recommentations.html
// Within the query string, the plus sign is reserved as shorthand
// notation for a space.
out[++k] = decodeURIComponent(m[1]).replace(/\+/g, ' ');
out[++k] = decodeURIComponent(m[2] || '').replace(/\+/g, ' ');
}
this.paramCache_ = out;
}
}
};
/**
* sets the values of the named cgi parameters.
*
* <p>So, <code>uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])
* </code> yields <tt>foo?a=b&c=new&e=f</tt>.</p>
*
* @param key {string}
* @param values {Array.<string>} the new values. If values is a single string
* then it will be treated as the sole value.
*/
URI.prototype.setParameterValues = function (key, values) {
// be nice and avoid subtle bugs where [] operator on string performs charAt
// on some browsers and crashes on IE
if (typeof values === 'string') {
values = [ values ];
}
this.checkParameterCache_();
var newValueIndex = 0;
var pc = this.paramCache_;
var params = [];
for (var i = 0, k = 0; i < pc.length; i += 2) {
if (key === pc[i]) {
if (newValueIndex < values.length) {
params.push(key, values[newValueIndex++]);
}
} else {
params.push(pc[i], pc[i + 1]);
}
}
while (newValueIndex < values.length) {
params.push(key, values[newValueIndex++]);
}
this.setAllParameters(params);
return this;
};
URI.prototype.removeParameter = function (key) {
return this.setParameterValues(key, []);
};
/**
* returns the parameters specified in the query part of the uri as a list of
* keys and values like [ key0, value0, key1, value1, ... ].
*
* @return {Array.<string>}
*/
URI.prototype.getAllParameters = function () {
this.checkParameterCache_();
return this.paramCache_.slice(0, this.paramCache_.length);
};
/**
* returns the value<b>s</b> for a given cgi parameter as a list of decoded
* query parameter values.
* @return {Array.<string>}
*/
URI.prototype.getParameterValues = function (paramNameUnescaped) {
this.checkParameterCache_();
var values = [];
for (var i = 0; i < this.paramCache_.length; i += 2) {
if (paramNameUnescaped === this.paramCache_[i]) {
values.push(this.paramCache_[i + 1]);
}
}
return values;
};
/**
* returns a map of cgi parameter names to (non-empty) lists of values.
* @return {Object.<string,Array.<string>>}
*/
URI.prototype.getParameterMap = function (paramNameUnescaped) {
this.checkParameterCache_();
var paramMap = {};
for (var i = 0; i < this.paramCache_.length; i += 2) {
var key = this.paramCache_[i++],
value = this.paramCache_[i++];
if (!(key in paramMap)) {
paramMap[key] = [value];
} else {
paramMap[key].push(value);
}
}
return paramMap;
};
/**
* returns the first value for a given cgi parameter or null if the given
* parameter name does not appear in the query string.
* If the given parameter name does appear, but has no '<tt>=</tt>' following
* it, then the empty string will be returned.
* @return {string|null}
*/
URI.prototype.getParameterValue = function (paramNameUnescaped) {
this.checkParameterCache_();
for (var i = 0; i < this.paramCache_.length; i += 2) {
if (paramNameUnescaped === this.paramCache_[i]) {
return this.paramCache_[i + 1];
}
}
return null;
};
URI.prototype.getFragment = function () {
return this.fragment_ && decodeURIComponent(this.fragment_);
};
URI.prototype.getRawFragment = function () {
return this.fragment_;
};
URI.prototype.setFragment = function (newFragment) {
this.fragment_ = newFragment ? encodeURIComponent(newFragment) : null;
return this;
};
URI.prototype.setRawFragment = function (newFragment) {
this.fragment_ = newFragment ? newFragment : null;
return this;
};
URI.prototype.hasFragment = function () {
return null !== this.fragment_;
};
function nullIfAbsent(matchPart) {
return ('string' == typeof matchPart) && (matchPart.length > 0)
? matchPart
: null;
}
/**
* a regular expression for breaking a URI into its component parts.
*
* <p>http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234 says
* As the "first-match-wins" algorithm is identical to the "greedy"
* disambiguation method used by POSIX regular expressions, it is natural and
* commonplace to use a regular expression for parsing the potential five
* components of a URI reference.
*
* <p>The following line is the regular expression for breaking-down a
* well-formed URI reference into its components.
*
* <pre>
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
* 12 3 4 5 6 7 8 9
* </pre>
*
* <p>The numbers in the second line above are only to assist readability; they
* indicate the reference points for each subexpression (i.e., each paired
* parenthesis). We refer to the value matched for subexpression <n> as $<n>.
* For example, matching the above expression to
* <pre>
* http://www.ics.uci.edu/pub/ietf/uri/#Related
* </pre>
* results in the following subexpression matches:
* <pre>
* $1 = http:
* $2 = http
* $3 = //www.ics.uci.edu
* $4 = www.ics.uci.edu
* $5 = /pub/ietf/uri/
* $6 = <undefined>
* $7 = <undefined>
* $8 = #Related
* $9 = Related
* </pre>
* where <undefined> indicates that the component is not present, as is the
* case for the query component in the above example. Therefore, we can
* determine the value of the five components as
* <pre>
* scheme = $2
* authority = $4
* path = $5
* query = $7
* fragment = $9
* </pre>
*
* <p>msamuel: I have modified the regular expression slightly to expose the
* credentials, domain, and port separately from the authority.
* The modified version yields
* <pre>
* $1 = http scheme
* $2 = <undefined> credentials -\
* $3 = www.ics.uci.edu domain | authority
* $4 = <undefined> port -/
* $5 = /pub/ietf/uri/ path
* $6 = <undefined> query without ?
* $7 = Related fragment without #
* </pre>
*/
var URI_RE_ = new RegExp(
"^" +
"(?:" +
"([^:/?#]+)" + // scheme
":)?" +
"(?://" +
"(?:([^/?#]*)@)?" + // credentials
"([^/?#:@]*)" + // domain
"(?::([0-9]+))?" + // port
")?" +
"([^?#]+)?" + // path
"(?:\\?([^#]*))?" + // query
"(?:#(.*))?" + // fragment
"$"
);
var URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_ = /[#\/\?@]/g;
var URI_DISALLOWED_IN_PATH_ = /[\#\?]/g;
URI.parse = parse;
URI.create = create;
URI.resolve = resolve;
URI.collapse_dots = collapse_dots; // Visible for testing.
// lightweight string-based api for loadModuleMaker
URI.utils = {
mimeTypeOf: function (uri) {
var uriObj = parse(uri);
if (/\.html$/.test(uriObj.getPath())) {
return 'text/html';
} else {
return 'application/javascript';
}
},
resolve: function (base, uri) {
if (base) {
return resolve(parse(base), parse(uri)).toString();
} else {
return '' + uri;
}
}
};
return URI;
})();
// Copyright Google Inc.
// Licensed under the Apache Licence Version 2.0
// Autogenerated at Mon Feb 25 13:05:42 EST 2013
// @overrides window
// @provides html4
var html4 = {};
html4.atype = {
'NONE': 0,
'URI': 1,
'URI_FRAGMENT': 11,
'SCRIPT': 2,
'STYLE': 3,
'HTML': 12,
'ID': 4,
'IDREF': 5,
'IDREFS': 6,
'GLOBAL_NAME': 7,
'LOCAL_NAME': 8,
'CLASSES': 9,
'FRAME_TARGET': 10,
'MEDIA_QUERY': 13
};
html4[ 'atype' ] = html4.atype;
html4.ATTRIBS = {
'*::class': 9,
'*::dir': 0,
'*::draggable': 0,
'*::hidden': 0,
'*::id': 4,
'*::inert': 0,
'*::itemprop': 0,
'*::itemref': 6,
'*::itemscope': 0,
'*::lang': 0,
'*::onblur': 2,
'*::onchange': 2,
'*::onclick': 2,
'*::ondblclick': 2,
'*::onfocus': 2,
'*::onkeydown': 2,
'*::onkeypress': 2,
'*::onkeyup': 2,
'*::onload': 2,
'*::onmousedown': 2,
'*::onmousemove': 2,
'*::onmouseout': 2,
'*::onmouseover': 2,
'*::onmouseup': 2,
'*::onreset': 2,
'*::onscroll': 2,
'*::onselect': 2,
'*::onsubmit': 2,
'*::onunload': 2,
'*::spellcheck': 0,
'*::style': 3,
'*::title': 0,
'*::translate': 0,
'a::accesskey': 0,
'a::coords': 0,
'a::href': 1,
'a::hreflang': 0,
'a::name': 7,
'a::onblur': 2,
'a::onfocus': 2,
'a::shape': 0,
'a::tabindex': 0,
'a::target': 10,
'a::type': 0,
'area::accesskey': 0,
'area::alt': 0,
'area::coords': 0,
'area::href': 1,
'area::nohref': 0,
'area::onblur': 2,
'area::onfocus': 2,
'area::shape': 0,
'area::tabindex': 0,
'area::target': 10,
'audio::controls': 0,
'audio::loop': 0,
'audio::mediagroup': 5,
'audio::muted': 0,
'audio::preload': 0,
'bdo::dir': 0,
'blockquote::cite': 1,
'br::clear': 0,
'button::accesskey': 0,
'button::disabled': 0,
'button::name': 8,
'button::onblur': 2,
'button::onfocus': 2,
'button::tabindex': 0,
'button::type': 0,
'button::value': 0,
'canvas::height': 0,
'canvas::width': 0,
'caption::align': 0,
'col::align': 0,
'col::char': 0,
'col::charoff': 0,
'col::span': 0,
'col::valign': 0,
'col::width': 0,
'colgroup::align': 0,
'colgroup::char': 0,
'colgroup::charoff': 0,
'colgroup::span': 0,
'colgroup::valign': 0,
'colgroup::width': 0,
'command::checked': 0,
'command::command': 5,
'command::disabled': 0,
'command::icon': 1,
'command::label': 0,
'command::radiogroup': 0,
'command::type': 0,
'data::value': 0,
'del::cite': 1,
'del::datetime': 0,
'details::open': 0,
'dir::compact': 0,
'div::align': 0,
'dl::compact': 0,
'fieldset::disabled': 0,
'font::color': 0,
'font::face': 0,
'font::size': 0,
'form::accept': 0,
'form::action': 1,
'form::autocomplete': 0,
'form::enctype': 0,
'form::method': 0,
'form::name': 7,
'form::novalidate': 0,
'form::onreset': 2,
'form::onsubmit': 2,
'form::target': 10,
'h1::align': 0,
'h2::align': 0,
'h3::align': 0,
'h4::align': 0,
'h5::align': 0,
'h6::align': 0,
'hr::align': 0,
'hr::noshade': 0,
'hr::size': 0,
'hr::width': 0,
'iframe::align': 0,
'iframe::frameborder': 0,
'iframe::height': 0,
'iframe::marginheight': 0,
'iframe::marginwidth': 0,
'iframe::width': 0,
'img::align': 0,
'img::alt': 0,
'img::border': 0,
'img::height': 0,
'img::hspace': 0,
'img::ismap': 0,
'img::name': 7,
'img::src': 1,
'img::usemap': 11,
'img::vspace': 0,
'img::width': 0,
'input::accept': 0,
'input::accesskey': 0,
'input::align': 0,
'input::alt': 0,
'input::autocomplete': 0,
'input::checked': 0,
'input::disabled': 0,
'input::inputmode': 0,
'input::ismap': 0,
'input::list': 5,
'input::max': 0,
'input::maxlength': 0,
'input::min': 0,
'input::multiple': 0,
'input::name': 8,
'input::onblur': 2,
'input::onchange': 2,
'input::onfocus': 2,
'input::onselect': 2,
'input::placeholder': 0,
'input::readonly': 0,
'input::required': 0,
'input::size': 0,
'input::src': 1,
'input::step': 0,
'input::tabindex': 0,
'input::type': 0,
'input::usemap': 11,
'input::value': 0,
'ins::cite': 1,
'ins::datetime': 0,
'label::accesskey': 0,
'label::for': 5,
'label::onblur': 2,
'label::onfocus': 2,
'legend::accesskey': 0,
'legend::align': 0,
'li::type': 0,
'li::value': 0,
'map::name': 7,
'menu::compact': 0,
'menu::label': 0,
'menu::type': 0,
'meter::high': 0,
'meter::low': 0,
'meter::max': 0,
'meter::min': 0,
'meter::value': 0,
'ol::compact': 0,
'ol::reversed': 0,
'ol::start': 0,
'ol::type': 0,
'optgroup::disabled': 0,
'optgroup::label': 0,
'option::disabled': 0,
'option::label': 0,
'option::selected': 0,
'option::value': 0,
'output::for': 6,
'output::name': 8,
'p::align': 0,
'pre::width': 0,
'progress::max': 0,
'progress::min': 0,
'progress::value': 0,
'q::cite': 1,
'select::autocomplete': 0,
'select::disabled': 0,
'select::multiple': 0,
'select::name': 8,
'select::onblur': 2,
'select::onchange': 2,
'select::onfocus': 2,
'select::required': 0,
'select::size': 0,
'select::tabindex': 0,
'source::type': 0,
'table::align': 0,
'table::bgcolor': 0,
'table::border': 0,
'table::cellpadding': 0,
'table::cellspacing': 0,
'table::frame': 0,
'table::rules': 0,
'table::summary': 0,
'table::width': 0,
'tbody::align': 0,
'tbody::char': 0,
'tbody::charoff': 0,
'tbody::valign': 0,
'td::abbr': 0,
'td::align': 0,
'td::axis': 0,
'td::bgcolor': 0,
'td::char': 0,
'td::charoff': 0,
'td::colspan': 0,
'td::headers': 6,
'td::height': 0,
'td::nowrap': 0,
'td::rowspan': 0,
'td::scope': 0,
'td::valign': 0,
'td::width': 0,
'textarea::accesskey': 0,
'textarea::autocomplete': 0,
'textarea::cols': 0,
'textarea::disabled': 0,
'textarea::inputmode': 0,
'textarea::name': 8,
'textarea::onblur': 2,
'textarea::onchange': 2,
'textarea::onfocus': 2,
'textarea::onselect': 2,
'textarea::placeholder': 0,
'textarea::readonly': 0,
'textarea::required': 0,
'textarea::rows': 0,
'textarea::tabindex': 0,
'textarea::wrap': 0,
'tfoot::align': 0,
'tfoot::char': 0,
'tfoot::charoff': 0,
'tfoot::valign': 0,
'th::abbr': 0,
'th::align': 0,
'th::axis': 0,
'th::bgcolor': 0,
'th::char': 0,
'th::charoff': 0,
'th::colspan': 0,
'th::headers': 6,
'th::height': 0,
'th::nowrap': 0,
'th::rowspan': 0,
'th::scope': 0,
'th::valign': 0,
'th::width': 0,
'thead::align': 0,
'thead::char': 0,
'thead::charoff': 0,
'thead::valign': 0,
'tr::align': 0,
'tr::bgcolor': 0,
'tr::char': 0,
'tr::charoff': 0,
'tr::valign': 0,
'track::default': 0,
'track::kind': 0,
'track::label': 0,
'track::srclang': 0,
'ul::compact': 0,
'ul::type': 0,
'video::controls': 0,
'video::height': 0,
'video::loop': 0,
'video::mediagroup': 5,
'video::muted': 0,
'video::poster': 1,
'video::preload': 0,
'video::width': 0
};
html4[ 'ATTRIBS' ] = html4.ATTRIBS;
html4.eflags = {
'OPTIONAL_ENDTAG': 1,
'EMPTY': 2,
'CDATA': 4,
'RCDATA': 8,
'UNSAFE': 16,
'FOLDABLE': 32,
'SCRIPT': 64,
'STYLE': 128,
'VIRTUALIZED': 256
};
html4[ 'eflags' ] = html4.eflags;
// these are bitmasks of the eflags above.
html4.ELEMENTS = {
'a': 0,
'abbr': 0,
'acronym': 0,
'address': 0,
'applet': 272,
'area': 2,
'article': 0,
'aside': 0,
'audio': 0,
'b': 0,
'base': 274,
'basefont': 274,
'bdi': 0,
'bdo': 0,
'big': 0,
'blockquote': 0,
'body': 305,
'br': 2,
'button': 0,
'canvas': 0,
'caption': 0,
'center': 0,
'cite': 0,
'code': 0,
'col': 2,
'colgroup': 1,
'command': 2,
'data': 0,
'datalist': 0,
'dd': 1,
'del': 0,
'details': 0,
'dfn': 0,
'dialog': 272,
'dir': 0,
'div': 0,
'dl': 0,
'dt': 1,
'em': 0,
'fieldset': 0,
'figcaption': 0,
'figure': 0,
'font': 0,
'footer': 0,
'form': 0,
'frame': 274,
'frameset': 272,
'h1': 0,
'h2': 0,
'h3': 0,
'h4': 0,
'h5': 0,
'h6': 0,
'head': 305,
'header': 0,
'hgroup': 0,
'hr': 2,
'html': 305,
'i': 0,
'iframe': 16,
'img': 2,
'input': 2,
'ins': 0,
'isindex': 274,
'kbd': 0,
'keygen': 274,
'label': 0,
'legend': 0,
'li': 1,
'link': 274,
'map': 0,
'mark': 0,
'menu': 0,
'meta': 274,
'meter': 0,
'nav': 0,
'nobr': 0,
'noembed': 276,
'noframes': 276,
'noscript': 276,
'object': 272,
'ol': 0,
'optgroup': 0,
'option': 1,
'output': 0,
'p': 1,
'param': 274,
'pre': 0,
'progress': 0,
'q': 0,
's': 0,
'samp': 0,
'script': 84,
'section': 0,
'select': 0,
'small': 0,
'source': 2,
'span': 0,
'strike': 0,
'strong': 0,
'style': 148,
'sub': 0,
'summary': 0,
'sup': 0,
'table': 0,
'tbody': 1,
'td': 1,
'textarea': 8,
'tfoot': 1,
'th': 1,
'thead': 1,
'time': 0,
'title': 280,
'tr': 1,
'track': 2,
'tt': 0,
'u': 0,
'ul': 0,
'var': 0,
'video': 0,
'wbr': 2
};
html4[ 'ELEMENTS' ] = html4.ELEMENTS;
html4.ELEMENT_DOM_INTERFACES = {
'a': 'HTMLAnchorElement',
'abbr': 'HTMLElement',
'acronym': 'HTMLElement',
'address': 'HTMLElement',
'applet': 'HTMLAppletElement',
'area': 'HTMLAreaElement',
'article': 'HTMLElement',
'aside': 'HTMLElement',
'audio': 'HTMLAudioElement',
'b': 'HTMLElement',
'base': 'HTMLBaseElement',
'basefont': 'HTMLBaseFontElement',
'bdi': 'HTMLElement',
'bdo': 'HTMLElement',
'big': 'HTMLElement',
'blockquote': 'HTMLQuoteElement',
'body': 'HTMLBodyElement',
'br': 'HTMLBRElement',
'button': 'HTMLButtonElement',
'canvas': 'HTMLCanvasElement',
'caption': 'HTMLTableCaptionElement',
'center': 'HTMLElement',
'cite': 'HTMLElement',
'code': 'HTMLElement',
'col': 'HTMLTableColElement',
'colgroup': 'HTMLTableColElement',
'command': 'HTMLCommandElement',
'data': 'HTMLElement',
'datalist': 'HTMLDataListElement',
'dd': 'HTMLElement',
'del': 'HTMLModElement',
'details': 'HTMLDetailsElement',
'dfn': 'HTMLElement',
'dialog': 'HTMLDialogElement',
'dir': 'HTMLDirectoryElement',
'div': 'HTMLDivElement',
'dl': 'HTMLDListElement',
'dt': 'HTMLElement',
'em': 'HTMLElement',
'fieldset': 'HTMLFieldSetElement',
'figcaption': 'HTMLElement',
'figure': 'HTMLElement',
'font': 'HTMLFontElement',
'footer': 'HTMLElement',
'form': 'HTMLFormElement',
'frame': 'HTMLFrameElement',
'frameset': 'HTMLFrameSetElement',
'h1': 'HTMLHeadingElement',
'h2': 'HTMLHeadingElement',
'h3': 'HTMLHeadingElement',
'h4': 'HTMLHeadingElement',
'h5': 'HTMLHeadingElement',
'h6': 'HTMLHeadingElement',
'head': 'HTMLHeadElement',
'header': 'HTMLElement',
'hgroup': 'HTMLElement',
'hr': 'HTMLHRElement',
'html': 'HTMLHtmlElement',
'i': 'HTMLElement',
'iframe': 'HTMLIFrameElement',
'img': 'HTMLImageElement',
'input': 'HTMLInputElement',
'ins': 'HTMLModElement',
'isindex': 'HTMLUnknownElement',
'kbd': 'HTMLElement',
'keygen': 'HTMLKeygenElement',
'label': 'HTMLLabelElement',
'legend': 'HTMLLegendElement',
'li': 'HTMLLIElement',
'link': 'HTMLLinkElement',
'map': 'HTMLMapElement',
'mark': 'HTMLElement',
'menu': 'HTMLMenuElement',
'meta': 'HTMLMetaElement',
'meter': 'HTMLMeterElement',
'nav': 'HTMLElement',
'nobr': 'HTMLElement',
'noembed': 'HTMLElement',
'noframes': 'HTMLElement',
'noscript': 'HTMLElement',
'object': 'HTMLObjectElement',
'ol': 'HTMLOListElement',
'optgroup': 'HTMLOptGroupElement',
'option': 'HTMLOptionElement',
'output': 'HTMLOutputElement',
'p': 'HTMLParagraphElement',
'param': 'HTMLParamElement',
'pre': 'HTMLPreElement',
'progress': 'HTMLProgressElement',
'q': 'HTMLQuoteElement',
's': 'HTMLElement',
'samp': 'HTMLElement',
'script': 'HTMLScriptElement',
'section': 'HTMLElement',
'select': 'HTMLSelectElement',
'small': 'HTMLElement',
'source': 'HTMLSourceElement',
'span': 'HTMLSpanElement',
'strike': 'HTMLElement',
'strong': 'HTMLElement',
'style': 'HTMLStyleElement',
'sub': 'HTMLElement',
'summary': 'HTMLElement',
'sup': 'HTMLElement',
'table': 'HTMLTableElement',
'tbody': 'HTMLTableSectionElement',
'td': 'HTMLTableDataCellElement',
'textarea': 'HTMLTextAreaElement',
'tfoot': 'HTMLTableSectionElement',
'th': 'HTMLTableHeaderCellElement',
'thead': 'HTMLTableSectionElement',
'time': 'HTMLTimeElement',
'title': 'HTMLTitleElement',
'tr': 'HTMLTableRowElement',
'track': 'HTMLTrackElement',
'tt': 'HTMLElement',
'u': 'HTMLElement',
'ul': 'HTMLUListElement',
'var': 'HTMLElement',
'video': 'HTMLVideoElement',
'wbr': 'HTMLElement'
};
html4[ 'ELEMENT_DOM_INTERFACES' ] = html4.ELEMENT_DOM_INTERFACES;
html4.ueffects = {
'NOT_LOADED': 0,
'SAME_DOCUMENT': 1,
'NEW_DOCUMENT': 2
};
html4[ 'ueffects' ] = html4.ueffects;
html4.URIEFFECTS = {
'a::href': 2,
'area::href': 2,
'blockquote::cite': 0,
'command::icon': 1,
'del::cite': 0,
'form::action': 2,
'img::src': 1,
'input::src': 1,
'ins::cite': 0,
'q::cite': 0,
'video::poster': 1
};
html4[ 'URIEFFECTS' ] = html4.URIEFFECTS;
html4.ltypes = {
'UNSANDBOXED': 2,
'SANDBOXED': 1,
'DATA': 0
};
html4[ 'ltypes' ] = html4.ltypes;
html4.LOADERTYPES = {
'a::href': 2,
'area::href': 2,
'blockquote::cite': 2,
'command::icon': 1,
'del::cite': 2,
'form::action': 2,
'img::src': 1,
'input::src': 1,
'ins::cite': 2,
'q::cite': 2,
'video::poster': 1
};
html4[ 'LOADERTYPES' ] = html4.LOADERTYPES;
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* An HTML sanitizer that can satisfy a variety of security policies.
*
* <p>
* The HTML sanitizer is built around a SAX parser and HTML element and
* attributes schemas.
*
* If the cssparser is loaded, inline styles are sanitized using the
* css property and value schemas. Else they are remove during
* sanitization.
*
* If it exists, uses parseCssDeclarations, sanitizeCssProperty, cssSchema
*
* @author mikesamuel@gmail.com
* @author jasvir@gmail.com
* \@requires html4, URI
* \@overrides window
* \@provides html, html_sanitize
*/
// The Turkish i seems to be a non-issue, but abort in case it is.
if ('I'.toLowerCase() !== 'i') { throw 'I/i problem'; }
/**
* \@namespace
*/
var html = (function(html4) {
// For closure compiler
var parseCssDeclarations, sanitizeCssProperty, cssSchema;
if ('undefined' !== typeof window) {
parseCssDeclarations = window['parseCssDeclarations'];
sanitizeCssProperty = window['sanitizeCssProperty'];
cssSchema = window['cssSchema'];
}
// The keys of this object must be 'quoted' or JSCompiler will mangle them!
// This is a partial list -- lookupEntity() uses the host browser's parser
// (when available) to implement full entity lookup.
// Note that entities are in general case-sensitive; the uppercase ones are
// explicitly defined by HTML5 (presumably as compatibility).
var ENTITIES = {
'lt': '<',
'LT': '<',
'gt': '>',
'GT': '>',
'amp': '&',
'AMP': '&',
'quot': '"',
'apos': '\'',
'nbsp': '\240'
};
// Patterns for types of entity/character reference names.
var decimalEscapeRe = /^#(\d+)$/;
var hexEscapeRe = /^#x([0-9A-Fa-f]+)$/;
// contains every entity per http://www.w3.org/TR/2011/WD-html5-20110113/named-character-references.html
var safeEntityNameRe = /^[A-Za-z][A-za-z0-9]+$/;
// Used as a hook to invoke the browser's entity parsing. <textarea> is used
// because its content is parsed for entities but not tags.
// TODO(kpreid): This retrieval is a kludge and leads to silent loss of
// functionality if the document isn't available.
var entityLookupElement =
('undefined' !== typeof window && window['document'])
? window['document'].createElement('textarea') : null;
/**
* Decodes an HTML entity.
*
* {\@updoc
* $ lookupEntity('lt')
* # '<'
* $ lookupEntity('GT')
* # '>'
* $ lookupEntity('amp')
* # '&'
* $ lookupEntity('nbsp')
* # '\xA0'
* $ lookupEntity('apos')
* # "'"
* $ lookupEntity('quot')
* # '"'
* $ lookupEntity('#xa')
* # '\n'
* $ lookupEntity('#10')
* # '\n'
* $ lookupEntity('#x0a')
* # '\n'
* $ lookupEntity('#010')
* # '\n'
* $ lookupEntity('#x00A')
* # '\n'
* $ lookupEntity('Pi') // Known failure
* # '\u03A0'
* $ lookupEntity('pi') // Known failure
* # '\u03C0'
* }
*
* @param {string} name the content between the '&' and the ';'.
* @return {string} a single unicode code-point as a string.
*/
function lookupEntity(name) {
// TODO: entity lookup as specified by HTML5 actually depends on the
// presence of the ";".
if (ENTITIES.hasOwnProperty(name)) { return ENTITIES[name]; }
var m = name.match(decimalEscapeRe);
if (m) {
return String.fromCharCode(parseInt(m[1], 10));
} else if (!!(m = name.match(hexEscapeRe))) {
return String.fromCharCode(parseInt(m[1], 16));
} else if (entityLookupElement && safeEntityNameRe.test(name)) {
entityLookupElement.innerHTML = '&' + name + ';';
var text = entityLookupElement.textContent;
ENTITIES[name] = text;
return text;
} else {
return '&' + name + ';';
}
}
function decodeOneEntity(_, name) {
return lookupEntity(name);
}
var nulRe = /\0/g;
function stripNULs(s) {
return s.replace(nulRe, '');
}
var ENTITY_RE_1 = /&(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/g;
var ENTITY_RE_2 = /^(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/;
/**
* The plain text of a chunk of HTML CDATA which possibly containing.
*
* {\@updoc
* $ unescapeEntities('')
* # ''
* $ unescapeEntities('hello World!')
* # 'hello World!'
* $ unescapeEntities('1 &lt; 2 &amp;&AMP; 4 &gt; 3&#10;')
* # '1 < 2 && 4 > 3\n'
* $ unescapeEntities('&lt;&lt <- unfinished entity&gt;')
* # '<&lt <- unfinished entity>'
* $ unescapeEntities('/foo?bar=baz&copy=true') // & often unescaped in URLS
* # '/foo?bar=baz&copy=true'
* $ unescapeEntities('pi=&pi;&#x3c0;, Pi=&Pi;\u03A0') // FIXME: known failure
* # 'pi=\u03C0\u03c0, Pi=\u03A0\u03A0'
* }
*
* @param {string} s a chunk of HTML CDATA. It must not start or end inside
* an HTML entity.
*/
function unescapeEntities(s) {
return s.replace(ENTITY_RE_1, decodeOneEntity);
}
var ampRe = /&/g;
var looseAmpRe = /&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi;
var ltRe = /[<]/g;
var gtRe = />/g;
var quotRe = /\"/g;
/**
* Escapes HTML special characters in attribute values.
*
* {\@updoc
* $ escapeAttrib('')
* # ''
* $ escapeAttrib('"<<&==&>>"') // Do not just escape the first occurrence.
* # '&#34;&lt;&lt;&amp;&#61;&#61;&amp;&gt;&gt;&#34;'
* $ escapeAttrib('Hello <World>!')
* # 'Hello &lt;World&gt;!'
* }
*/
function escapeAttrib(s) {
return ('' + s).replace(ampRe, '&amp;').replace(ltRe, '&lt;')
.replace(gtRe, '&gt;').replace(quotRe, '&#34;');
}
/**
* Escape entities in RCDATA that can be escaped without changing the meaning.
* {\@updoc
* $ normalizeRCData('1 < 2 &&amp; 3 > 4 &amp;& 5 &lt; 7&8')
* # '1 &lt; 2 &amp;&amp; 3 &gt; 4 &amp;&amp; 5 &lt; 7&amp;8'
* }
*/
function normalizeRCData(rcdata) {
return rcdata
.replace(looseAmpRe, '&amp;$1')
.replace(ltRe, '&lt;')
.replace(gtRe, '&gt;');
}
// TODO(felix8a): validate sanitizer regexs against the HTML5 grammar at
// http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html
// We initially split input so that potentially meaningful characters
// like '<' and '>' are separate tokens, using a fast dumb process that
// ignores quoting. Then we walk that token stream, and when we see a
// '<' that's the start of a tag, we use ATTR_RE to extract tag
// attributes from the next token. That token will never have a '>'
// character. However, it might have an unbalanced quote character, and
// when we see that, we combine additional tokens to balance the quote.
var ATTR_RE = new RegExp(
'^\\s*' +
'([-.:\\w]+)' + // 1 = Attribute name
'(?:' + (
'\\s*(=)\\s*' + // 2 = Is there a value?
'(' + ( // 3 = Attribute value
// TODO(felix8a): maybe use backref to match quotes
'(\")[^\"]*(\"|$)' + // 4, 5 = Double-quoted string
'|' +
'(\')[^\']*(\'|$)' + // 6, 7 = Single-quoted string
'|' +
// Positive lookahead to prevent interpretation of
// <foo a= b=c> as <foo a='b=c'>
// TODO(felix8a): might be able to drop this case
'(?=[a-z][-\\w]*\\s*=)' +
'|' +
// Unquoted value that isn't an attribute name
// (since we didn't match the positive lookahead above)
'[^\"\'\\s]*' ) +
')' ) +
')?',
'i');
// false on IE<=8, true on most other browsers
var splitWillCapture = ('a,b'.split(/(,)/).length === 3);
// bitmask for tags with special parsing, like <script> and <textarea>
var EFLAGS_TEXT = html4.eflags['CDATA'] | html4.eflags['RCDATA'];
/**
* Given a SAX-like event handler, produce a function that feeds those
* events and a parameter to the event handler.
*
* The event handler has the form:{@code
* {
* // Name is an upper-case HTML tag name. Attribs is an array of
* // alternating upper-case attribute names, and attribute values. The
* // attribs array is reused by the parser. Param is the value passed to
* // the saxParser.
* startTag: function (name, attribs, param) { ... },
* endTag: function (name, param) { ... },
* pcdata: function (text, param) { ... },
* rcdata: function (text, param) { ... },
* cdata: function (text, param) { ... },
* startDoc: function (param) { ... },
* endDoc: function (param) { ... }
* }}
*
* @param {Object} handler a record containing event handlers.
* @return {function(string, Object)} A function that takes a chunk of HTML
* and a parameter. The parameter is passed on to the handler methods.
*/
function makeSaxParser(handler) {
// Accept quoted or unquoted keys (Closure compat)
var hcopy = {
cdata: handler.cdata || handler['cdata'],
comment: handler.comment || handler['comment'],
endDoc: handler.endDoc || handler['endDoc'],
endTag: handler.endTag || handler['endTag'],
pcdata: handler.pcdata || handler['pcdata'],
rcdata: handler.rcdata || handler['rcdata'],
startDoc: handler.startDoc || handler['startDoc'],
startTag: handler.startTag || handler['startTag']
};
return function(htmlText, param) {
return parse(htmlText, hcopy, param);
};
}
// Parsing strategy is to split input into parts that might be lexically
// meaningful (every ">" becomes a separate part), and then recombine
// parts if we discover they're in a different context.
// TODO(felix8a): Significant performance regressions from -legacy,
// tested on
// Chrome 18.0
// Firefox 11.0
// IE 6, 7, 8, 9
// Opera 11.61
// Safari 5.1.3
// Many of these are unusual patterns that are linearly slower and still
// pretty fast (eg 1ms to 5ms), so not necessarily worth fixing.
// TODO(felix8a): "<script> && && && ... <\/script>" is slower on all
// browsers. The hotspot is htmlSplit.
// TODO(felix8a): "<p title='>>>>...'><\/p>" is slower on all browsers.
// This is partly htmlSplit, but the hotspot is parseTagAndAttrs.
// TODO(felix8a): "<a><\/a><a><\/a>..." is slower on IE9.
// "<a>1<\/a><a>1<\/a>..." is faster, "<a><\/a>2<a><\/a>2..." is faster.
// TODO(felix8a): "<p<p<p..." is slower on IE[6-8]
var continuationMarker = {};
function parse(htmlText, handler, param) {
var m, p, tagName;
var parts = htmlSplit(htmlText);
var state = {
noMoreGT: false,
noMoreEndComments: false
};
parseCPS(handler, parts, 0, state, param);
}
function continuationMaker(h, parts, initial, state, param) {
return function () {
parseCPS(h, parts, initial, state, param);
};
}
function parseCPS(h, parts, initial, state, param) {
try {
if (h.startDoc && initial == 0) { h.startDoc(param); }
var m, p, tagName;
for (var pos = initial, end = parts.length; pos < end;) {
var current = parts[pos++];
var next = parts[pos];
switch (current) {
case '&':
if (ENTITY_RE_2.test(next)) {
if (h.pcdata) {
h.pcdata('&' + next, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
pos++;
} else {
if (h.pcdata) { h.pcdata("&amp;", param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<\/':
if (m = /^([-\w:]+)[^\'\"]*/.exec(next)) {
if (m[0].length === next.length && parts[pos + 1] === '>') {
// fast case, no attribute parsing needed
pos += 2;
tagName = m[1].toLowerCase();
if (h.endTag) {
h.endTag(tagName, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
} else {
// slow case, need to parse attributes
// TODO(felix8a): do we really care about misparsing this?
pos = parseEndTag(
parts, pos, h, param, continuationMarker, state);
}
} else {
if (h.pcdata) {
h.pcdata('&lt;/', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<':
if (m = /^([-\w:]+)\s*\/?/.exec(next)) {
if (m[0].length === next.length && parts[pos + 1] === '>') {
// fast case, no attribute parsing needed
pos += 2;
tagName = m[1].toLowerCase();
if (h.startTag) {
h.startTag(tagName, [], param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
// tags like <script> and <textarea> have special parsing
var eflags = html4.ELEMENTS[tagName];
if (eflags & EFLAGS_TEXT) {
var tag = { name: tagName, next: pos, eflags: eflags };
pos = parseText(
parts, tag, h, param, continuationMarker, state);
}
} else {
// slow case, need to parse attributes
pos = parseStartTag(
parts, pos, h, param, continuationMarker, state);
}
} else {
if (h.pcdata) {
h.pcdata('&lt;', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<\!--':
// The pathological case is n copies of '<\!--' without '-->', and
// repeated failure to find '-->' is quadratic. We avoid that by
// remembering when search for '-->' fails.
if (!state.noMoreEndComments) {
// A comment <\!--x--> is split into three tokens:
// '<\!--', 'x--', '>'
// We want to find the next '>' token that has a preceding '--'.
// pos is at the 'x--'.
for (p = pos + 1; p < end; p++) {
if (parts[p] === '>' && /--$/.test(parts[p - 1])) { break; }
}
if (p < end) {
if (h.comment) {
var comment = parts.slice(pos, p).join('');
h.comment(
comment.substr(0, comment.length - 2), param,
continuationMarker,
continuationMaker(h, parts, p + 1, state, param));
}
pos = p + 1;
} else {
state.noMoreEndComments = true;
}
}
if (state.noMoreEndComments) {
if (h.pcdata) {
h.pcdata('&lt;!--', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '<\!':
if (!/^\w/.test(next)) {
if (h.pcdata) {
h.pcdata('&lt;!', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
} else {
// similar to noMoreEndComment logic
if (!state.noMoreGT) {
for (p = pos + 1; p < end; p++) {
if (parts[p] === '>') { break; }
}
if (p < end) {
pos = p + 1;
} else {
state.noMoreGT = true;
}
}
if (state.noMoreGT) {
if (h.pcdata) {
h.pcdata('&lt;!', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
}
break;
case '<?':
// similar to noMoreEndComment logic
if (!state.noMoreGT) {
for (p = pos + 1; p < end; p++) {
if (parts[p] === '>') { break; }
}
if (p < end) {
pos = p + 1;
} else {
state.noMoreGT = true;
}
}
if (state.noMoreGT) {
if (h.pcdata) {
h.pcdata('&lt;?', param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
}
break;
case '>':
if (h.pcdata) {
h.pcdata("&gt;", param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
break;
case '':
break;
default:
if (h.pcdata) {
h.pcdata(current, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
break;
}
}
if (h.endDoc) { h.endDoc(param); }
} catch (e) {
if (e !== continuationMarker) { throw e; }
}
}
// Split str into parts for the html parser.
function htmlSplit(str) {
// can't hoist this out of the function because of the re.exec loop.
var re = /(<\/|<\!--|<[!?]|[&<>])/g;
str += '';
if (splitWillCapture) {
return str.split(re);
} else {
var parts = [];
var lastPos = 0;
var m;
while ((m = re.exec(str)) !== null) {
parts.push(str.substring(lastPos, m.index));
parts.push(m[0]);
lastPos = m.index + m[0].length;
}
parts.push(str.substring(lastPos));
return parts;
}
}
function parseEndTag(parts, pos, h, param, continuationMarker, state) {
var tag = parseTagAndAttrs(parts, pos);
// drop unclosed tags
if (!tag) { return parts.length; }
if (h.endTag) {
h.endTag(tag.name, param, continuationMarker,
continuationMaker(h, parts, pos, state, param));
}
return tag.next;
}
function parseStartTag(parts, pos, h, param, continuationMarker, state) {
var tag = parseTagAndAttrs(parts, pos);
// drop unclosed tags
if (!tag) { return parts.length; }
if (h.startTag) {
h.startTag(tag.name, tag.attrs, param, continuationMarker,
continuationMaker(h, parts, tag.next, state, param));
}
// tags like <script> and <textarea> have special parsing
if (tag.eflags & EFLAGS_TEXT) {
return parseText(parts, tag, h, param, continuationMarker, state);
} else {
return tag.next;
}
}
var endTagRe = {};
// Tags like <script> and <textarea> are flagged as CDATA or RCDATA,
// which means everything is text until we see the correct closing tag.
function parseText(parts, tag, h, param, continuationMarker, state) {
var end = parts.length;
if (!endTagRe.hasOwnProperty(tag.name)) {
endTagRe[tag.name] = new RegExp('^' + tag.name + '(?:[\\s\\/]|$)', 'i');
}
var re = endTagRe[tag.name];
var first = tag.next;
var p = tag.next + 1;
for (; p < end; p++) {
if (parts[p - 1] === '<\/' && re.test(parts[p])) { break; }
}
if (p < end) { p -= 1; }
var buf = parts.slice(first, p).join('');
if (tag.eflags & html4.eflags['CDATA']) {
if (h.cdata) {
h.cdata(buf, param, continuationMarker,
continuationMaker(h, parts, p, state, param));
}
} else if (tag.eflags & html4.eflags['RCDATA']) {
if (h.rcdata) {
h.rcdata(normalizeRCData(buf), param, continuationMarker,
continuationMaker(h, parts, p, state, param));
}
} else {
throw new Error('bug');
}
return p;
}
// at this point, parts[pos-1] is either "<" or "<\/".
function parseTagAndAttrs(parts, pos) {
var m = /^([-\w:]+)/.exec(parts[pos]);
var tag = {};
tag.name = m[1].toLowerCase();
tag.eflags = html4.ELEMENTS[tag.name];
var buf = parts[pos].substr(m[0].length);
// Find the next '>'. We optimistically assume this '>' is not in a
// quoted context, and further down we fix things up if it turns out to
// be quoted.
var p = pos + 1;
var end = parts.length;
for (; p < end; p++) {
if (parts[p] === '>') { break; }
buf += parts[p];
}
if (end <= p) { return void 0; }
var attrs = [];
while (buf !== '') {
m = ATTR_RE.exec(buf);
if (!m) {
// No attribute found: skip garbage
buf = buf.replace(/^[\s\S][^a-z\s]*/, '');
} else if ((m[4] && !m[5]) || (m[6] && !m[7])) {
// Unterminated quote: slurp to the next unquoted '>'
var quote = m[4] || m[6];
var sawQuote = false;
var abuf = [buf, parts[p++]];
for (; p < end; p++) {
if (sawQuote) {
if (parts[p] === '>') { break; }
} else if (0 <= parts[p].indexOf(quote)) {
sawQuote = true;
}
abuf.push(parts[p]);
}
// Slurp failed: lose the garbage
if (end <= p) { break; }
// Otherwise retry attribute parsing
buf = abuf.join('');
continue;
} else {
// We have an attribute
var aName = m[1].toLowerCase();
var aValue = m[2] ? decodeValue(m[3]) : '';
attrs.push(aName, aValue);
buf = buf.substr(m[0].length);
}
}
tag.attrs = attrs;
tag.next = p + 1;
return tag;
}
function decodeValue(v) {
var q = v.charCodeAt(0);
if (q === 0x22 || q === 0x27) { // " or '
v = v.substr(1, v.length - 2);
}
return unescapeEntities(stripNULs(v));
}
/**
* Returns a function that strips unsafe tags and attributes from html.
* @param {function(string, Array.<string>): ?Array.<string>} tagPolicy
* A function that takes (tagName, attribs[]), where tagName is a key in
* html4.ELEMENTS and attribs is an array of alternating attribute names
* and values. It should return a record (as follows), or null to delete
* the element. It's okay for tagPolicy to modify the attribs array,
* but the same array is reused, so it should not be held between calls.
* Record keys:
* attribs: (required) Sanitized attributes array.
* tagName: Replacement tag name.
* @return {function(string, Array)} A function that sanitizes a string of
* HTML and appends result strings to the second argument, an array.
*/
function makeHtmlSanitizer(tagPolicy) {
var stack;
var ignoring;
var emit = function (text, out) {
if (!ignoring) { out.push(text); }
};
return makeSaxParser({
'startDoc': function(_) {
stack = [];
ignoring = false;
},
'startTag': function(tagNameOrig, attribs, out) {
if (ignoring) { return; }
if (!html4.ELEMENTS.hasOwnProperty(tagNameOrig)) { return; }
var eflagsOrig = html4.ELEMENTS[tagNameOrig];
if (eflagsOrig & html4.eflags['FOLDABLE']) {
return;
}
var decision = tagPolicy(tagNameOrig, attribs);
if (!decision) {
ignoring = !(eflagsOrig & html4.eflags['EMPTY']);
return;
} else if (typeof decision !== 'object') {
throw new Error('tagPolicy did not return object (old API?)');
}
if ('attribs' in decision) {
attribs = decision['attribs'];
} else {
throw new Error('tagPolicy gave no attribs');
}
var eflagsRep;
var tagNameRep;
if ('tagName' in decision) {
tagNameRep = decision['tagName'];
eflagsRep = html4.ELEMENTS[tagNameRep];
} else {
tagNameRep = tagNameOrig;
eflagsRep = eflagsOrig;
}
// TODO(mikesamuel): relying on tagPolicy not to insert unsafe
// attribute names.
// If this is an optional-end-tag element and either this element or its
// previous like sibling was rewritten, then insert a close tag to
// preserve structure.
if (eflagsOrig & html4.eflags['OPTIONAL_ENDTAG']) {
var onStack = stack[stack.length - 1];
if (onStack && onStack.orig === tagNameOrig &&
(onStack.rep !== tagNameRep || tagNameOrig !== tagNameRep)) {
out.push('<\/', onStack.rep, '>');
}
}
if (!(eflagsOrig & html4.eflags['EMPTY'])) {
stack.push({orig: tagNameOrig, rep: tagNameRep});
}
out.push('<', tagNameRep);
for (var i = 0, n = attribs.length; i < n; i += 2) {
var attribName = attribs[i],
value = attribs[i + 1];
if (value !== null && value !== void 0) {
out.push(' ', attribName, '="', escapeAttrib(value), '"');
}
}
out.push('>');
if ((eflagsOrig & html4.eflags['EMPTY'])
&& !(eflagsRep & html4.eflags['EMPTY'])) {
// replacement is non-empty, synthesize end tag
out.push('<\/', tagNameRep, '>');
}
},
'endTag': function(tagName, out) {
if (ignoring) {
ignoring = false;
return;
}
if (!html4.ELEMENTS.hasOwnProperty(tagName)) { return; }
var eflags = html4.ELEMENTS[tagName];
if (!(eflags & (html4.eflags['EMPTY'] | html4.eflags['FOLDABLE']))) {
var index;
if (eflags & html4.eflags['OPTIONAL_ENDTAG']) {
for (index = stack.length; --index >= 0;) {
var stackElOrigTag = stack[index].orig;
if (stackElOrigTag === tagName) { break; }
if (!(html4.ELEMENTS[stackElOrigTag] &
html4.eflags['OPTIONAL_ENDTAG'])) {
// Don't pop non optional end tags looking for a match.
return;
}
}
} else {
for (index = stack.length; --index >= 0;) {
if (stack[index].orig === tagName) { break; }
}
}
if (index < 0) { return; } // Not opened.
for (var i = stack.length; --i > index;) {
var stackElRepTag = stack[i].rep;
if (!(html4.ELEMENTS[stackElRepTag] &
html4.eflags['OPTIONAL_ENDTAG'])) {
out.push('<\/', stackElRepTag, '>');
}
}
if (index < stack.length) {
tagName = stack[index].rep;
}
stack.length = index;
out.push('<\/', tagName, '>');
}
},
'pcdata': emit,
'rcdata': emit,
'cdata': emit,
'endDoc': function(out) {
for (; stack.length; stack.length--) {
out.push('<\/', stack[stack.length - 1].rep, '>');
}
}
});
}
var ALLOWED_URI_SCHEMES = /^(?:https?|mailto|data)$/i;
function safeUri(uri, effect, ltype, hints, naiveUriRewriter) {
if (!naiveUriRewriter) { return null; }
try {
var parsed = URI.parse('' + uri);
if (parsed) {
if (!parsed.hasScheme() ||
ALLOWED_URI_SCHEMES.test(parsed.getScheme())) {
var safe = naiveUriRewriter(parsed, effect, ltype, hints);
return safe ? safe.toString() : null;
}
}
} catch (e) {
return null;
}
return null;
}
function log(logger, tagName, attribName, oldValue, newValue) {
if (!attribName) {
logger(tagName + " removed", {
change: "removed",
tagName: tagName
});
}
if (oldValue !== newValue) {
var changed = "changed";
if (oldValue && !newValue) {
changed = "removed";
} else if (!oldValue && newValue) {
changed = "added";
}
logger(tagName + "." + attribName + " " + changed, {
change: changed,
tagName: tagName,
attribName: attribName,
oldValue: oldValue,
newValue: newValue
});
}
}
function lookupAttribute(map, tagName, attribName) {
var attribKey;
attribKey = tagName + '::' + attribName;
if (map.hasOwnProperty(attribKey)) {
return map[attribKey];
}
attribKey = '*::' + attribName;
if (map.hasOwnProperty(attribKey)) {
return map[attribKey];
}
return void 0;
}
function getAttributeType(tagName, attribName) {
return lookupAttribute(html4.ATTRIBS, tagName, attribName);
}
function getLoaderType(tagName, attribName) {
return lookupAttribute(html4.LOADERTYPES, tagName, attribName);
}
function getUriEffect(tagName, attribName) {
return lookupAttribute(html4.URIEFFECTS, tagName, attribName);
}
/**
* Sanitizes attributes on an HTML tag.
* @param {string} tagName An HTML tag name in lowercase.
* @param {Array.<?string>} attribs An array of alternating names and values.
* @param {?function(?string): ?string} opt_naiveUriRewriter A transform to
* apply to URI attributes; it can return a new string value, or null to
* delete the attribute. If unspecified, URI attributes are deleted.
* @param {function(?string): ?string} opt_nmTokenPolicy A transform to apply
* to attributes containing HTML names, element IDs, and space-separated
* lists of classes; it can return a new string value, or null to delete
* the attribute. If unspecified, these attributes are kept unchanged.
* @return {Array.<?string>} The sanitized attributes as a list of alternating
* names and values, where a null value means to omit the attribute.
*/
function sanitizeAttribs(tagName, attribs,
opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger) {
// TODO(felix8a): it's obnoxious that domado duplicates much of this
// TODO(felix8a): maybe consistently enforce constraints like target=
for (var i = 0; i < attribs.length; i += 2) {
var attribName = attribs[i];
var value = attribs[i + 1];
var oldValue = value;
var atype = null, attribKey;
if ((attribKey = tagName + '::' + attribName,
html4.ATTRIBS.hasOwnProperty(attribKey)) ||
(attribKey = '*::' + attribName,
html4.ATTRIBS.hasOwnProperty(attribKey))) {
atype = html4.ATTRIBS[attribKey];
}
if (atype !== null) {
switch (atype) {
case html4.atype['NONE']: break;
case html4.atype['SCRIPT']:
value = null;
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
break;
case html4.atype['STYLE']:
if ('undefined' === typeof parseCssDeclarations) {
value = null;
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
break;
}
var sanitizedDeclarations = [];
parseCssDeclarations(
value,
{
declaration: function (property, tokens) {
var normProp = property.toLowerCase();
var schema = cssSchema[normProp];
if (!schema) {
return;
}
sanitizeCssProperty(
normProp, schema, tokens,
opt_naiveUriRewriter
? function (url) {
return safeUri(
url, html4.ueffects.SAME_DOCUMENT,
html4.ltypes.SANDBOXED,
{
"TYPE": "CSS",
"CSS_PROP": normProp
}, opt_naiveUriRewriter);
}
: null);
sanitizedDeclarations.push(property + ': ' + tokens.join(' '));
}
});
value = sanitizedDeclarations.length > 0 ?
sanitizedDeclarations.join(' ; ') : null;
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
break;
case html4.atype['ID']:
case html4.atype['IDREF']:
case html4.atype['IDREFS']:
case html4.atype['GLOBAL_NAME']:
case html4.atype['LOCAL_NAME']:
case html4.atype['CLASSES']:
value = opt_nmTokenPolicy ? opt_nmTokenPolicy(value) : value;
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
break;
case html4.atype['URI']:
value = safeUri(value,
getUriEffect(tagName, attribName),
getLoaderType(tagName, attribName),
{
"TYPE": "MARKUP",
"XML_ATTR": attribName,
"XML_TAG": tagName
}, opt_naiveUriRewriter);
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
break;
case html4.atype['URI_FRAGMENT']:
if (value && '#' === value.charAt(0)) {
value = value.substring(1); // remove the leading '#'
value = opt_nmTokenPolicy ? opt_nmTokenPolicy(value) : value;
if (value !== null && value !== void 0) {
value = '#' + value; // restore the leading '#'
}
} else {
value = null;
}
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
break;
default:
value = null;
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
break;
}
} else {
value = null;
if (opt_logger) {
log(opt_logger, tagName, attribName, oldValue, value);
}
}
attribs[i + 1] = value;
}
return attribs;
}
/**
* Creates a tag policy that omits all tags marked UNSAFE in html4-defs.js
* and applies the default attribute sanitizer with the supplied policy for
* URI attributes and NMTOKEN attributes.
* @param {?function(?string): ?string} opt_naiveUriRewriter A transform to
* apply to URI attributes. If not given, URI attributes are deleted.
* @param {function(?string): ?string} opt_nmTokenPolicy A transform to apply
* to attributes containing HTML names, element IDs, and space-separated
* lists of classes. If not given, such attributes are left unchanged.
* @return {function(string, Array.<?string>)} A tagPolicy suitable for
* passing to html.sanitize.
*/
function makeTagPolicy(
opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger) {
return function(tagName, attribs) {
if (!(html4.ELEMENTS[tagName] & html4.eflags['UNSAFE'])) {
return {
'attribs': sanitizeAttribs(tagName, attribs,
opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger)
};
} else {
if (opt_logger) {
log(opt_logger, tagName, undefined, undefined, undefined);
}
}
};
}
/**
* Sanitizes HTML tags and attributes according to a given policy.
* @param {string} inputHtml The HTML to sanitize.
* @param {function(string, Array.<?string>)} tagPolicy A function that
* decides which tags to accept and sanitizes their attributes (see
* makeHtmlSanitizer above for details).
* @return {string} The sanitized HTML.
*/
function sanitizeWithPolicy(inputHtml, tagPolicy) {
var outputArray = [];
makeHtmlSanitizer(tagPolicy)(inputHtml, outputArray);
return outputArray.join('');
}
/**
* Strips unsafe tags and attributes from HTML.
* @param {string} inputHtml The HTML to sanitize.
* @param {?function(?string): ?string} opt_naiveUriRewriter A transform to
* apply to URI attributes. If not given, URI attributes are deleted.
* @param {function(?string): ?string} opt_nmTokenPolicy A transform to apply
* to attributes containing HTML names, element IDs, and space-separated
* lists of classes. If not given, such attributes are left unchanged.
*/
function sanitize(inputHtml,
opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger) {
var tagPolicy = makeTagPolicy(
opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger);
return sanitizeWithPolicy(inputHtml, tagPolicy);
}
// Export both quoted and unquoted names for Closure linkage.
var html = {};
html.escapeAttrib = html['escapeAttrib'] = escapeAttrib;
html.makeHtmlSanitizer = html['makeHtmlSanitizer'] = makeHtmlSanitizer;
html.makeSaxParser = html['makeSaxParser'] = makeSaxParser;
html.makeTagPolicy = html['makeTagPolicy'] = makeTagPolicy;
html.normalizeRCData = html['normalizeRCData'] = normalizeRCData;
html.sanitize = html['sanitize'] = sanitize;
html.sanitizeAttribs = html['sanitizeAttribs'] = sanitizeAttribs;
html.sanitizeWithPolicy = html['sanitizeWithPolicy'] = sanitizeWithPolicy;
html.unescapeEntities = html['unescapeEntities'] = unescapeEntities;
return html;
})(html4);
var html_sanitize = html['sanitize'];
// Loosen restrictions of Caja's
// html-sanitizer to allow for styling
html4.ATTRIBS['*::style'] = 0;
html4.ELEMENTS['style'] = 0;
html4.ATTRIBS['a::target'] = 0;
html4.ELEMENTS['video'] = 0;
html4.ATTRIBS['video::src'] = 0;
html4.ATTRIBS['video::poster'] = 0;
html4.ATTRIBS['video::controls'] = 0;
html4.ELEMENTS['audio'] = 0;
html4.ATTRIBS['audio::src'] = 0;
html4.ATTRIBS['video::autoplay'] = 0;
html4.ATTRIBS['video::controls'] = 0;
if (true) {
module.exports = html_sanitize;
}
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _fieldCollection = __webpack_require__(51);
var _fieldCollection2 = _interopRequireDefault(_fieldCollection);
var _model = __webpack_require__(166);
var recordModel = _interopRequireWildcard(_model);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var RecordCollection = function () {
function RecordCollection(recordsList, fieldsColl, statusbitList, predefinedValues) {
_classCallCheck(this, RecordCollection);
this.records = recordsList;
this.statusbits = statusbitList;
this.fieldCollection = fieldsColl;
this.predefinedValues = predefinedValues;
// set each models
this.initializeRecordModels();
}
_createClass(RecordCollection, [{
key: 'getRecords',
value: function getRecords() {
return this.records;
}
}, {
key: 'getRecordByIndex',
value: function getRecordByIndex() {
var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (this.records[id] !== undefined) {
return this.records[id];
}
return false;
}
}, {
key: 'initializeRecordModels',
value: function initializeRecordModels() {
for (var recordIndex in this.records) {
// let fields = this.setRecordFields(recordIndex);
this.records[recordIndex].fields = this.setRecordFields(recordIndex);
//options.fields = fields;
}
}
}, {
key: 'setRecordFields',
value: function setRecordFields(recordIndex) {
var fields = {};
for (var fieldIndex in this.records[recordIndex].fields) {
var meta_struct_id = this.records[recordIndex].fields[fieldIndex].meta_struct_id;
var currentField = this.fieldCollection.getFieldByIndex(meta_struct_id);
var fieldOptions = this.fieldCollection.getFieldOptionsById(meta_struct_id);
var databoxField = new recordModel.databoxField(currentField.name, currentField.label, meta_struct_id, fieldOptions);
var values = [];
for (var v in this.records[recordIndex].fields[fieldIndex].values) {
var meta_id = this.records[recordIndex].fields[fieldIndex].values[v].meta_id;
var value = this.records[recordIndex].fields[fieldIndex].values[v].value;
var vocabularyId = this.records[recordIndex].fields[fieldIndex].values[v].vocabularyId;
values.push(new recordModel.recordFieldValue(meta_id, value, vocabularyId));
}
fields[fieldIndex] = new recordModel.recordField(databoxField, values);
}
return fields;
}
/**
* Merge all suggestions for 1 or n records
* @returns {{}}
*/
}, {
key: 'getFieldSuggestedValues',
value: function getFieldSuggestedValues() {
var suggestedValuesCollection = {};
var t_selcol = {};
var ncolsel = 0;
var nrecsel = 0;
for (var recordIndex in this.records) {
if (!this.records[recordIndex]._selected) {
continue;
}
nrecsel++;
var bid = 'b' + this.records[recordIndex].bid;
if (t_selcol[bid]) {
continue;
}
t_selcol[bid] = 1;
ncolsel++;
for (var f in this.predefinedValues[bid]) {
if (!suggestedValuesCollection[f]) {
suggestedValuesCollection[f] = {};
}
for (var ivs in this.predefinedValues[bid][f]) {
var vs = this.predefinedValues[bid][f][ivs];
if (!suggestedValuesCollection[f][vs]) {
suggestedValuesCollection[f][vs] = 0;
}
suggestedValuesCollection[f][vs]++;
}
}
}
return suggestedValuesCollection;
}
}, {
key: 'setStatus',
value: function setStatus(bit, val) {
for (var id in this.records) {
// toutes les fiches selectionnees
if (this.records[id]._selected) {
if (this.records[id].editableStatus === true) {
this.records[id].statbits[bit].value = val;
this.records[id].statbits[bit].dirty = true;
}
}
}
}
}, {
key: 'isDirty',
value: function isDirty() {
var dirty = false;
for (var recordIndex in this.records) {
for (var fieldIndex in this.records[recordIndex].fields) {
if (dirty |= this.records[recordIndex].fields[fieldIndex].isDirty()) {
break;
}
}
for (var bitIndex in this.records[recordIndex].statbits) {
if (dirty |= this.records[recordIndex].statbits[bitIndex].dirty) {
break;
}
}
}
return dirty;
}
}, {
key: 'gatherUpdatedRecords',
value: function gatherUpdatedRecords() {
var t = [];
for (var recordIndex in this.records) {
var record_datas = {
record_id: this.records[recordIndex].rid,
metadatas: [],
edit: 0,
status: null
};
var editDirty = false;
for (var f in this.records[recordIndex].fields) {
if (!this.records[recordIndex].fields[f].isDirty()) {
continue;
}
editDirty = true;
record_datas.edit = 1;
record_datas.metadatas = record_datas.metadatas.concat(this.records[recordIndex].fields[f].exportDatas());
}
// les statbits
var tsb = [];
for (var n = 0; n < 64; n++) {
tsb[n] = 'x';
}
var sb_dirty = false;
for (var _n in this.records[recordIndex].statbits) {
if (this.records[recordIndex].statbits[_n].dirty) {
tsb[63 - _n] = this.records[recordIndex].statbits[_n].value;
sb_dirty = true;
}
}
if (sb_dirty || editDirty) {
if (sb_dirty === true) {
record_datas.status = tsb.join('');
}
t.push(record_datas);
}
}
return t;
}
}, {
key: 'removeRecordFieldValue',
value: function removeRecordFieldValue(recordIndex, fieldIndex, params) {
var value = params.value,
vocabularyId = params.vocabularyId;
this.records[recordIndex].fields[fieldIndex].removeValue(value, vocabularyId);
}
}, {
key: 'addRecordFieldValue',
value: function addRecordFieldValue(recordIndex, fieldIndex, params) {
var value = params.value,
merge = params.merge,
vocabularyId = params.vocabularyId;
this.records[recordIndex].fields[fieldIndex].addValue(value, merge, vocabularyId);
}
/* options.recordCollection.removeRecordFieldValue(r, currentFieldId, {
value, vocabularyId
})*/
// currentRecord.fields[currentFieldId].removeValue(value, VocabularyId);
}]);
return RecordCollection;
}();
exports.default = RecordCollection;
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.recordField = exports.recordFieldValue = exports.databoxField = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function checkVocabId(VocabularyId) {
if (typeof VocabularyId === 'undefined') {
VocabularyId = null;
}
if (VocabularyId === '') {
VocabularyId = null;
}
return VocabularyId;
}
var recordFieldValue = function recordFieldValue(meta_id, value, VocabularyId) {
VocabularyId = checkVocabId(VocabularyId);
this.datas = {
meta_id: meta_id,
value: value,
VocabularyId: VocabularyId
};
var $this = this;
};
recordFieldValue.prototype = {
getValue: function getValue() {
return this.datas.value;
},
getMetaId: function getMetaId() {
return this.datas.meta_id;
},
getVocabularyId: function getVocabularyId() {
return this.datas.VocabularyId;
},
setValue: function setValue(value, VocabularyId) {
this.datas.value = value;
this.datas.VocabularyId = checkVocabId(VocabularyId);
return this;
},
remove: function remove() {
this.datas.value = '';
this.datas.VocabularyId = null;
return this;
}
};
var databoxField = function databoxField(name, label, meta_struct_id, options) {
var defaults = {
multi: false,
required: false,
readonly: false,
maxLength: null,
minLength: null,
type: 'string',
separator: null,
vocabularyControl: null,
vocabularyRestricted: false
};
options = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? options : {};
if (isNaN(meta_struct_id)) {
throw 'meta_struct_id should be a number';
}
this.name = name;
this.label = label;
this.meta_struct_id = meta_struct_id;
this.options = _jquery2.default.extend(defaults, options);
if (this.options.multi === true && this.options.separator === null) {
this.options.separator = ';';
}
};
databoxField.prototype = {
getMetaStructId: function getMetaStructId() {
return this.meta_struct_id;
},
getName: function getName() {
return this.name;
},
getLabel: function getLabel() {
return this.label;
},
isMulti: function isMulti() {
return this.options.multi;
},
isRequired: function isRequired() {
return this.options.required;
},
isReadonly: function isReadonly() {
return this.options.readonly;
},
getMaxLength: function getMaxLength() {
return this.options.maxLength;
},
getMinLength: function getMinLength() {
return this.options.minLength;
},
getType: function getType() {
return this.options.type;
},
getSeparator: function getSeparator() {
return this.options.separator;
}
};
var recordField = function recordField(databoxField, arrayValues) {
this.databoxField = databoxField;
this.options = {
dirty: false
};
this.datas = [];
if (arrayValues instanceof Array) {
if (arrayValues.length > 1 && !databoxField.isMulti()) {
throw 'You can not add multiple values to a non multi field ' + databoxField.getName();
}
var first = true;
for (var v in arrayValues) {
if (_typeof(arrayValues[v]) !== 'object') {
if (window.console) {
console.error('Trying to add a non-recordFieldValue to the field...');
}
continue;
}
if (isNaN(arrayValues[v].getMetaId())) {
if (window.console) {
console.error('Trying to add a recordFieldValue without metaId...');
}
continue;
}
if (!first && this.options.multi === false) {
if (window.console) {
console.error('Trying to add multi values in a non-multi field');
}
}
/*if (window.console) {
console.log('adding a value : ', arrayValues[v]);
}*/
this.datas.push(arrayValues[v]);
first = false;
}
}
var $this = this;
};
recordField.prototype = {
getName: function getName() {
return this.databoxField.getName();
},
getMetaStructId: function getMetaStructId() {
return this.databoxField.getMetaStructId();
},
isMulti: function isMulti() {
return this.databoxField.isMulti();
},
isRequired: function isRequired() {
return this.databoxField.isRequired();
},
isDirty: function isDirty() {
return this.options.dirty;
},
addValue: function addValue(value, merge, VocabularyId) {
VocabularyId = checkVocabId(VocabularyId);
merge = !!merge;
/* if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
return this;
}*/
if (window.console) {
console.log('adding value ', value, ' vocId : ', VocabularyId, ' ; merge is ', merge);
}
if (this.isMulti()) {
if (!this.hasValue(value, VocabularyId)) {
if (window.console) {
console.log('adding new multi value ', value);
}
this.datas.push(new recordFieldValue(null, value, VocabularyId));
this.options.dirty = true;
} else {
if (window.console) {
console.log('already have ', value);
}
}
} else {
if (merge === true && this.isEmpty() === false && VocabularyId === null) {
if (window.console) {
console.log('Merging value ', value);
}
this.datas[0].setValue(this.datas[0].getValue() + ' ' + value, VocabularyId);
this.options.dirty = true;
} else {
if (merge === true && this.isEmpty() === false && VocabularyId !== null) {
if (window.console) {
console.error('Cannot merge vocabularies');
}
this.datas[0].setValue(value, VocabularyId);
} else {
if (!this.hasValue(value, VocabularyId)) {
if (this.datas.length === 0) {
/*if (window.console) {
console.log('Adding new value ', value);
}*/
this.datas.push(new recordFieldValue(null, value, VocabularyId));
} else {
if (window.console) {
console.log('Updating value ', value);
}
this.datas[0].setValue(value, VocabularyId);
}
this.options.dirty = true;
}
}
}
}
return this;
},
hasValue: function hasValue(value, VocabularyId) {
if (typeof value === 'undefined') {
if (window.console) {
console.error('Trying to check the presence of an undefined value');
}
}
VocabularyId = checkVocabId(VocabularyId);
for (var d in this.datas) {
if (VocabularyId !== null) {
if (this.datas[d].getVocabularyId() === VocabularyId) {
if (window.console) {
console.log('already got the vocab ID');
}
return true;
}
} else if (this.datas[d].getVocabularyId() === null && this.datas[d].getValue() === value) {
if (window.console) {
console.log('already got this value');
}
return true;
}
}
return false;
},
removeValue: function removeValue(value, vocabularyId) {
if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
return this;
}
vocabularyId = checkVocabId(vocabularyId);
if (window.console) {
console.log('Try to remove value ', value, vocabularyId, this.datas);
}
for (var d in this.datas) {
if (window.console) {
console.log('loopin... ', this.datas[d].getValue());
}
if (this.datas[d].getVocabularyId() !== null) {
if (this.datas[d].getVocabularyId() === vocabularyId) {
if (window.console) {
console.log('Found within the vocab ! removing... ');
}
this.datas[d].remove();
this.options.dirty = true;
}
} else if (this.datas[d].getValue() === value) {
if (window.console) {
console.log('Found ! removing... ');
}
this.datas[d].remove();
this.options.dirty = true;
}
}
return this;
},
isEmpty: function isEmpty() {
var empty = true;
for (var d in this.datas) {
if (this.datas[d].getValue() !== '') {
empty = false;
}
}
return empty;
},
empty: function empty() {
if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
return this;
}
for (var d in this.datas) {
this.datas[d].remove();
this.options.dirty = true;
}
return this;
},
getValue: function getValue() {
if (this.isMulti()) {
throw 'This field is multi, I can not give you a single value';
}
if (this.isEmpty()) {
return null;
}
return this.datas[0];
},
getValues: function getValues() {
if (!this.isMulti()) {
throw 'This field is not multi, I can not give you multiple values';
}
if (this.isEmpty()) {
return [];
}
var arrayValues = [];
for (var d in this.datas) {
if (this.datas[d].getValue() === '') {
continue;
}
arrayValues.push(this.datas[d]);
}
return arrayValues;
},
sort: function sort(algo) {
this.datas.sort(algo);
return this;
},
getSerializedValues: function getSerializedValues() {
var arrayValues = [];
var values = this.getValues();
for (var v in values) {
arrayValues.push(values[v].getValue());
}
return arrayValues.join(' ; ');
},
replaceValue: function replaceValue(search, replace) {
if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
return 0;
}
var n = 0;
for (var d in this.datas) {
if (this.datas[d].getVocabularyId() !== null) {
continue;
}
var value = this.datas[d].getValue();
var replacedValue = value.replace(search, replace);
if (value === replacedValue) {
continue;
}
n++;
this.removeValue(value);
if (!this.hasValue(replacedValue)) {
this.addValue(replacedValue);
}
this.options.dirty = true;
}
return n;
},
exportDatas: function exportDatas() {
var returnValue = [];
for (var d in this.datas) {
var temp = {
meta_id: this.datas[d].getMetaId() ? this.datas[d].getMetaId() : '',
meta_struct_id: this.getMetaStructId(),
value: this.datas[d].getValue()
};
if (this.datas[d].getVocabularyId()) {
temp.vocabularyId = this.datas[d].getVocabularyId();
}
returnValue.push(temp);
}
return returnValue;
}
};
exports.databoxField = databoxField;
exports.recordFieldValue = recordFieldValue;
exports.recordField = recordField;
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var StatusCollection = function () {
function StatusCollection(statusList) {
_classCallCheck(this, StatusCollection);
this.status = statusList;
}
_createClass(StatusCollection, [{
key: 'getStatus',
value: function getStatus() {
return this.status;
}
}, {
key: 'fillWithRecordValues',
value: function fillWithRecordValues(records) {
var prefilledStatus = {};
for (var statusIndex in this.status) {
prefilledStatus[statusIndex] = (0, _lodash2.default)({}, this.status[statusIndex]);
prefilledStatus[statusIndex]._value = '-1'; // val unknown
for (var i in records) {
if (!records[i]._selected) {
continue;
}
if (records[i].statbits.length === 0) {
continue;
}
if (prefilledStatus[statusIndex]._value === '-1') {
prefilledStatus[statusIndex]._value = records[i].statbits[statusIndex].value;
} else if (prefilledStatus[statusIndex]._value !== records[i].statbits[statusIndex].value) {
prefilledStatus[statusIndex]._value = '2';
}
}
}
return prefilledStatus;
}
}]);
return StatusCollection;
}();
exports.default = StatusCollection;
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var deleteRecord = function deleteRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var workzoneSelection = [];
var searchSelection = [];
var openModal = function openModal(datas) {
var $dialog = _dialog2.default.create(services, {
size: '480x160',
title: localeService.t('warning')
});
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/records/delete/what/',
dataType: 'html',
data: datas,
success: function success(data) {
$dialog.setOption('height', 'auto');
$dialog.setContent(data);
//reset top position of dialog
$dialog.getDomElement().offsetParent().css('top', ((0, _jquery2.default)(window).height() - $dialog.getDomElement()[0].clientHeight) / 2);
_onDialogReady();
}
});
return false;
};
var _onDialogReady = function _onDialogReady() {
var $dialog = _dialog2.default.get(1);
var $dialogBox = $dialog.getDomElement();
var $closeButton = (0, _jquery2.default)('button.ui-dialog-titlebar-close', $dialogBox.parent());
var $cancelButton = (0, _jquery2.default)('button.cancel', $dialogBox);
var $delChildren = (0, _jquery2.default)("input[name='del_children']", $dialogBox);
var titleBox = (0, _jquery2.default)(".ui-dialog-title", $dialogBox.parent());
titleBox.prepend('<i class="fa fa-exclamation-triangle" style="margin-right: 10px"></i>');
/**
* the checkbox "delete stories children too" changes
**/
$delChildren.bind("change", function () {
fSetDelChildren((0, _jquery2.default)(this).is(':checked'));
});
$cancelButton.bind('click', function () {
$dialog.close();
});
/**
* set the dlg content according the "delete children" ckbox
* the counts (records will be deleted, records rejected...) will update
*/
var fSetDelChildren = function fSetDelChildren(delChildren) {
if (delChildren) {
(0, _jquery2.default)("#delete_records_parent_only").hide();
(0, _jquery2.default)("#delete_records_with_children").show();
} else {
(0, _jquery2.default)("#delete_records_with_children").hide();
(0, _jquery2.default)("#delete_records_parent_only").show();
}
};
/**
* click ok : run delete tasks
*/
(0, _jquery2.default)('button.submiter', $dialogBox).bind('click', function () {
var CHUNKSIZE = 3,
MAXTASKS = 5;
var $this = (0, _jquery2.default)(this);
var $form = (0, _jquery2.default)(this).closest("form"),
$counter = $form.find(".to_delete_count"),
$trash_counter = $form.find(".to_trash_count"),
$loader = $form.find(".form-action-loader");
var lst = (0, _jquery2.default)("input[name='lst']", $form).val().split(';');
/**
* same parameters for every delete call, except the list of (CHUNKSIZE) records
* nb: do NOT ask to delete children since they're included in lst
*/
var ajaxParms = {
type: $form.attr("method"),
url: $form.attr("action"),
data: {
'lst': "" // set in f
},
dataType: "json"
};
var runningTasks = 0,
// number of running tasks
canceling = false;
/**
* cancel or close dlg will ask tasks to stop
*/
var fCancel = function fCancel() {
$closeButton.hide();
$cancelButton.hide();
$loader.show();
canceling = true;
};
/**
* task fct : will loop itself while there is job to do
*
* @param iTask (int) The task number 0...MAXTASKS-1, usefull only to debug
*/
var fTask = function fTask(iTask) {
if (canceling) {
return;
}
// pop & truncate
ajaxParms.data.lst = lst.splice(0, CHUNKSIZE).join(';');
_jquery2.default.ajax(ajaxParms).success(function (data) {
// prod feedback only if result ok
_jquery2.default.each(data, function (i, n) {
var imgt = (0, _jquery2.default)('#IMGT_' + n),
chim = (0, _jquery2.default)('.CHIM_' + n),
stories = (0, _jquery2.default)('.STORY_' + n);
(0, _jquery2.default)('.doc_infos', imgt).remove();
try {
$imgt.draggable("destroy");
} catch (e) {
// no-op
}
imgt.unbind("click").removeAttr("ondblclick").removeClass("selected").removeClass("IMGT").find("img").unbind();
imgt.find(".thumb img").attr("src", "/assets/common/images/icons/deleted.png").css({
width: '100%',
height: 'auto',
margin: '0 10px',
top: '0'
});
chim.parent().slideUp().remove();
imgt.find(".status,.title,.bottom").empty();
appEvents.emit('search.selection.remove', { records: n });
if (stories.length > 0) {
appEvents.emit('workzone.refresh');
} else {
appEvents.emit('workzone.selection.remove', { records: n });
}
});
}).then(function () {
// go on even in case of error
// countdown
$counter.html(lst.length);
$trash_counter.html(lst.length);
if (lst.length === 0 || canceling) {
// end of a task
if (--runningTasks === 0) {
$dialog.close();
(0, _jquery2.default)('#nbrecsel').empty().append(lst.length);
}
} else {
// don't recurse, give a delay to running fct to end
window.setTimeout(fTask, 10, iTask);
}
});
};
// cancel or close the dlg is the same : wait
$dialog.setOption('closeOnEscape', false);
$closeButton.unbind("click").bind("click", fCancel);
$cancelButton.unbind("click").bind("click", fCancel);
// run a bunch of tasks in //
for (runningTasks = 0; runningTasks < MAXTASKS && lst.length > 0; runningTasks++) {
fTask(runningTasks); // pass the task his index to get nice console logs
}
});
fSetDelChildren(false);
};
return { openModal: openModal };
};
exports.default = deleteRecord;
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var propertyRecord = function propertyRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var openModal = function openModal(datas) {
return doProperty(datas);
};
var doProperty = function doProperty(datas) {
var $dialog = _dialog2.default.create(services, {
size: 'Medium',
title: (0, _jquery2.default)('#property-title').val()
});
_jquery2.default.ajax({
type: 'GET',
data: datas,
url: url + 'prod/records/property/',
success: function success(data) {
$dialog.setContent(data);
_onPropertyReady($dialog);
}
});
return true;
};
var _onPropertyReady = function _onPropertyReady($dialog) {
(0, _jquery2.default)('#tabs-records-property').tabs({
beforeLoad: function beforeLoad(event, ui) {
ui.ajaxSettings.data = {
lst: (0, _jquery2.default)('input[name=original_selection]', (0, _jquery2.default)(this)).val()
};
// load template only once
if (ui.tab.data('loaded')) {
event.preventDefault();
return;
}
ui.jqXHR.success(function () {
ui.tab.data('loaded', true);
ui.tab.find('span').html('');
typeTabContent($dialog, '#' + ui.tab.attr('aria-controls'));
});
ui.tab.find('span').html('<i>' + localeService.t('loading') + '</i>');
},
load: function load(event, ui) {
ui.tab.find('span').empty();
}
});
propertyTabContent($dialog);
};
/**
* Property Tab
* @param $dialogBox
*/
var propertyTabContent = function propertyTabContent($dialog) {
var $propertyContainer = (0, _jquery2.default)('#property-status');
$propertyContainer.on('click', 'button.cancel', function () {
$dialog.close();
});
$propertyContainer.on('click', 'button.submiter', function () {
var $this = (0, _jquery2.default)(this);
var form = (0, _jquery2.default)(this).closest('form');
var loader = form.find('form-action-loader');
_jquery2.default.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {
$this.attr('disabled', true);
loader.show();
},
success: function success(data) {
$dialog.close();
},
complete: function complete() {
$this.attr('disabled', false);
loader.hide();
}
});
});
};
/**
* Type Tab
* @param $dialog
* @param typeContainerId
*/
var typeTabContent = function typeTabContent($dialog, typeContainerId) {
var $typeContainer = (0, _jquery2.default)(typeContainerId);
$typeContainer.on('click', 'button.cancel', function () {
$dialog.close();
});
$typeContainer.on('click', 'button.submiter', function () {
var $this = (0, _jquery2.default)(this);
var form = (0, _jquery2.default)(this).closest('form');
var loader = form.find('form-action-loader');
_jquery2.default.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {
$this.attr('disabled', true);
loader.show();
},
success: function success(data) {
$dialog.close();
},
complete: function complete() {
$this.attr('disabled', false);
loader.hide();
}
});
});
};
return { openModal: openModal };
};
exports.default = propertyRecord;
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _index = __webpack_require__(69);
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pushRecord = function pushRecord(services, datas) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var openModal = function openModal(datas) {
var $dialog = _dialog2.default.create(services, {
size: 'Full',
title: localeService.t('push')
});
$dialog.getDomElement().closest('.ui-dialog').addClass('push_dialog_container');
_jquery2.default.post(url + 'prod/push/sendform/', datas, function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
return true;
};
var _onDialogReady = function _onDialogReady() {
(0, _index2.default)(services).initialize({
feedback: {
containerId: '#PushBox',
context: 'Push'
},
listManager: {
containerId: '#ListManager'
}
});
};
return { openModal: openModal };
};
exports.default = pushRecord;
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _index = __webpack_require__(70);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _selectable = __webpack_require__(23);
var _selectable2 = _interopRequireDefault(_selectable);
var _addUser = __webpack_require__(71);
var _addUser2 = _interopRequireDefault(_addUser);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
__webpack_require__(14);
var Feedback = function Feedback(services, options) {
var _this = this;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = void 0;
var containerId = options.containerId,
context = options.context;
this.url = url;
this.container = $container = (0, _jquery2.default)(containerId);
this.userList = new _index.Lists();
this.Context = context;
this.selection = new _selectable2.default(services, (0, _jquery2.default)('.user_content .badges', this.container), {
selector: '.badge'
});
(0, _addUser2.default)(services).initialize({ $container: this.container });
var $this = this;
this.container.on('mouseenter', '.list-trash-btn', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
$el.find('.image-normal').hide();
$el.find('.image-hover').show();
});
this.container.on('mouseleave', '.list-trash-btn', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
$el.find('.image-normal').show();
$el.find('.image-hover').hide();
});
this.container.on('click', '.list-trash-btn', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var list_id = $el.parent().data('list-id');
appEvents.emit('push.removeList', {
list_id: list_id,
container: containerId
});
});
this.container.on('click', '.push-refresh-list-action', function (event) {
event.preventDefault();
var callback = function callback(datas) {
var context = (0, _jquery2.default)(datas);
var dataList = (0, _jquery2.default)(context).find('.lists').prop('outerHTML');
var refreshContent = (0, _jquery2.default)('.LeftColumn .content .lists', $container);
refreshContent.removeClass('loading').append(dataList);
};
(0, _jquery2.default)('.LeftColumn .content .lists', $container).empty().addClass('loading');
$this.userList.get(callback, 'html');
});
this.container.on('click', '.content .options .select-all', function (event) {
$this.selection.selectAll();
});
this.container.on('click', '.content .options .unselect-all', function (event) {
$this.selection.empty();
});
this.container.on('click', '.content .options .delete-selection', function (event) {
_.each((0, _jquery2.default)('.badges.selectionnable').children(), function (item) {
var $elem = (0, _jquery2.default)(item);
if ($elem.hasClass('selected')) {
$elem.fadeOut(function () {
$elem.remove();
});
}
});
return false;
});
(0, _jquery2.default)('.UserTips', this.container).tooltip();
/*this.container.on('click', '.user_adder', function (event) {
event.preventDefault();
const url = configService.get('baseUrl');
var $this = $(this);
$.ajax({
type: 'GET',
url: `${url}prod/push/add-user/`,
dataType: 'html',
beforeSend: function () {
var options = {
size: 'Medium',
title: $this.html()
};
dialog.create(services, options, 2).getDomElement().addClass('loading');
},
success: function (data) {
dialog.get(2).getDomElement().removeClass('loading').empty().append(data);
return;
},
error: function () {
dialog.get(2).close();
return;
},
timeout: function () {
dialog.get(2).close();
return;
}
});
return false;
});*/
this.container.on('click', '.recommended_users', function (event) {
var usr_id = (0, _jquery2.default)('input[name="usr_id"]', (0, _jquery2.default)(this)).val();
$this.loadUser(usr_id, $this.selectUser);
return false;
});
this.container.on('click', '.recommended_users_list', function (event) {
var content = (0, _jquery2.default)('#push_user_recommendations').html();
var options = {
size: 'Small',
title: (0, _jquery2.default)(this).attr('title')
};
var $dialog = _dialog2.default.create(services, options, 2);
$dialog.setContent(content);
$dialog.getDomElement().find('a.adder').bind('click', function () {
(0, _jquery2.default)(this).addClass('added');
var usr_id = (0, _jquery2.default)(this).closest('tr').find('input[name="usr_id"]').val();
$this.loadUser(usr_id, $this.selectUser);
return false;
});
$dialog.getDomElement().find('a.adder').each(function (i, el) {
var usr_id = (0, _jquery2.default)(this).closest('tr').find('input[name="usr_id"]').val();
if ((0, _jquery2.default)('.badge_' + usr_id, $this.container).length > 0) {
(0, _jquery2.default)(this).addClass('added');
}
});
return false;
});
//this.container.on('submit', '#PushBox form[name="FeedBackForm"]', function (event) {
(0, _jquery2.default)('#PushBox form[name="FeedBackForm"]').bind('submit', function () {
var $this = (0, _jquery2.default)(this);
_jquery2.default.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
dataType: 'json',
data: $this.serializeArray(),
beforeSend: function beforeSend() {},
success: function success(data) {
if (data.success) {
humane.info(data.message);
_dialog2.default.close(1);
appEvents.emit('workzone.refresh');
} else {
humane.error(data.message);
}
return;
},
error: function error() {
return;
},
timeout: function timeout() {
return;
}
});
return false;
});
(0, _jquery2.default)('.FeedbackSend', this.container).bind('click', function (event) {
if ((0, _jquery2.default)('.badges .badge', $container).length === 0) {
alert(localeService.t('FeedBackNoUsersSelected'));
return;
}
var buttons = {};
buttons[localeService.t('annuler')] = function () {
$dialog.close();
};
buttons[localeService.t('send')] = function () {
if (_jquery2.default.trim((0, _jquery2.default)('input[name="name"]', $dialog.getDomElement()).val()) === '') {
var options = {
size: 'Alert',
closeButton: true,
title: localeService.t('warning')
};
var $dialogAlert = _dialog2.default.create(services, options, 3);
$dialogAlert.setContent(localeService.t('FeedBackNameMandatory'));
return false;
}
$dialog.close();
(0, _jquery2.default)('input[name="name"]', $FeedBackForm).val((0, _jquery2.default)('input[name="name"]', $dialog.getDomElement()).val());
(0, _jquery2.default)('input[name="duration"]', $FeedBackForm).val((0, _jquery2.default)('select[name="duration"]', $dialog.getDomElement()).val());
(0, _jquery2.default)('textarea[name="message"]', $FeedBackForm).val((0, _jquery2.default)('textarea[name="message"]', $dialog.getDomElement()).val());
(0, _jquery2.default)('input[name="recept"]', $FeedBackForm).prop('checked', (0, _jquery2.default)('input[name="recept"]', $dialog.getDomElement()).prop('checked'));
(0, _jquery2.default)('input[name="force_authentication"]', $FeedBackForm).prop('checked', (0, _jquery2.default)('input[name="force_authentication"]', $dialog.getDomElement()).prop('checked'));
$FeedBackForm.trigger('submit');
};
var options = {
size: '558x352',
buttons: buttons,
loading: true,
title: localeService.t('send'),
closeOnEscape: true
};
var $el = (0, _jquery2.default)(event.currentTarget);
if ($el.hasClass('validation')) {
options.isValidation = true;
options.size = '558x415';
}
var $dialog = _dialog2.default.create(services, options, 2);
$dialog.getDomElement().closest('.ui-dialog').addClass('dialog_container');
if (options.isValidation) {
$dialog.getDomElement().closest('.ui-dialog').addClass('validation');
}
var $FeedBackForm = (0, _jquery2.default)('form[name="FeedBackForm"]', $container);
var html = _.template((0, _jquery2.default)('#feedback_sendform_tpl').html());
$dialog.setContent(html);
var feedbackTitle = (0, _jquery2.default)('#feedbackTitle').val();
var pushTitle = (0, _jquery2.default)('#pushTitle').val();
if (options.isValidation) {
(0, _jquery2.default)('input[name="name"]').attr("placeholder", feedbackTitle);
} else {
(0, _jquery2.default)('input[name="name"]').attr("placeholder", pushTitle);
}
(0, _jquery2.default)('input[name="name"]', $dialog.getDomElement()).val((0, _jquery2.default)('input[name="name"]', $FeedBackForm).val());
(0, _jquery2.default)('textarea[name="message"]', $dialog.getDomElement()).val((0, _jquery2.default)('textarea[name="message"]', $FeedBackForm).val());
(0, _jquery2.default)('.' + $this.Context, $dialog.getDomElement()).show();
(0, _jquery2.default)('form', $dialog.getDomElement()).submit(function () {
return false;
});
});
(0, _jquery2.default)('.user_content .badges', this.container).disableSelection();
// toggle download feature for users
this.container.on('click', '.user_content .badges .badge .toggle', function (event) {
var $this = (0, _jquery2.default)(this);
$this.toggleClass('status_off status_on');
$this.find('input').val($this.hasClass('status_on') ? '1' : '0');
return false;
});
this.container.on('mouseenter', '#info-box-trigger', function (event) {
(0, _jquery2.default)('#info-box').show();
});
this.container.on('mouseleave', '#info-box-trigger', function (event) {
(0, _jquery2.default)('#info-box').hide();
});
// toggle feature state of selected users
this.container.on('click', '.general_togglers .general_toggler', function (event) {
var feature = (0, _jquery2.default)(this).attr('feature');
var $badges = (0, _jquery2.default)('.user_content .badge.selected', this.container);
var toggles = (0, _jquery2.default)('.status_off.toggle_' + feature, $badges);
if (toggles.length === 0) {
toggles = (0, _jquery2.default)('.status_on.toggle_' + feature, $badges);
}
if (toggles.length === 0) {
humane.info('No user selected');
}
toggles.trigger('click');
return false;
});
this.container.on('click', '.user_content .badges .badge .deleter', function (event) {
var $elem = (0, _jquery2.default)(this).closest('.badge');
$elem.fadeOut(function () {
$elem.remove();
});
return false;
});
this.container.on('click', '.list_manager', function (event) {
(0, _jquery2.default)('#PushBox').hide();
(0, _jquery2.default)('#ListManager').show();
return false;
});
this.container.on('click', 'a.list_push_loader', function (event) {
var url = (0, _jquery2.default)(this).attr('href');
var callbackList = function callbackList(list) {
for (var i in list.entries) {
this.selectUser(list.entries[i].User);
}
};
$this.loadList(url, callbackList);
return false;
});
(0, _jquery2.default)('form.list_saver', this.container).bind('submit', function () {
var $form = (0, _jquery2.default)(event.currentTarget);
var $input = (0, _jquery2.default)('input[name="name"]', $form);
var users = _this.getUsers();
if (users.length === 0) {
humane.error('No users');
return false;
}
// appEvents.emit('push.createList', {name: $input.val(), collection: users});
$this.createList({ name: $input.val(), collection: users });
$input.val('');
/*
p4.Lists.create($input.val(), function (list) {
$input.val('');
list.addUsers(users);
});*/
return false;
});
(0, _jquery2.default)('input[name="users-search"]', this.container).autocomplete({
minLength: 2,
source: function source(request, response) {
_jquery2.default.ajax({
url: url + 'prod/push/search-user/',
dataType: 'json',
data: {
query: request.term
},
success: function success(data) {
response(data);
}
});
},
focus: function focus(event, ui) {
// $('input[name="users-search"]').val(ui.item.label);
},
select: function select(event, ui) {
if (ui.item.type === 'USER') {
$this.selectUser(ui.item);
} else if (ui.item.type === 'LIST') {
for (var e in ui.item.entries) {
$this.selectUser(ui.item.entries[e].User);
}
}
return false;
}
}).data('ui-autocomplete')._renderItem = function (ul, item) {
var html = '';
if (item.type === 'USER') {
html = _.template((0, _jquery2.default)('#list_user_tpl').html())({
item: item
});
if ($this.Context === 'Push') {
setTimeout(function () {
(0, _jquery2.default)('.ui-menu .ui-menu-item a').css('box-shadow', 'inset 0 -1px #2196f3');
(0, _jquery2.default)('img[src="/assets/common/images/icons/user-orange.png"]').attr('src', '/assets/common/images/icons/user-blue.png');
}, 100);
} else if ($this.Context === 'Feedback') {
setTimeout(function () {
(0, _jquery2.default)('.ui-menu .ui-menu-item a').css('box-shadow', 'inset 0 -1px #8bc34a');
(0, _jquery2.default)('img[src="/assets/common/images/icons/user-orange.png"]').attr('src', '/assets/common/images/icons/user-green.png');
}, 100);
}
} else if (item.type === 'LIST') {
html = _.template((0, _jquery2.default)('#list_list_tpl').html())({
item: item
});
}
return (0, _jquery2.default)(html).data('ui-autocomplete-item', item).appendTo(ul);
};
return this;
};
Feedback.prototype = {
selectUser: function selectUser(user) {
if ((typeof user === 'undefined' ? 'undefined' : _typeof(user)) !== 'object') {
if (window.console) {
console.log('trying to select a user with wrong datas');
}
}
if ((0, _jquery2.default)('.badge_' + user.usr_id, this.container).length > 0) {
humane.info('User already selected');
return;
}
var html = _.template((0, _jquery2.default)('#' + this.Context.toLowerCase() + '_badge_tpl').html())({
user: user
});
// p4.Feedback.appendBadge(html);
this.appendBadge(html);
},
loadUser: function loadUser(usr_id, callback) {
var $this = this;
_jquery2.default.ajax({
type: 'GET',
url: this.url + 'prod/push/user/' + usr_id + '/',
dataType: 'json',
data: {
usr_id: usr_id
},
success: function success(data) {
if (typeof callback === 'function') {
callback.call($this, data);
}
}
});
},
createList: function createList(options) {
var name = options.name,
collection = options.collection;
this.userList.create(name, function (list) {
list.addUsers(collection);
});
},
loadList: function loadList(url, callback) {
var $this = this;
_jquery2.default.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function success(data) {
if (typeof callback === 'function') {
callback.call($this, data);
}
}
});
},
appendBadge: function appendBadge(badge) {
(0, _jquery2.default)('.user_content .badges', this.container).append(badge);
},
addUser: function addUser(options) {
var $userForm = options.$userForm,
callback = options.callback;
var $this = this;
_jquery2.default.ajax({
type: 'POST',
url: this.url + 'prod/push/add-user/',
dataType: 'json',
data: $userForm.serializeArray(),
success: function success(data) {
if (data.success) {
humane.info(data.message);
$this.selectUser(data.user);
callback;
} else {
humane.error(data.message);
}
}
});
},
getSelection: function getSelection() {
return this.selection;
},
getUsers: function getUsers() {
return (0, _jquery2.default)('.user_content .badge', this.container).map(function () {
return (0, _jquery2.default)('input[name="id"]', (0, _jquery2.default)(this)).val();
});
}
};
exports.default = Feedback;
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _index = __webpack_require__(70);
var _listEditor = __webpack_require__(173);
var _listEditor2 = _interopRequireDefault(_listEditor);
var _listShare = __webpack_require__(174);
var _listShare2 = _interopRequireDefault(_listShare);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _selectable = __webpack_require__(23);
var _selectable2 = _interopRequireDefault(_selectable);
var _addUser = __webpack_require__(71);
var _addUser2 = _interopRequireDefault(_addUser);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
var ListManager = function ListManager(services, options) {
var _this2 = this;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var containerId = options.containerId;
var url = configService.get('baseUrl');
var $container = void 0;
var _this = this;
this.list = null;
this.container = $container = (0, _jquery2.default)(containerId);
this.userList = new _index.Lists();
this.removeUserItemsArray = [];
this.addUserItemsArray = [];
this.removeUserMethod = '';
this.addUserMethod = '';
(0, _addUser2.default)(services).initialize({ $container: this.container });
$container.on('click', '.back_link', function () {
(0, _jquery2.default)('#PushBox').show();
(0, _jquery2.default)('#ListManager').hide();
return false;
}).on('click', '.push-list-share-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var listId = $el.data('list-id');
(0, _listShare2.default)(services).openModal({
listId: listId, modalOptions: {
size: '288x500',
closeButton: true,
title: $el.attr('title')
}, modalLevel: 2
});
return false;
}).on('click', 'a.user_adder', function () {
var $this = (0, _jquery2.default)(this);
_jquery2.default.ajax({
type: 'GET',
url: $this.attr('href'),
dataType: 'html',
beforeSend: function beforeSend() {
var options = {
size: 'Medium',
title: $this.html()
};
_dialog2.default.create(services, options, 2).getDomElement().addClass('loading');
},
success: function success(data) {
_dialog2.default.get(2).getDomElement().removeClass('loading').empty().append(data);
return;
},
error: function error() {
_dialog2.default.get(2).close();
return;
},
timeout: function timeout() {
_dialog2.default.get(2).close();
return;
}
});
return false;
}).on('mouseenter', '.list-trash-btn', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
$el.find('.image-normal').hide();
$el.find('.image-hover').show();
}).on('mouseleave', '.list-trash-btn', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
$el.find('.image-normal').show();
$el.find('.image-hover').hide();
}).on('click', '.list-trash-btn', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var list_id = $el.parent().data('list-id');
appEvents.emit('push.removeList', {
list_id: list_id,
container: containerId
});
});
var initLeft = function initLeft() {
$container.on('click', '.push-refresh-list-action', function (event) {
event.preventDefault();
//$('a.list_refresh', $container).bind('click', (event) => {
// /prod/lists/all/
var selectedList = (0, _jquery2.default)('.lists_manager_list.selected').data('list-id');
var callback = function callback(datas, selected) {
(0, _jquery2.default)('.all-lists', $container).removeClass('loading').append(datas);
if (typeof selected === 'number') {
(0, _jquery2.default)('.all-lists').find('.lists_manager_list[data-list-id="' + selected + '"]').addClass('selected');
}
// initLeft();
};
(0, _jquery2.default)('.all-lists', $container).empty().addClass('loading');
_this2.userList.get(callback, 'html', selectedList);
});
$container.on('click', '.push-add-list-action', function (event) {
event.preventDefault();
var makeDialog = function makeDialog(box) {
var buttons = {};
buttons[localeService.t('valider')] = function () {
var callbackOK = function callbackOK() {
(0, _jquery2.default)('a.list_refresh', $container).trigger('click');
_dialog2.default.get(2).close();
};
var name = (0, _jquery2.default)('input[name="name"]', _dialog2.default.get(2).getDomElement()).val();
if (_jquery2.default.trim(name) === '') {
alert((0, _jquery2.default)('#push-list-name-empty').val());
return;
}
_this2.userList.create(name, callbackOK);
};
// /prod/lists/list/
var options = {
cancelButton: true,
buttons: buttons,
title: (0, _jquery2.default)('#push-new-list-title').val(),
size: '450x170'
};
var $dialog = _dialog2.default.create(services, options, 2);
$dialog.getDomElement().closest('.ui-dialog').addClass('dialog_container dialog_add_list').find('.ui-dialog-buttonset button:first-child .ui-button-text').text((0, _jquery2.default)('#btn-add').val());
$dialog.setContent(box);
};
var html = _.template((0, _jquery2.default)('#list_editor_dialog_add_tpl').html());
makeDialog(html);
return false;
});
/*$('li.list a.list_link', $container).bind('click', function (event) {
var $this = $(this);
$this.closest('.lists').find('.list.selected').removeClass('selected');
$this.parent('li.list').addClass('selected');
return false;
});*/
$container.on('click', '.list-edit-action', function (event) {
event.preventDefault();
_this.removeUserItemsArray = [];
_this.addUserItemsArray = [];
_this.removeUserMethod = '';
_this.addUserMethod = '';
var $el = (0, _jquery2.default)(event.currentTarget);
var listId = $el.data('list-id');
var el_url = $el.attr('href');
var callbackList = function callbackList(list) {
for (var i in list.entries) {
this.selectUser(list.entries[i].User);
}
};
$el.closest('.lists').find('.list').removeClass('selected');
$el.parent().addClass('selected');
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/push/edit-list/' + listId + '/',
dataType: 'html',
success: function success(data) {
_this2.workOn(listId);
(0, _jquery2.default)('.editor', $container).removeClass('loading').append(data);
_this2.loadList(el_url, callbackList);
initRight();
(0, _listEditor2.default)(services, {
$container: $container, listManagerInstance: _this
});
},
beforeSend: function beforeSend() {
(0, _jquery2.default)('.editor', $container).empty().addClass('loading');
}
});
});
$container.on('click', '.listmanager-delete-list-user-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var listId = $el.data('list-id');
var userId = $el.data('user-id');
var badge = (0, _jquery2.default)(_this2).closest('.badge');
// var usr_id = badge.find('input[name="id"]').val();
_this2.getList().removeUser(userId, function (list, data) {
badge.remove();
});
});
};
var initRight = function initRight() {
var $container = (0, _jquery2.default)('#ListManager .editor');
var selection = new _selectable2.default(services, (0, _jquery2.default)('.user_content .badges', _this.container), {
selector: '.badge'
});
(0, _jquery2.default)('form[name="list-editor-search"]', $container).bind('submit', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(this);
var dest = (0, _jquery2.default)('.list-editor-results', $container);
_jquery2.default.ajax({
url: $this.attr('action'),
type: $this.attr('method'),
dataType: 'html',
data: $this.serializeArray(),
beforeSend: function beforeSend() {
dest.empty().addClass('loading');
},
success: function success(datas) {
dest.empty().removeClass('loading').append(datas);
(0, _listEditor2.default)(services, {
$container: $container, listManagerInstance: _this
});
}
});
});
(0, _jquery2.default)('form[name="list-editor-search"] select, form[name="list-editor-search"] input[name="ListUser"]', $container).bind('change', function () {
(0, _jquery2.default)(this).closest('form').trigger('submit');
});
(0, _jquery2.default)('.EditToggle', $container).bind('click', function (event) {
event.preventDefault();
(0, _jquery2.default)('.content.readselect, .content.readwrite, .editor_header', (0, _jquery2.default)('#ListManager')).toggle();
});
(0, _jquery2.default)('.Refresher', $container).bind('click', function (event) {
event.preventDefault();
(0, _jquery2.default)('#ListManager ul.lists .list.selected a').trigger('click');
});
(0, _jquery2.default)('form[name="SaveName"]', $container).bind('submit', function () {
var $this = (0, _jquery2.default)(this);
_jquery2.default.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
dataType: 'json',
data: $this.serializeArray(),
beforeSend: function beforeSend() {},
success: function success(data) {
if (data.success) {
humane.info(data.message);
(0, _jquery2.default)('#ListManager .lists .list_refresh').trigger('click');
} else {
humane.error(data.message);
}
return;
},
error: function error() {
return;
},
timeout: function timeout() {
return;
}
});
return false;
});
// //button.deleter
// $('.listmanager-delete-list-action', $container).bind('click', function (event) {
// var list_id = $(this).data('list-id');
// var makeDialog = function (box) {
// var buttons = {};
// buttons[localeService.t('valider')] = function () {
// var callbackOK = function () {
// $('#ListManager .all-lists a.list_refresh').trigger('click');
// dialog.get(2).close();
// };
// var List = new List(list_id);
// List.remove(callbackOK);
// };
// var options = {
// cancelButton: true,
// buttons: buttons,
// size: 'Alert'
// };
// dialog.create(services, options, 2).setContent(box);
// };
// var html = _.template($('#list_editor_dialog_delete_tpl').html());
// makeDialog(html);
// return false;
// });
(0, _jquery2.default)('input[name="users-search"]', $container).autocomplete({
minLength: 2,
source: function source(request, response) {
_jquery2.default.ajax({
url: url + 'prod/push/search-user/',
dataType: 'json',
data: {
query: request.term
},
success: function success(data) {
response(data);
}
});
},
focus: function focus(event, ui) {
// $('input[name="users-search"]').val(ui.item.label);
},
select: function select(event, ui) {
if (ui.item.type === 'USER') {
_this.selectUser(ui.item);
_this.updateUsersHandler('add', ui.item.usr_id);
} else if (ui.item.type === 'LIST') {
for (var e in ui.item.entries) {
_this.selectUser(ui.item.entries[e].User);
_this.updateUsersHandler('add', ui.item.entries[e].User.usr_id);
}
}
(0, _jquery2.default)('#saveListFooter').show();
return false;
}
}).data('ui-autocomplete')._renderItem = function (ul, item) {
var html = '';
if (item.type === 'USER') {
html = _.template((0, _jquery2.default)('#list_user_tpl').html())({
item: item
});
} else if (item.type === 'LIST') {
html = _.template((0, _jquery2.default)('#list_list_tpl').html())({
item: item
});
}
return (0, _jquery2.default)(html).data('ui-autocomplete-item', item).appendTo(ul);
};
(0, _jquery2.default)('.user_content .badges', _this.container).disableSelection();
$container.on('click', '.content .options .select-all', function () {
selection.selectAll();
});
$container.on('click', '.content .options .unselect-all', function () {
selection.empty();
});
$container.on('click', '.content .options .delete-selection', function () {
var $elems = (0, _jquery2.default)('#ListManager .badges.selectionnable .badge.selected');
_.each($elems, function (item) {
var $elem = (0, _jquery2.default)(item);
var $elemID = $elem.find('input[name=id]').val();
if ($elem.hasClass('selected') && _this.removeUserItemsArray.indexOf($elemID) === -1) {
_this.updateUsersHandler('remove', $elemID);
}
});
$elems.fadeOut(300, 'swing', function () {
(0, _jquery2.default)(this).remove();
(0, _jquery2.default)('#saveListFooter').show();
});
});
$container.on('submit', 'form.list_saver', function (event) {
event.preventDefault();
var $form = (0, _jquery2.default)(event.currentTarget);
var name = (0, _jquery2.default)('.header h2', $container).text();
var users = _this.getUsers();
if (users.length === 0) {
humane.error('No users');
return false;
} else {
if (_this.removeUserMethod === 'remove' && _this.removeUserItemsArray.length > 0) {
var $editor = (0, _jquery2.default)('#list-editor-search-results');
_.each(_this.removeUserItemsArray, function (item) {
(0, _jquery2.default)('tbody tr', $editor).each(function (i, el) {
var $el = (0, _jquery2.default)(el);
var $elID = (0, _jquery2.default)('input[name="usr_id"]', $el).val();
if (item == $elID) $el.removeClass('selected');
});
_this.getList().removeUser(item);
});
var ListCounter = (0, _jquery2.default)('#ListManager .counter.current, #ListManager .lists .list.selected .counter');
ListCounter.each(function (i, el) {
var n = parseInt((0, _jquery2.default)(el).text(), 10);
if ((0, _jquery2.default)(el).hasClass('current')) (0, _jquery2.default)(el).text(n - _this.removeUserItemsArray.length + ' people');else (0, _jquery2.default)(el).text(n - _this.removeUserItemsArray.length);
});
(0, _jquery2.default)('#saveListFooter').hide();
_this.removeUserItemsArray = [];
_this.removeUserMethod = '';
} else if (_this.addUserMethod === 'add' && _this.addUserItemsArray.length > 0) {
var $editor = (0, _jquery2.default)('#list-editor-search-results');
_.each(_this.addUserItemsArray, function (item) {
(0, _jquery2.default)('tbody tr', $editor).each(function (i, el) {
var $el = (0, _jquery2.default)(el);
var $elID = (0, _jquery2.default)('input[name="usr_id"]', $el).val();
if (item == $elID) $el.addClass('selected');
});
_this.getList().addUser(item);
});
var ListCounter = (0, _jquery2.default)('#ListManager .counter.current, #ListManager .lists .list.selected .counter');
ListCounter.each(function (i, el) {
var n = parseInt((0, _jquery2.default)(el).text(), 10);
if ((0, _jquery2.default)(el).hasClass('current')) (0, _jquery2.default)(el).text(n + _this.addUserItemsArray.length + ' people');else (0, _jquery2.default)(el).text(n + _this.addUserItemsArray.length);
});
(0, _jquery2.default)('#saveListFooter').hide();
_this.addUserItemsArray = [];
_this.addUserMethod = '';
}
}
});
$container.on('click', '.badges a.deleter', function (event) {
var badge = (0, _jquery2.default)(event.currentTarget).closest('.badge');
var usr_id = badge.find('input[name="id"]').val();
var ListCounter = (0, _jquery2.default)('#ListManager .counter.current, #ListManager .lists .list.selected .counter');
var $editor = (0, _jquery2.default)('#list-editor-search-results');
var callback = function callback(list, datas) {
ListCounter.each(function (i, el) {
var n = parseInt((0, _jquery2.default)(el).text(), 10);
if ((0, _jquery2.default)(el).hasClass('current')) (0, _jquery2.default)(el).text(n - 1 + ' people');else (0, _jquery2.default)(el).text(n - 1);
});
badge.fadeOut('300', 'swing', function () {
badge.remove();
});
};
_this.getList().removeUser(usr_id, callback);
(0, _jquery2.default)('tbody tr', $editor).each(function (i, el) {
var $el = (0, _jquery2.default)(el);
var $elID = (0, _jquery2.default)('input[name="usr_id"]', $el).val();
if (usr_id === $elID) $el.removeClass('selected');
});
return false;
});
};
initLeft();
return this;
};
ListManager.prototype = {
selectUser: function selectUser(user) {
if ((typeof user === 'undefined' ? 'undefined' : _typeof(user)) !== 'object') {
if (window.console) {
console.log('trying to select a user with wrong datas');
}
}
if ((0, _jquery2.default)('.badge_' + user.usr_id, this.container).length > 0) {
humane.info('User already selected');
return;
} else {
var html = _.template((0, _jquery2.default)('#list_manager_badge_tpl').html())({
user: user
});
// p4.Feedback.appendBadge(html);
// this.getList().addUser(user.usr_id);
this.appendBadge(html);
}
},
workOn: function workOn(list_id) {
this.list = new _index.List(list_id);
},
getList: function getList() {
return this.list;
},
appendBadge: function appendBadge(datas) {
(0, _jquery2.default)('#ListManager .badges').append(datas);
},
createList: function createList(options) {
var name = options.name,
collection = options.collection;
this.userList.create(name, function (list) {
list.addUsers(collection);
});
},
removeList: function removeList(list_id, callback) {
this.list = new _index.List(list_id);
this.list.remove(callback);
},
loadList: function loadList(url, callback) {
var $this = this;
_jquery2.default.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function success(data) {
if (typeof callback === 'function') {
callback.call($this, data);
}
}
});
},
updateUsers: function updateUsers(action) {
if (action === 'remove') {}
return removedItems;
},
getUsers: function getUsers() {
return (0, _jquery2.default)('.user_content .badge', this.container).map(function () {
return (0, _jquery2.default)('input[name="id"]', (0, _jquery2.default)(this)).val();
});
},
updateUsersHandler: function updateUsersHandler(method, item) {
if (method === 'remove') {
this.removeUserItemsArray.push(item);
this.removeUserMethod = method;
} else if (method === 'add') {
this.addUserItemsArray.push(item);
this.addUserMethod = method;
}
}
};
exports.default = ListManager;
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var listEditor = function listEditor(services, options) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $container = options.$container,
listManagerInstance = options.listManagerInstance;
var $editor = (0, _jquery2.default)('#list-editor-search-results');
var $form = (0, _jquery2.default)('#ListManager .editor').find('form[name="list-editor-search"]');
(0, _jquery2.default)('a.next, a.prev', $editor).bind('click', function (event) {
event.preventDefault();
var page = (0, _jquery2.default)(this).attr('value');
(0, _jquery2.default)('input[name="page"]', $form).val(page);
$form.trigger('submit');
});
(0, _jquery2.default)('input[name="page"]', $form).val('');
(0, _jquery2.default)('th.sortable', $editor).bind('click', function () {
var $this = (0, _jquery2.default)(this);
var sort = (0, _jquery2.default)('input', $this).val();
var ord = 'asc';
if (sort === (0, _jquery2.default)('input[name="srt"]', $form).val() && (0, _jquery2.default)('input[name="ord"]', $form).val() === 'asc') {
ord = 'desc';
}
(0, _jquery2.default)('input[name="srt"]', $form).val(sort);
(0, _jquery2.default)('input[name="ord"]', $form).val(ord);
$form.trigger('submit');
}).bind('mouseover', function () {
(0, _jquery2.default)(this).addClass('hover');
}).bind('mouseout', function () {
(0, _jquery2.default)(this).removeClass('hover');
});
(0, _jquery2.default)('tbody tr', $editor).bind('click', function () {
var $this = (0, _jquery2.default)(this);
var usr_id = (0, _jquery2.default)('input[name="usr_id"]', $this).val();
var counters = (0, _jquery2.default)('#ListManager .counter.current, #ListManager .lists .list.selected .counter');
if ($this.hasClass('selected')) {
$this.removeClass('selected');
listManagerInstance.getList().removeUser(usr_id);
counters.each(function (i, el) {
var n = parseInt((0, _jquery2.default)(el).text().split(' ')[0], 10);
if ((0, _jquery2.default)(el).hasClass('current')) (0, _jquery2.default)(el).text(n - 1 + ' people');else (0, _jquery2.default)(el).text(n - 1);
});
} else {
$this.addClass('selected');
listManagerInstance.getList().addUser(usr_id);
counters.each(function (i, el) {
var n = parseInt((0, _jquery2.default)(el).text(), 10);
if ((0, _jquery2.default)(el).hasClass('current')) (0, _jquery2.default)(el).text(n + 1 + ' people');else (0, _jquery2.default)(el).text(n + 1);
});
}
});
};
exports.default = listEditor;
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
var listShare = function listShare(services, options) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $dialog = null;
var initialize = function initialize() {};
var openModal = function openModal(options) {
var listId = options.listId,
modalOptions = options.modalOptions,
modalLevel = options.modalLevel;
$dialog = _dialog2.default.create(services, modalOptions, modalLevel);
$dialog.getDomElement().closest('.ui-dialog').addClass('dialog_container dialog_share_list');
return _jquery2.default.get(url + 'prod/lists/list/' + listId + '/share/', function (data) {
$dialog.setContent(data);
onModalReady(listId);
});
};
var onModalReady = function onModalReady(listId) {
var $container = (0, _jquery2.default)('#ListShare');
var $completer_form = (0, _jquery2.default)('form[name="list_share_user"]', $container);
var $owners_form = (0, _jquery2.default)('form[name="owners"]', $container);
var $autocompleter = (0, _jquery2.default)('input[name="user"]', $completer_form);
var $dialog = _dialog2.default.get(2);
$completer_form.bind('submit', function () {
return false;
});
(0, _jquery2.default)('select[name="role"]', $owners_form).bind('change', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var userId = $el.data('user-id');
shareWith(userId, $el.val());
return false;
});
$container.on('click', '.listmanager-share-delete-user-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var userId = $el.data('user-id');
var $owner = $el.closest('.owner');
unShareWith(userId, function (data) {
$owner.remove();
});
return false;
});
function shareWith(userId, role) {
role = typeof role === 'undefined' ? 1 : role;
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/lists/list/' + listId + '/share/' + userId + '/',
dataType: 'json',
data: { role: role },
beforeSend: function beforeSend() {},
success: function success(data) {
if (data.success) {
humane.info(data.message);
} else {
humane.error(data.message);
}
(0, _jquery2.default)('.push-list-share-action').trigger('click');
$dialog.refresh();
return;
}
});
}
function unShareWith(userId, callback) {
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/lists/list/' + listId + '/unshare/' + userId + '/',
dataType: 'json',
data: {},
beforeSend: function beforeSend() {},
success: function success(data) {
if (data.success) {
humane.info(data.message);
callback(data);
} else {
humane.error(data.message);
}
$dialog.refresh();
return;
}
});
}
$autocompleter.autocomplete({
minLength: 2,
source: function source(request, response) {
_jquery2.default.ajax({
url: url + 'prod/push/search-user/',
dataType: 'json',
data: {
query: request.term
},
success: function success(data) {
response(data);
}
});
},
select: function select(event, ui) {
if (ui.item.type === 'USER') {
shareWith(ui.item.usr_id);
}
return false;
}
}).data('ui-autocomplete')._renderItem = function (ul, item) {
if (item.type === 'USER') {
var html = _.template((0, _jquery2.default)('#list_user_tpl').html())({
item: item
});
return (0, _jquery2.default)(html).data('ui-autocomplete-item', item).appendTo(ul);
}
};
};
return {
openModal: openModal
};
};
exports.default = listShare;
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _publication = __webpack_require__(57);
var _publication2 = _interopRequireDefault(_publication);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var recordPublishModal = function recordPublishModal(services, datas) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var openModal = function openModal(datas) {
_jquery2.default.post(url + 'prod/feeds/requestavailable/', datas, function (data) {
return (0, _publication2.default)(services).openModal(data);
});
return true;
};
return { openModal: openModal };
};
exports.default = recordPublishModal;
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _sharingManager = __webpack_require__(177);
var _sharingManager2 = _interopRequireDefault(_sharingManager);
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
var recordToolsModal = function recordToolsModal(services, datas) {
var activeTab = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $dialog = null;
var toolsStream = new Rx.Subject();
toolsStream.subscribe(function (params) {
switch (params.action) {
case 'refresh':
openModal.apply(null, params.options);
break;
default:
}
});
var openModal = function openModal(datas, activeTab) {
$dialog = _dialog2.default.create(services, {
size: 'Custom',
customWidth: 770,
customHeight: 650,
title: localeService.t('toolbox'),
loading: true
});
return _jquery2.default.get(url + 'prod/tools/', datas, function (data) {
$dialog.setContent(data);
$dialog.setOption('contextArgs', datas);
_onModalReady(data, window.toolsConfig, activeTab);
return;
});
};
var _onModalReady = function _onModalReady(template, data, activeTab) {
var $scope = (0, _jquery2.default)('#prod-tool-box');
var tabs = (0, _jquery2.default)('#tool-tabs', $scope).tabs();
if (activeTab !== false) {
tabs.tabs('option', 'active', activeTab);
}
(0, _jquery2.default)('.iframe_submiter', $scope).bind('click', function () {
var form = (0, _jquery2.default)(this).closest('form');
form.submit();
form.find('.load').empty().html(localeService.t('loading') + ' ...');
(0, _jquery2.default)('#uploadHdsub').contents().find('.content').empty();
(0, _jquery2.default)('#uploadHdsub').load(function () {
form.find('.load').empty();
var iframeContent = (0, _jquery2.default)('#uploadHdsub').contents().find('.content').html();
form.closest('div').find('.resultAction').empty().append(iframeContent);
});
});
(0, _jquery2.default)('.action_submiter', $scope).bind('click', function () {
var $this = (0, _jquery2.default)(this);
var form = (0, _jquery2.default)(this).closest('form');
(0, _jquery2.default)('.confirm_block').removeClass('hide');
_jquery2.default.ajax({
url: form.attr('action'),
type: form.attr('method'),
dataType: 'json',
data: form.serializeArray(),
beforeSend: function beforeSend() {
$this.prop('disabled', true);
setTimeout(function () {
_dialog2.default.get(1).close();
}, 1500);
},
success: function success(data) {
if (!data.success) {
humane.error(data.message);
} else {
console.log('sub-definitions recreated');
}
},
complete: function complete() {
$this.prop('disabled', false);
}
});
return false;
});
(0, _jquery2.default)('.action_cancel', $scope).bind('click', function () {
_dialog2.default.get(1).close();
return false;
});
// available if only 1 record is selected:
if (data.selectionLength === 1) {
(0, _sharingManager2.default)({ configService: configService, localeService: localeService, toolsStream: toolsStream }).initialize({
$container: $dialog, data: data, tabs: tabs,
dialogParams: $dialog.getOption('contextArgs')
});
}
};
return { openModal: openModal };
};
exports.default = recordToolsModal;
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var sharingManager = function sharingManager(services, datas) {
var activeTab = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var configService = services.configService,
localeService = services.localeService,
toolsStream = services.toolsStream;
var url = configService.get('baseUrl');
var $container = null;
var dialogParams = {};
var initialize = function initialize(params) {
//let {$container, data, tabs, dialogParams} = params;
$container = params.$container;
dialogParams = params.dialogParams;
console.log('>>>>', dialogParams);
if (params.data.selectionLength === 1) {
_onUniqueSelection(params.data.databaseId, params.data.records[0].id, params.tabs);
}
};
var _onUniqueSelection = function _onUniqueSelection(databaseId, recordId, tabs) {
(0, _jquery2.default)('#tools-sharing .stateChange_button').bind('click', function (event) {
var $btn = (0, _jquery2.default)(event.currentTarget);
var state = true;
// inverse state
if ($btn.data('state') === 1) {
state = false;
}
// submit changes
_jquery2.default.post('tools/sharing-editor/' + databaseId + '/' + recordId + '/', {
name: $btn.data('name'),
state: state
}).done(function (data) {
// self reload tab with current active tab:
activeTab = tabs.tabs('option', 'active');
toolsStream.onNext({
action: 'refresh',
options: [dialogParams, activeTab]
});
}).error(function (err) {
alert('forbidden action');
});
return false;
});
};
return {
initialize: initialize
};
};
exports.default = sharingManager;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _index = __webpack_require__(69);
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var recordFeedbackModal = function recordFeedbackModal(services, datas) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var openModal = function openModal(datas) {
/* disable push closeonescape as an over dialog may exist (add user) */
var $dialog = _dialog2.default.create(services, {
size: 'Full',
title: localeService.t('feedback')
});
$dialog.getDomElement().closest('.ui-dialog').addClass('feedback_dialog_container');
_jquery2.default.post(url + 'prod/push/validateform/', datas, function (data) {
// data content's javascript can't be fully refactored
$dialog.setContent(data);
_onDialogReady();
return;
});
return true;
};
var _onDialogReady = function _onDialogReady() {
(0, _index2.default)(services).initialize({
feedback: {
containerId: '#PushBox',
context: 'Feedback'
},
listManager: {
containerId: '#ListManager'
}
});
};
return { openModal: openModal };
};
exports.default = recordFeedbackModal;
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _index = __webpack_require__(180);
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bridgeRecord = function bridgeRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var openModal = function openModal(datas) {
var $dialog = _dialog2.default.create(services, {
size: 'Full',
title: 'Bridge',
loading: false
});
return _jquery2.default.post(url + 'prod/bridge/manager/', datas, function (data) {
$dialog.setContent(data);
_onDialogReady();
return;
});
};
var _onDialogReady = function _onDialogReady() {
(0, _index2.default)(services).initialize();
};
return { openModal: openModal };
};
exports.default = bridgeRecord;
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var recordBridge = function recordBridge(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var pub_tabs = (0, _jquery2.default)('#pub_tabs');
var container = (0, _jquery2.default)('#dialog_publicator');
var managerUrl = container.data('url');
var $panel = void 0;
var initialize = function initialize() {
pub_tabs.tabs({
beforeLoad: function beforeLoad(event, ui) {
ui.tab.html_tab = ui.tab.find('span').html();
ui.tab.find('span').html('<i>' + localeService.t('Loading') + '...</i>');
},
load: function load(event, ui) {
ui.tab.find('span').empty().append(ui.tab.html_tab);
$panel = (0, _jquery2.default)(ui.panel);
(0, _jquery2.default)('.container-bridge', $panel).removeClass('loading');
$panel.addClass('PNB');
$panel.wrapInner("<div class='PNB10 container-bridge' />");
panel_load($panel);
},
beforeActivate: function beforeActivate(event, ui) {
if ((0, _jquery2.default)(ui.tab).hasClass('account')) {
var container = (0, _jquery2.default)('.container-bridge', ui.panel);
container.empty();
(0, _jquery2.default)('.container', ui.panel).addClass('loading');
}
}
}).addClass('ui-tabs-vertical ui-helper-clearfix');
(0, _jquery2.default)('.ui-tabs-nav', pub_tabs).removeClass('ui-corner-all');
(0, _jquery2.default)('.new_bridge_button', pub_tabs).bind('click', function () {
var url = (0, _jquery2.default)(this).parent('form').find('input[name="url"]').val();
popme(url);
return false;
});
(0, _jquery2.default)('ul li a.account', pub_tabs).bind('click', function () {
(0, _jquery2.default)('#dialog_publicator form[name="current_datas"] input[name="account_id"]').val((0, _jquery2.default)('input[name="account_id"]', this).val());
});
(0, _jquery2.default)('ul li.ui-tabs-selected a.account', pub_tabs).trigger('click');
(0, _jquery2.default)('#publicator_selection .PNB10:first').selectable();
(0, _jquery2.default)('#publicator_selection button.act_upload').bind('click', function () {
var $this = (0, _jquery2.default)(this);
var $form = $this.closest('form');
(0, _jquery2.default)('input[name=lst]', $form).val(_jquery2.default.makeArray((0, _jquery2.default)('#publicator_selection .diapo.ui-selected').map(function (i, el) {
return (0, _jquery2.default)(el).attr('id').split('_').slice(2, 4).join('_');
})).join(';'));
var account_id = (0, _jquery2.default)('form[name="current_datas"] input[name="account_id"]').val();
(0, _jquery2.default)('input[name="account_id"]', $form).val(account_id);
var $panel = (0, _jquery2.default)('#pub_tabs .ui-tabs-panel:visible');
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/bridge/upload/',
data: $form.serializeArray(),
beforeSend: function beforeSend() {
$panel.empty().addClass('loading');
},
success: function success(datas) {
$panel.removeClass('loading').append(datas);
panel_load($panel);
},
error: function error() {
$panel.removeClass('loading');
},
timeout: function timeout() {
$panel.removeClass('loading');
}
});
return false;
});
(0, _jquery2.default)('li', pub_tabs).removeClass('ui-corner-top').addClass('ui-corner-left');
(0, _jquery2.default)('#api_connexion').click(function () {
if (container.data('ui-dialog')) {
container.dialog('close');
}
});
};
function popme(url) {
var newwindow = window.open(url, 'logger', 'height=500,width=800');
if (window.focus) {
newwindow.focus();
}
return false;
}
function panel_load($panel) {
(0, _jquery2.default)('.new_bridge_button', $panel).bind('click', function () {
var url = (0, _jquery2.default)(this).parent('form').find('input[name="url"]').val();
popme(url);
return false;
});
(0, _jquery2.default)('.error_box, .notice_box', $panel).delay(10000).fadeOut();
(0, _jquery2.default)('.back_link', $panel).bind('click', function () {
if ((0, _jquery2.default)('#pub_tabs').data('ui-tabs')) {
(0, _jquery2.default)('#pub_tabs').tabs('load', (0, _jquery2.default)('#pub_tabs').tabs('option', 'active'));
}
return false;
});
(0, _jquery2.default)('.bridge_action', $panel).bind('click', function () {
var $this = (0, _jquery2.default)(this);
_jquery2.default.ajax({
type: 'GET',
url: (0, _jquery2.default)(this).attr('href'),
beforeSend: function beforeSend() {
var container = (0, _jquery2.default)('.container-bridge', $panel);
container.empty();
if (!$this.hasClass('bridge_logout')) {
container.addClass('loading');
}
},
success: function success(datas) {
(0, _jquery2.default)('.container-bridge', $panel).removeClass('loading').append(datas);
panel_load($panel);
},
error: function error() {
$panel.removeClass('loading');
},
timeout: function timeout() {
$panel.removeClass('loading');
}
});
return false;
});
(0, _jquery2.default)('.delete-account', $panel).bind('click', function () {
var account_id = (0, _jquery2.default)(this).val();
var buttons = {};
buttons[localeService.t('valider')] = function () {
_jquery2.default.ajax({
type: 'POST',
dataType: 'json',
url: url + 'prod/bridge/adapter/' + account_id + '/delete/',
data: {},
success: function success(datas) {
if (datas.success) {
confirmBox.close();
appEvents.emit('push.reload', managerUrl);
// pushModule.reloadBridge(managerUrl);
} else {
confirmBox.close();
var alertBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true
}, 2);
alertBox.setContent(datas.message);
}
}
});
};
var confirmBox = _dialog2.default.create(services, {
size: 'Alert',
closeOnEscape: true,
closeButton: true,
cancelButton: true,
buttons: buttons
}, 2);
confirmBox.setContent(localeService.t('You are about to delete this account. Would you like to continue ?'));
});
(0, _jquery2.default)('.form_submitter', $panel).bind('click', function () {
var $form = (0, _jquery2.default)(this).closest('form');
var method = $form.attr('method');
method = _jquery2.default.inArray(method.toLowerCase(), ['post', 'get']) ? method : 'POST';
_jquery2.default.ajax({
type: method,
url: $form.attr('action'),
data: $form.serializeArray(),
beforeSend: function beforeSend() {
$panel.empty().addClass('loading');
},
success: function success(datas) {
$panel.removeClass('loading').append(datas);
panel_load($panel);
},
error: function error() {
$panel.removeClass('loading');
},
timeout: function timeout() {
$panel.removeClass('loading');
}
});
return false;
});
(0, _jquery2.default)('.bridge_all_selector', $panel).bind('click', function () {
var checkboxes = (0, _jquery2.default)('.bridge_element_selector', $panel);
var $this = (0, _jquery2.default)(this);
checkboxes.each(function (i, checkbox) {
if ((0, _jquery2.default)(checkbox).is(':checked') !== $this.is(':checked')) {
var event = _jquery2.default.Event('click');
event.selector_all = true;
(0, _jquery2.default)(checkbox).trigger(event);
}
});
});
(0, _jquery2.default)('.bridge_element_selector', $panel).bind('click', function (event) {
var $this = (0, _jquery2.default)(this);
if (event.selector_all) {
$this.prop('checked', (0, _jquery2.default)('.bridge_all_selector', $panel).is(':checked'));
}
(0, _jquery2.default)('form[name="bridge_selection"] input[name="elements_list"]', $panel).val(_jquery2.default.makeArray((0, _jquery2.default)('.bridge_element_selector:checked', $panel).map(function (i, el) {
return (0, _jquery2.default)(el).val();
})).join(';'));
if ($this.is(':checked')) {
$this.closest('.element').addClass('selected');
} else {
$this.closest('.element').removeClass('selected');
}
if (!event.selector_all) {
var bool = !((0, _jquery2.default)('.bridge_element_selector:checked', $panel).length !== (0, _jquery2.default)('.bridge_element_selector', $panel).length);
(0, _jquery2.default)('.bridge_all_selector', $panel).prop('checked', bool);
} else {
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
});
(0, _jquery2.default)('a.form_multiple_submitter', $panel).bind('click', function () {
var $form = (0, _jquery2.default)(this).closest('form');
var elements = (0, _jquery2.default)('form[name="bridge_selection"] input[name="elements_list"]', $panel).val();
var n_elements = 0;
if (_jquery2.default.trim(elements) !== '') {
n_elements = elements.split(';').length;
}
if (n_elements === 0 && $form.hasClass('action_works_standalone') === false) {
alert('No records selected');
return false;
}
if (n_elements === 1 && $form.hasClass('action_works_single_element') === false) {
alert('This action works only with a single records');
return false;
}
if (n_elements > 1 && $form.hasClass('action_works_many_element') === false) {
alert('This action works only with many records');
return false;
}
(0, _jquery2.default)('input[name="elements_list"]', $form).val(elements);
_jquery2.default.ajax({
type: 'GET',
url: $form.attr('action'),
data: $form.serializeArray(),
beforeSend: function beforeSend() {
$panel.empty().addClass('loading');
},
success: function success(datas) {
$panel.removeClass('loading').append(datas);
panel_load($panel);
},
error: function error() {
$panel.removeClass('loading');
},
timeout: function timeout() {
$panel.removeClass('loading');
}
});
return false;
});
}
return {
initialize: initialize
};
};
exports.default = recordBridge;
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _screenCapture = __webpack_require__(182);
var _screenCapture2 = _interopRequireDefault(_screenCapture);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var videoScreenCapture = function videoScreenCapture(services, datas) {
var activeTab = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize(params) {
var $container = params.$container,
data = params.data;
var ThumbEditor = new _screenCapture2.default('thumb_video', 'thumb_canvas', {
altCanvas: (0, _jquery2.default)('#alt_canvas_container .alt_canvas')
});
if (ThumbEditor.isSupported()) {
var launch_thumb_camera_button = function launch_thumb_camera_button() {
/** set current time on real video capture**/
var realVideoCurrent = document.getElementById('thumb_video_A').currentTime;
document.getElementById('thumb_video').currentTime = realVideoCurrent;
(0, _jquery2.default)('#thumb_delete_button', $container).show();
(0, _jquery2.default)('#thumb_download_button', $container).show();
var screenshot = '';
/**screenshot at the real currentTime**/
function getScreenShot() {
var screenshot = ThumbEditor.screenshot();
if ($container.find('#thumb_canvas').height() >= 210) {
$container.find('#thumb_canvas').css('height', '210px');
$container.find('#grid').css('min-height', '210px');
}
$container.find('.frame_canva').css('width', $container.find('#thumb_canvas').width());
$container.find('.canvas-wrap').css('overflow', 'hidden').css('width', $container.find('#thumb_canvas').width());
(0, _jquery2.default)('.selected', $gridContainer).removeClass('selected');
var grid_wrapper = document.createElement('div');
(0, _jquery2.default)(grid_wrapper).addClass('grid-wrapper').addClass('selected').attr('id', 'working_' + screenshot.getId()).append('<div id="small_thumb_download_button"/>').append('<div id="small_thumb_delete_button"/>');
var img = (0, _jquery2.default)('<img />');
img.attr('src', screenshot.getDataURI()).attr('alt', screenshot.getVideoTime()).appendTo((0, _jquery2.default)(grid_wrapper));
var grid_item = document.createElement('div');
(0, _jquery2.default)(grid_item).addClass('grid-item').append((0, _jquery2.default)(grid_wrapper)).appendTo($gridContainer);
(0, _jquery2.default)('#videotools-spinner').addClass('hidden');
}
setTimeout(getScreenShot, 1000);
};
var $gridContainer = (0, _jquery2.default)('#grid', $container);
$gridContainer.on('mousedown', '.grid-wrapper', function () {
(0, _jquery2.default)('.selected', $gridContainer).removeClass('selected');
(0, _jquery2.default)(this).addClass('selected');
$container.find('.canvas-wrap').css('max-height', '210px').css('width', 'auto');
$container.find('#thumb_canvas').removeAttr('style').removeAttr('height');
var $self = this;
var selectedScreenId = $self.getAttribute('id').split('_').pop();
var screenshots = ThumbEditor.store.get(selectedScreenId);
ThumbEditor.copy(screenshots.getDataURI(), screenshots.getAltScreenShots());
});
$gridContainer.on('mouseup', '.grid-wrapper', function () {
if ($container.find('#thumb_canvas').height() >= 210) {
$container.find('#thumb_canvas').css('height', '210px');
}
});
$container.on('click', '#thumb_download_button', function () {
downloadThumbnail($gridContainer.find('.selected'), $container);
});
$container.on('click', '#thumb_delete_button', function () {
deleteThumbnail($gridContainer.find('.selected'), $container, ThumbEditor);
});
$container.on('click', '.close_action_frame', function () {
(0, _jquery2.default)(this).closest('.action_frame').hide();
});
$container.on('click', '#thumb_camera_button', function () {
(0, _jquery2.default)('#videotools-spinner').removeClass('hidden');
setTimeout(launch_thumb_camera_button, 10);
});
;
$container.on('mouseup', '#thumb_camera_button', function () {
$container.find('#thumb_canvas').removeAttr('style');
});
$gridContainer.on('click', '#small_thumb_download_button', function () {
downloadThumbnail((0, _jquery2.default)(this).parent(), $container);
return false;
});
$gridContainer.on('click', '#small_thumb_delete_button', function () {
deleteThumbnail((0, _jquery2.default)(this).parent(), $container, ThumbEditor);
return false;
});
(0, _jquery2.default)('#thumb_canvas').on('tool_event', function () {
var thumbnail = (0, _jquery2.default)('.selected', $gridContainer);
if (thumbnail.length === 0) {
console.error('No image selected');
return;
}
thumbnail.attr('src', ThumbEditor.getCanvaImage());
});
$container.on('click', '#thumb_validate_button', function () {
var thumbnail = (0, _jquery2.default)('.selected', $gridContainer);
var content = '';
if (thumbnail.length === 0) {
var confirmationDialog = _dialog2.default.create(services, {
size: 'Custom',
customWidth: 360,
customHeight: 160,
title: data.translations.alertTitle,
closeOnEscape: true
}, 3);
confirmationDialog.getDomElement().closest('.ui-dialog').addClass('screenCapture_validate_dialog');
content = (0, _jquery2.default)('<div />').css({
'text-align': 'center',
width: '100%',
'font-size': '14px'
}).append(data.translations.noImgSelected);
confirmationDialog.setContent(content);
return false;
} else {
var buttons = {};
var record_id = (0, _jquery2.default)('input[name=record_id]').val();
var sbas_id = (0, _jquery2.default)('input[name=sbas_id]').val();
var selectedScreenId = thumbnail.attr('id').split('_').pop();
var screenshots = ThumbEditor.store.get(selectedScreenId);
var screenData = screenshots.getAltScreenShots();
var subDefs = [];
for (var i = 0; i < screenData.length; i++) {
subDefs.push({
name: screenData[i].name,
src: screenData[i].dataURI
});
}
buttons = [{
text: localeService.t('cancel'),
click: function click() {
(0, _jquery2.default)(this).dialog('close');
}
}, {
text: localeService.t('valider'),
click: function click() {
var confirmDialog = _dialog2.default.get(2);
var buttonPanel = confirmDialog.getDomElement().closest('.ui-dialog').find('.ui-dialog-buttonpane');
var loadingDiv = buttonPanel.find('.info-div');
if (loadingDiv.length === 0) {
loadingDiv = (0, _jquery2.default)('<div />').css({
width: '120px',
height: '40px',
float: 'left',
'line-height': '40px',
'padding-left': '40px',
'text-align': 'left',
'background-position': 'left center'
}).attr('class', 'info-div').prependTo(buttonPanel);
}
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/tools/thumb-extractor/apply/',
data: {
sub_def: subDefs,
record_id: record_id,
sbas_id: sbas_id
},
beforeSend: function beforeSend() {
disableConfirmButton(confirmDialog);
loadingDiv.empty().addClass('loading').append(data.translations.processing);
},
success: function success(data) {
loadingDiv.empty().removeClass('loading');
if (data.success) {
confirmDialog.close();
_dialog2.default.get(1).close();
} else {
loadingDiv.append(content);
enableConfirmButton(confirmDialog);
}
}
});
}
}];
// show confirm box, content is loaded here /prod/tools/thumb-extractor/confirm-box/
var validationDialog = _dialog2.default.create(services, {
size: 'Custom',
customWidth: 360,
customHeight: 285,
title: data.translations.thumbnailTitle,
cancelButton: true,
buttons: buttons
}, 2);
validationDialog.getDomElement().closest('.ui-dialog').addClass('screenCapture_validate_dialog');
var datas = {
image: (0, _jquery2.default)('.selected', $gridContainer).find('img').attr('src'),
sbas_id: sbas_id,
record_id: record_id
};
return _jquery2.default.ajax({
type: 'POST',
url: url + 'prod/tools/thumb-extractor/confirm-box/',
data: datas,
success: function success(data) {
if (data.error) {
content = (0, _jquery2.default)('<div />').css({
'font-size': '16px',
'text-align': 'center'
}).append(data.datas);
validationDialog.setContent(content);
disableConfirmButton(validationDialog);
} else {
validationDialog.setContent(data.datas);
}
}
});
}
});
} else {
// not supported
(0, _jquery2.default)('#thumbExtractor').empty().append(localeService.t('browserFeatureSupport'));
}
};
var downloadThumbnail = function downloadThumbnail(element, $container) {
var imageInBase64 = element.find('img').attr('src');
var mimeInfo = base64MimeType(imageInBase64);
var ext = mimeInfo.split('/').pop();
var filename = "preview" + element.find('img').attr('alt') + "." + ext;
download(imageInBase64, filename, mimeInfo);
};
var deleteThumbnail = function deleteThumbnail(element, $container, ThumbEditor) {
var imgWrapper = element;
var id = imgWrapper.attr('id').split('_').pop();
var previous = imgWrapper.parent().prev();
var next = imgWrapper.parent().next();
if (previous.length > 0) {
previous.find('.grid-wrapper').trigger('mousedown');
previous.find('.grid-wrapper').trigger('mouseup');
} else if (next.length > 0) {
next.find('.grid-wrapper').trigger('mousedown');
next.find('.grid-wrapper').trigger('mouseup');
} else {
(0, _jquery2.default)('#thumb_delete_button', $container).hide();
(0, _jquery2.default)('#thumb_download_button', $container).hide();
(0, _jquery2.default)('#thumb_canvas').attr('width', 0);
(0, _jquery2.default)('#thumb_canvas').attr('height', 0);
(0, _jquery2.default)('.frame_canva').removeAttr('style');
}
imgWrapper.parent().remove();
ThumbEditor.store.remove(id);
};
var disableConfirmButton = function disableConfirmButton(dialog) {
dialog.getDomElement().closest('.ui-dialog').find('.ui-dialog-buttonpane button').filter(function () {
return (0, _jquery2.default)(this).text() === localeService.t('valider');
}).addClass('ui-state-disabled').attr('disabled', true);
};
var enableConfirmButton = function enableConfirmButton(dialog) {
dialog.getDomElement().closest('.ui-dialog').find('.ui-dialog-buttonpane button').filter(function () {
return (0, _jquery2.default)(this).text() === localeService.t('valider');
}).removeClass('ui-state-disabled').attr('disabled', false);
};
var base64MimeType = function base64MimeType(encoded) {
var result = null;
if (typeof encoded !== 'string') {
return result;
}
var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);
if (mime && mime.length) {
result = mime[1];
}
return result;
};
return {
initialize: initialize
};
};
exports.default = videoScreenCapture;
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _canvaImage = __webpack_require__(183);
var _canvaImage2 = _interopRequireDefault(_canvaImage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Image Object
* @param domElement
* @constructor
*/
var Image = function Image(domElement) {
this.domElement = domElement;
};
Image.prototype = {
getDomElement: function getDomElement() {
return this.domElement;
},
getHeight: function getHeight() {
return this.domElement.offsetHeight;
},
getWidth: function getWidth() {
return this.domElement.offsetWidth;
}
};
/**
* Video Object inherits from Image object
* @param domElement
* @constructor
*/
var Video = function Video(domElement) {
Image.call(this, domElement);
this.aspectRatio = domElement.getAttribute('data-ratio');
};
Video.prototype = new Image();
Video.prototype.constructor = Video;
Video.prototype.getCurrentTime = function () {
return Math.floor(this.domElement.currentTime);
};
Video.prototype.getAspectRatio = function () {
return this.aspectRatio;
};
/**
* Cache Object
* @constructor
*/
var Store = function Store() {
this.datas = {};
};
Store.prototype = {
set: function set(id, item) {
this.datas[id] = item;
return this;
},
get: function get(id) {
if (!this.datas[id]) {
throw 'Unknown ID';
}
return this.datas[id];
},
remove: function remove(id) {
// never reuse same id
this.datas[id] = null;
},
getLength: function getLength() {
var count = 0;
for (var k in this.datas) {
if (this.datas.hasOwnProperty(k)) {
++count;
}
}
return count;
}
};
/**
* Screenshot Object
* @param id
* @param canva
* @param video
* @param altCanvas
* @constructor
*/
var ScreenShot = function ScreenShot(id, canva, video, altCanvas) {
var date = new Date();
canva.resize(video);
canva.copy(video);
// handle alternative canvas:
altCanvas = altCanvas === undefined ? [] : altCanvas;
this.altScreenShots = [];
if (altCanvas.length > 0) {
for (var i = 0; i < altCanvas.length; i++) {
var canvaEl = altCanvas[i].el;
canvaEl.resize(video);
canvaEl.copy(video);
this.altScreenShots.push({
dataURI: canvaEl.extractImage(),
name: altCanvas[i].name
});
}
}
this.id = id;
this.timestamp = date.getTime();
this.dataURI = canva.extractImage();
this.videoTime = video.getCurrentTime();
};
ScreenShot.prototype = {
getId: function getId() {
return this.id;
},
getDataURI: function getDataURI() {
return this.dataURI;
},
getTimeStamp: function getTimeStamp() {
return this.timestamp;
},
getVideoTime: function getVideoTime() {
return this.videoTime;
},
getAltScreenShots: function getAltScreenShots() {
return this.altScreenShots;
}
};
/**
* THUMB EDITOR
* @param videoId
* @param canvaId
* @param outputOptions
* @returns {{isSupported: isSupported, screenshot: screenshot, store: Store, copy: copy, getCanvaImage: getCanvaImage, resetCanva: resetCanva, getNbScreenshot: getNbScreenshot}}
* @constructor
*/
var ScreenCapture = function ScreenCapture(videoId, canvaId, outputOptions) {
var editorVideo = void 0;
var domElement = document.getElementById(videoId);
if (domElement !== null) {
editorVideo = new Video(domElement);
}
var store = new Store();
function getCanva() {
return document.getElementById(canvaId);
}
outputOptions = outputOptions || {};
function setAltCanvas() {
var domElements = [];
var altCanvas = outputOptions.altCanvas;
if (altCanvas.length > 0) {
for (var i = 0; i < altCanvas.length; i++) {
domElements.push({
el: new _canvaImage2.default(altCanvas[i]),
width: altCanvas[i].getAttribute('data-width'),
name: altCanvas[i].getAttribute('data-name')
});
}
}
return domElements;
}
return {
isSupported: function isSupported() {
var elem = document.createElement('canvas');
return !!document.getElementById(videoId) && document.getElementById(canvaId) && !!elem.getContext && !!elem.getContext('2d');
},
screenshot: function screenshot() {
var screenshot = new ScreenShot(store.getLength() + 1, new _canvaImage2.default(getCanva()), editorVideo, setAltCanvas());
store.set(screenshot.getId(), screenshot);
return screenshot;
},
store: store,
copy: function copy(mainSource, altSources) {
var elementDomNode = document.createElement('img');
elementDomNode.src = mainSource;
var element = new Image(elementDomNode);
var editorCanva = new _canvaImage2.default(getCanva());
var altEditorCanva = setAltCanvas();
editorCanva.reset().resize(editorVideo).copy(element);
// handle alternative canvas:
if (altEditorCanva.length > 0) {
for (var i = 0; i < altEditorCanva.length; i++) {
var tmpEl = document.createElement('img');
tmpEl.src = altSources[i].dataURI;
var canvaEl = altEditorCanva[i].el;
canvaEl.reset().resize(editorVideo, altEditorCanva[i].width).copy(new Image(tmpEl)); // @TODO: should copy the right stored image
}
}
},
getCanvaImage: function getCanvaImage() {
var canva = new _canvaImage2.default(getCanva());
return canva.extractImage();
},
resetCanva: function resetCanva() {
var editorCanva = new _canvaImage2.default(getCanva());
editorCanva.reset();
},
getNbScreenshot: function getNbScreenshot() {
return store.getLength();
}
};
};
exports.default = ScreenCapture;
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Canva Object
* @param domCanva
* @constructor
*/
var Canva = function Canva(domCanva) {
this.domCanva = domCanva;
};
Canva.prototype = {
resize: function resize(elementDomNode, forceWidth) {
var w = elementDomNode.getWidth();
var h = null;
var maxH = elementDomNode.getHeight();
var ratio = 1;
if (elementDomNode.getAspectRatio() !== '') {
ratio = parseFloat(elementDomNode.getAspectRatio());
h = Math.round(w * (1 / ratio));
if (h < maxH) {
h = maxH;
w = Math.round(h * ratio);
}
} else {
h = maxH;
}
if (forceWidth !== undefined) {
w = parseInt(forceWidth, 10);
if (elementDomNode.getAspectRatio() !== '') {
h = Math.round(w * (1 / ratio));
} else {
h = maxH;
}
}
this.domCanva.setAttribute('width', w);
this.domCanva.setAttribute('height', h);
return this;
},
getContext2d: function getContext2d() {
if (this.domCanva.getContext === undefined) {
/* eslint-disable no-undef */
return G_vmlCanvasManager.initElement(this.domCanva).getContext('2d');
}
return this.domCanva.getContext('2d');
},
extractImage: function extractImage() {
return this.domCanva.toDataURL('image/png');
},
reset: function reset() {
var context = this.getContext2d();
var w = this.getWidth();
var h = this.getHeight();
context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, w, h);
context.restore();
return this;
},
copy: function copy(elementDomNode) {
var context = this.getContext2d();
context.drawImage(elementDomNode.getDomElement(), 0, 0, this.getWidth(), this.getHeight());
return this;
},
getDomElement: function getDomElement() {
return this.domCanva;
},
getHeight: function getHeight() {
return this.domCanva.offsetHeight;
},
getWidth: function getWidth() {
return this.domCanva.offsetWidth;
}
};
exports.default = Canva;
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _videojsFlash = __webpack_require__(62);
var _videojsFlash2 = _interopRequireDefault(_videojsFlash);
var _fieldCollection = __webpack_require__(51);
var _fieldCollection2 = _interopRequireDefault(_fieldCollection);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var videoRangeCapture = function videoRangeCapture(services, datas) {
var activeTab = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $container = null;
var videojs = {};
var initData = {};
var options = {
playbackRates: [],
fluid: true
};
var rangeCapture = void 0;
var initialize = function initialize(params) {
$container = params.$container;
initData = params.data;
var aspectRatio = configService.get('resource.aspectRatio');
if (configService.get('resource.aspectRatio') !== null) {
options.aspectRatio = configService.get('resource.aspectRatio');
}
if (configService.get('resource.playbackRates') !== null) {
options.playbackRates = configService.get('resource.playbackRates');
}
if (initData.videoEditorConfig !== null) {
options.seekBackwardStep = initData.videoEditorConfig.seekBackwardStep;
options.seekForwardStep = initData.videoEditorConfig.seekForwardStep;
options.playbackRates = initData.videoEditorConfig.playbackRates === undefined ? [1, 2, 3] : initData.videoEditorConfig.playbackRates;
options.vttFieldValue = false;
options.ChapterVttFieldName = initData.videoEditorConfig.ChapterVttFieldName === undefined ? false : initData.videoEditorConfig.ChapterVttFieldName;
}
options.techOrder = ['html5', 'flash'];
options.autoplay = false;
options.recordId = initData.recordId;
options.record = initData.records[0];
options.databoxId = initData.databoxId;
options.translations = initData.translations;
options.services = params.services;
options.preferences = initData.preferences;
// get default videoTextTrack value
if (options.ChapterVttFieldName !== false) {
var fieldCollection = new _fieldCollection2.default(initData.T_fields);
var vttField = fieldCollection.getFieldByName(options.ChapterVttFieldName);
if (vttField !== false) {
if (vttField._value.VideoTextTrackChapters != undefined) {
options.vttFieldValue = vttField._value.VideoTextTrackChapters[0];
}
options.meta_struct_id = vttField.id;
}
}
__webpack_require__.e/* require.ensure */(1/* duplicate */).then((function () {
// load videoJs lib
//require('../../videoEditor/style/main.scss');
rangeCapture = __webpack_require__(87).default;
var rangeCaptureInstance = rangeCapture(services);
rangeCaptureInstance.initialize(params, options);
//render(initData);
}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
};
return { initialize: initialize };
};
exports.default = videoRangeCapture;
/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
;
var videoSubtitleCapture = function videoSubtitleCapture(services, datas) {
var activeTab = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize(params, userOptions) {
var $container = params.$container,
data = params.data;
var initialData = data;
var videoSource = "/embed/?url=/datafiles/" + initialData.databoxId + "/" + initialData.recordId + "/preview/%3Fetag";
function loadVideo() {
(0, _jquery2.default)('.video-subtitle-right .video-subtitle-wrapper').html('');
if (initialData.records[0].sources.length > 0) {
var prevWidth = initialData.records[0].sources[0].width;
var prevHeight = initialData.records[0].sources[0].height;
var prevRatio = initialData.records[0].sources[0].ratio;
(0, _jquery2.default)('.video-subtitle-right .video-subtitle-wrapper').append("<iframe class='video-player' src=" + videoSource + " data-width=" + prevWidth + " data-height=" + prevHeight + " data-ratio=" + prevRatio + " scrolling='no' marginheight='0' frameborder='0' allowfullscreen=''></iframe>");
resizeVideoPreview();
} else {
(0, _jquery2.default)('.video-subtitle-right .video-subtitle-wrapper').append("<img src='/assets/common/images/icons/substitution/video_webm.png'>");
}
}
function resizeVideoPreview() {
var $sel = (0, _jquery2.default)('.video-subtitle-wrapper');
var $Iframe = (0, _jquery2.default)('.video-subtitle-wrapper iframe');
// V is for "video" ; K is for "container" ; N is for "new"
var VW = $Iframe.data('width');
var VH = $Iframe.data('height');
var KW = (0, _jquery2.default)('#prod-tool-box').width() / 2;
var KH = (0, _jquery2.default)('.video-subtitle-left-inner').closest('#tool-tabs').height() - 100;
var NW, NH;
if ((NH = VH / VW * (NW = KW)) > KH) {
// try to fit exact horizontally, adjust vertically
// too bad... new height overflows container height
NW = VW / VH * (NH = KH); // so fit exact vertically, adjust horizontally
}
// (0, _jquery2.default)($Iframe).css('width', NW).css('height', NH);
(0, _jquery2.default)($Iframe).attr('width', NW).css('width', NW);
(0, _jquery2.default)($Iframe).attr('height', NH).css('height', NH);
}
loadVideo();
setTimeout(function () {
resizeVideoPreview();
}, 2000);
(0, _jquery2.default)('.subtitleEditortoggle').on('click', function (e) {
resizeVideoPreview();
});
$container.on('click', '.add-subtitle-vtt', function (e) {
e.preventDefault();
addSubTitleVtt();
setDiffTime();
});
var startVal = 0;
var endVal = 0;
var diffVal = 0;
var leftHeight = 300;
// Set height of left block
leftHeight = (0, _jquery2.default)('.video-subtitle-left-inner').closest('#tool-tabs').height();
(0, _jquery2.default)('.video-subtitle-left-inner').css('height', leftHeight - 147);
(0, _jquery2.default)('.video-request-left-inner').css('height', leftHeight);
(0, _jquery2.default)('.video-subtitle-right .video-subtitle-wrapper').css('height', leftHeight - 100);
(0, _jquery2.default)('.endTime').on('keyup change', function (e) {
setDefaultStartTime();
endVal = stringToseconde((0, _jquery2.default)(this).val());
startVal = stringToseconde((0, _jquery2.default)(this).closest('.video-subtitle-item').find('.startTime').val());
diffVal = millisecondeToTime(endVal - startVal);
(0, _jquery2.default)(this).closest('.video-subtitle-item').find('.showForTime').val(diffVal);
});
(0, _jquery2.default)('.startTime').on('keyup change', function (e) {
setDefaultStartTime();
startVal = stringToseconde((0, _jquery2.default)(this).val());
endVal = stringToseconde((0, _jquery2.default)(this).closest('.video-subtitle-item').find('.endTime').val());
diffVal = millisecondeToTime(endVal - startVal);
(0, _jquery2.default)(this).closest('.video-subtitle-item').find('.showForTime').val(diffVal);
});
function setDefaultStartTime(e) {
var DefaultStartT = (0, _jquery2.default)('.video-subtitle-item:last .endTime').val();
DefaultStartT = stringToseconde(DefaultStartT) + 1;
DefaultStartT = millisecondeToTime(DefaultStartT);
var DefaultEndT = stringToseconde(DefaultStartT) + 2000;
DefaultEndT = millisecondeToTime(DefaultEndT);
(0, _jquery2.default)('#defaultStartValue').val(DefaultStartT);
(0, _jquery2.default)('#defaultEndValue').val(DefaultEndT);
}
function setDiffTime(e) {
(0, _jquery2.default)('.endTime').on('keyup change', function (e) {
setDefaultStartTime();
endVal = stringToseconde((0, _jquery2.default)(this).val());
startVal = stringToseconde((0, _jquery2.default)(this).closest('.video-subtitle-item').find('.startTime').val());
diffVal = millisecondeToTime(endVal - startVal);
(0, _jquery2.default)(this).closest('.video-subtitle-item').find('.showForTime').val(diffVal);
});
(0, _jquery2.default)('.startTime').on('keyup change', function (e) {
setDefaultStartTime();
startVal = stringToseconde((0, _jquery2.default)(this).val());
endVal = stringToseconde((0, _jquery2.default)(this).closest('.video-subtitle-item').find('.endTime').val());
diffVal = millisecondeToTime(endVal - startVal);
(0, _jquery2.default)(this).closest('.video-subtitle-item').find('.showForTime').val(diffVal);
});
}
function stringToseconde(time) {
var tt = time.split(":");
var sec = tt[0] * 3600 + tt[1] * 60 + tt[2] * 1;
return sec * 1000;
}
function millisecondeToTime(duration) {
var milliseconds = parseInt(duration % 1000 / 100 * 100),
seconds = parseInt(duration / 1000 % 60),
minutes = parseInt(duration / (1000 * 60) % 60),
hours = parseInt(duration / (1000 * 60 * 60) % 24);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
// if(isNaN(hours) && isNaN(minutes) && isNaN(seconds) && isNaN(milliseconds) ) {
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
//}
}
$container.on('click', '.remove-item', function (e) {
e.preventDefault();
if ((0, _jquery2.default)(this).closest('.editing').length > 0) {
(0, _jquery2.default)(this).closest('.editing').remove();
} else {
(0, _jquery2.default)(this).closest('.video-subtitle-item').remove();
}
});
(0, _jquery2.default)('#submit-subtitle').on('click', function (e) {
e.preventDefault();
buildCaptionVtt('save');
});
(0, _jquery2.default)('#copy-subtitle').on('click', function (event) {
event.preventDefault();
buildCaptionVtt('copy');
});
function buildCaptionVtt(btn) {
try {
var allData = (0, _jquery2.default)('#video-subtitle-list').serializeArray();
allData = JSON.parse(JSON.stringify(allData));
allData = JSON.parse(JSON.stringify(allData));
var metaStructId = (0, _jquery2.default)('#metaStructId').val();
var countSubtitle = (0, _jquery2.default)('.video-subtitle-item').length;
if (allData) {
var i = 0;
var j = 0;
var captionText = "WEBVTT - with cue identifier\n\n";
while (i <= countSubtitle * 3) {
j = j + 1;
captionText += j + "\n" + allData[i].value + " --> " + allData[i + 1].value + "\n" + allData[i + 2].value + "\n\n";
i = i + 3;
if (i == countSubtitle * 3 - 3) {
(0, _jquery2.default)('#record-vtt').val(captionText);
console.log(captionText);
if (btn == 'save') {
//send data
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/tools/metadata/save/',
dataType: 'json',
data: {
databox_id: data.databoxId,
record_id: data.recordId,
meta_struct_id: metaStructId,
value: captionText
},
success: function success(data) {
if (!data.success) {
humane.error(localeService.t('prod:videoeditor:subtitletab:messsage:: error'));
} else {
humane.info(localeService.t('prod:videoeditor:subtitletab:messsage:: success'));
loadVideo();
}
}
});
}
if (btn == 'copy') {
return copyElContentClipboard('record-vtt');
}
}
}
;
}
} catch (err) {
return;
}
}
var copyElContentClipboard = function copyElContentClipboard(elId) {
var copyEl = document.getElementById(elId);
copyEl.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
} catch (err) {
console.log('unable to copy');
}
};
var addSubTitleVtt = function addSubTitleVtt() {
var countSubtitle = (0, _jquery2.default)('.video-subtitle-item').length;
if ((0, _jquery2.default)('.alert-wrapper').length) {
(0, _jquery2.default)('.alert-wrapper').remove();
}
if (countSubtitle > 1) {
setDefaultStartTime();
}
var item = (0, _jquery2.default)('#default-item').html();
(0, _jquery2.default)('.fields-wrapper').append(item);
(0, _jquery2.default)('.video-subtitle-item:last .time').attr('pattern', '[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]{3}$');
(0, _jquery2.default)('.video-subtitle-item:last .startTime').attr('name', 'startTime' + countSubtitle).addClass('startTime' + countSubtitle);
(0, _jquery2.default)('.video-subtitle-item:last .endTime').attr('name', 'endTime' + countSubtitle).addClass('endTime' + countSubtitle);
(0, _jquery2.default)('.video-subtitle-item:last .number').html(countSubtitle);
if (countSubtitle > 1) {
(0, _jquery2.default)('.video-subtitle-item:last .startTime').val((0, _jquery2.default)('#defaultStartValue').val());
(0, _jquery2.default)('.video-subtitle-item:last .endTime').val((0, _jquery2.default)('#defaultEndValue').val());
}
//setDiffTime();
};
// Edit subtitle
var fieldvalue = '';
var ResValue = '';
var captionValue = '';
var captionLength = '';
var timeValue = '';
//Show default caption to edit
fieldvalue = (0, _jquery2.default)('#caption_' + (0, _jquery2.default)('#metaStructId').val()).val();
editCaptionByLanguage(fieldvalue);
(0, _jquery2.default)('#metaStructId').on('keyup change', function (e) {
fieldvalue = (0, _jquery2.default)('#caption_' + (0, _jquery2.default)(this).val()).val();
editCaptionByLanguage(fieldvalue);
(0, _jquery2.default)('.editing > .caption-label').click(function (e) {
(0, _jquery2.default)(this).next('.video-subtitle-item').toggleClass('active');
(0, _jquery2.default)(this).toggleClass('caption_active');
});
});
(0, _jquery2.default)('.editing > .caption-label').click(function (e) {
(0, _jquery2.default)(this).next('.video-subtitle-item').toggleClass('active');
(0, _jquery2.default)(this).toggleClass('caption_active');
});
function editCaptionByLanguage(fieldvalue) {
(0, _jquery2.default)('.fields-wrapper').html('');
var item = (0, _jquery2.default)('#default-item').html();
if (fieldvalue != '' && fieldvalue != undefined) {
var withCueId = false;
//var fieldType = fieldvalue.split("WEBVTT");
var fieldType = fieldvalue.split("\n\n");
if (fieldType[0] === 'WEBVTT - with cue identifier') {
// with cue
ResValue = fieldvalue.split("WEBVTT - with cue identifier\n\n");
captionValue = ResValue[1].split("\n\n");
captionLength = captionValue.length;
console.log(captionValue);
for (var i = 0; i < captionLength - 1; i++) {
// Regex blank line
var ResValueItem = captionValue[i].replace(/\n\r/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/g);
var captionValueItem = ResValueItem[0].split("\n");
var captionNumber = captionValueItem[0];
var timing = captionValueItem[1];
var text1 = captionValueItem.slice(2);
if (text1.length > 1) {
var text = text1.join('\n');
} else {
var text = text1;
}
var timeValue = timing.split(" --> ");
var startTimeLabel = timeValue[0];
(0, _jquery2.default)('.fields-wrapper').append('<div class="item_' + i + ' editing"></div>');
(0, _jquery2.default)('.fields-wrapper .item_' + i + '').append('<p class="caption-label"><span class="number">' + captionNumber + '</span><span class="start-label"></span> --> <span class="end-label"></span><span class="duration"></span><span class="text-label"></span></p>');
(0, _jquery2.default)('.fields-wrapper .item_' + i + '').append(item);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.number').remove();
//Re-Build StartTime
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.start-label').text(startTimeLabel);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.startTime').val(startTimeLabel);
startVal = stringToseconde(timeValue[0]);
//Re-Build EndTime
timeValue = timeValue[1].split("\n");
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.end-label').text(timeValue[0]);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.endTime').val(timeValue[0]);
endVal = stringToseconde(timeValue[0]);
//Re-build Duration
diffVal = millisecondeToTime(endVal - startVal);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.duration').text(diffVal);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.showForTime').val(diffVal);
//Re-build caption text
var textTrimed = text && text.length > length ? text.substring(0, 30) + '...' : text;
if (timeValue[1] != '') {
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.text-label').text(textTrimed);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.captionText').val(text);
}
//end with cue number
}
} else {
ResValue = fieldvalue.split("WEBVTT\n\n");
captionValue = ResValue[1].split("\n\n");
captionLength = captionValue.length - 1;
var captionNumber;
for (var i = 0; i < captionLength; i++) {
captionNumber = i + 1;
timeValue = captionValue[i].split(" --> ");
var startTimeLabel = timeValue[0];
(0, _jquery2.default)('.fields-wrapper').append('<div class="item_' + i + ' editing"></div>');
(0, _jquery2.default)('.fields-wrapper .item_' + i + '').append('<p class="caption-label"><span class="number">' + captionNumber + '</span><span class="start-label"></span> --> <span class="end-label"></span><span class="duration"></span><span class="text-label"></span></p>');
(0, _jquery2.default)('.fields-wrapper .item_' + i + '').append(item);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.number').remove();
//Re-Build StartTime
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.start-label').text(startTimeLabel);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.startTime').val(startTimeLabel);
startVal = stringToseconde(timeValue[0]);
//Re-Build EndTime
timeValue = timeValue[1].split("\n");
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.end-label').text(timeValue[0]);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.endTime').val(timeValue[0]);
endVal = stringToseconde(timeValue[0]);
//Re-build Duration
diffVal = millisecondeToTime(endVal - startVal);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.duration').text(diffVal);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.showForTime').val(diffVal);
//Re-build caption text
var textTrimed = timeValue[1] && timeValue[1].length > length ? timeValue[1].substring(0, 30) + '...' : timeValue[1];
if (timeValue[1] != '') {
var text = timeValue.slice(1);
text = text.join('\n');
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').closest('.editing').find('.text-label').text(textTrimed);
(0, _jquery2.default)('.item_' + i + ' .video-subtitle-item ').find('.captionText').val(text);
}
}
}
setDiffTime();
} else {
var errorMsg = (0, _jquery2.default)('#no_caption').val();
(0, _jquery2.default)('.fields-wrapper').append('<p class="text-center alert-wrapper"><span class="alert alert-info">' + errorMsg + '</span></p>');
}
}
//Subtitle Request Tab
(0, _jquery2.default)('#submit-subtitle-request').on('click', function (e) {
e.preventDefault();
try {
var requestData = (0, _jquery2.default)('#video-subtitle-request').serializeArray();
requestData = JSON.parse(JSON.stringify(requestData));
console.log(requestData);
} catch (err) {
return;
}
});
};
/* const render = (initData) => {
let record = initData.records[0];
if (record.type !== 'video') {
return;
}
options.frameRates = {};
options.ratios = {};
const coverUrl = '';
let generateSourcesTpl = (record) => {
let recordSources = [];
_.each(record.sources, (s, i) => {
recordSources.push(`<source src="${s.src}" type="${s.type}" data-frame-rate="${s.framerate}">`)
options.frameRates[s.src] = s.framerate;
options.ratios[s.src] = s.ratio;
});
return recordSources.join(' ');
};
let sources = generateSourcesTpl(record);
$('.video-subtitle-right .video-subtitle-wrapper').html('');
$('.video-subtitle-right .video-subtitle-wrapper').append(
`<video id="embed-video" class="thumb_video embed-resource video-js vjs-default-skin vjs-big-play-centered" data-ratio="{{ prevRatio }}" controls
preload="none" width="100%" height="100%" poster="${coverUrl}" data-setup='{"language":"${localeService.getLocale()}"}'>${sources}
<track kind="captions" src=${$('#record-vtt').val()} srclang="en" label="English" default>
</video>`);
};*/
return {
initialize: initialize
};
};
exports.default = videoSubtitleCapture;
/***/ }),
/* 186 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var keyboard = function keyboard(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var initialize = function initialize() {};
var openModal = function openModal() {
(0, _jquery2.default)('#keyboard-stop').bind('click', function () {
var display = (0, _jquery2.default)(this).get(0).checked ? '0' : '1';
appCommons.userModule.setPref('keyboard_infos', display);
});
var buttons = {};
buttons[localeService.t('fermer')] = function () {
(0, _jquery2.default)('#keyboard-dialog').dialog('close');
};
(0, _jquery2.default)('#keyboard-dialog').dialog({
closeOnEscape: false,
resizable: false,
draggable: false,
modal: true,
width: 600,
height: 400,
overlay: {
backgroundColor: '#000',
opacity: 0.7
},
open: function open(event, ui) {
(0, _jquery2.default)(this).dialog('widget').css('z-index', '1999');
},
close: function close() {
(0, _jquery2.default)(this).dialog('widget').css('z-index', 'auto');
if ((0, _jquery2.default)('#keyboard-stop').get(0).checked) {
var dialog = (0, _jquery2.default)('#keyboard-dialog');
if (dialog.data('ui-dialog')) {
dialog.dialog('destroy');
}
dialog.remove();
}
}
}).dialog('option', 'buttons', buttons).dialog('open');
(0, _jquery2.default)('#keyboard-dialog').scrollTop(0);
};
return { initialize: initialize, openModal: openModal };
};
exports.default = keyboard;
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var humane = __webpack_require__(8);
var cgu = function cgu(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var $container = options.$container;
var $this = (0, _jquery2.default)('.cgu-dialog:first');
$this.dialog({
autoOpen: true,
closeOnEscape: false,
draggable: false,
modal: true,
resizable: false,
width: 800,
height: 500,
open: function open() {
$this.parents('.ui-dialog:first').find('.ui-dialog-titlebar-close').remove();
(0, _jquery2.default)('.cgus-accept', (0, _jquery2.default)(this)).bind('click', function () {
acceptCgus((0, _jquery2.default)('.cgus-accept', $this).attr('id'), (0, _jquery2.default)('.cgus-accept', $this).attr('date'));
$this.dialog('close').remove();
initialize(services, options);
});
(0, _jquery2.default)('.cgus-cancel', (0, _jquery2.default)(this)).bind('click', function () {
if (confirm(localeService.t('warningDenyCgus'))) {
cancelCgus((0, _jquery2.default)('.cgus-cancel', $this).attr('id').split('_').pop());
}
});
}
});
};
function acceptCgus(name, value) {
appCommons.userModule.setPref(name, value);
}
function cancelCgus(id) {
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/TOU/deny/' + id + '/',
dataType: 'json',
success: function success(data) {
if (data.success) {
alert(localeService.t('cgusRelog'));
self.location.replace(self.location.href);
} else {
humane.error(data.message);
}
}
});
}
return {
initialize: initialize
};
};
exports.default = cgu;
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var shareRecord = function shareRecord(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
var initialize = function initialize(options) {
var $container = options.$container;
$container.on('click', '.share-record-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var db = $el.data('db');
var recordId = $el.data('record-id');
doShare(db, recordId);
});
};
var doShare = function doShare(bas, rec) {
var $dialog = _dialog2.default.create(services, {
size: 'Medium',
title: localeService.t('share')
});
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/share/record/' + bas + '/' + rec + '/',
//dataType: 'html',
success: function success(data) {
$dialog.setContent(data);
_onShareReady();
}
});
return true;
};
var _onShareReady = function _onShareReady() {
(0, _jquery2.default)('input.ui-state-default').hover(function () {
(0, _jquery2.default)(this).addClass('ui-state-hover');
}, function () {
(0, _jquery2.default)(this).removeClass('ui-state-hover');
});
(0, _jquery2.default)('#permalinkUrlCopy').on('click', function (event) {
event.preventDefault();
return copyElContentClipboard('permalinkUrl');
});
(0, _jquery2.default)('#permaviewUrlCopy').on('click', function (event) {
event.preventDefault();
return copyElContentClipboard('permaviewUrl');
});
(0, _jquery2.default)('#embedCopy').on('click', function (event) {
event.preventDefault();
return copyElContentClipboard('embedRecordUrl');
});
var copyElContentClipboard = function copyElContentClipboard(elId) {
var copyEl = document.getElementById(elId);
copyEl.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
} catch (err) {
console.log('unable to copy');
}
};
};
return { initialize: initialize };
};
exports.default = shareRecord;
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var addToBasket = function addToBasket(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $container = null;
var initialize = function initialize() {
$container = (0, _jquery2.default)('body');
$container.on('click', '.record-add-to-basket-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dbId = $el.data('db-id');
var recordId = $el.data('record-id');
appEvents.emit('workzone.doAddToBasket', {
dbId: dbId, recordId: recordId, event: event.currentTarget
});
});
};
return { initialize: initialize };
};
exports.default = addToBasket;
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var removeFromBasket = function removeFromBasket(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $container = null;
var initialize = function initialize() {
$container = (0, _jquery2.default)('body');
$container.on('click', '.record-remove-from-basket-action', function (event) {
event.preventDefault();
appEvents.emit('workzone.doRemoveFromBasket', {
event: event.currentTarget,
confirm: false
});
});
};
return { initialize: initialize };
};
exports.default = removeFromBasket;
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var highlight = __webpack_require__(193);
var colorpicker = __webpack_require__(194);
var preferences = function preferences(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var initialize = function initialize() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var $container = options.$container;
render();
$container.on('change', '#ADVSRCH_FILTER_FACET', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('facet', $el.prop('checked'));
appEvents.emit('search.updateFacetData');
appEvents.emit('search.doRefreshState');
});
$container.on('click', '.open-preferences', function (event) {
event.preventDefault();
openModal(event);
});
$container.on('click', '.preferences-options-submit', function (event) {
event.preventDefault();
submitState();
});
$container.on('change', '.preferences-options-start-page', function (event) {
event.preventDefault();
setInitialStateOptions();
});
$container.on('change', '.preferences-options-search-reload', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('advanced_search_reload', $el.prop('checked') ? '1' : '0');
});
$container.on('change', '.preferences-options-use-truncation', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('use_truncation', $el.prop('checked') ? '1' : '0');
});
$container.on('change', '.preferences-options-presentation-thumbnail', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('view', $el.val());
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-presentation-list', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('view', $el.val());
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-rollover-caption', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('rollover_thumbnail', $el.val());
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-rollover-preview', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('rollover_thumbnail', $el.val());
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-technical-display', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('technical_display', $el.val());
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-rollover-preview', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('technical_display', $el.val());
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-rollover-preview', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('technical_display', $el.val());
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-doctype-display', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('doctype_display', $el.prop('checked') ? '1' : '0');
appEvents.emit('search.doRefreshState');
});
$container.on('change', '.preferences-options-basket-status', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('basket_status_display', $el.prop('checked') ? '1' : '0');
});
$container.on('change', '.preferences-options-basket-caption', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('basket_caption_display', $el.prop('checked') ? '1' : '0');
});
$container.on('change', '.preferences-options-basket-title', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('basket_title_display', $el.prop('checked') ? '1' : '0');
});
$container.on('change', '.preferences-options-basket-type', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
event.preventDefault();
appCommons.userModule.setPref('basket_type_display', $el.prop('checked') ? '1' : '0');
});
$container.on('click', '.preference-change-theme-action', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var color = $el.data('theme');
var minified = configService.get('debug') ? '' : '.min';
// setCss()
(0, _jquery2.default)('#skinCss').attr('href', '/assets/production/skin-' + color + minified + '.css');
/* $.post(`${configService.get('baseUrl')}/user/preferences/`, {
prop: 'css',
value: color,
t: Math.random()
});*/
var skin = '';
_jquery2.default.ajax({
type: 'POST',
url: url + 'user/preferences/',
data: {
prop: 'css',
value: color,
t: Math.random()
},
success: function success(data) {
(0, _jquery2.default)('body').removeClass().addClass('PNB ' + color);
/* console.log('saved:' + color);*/
return;
}
});
});
$container.on('change', '.preferences-options-collection-order', function (event) {
var el = (0, _jquery2.default)('#look_box_settings select[name=orderByName]');
event.preventDefault();
appCommons.userModule.setPref('order_collection_by', el.val());
});
(0, _jquery2.default)('.preferences-facet-order').change(function (event) {
var el = (0, _jquery2.default)('.look_box_settings select[name=orderFacet]');
event.preventDefault();
appCommons.userModule.setPref('order_facet', el.val());
appEvents.emit('search.updateFacetData');
});
(0, _jquery2.default)('.preferences-facet-values-order').change(function (event) {
var el = (0, _jquery2.default)('.look_box_settings select[name=facetValuesOrder]');
event.preventDefault();
appCommons.userModule.setPref('facet_values_order', el.val());
appEvents.emit('search.updateFacetData');
});
$container.on('change', '.upload-options-collection', function (event) {
var el = (0, _jquery2.default)('.settings-box select[name=base_id]');
event.preventDefault();
appCommons.userModule.setPref('upload_last_used_collection', el.val());
});
(0, _jquery2.default)('#nperpage_slider').slider({
value: parseInt((0, _jquery2.default)('#nperpage_value').val(), 10),
min: 10,
max: 100,
step: 10,
slide: function slide(event, ui) {
(0, _jquery2.default)('#nperpage_value').val(ui.value);
},
stop: function stop(event, ui) {
appCommons.userModule.setPref('images_per_page', (0, _jquery2.default)('#nperpage_value').val());
}
});
(0, _jquery2.default)('#sizeAns_slider').slider({
value: parseInt((0, _jquery2.default)('#sizeAns_value').val(), 10),
min: 90,
max: 270,
step: 10,
slide: function slide(event, ui) {
(0, _jquery2.default)('#sizeAns_value').val(ui.value);
},
stop: function stop(event, ui) {
appCommons.userModule.setPref('images_size', (0, _jquery2.default)('#sizeAns_value').val());
}
});
(0, _jquery2.default)('#backcolorpickerHolder').ColorPicker({
flat: true,
color: '404040',
livePreview: false,
eventName: 'mouseover',
onSubmit: function onSubmit(hsb, hex, rgb, el) {
var back_hex = '';
var unactive = '';
var sim_b;
if (hsb.b >= 50) {
back_hex = '000000';
sim_b = 0.1 * hsb.b;
} else {
back_hex = 'FFFFFF';
sim_b = 100 - 0.1 * (100 - hsb.b);
}
sim_b = 0.1 * hsb.b;
var sim_rgb = appCommons.utilsModule.hsl2rgb(hsb.h, hsb.s, sim_b);
var sim_hex = appCommons.utilsModule.RGBtoHex(sim_rgb.r, sim_rgb.g, sim_rgb.b);
appCommons.userModule.setPref('background-selection', hex);
appCommons.userModule.setPref('background-selection-disabled', sim_hex);
appCommons.userModule.setPref('fontcolor-selection', back_hex);
(0, _jquery2.default)('style[title=color_selection]').empty();
var datas = '.diapo.selected,#reorder_box .diapo.selected, #EDIT_ALL .diapo.selected, .list.selected, .list.selected .diapo' + '{' + ' COLOR: #' + back_hex + ';' + ' BACKGROUND-COLOR: #' + hex + ';' + '}';
(0, _jquery2.default)('style[title=color_selection]').empty().text(datas);
}
});
(0, _jquery2.default)('#backcolorpickerHolder').find('.colorpicker_submit').append((0, _jquery2.default)('#backcolorpickerHolder .submiter')).bind('click', function () {
(0, _jquery2.default)(this).highlight('#CCCCCC');
});
(0, _jquery2.default)('#look_box .tabs').tabs();
};
var render = function render() {
var availableThemes = configService.get('availableThemes');
var themeTpl = '';
for (var t in availableThemes) {
var curTheme = availableThemes[t];
themeTpl += '<div class="colorpicker_box preference-change-theme-action" data-theme="' + curTheme.name + '" style="width:16px;height:16px;background-color:#' + curTheme.name + ';">&nbsp;</div>';
}
// generates themes
(0, _jquery2.default)('#theme-container').empty().append(themeTpl);
};
// look_box
function setInitialStateOptions() {
var el = (0, _jquery2.default)('#look_box_settings select[name=start_page]');
switch (el.val()) {
case 'LAST_QUERY':
case 'PUBLI':
case 'HELP':
(0, _jquery2.default)('#look_box_settings input[name=start_page_value]').hide();
break;
case 'QUERY':
(0, _jquery2.default)('#look_box_settings input[name=start_page_value]').show();
break;
default:
}
}
function submitState() {
var el = (0, _jquery2.default)('#look_box_settings select[name=start_page]');
var val = el.val();
var start_page_query = (0, _jquery2.default)('#look_box_settings input[name=start_page_value]').val();
if (val === 'QUERY') {
appCommons.userModule.setPref('start_page_query', start_page_query);
}
appCommons.userModule.setPref('start_page', val);
}
function openModal(event) {
(0, _jquery2.default)('#look_box').dialog({
closeOnEscape: true,
resizable: false,
width: 450,
height: 500,
modal: true,
draggable: false,
overlay: {
backgroundColor: '#000',
opacity: 0.7
}
}).dialog('open');
}
return {
initialize: initialize,
openModal: openModal
};
};
exports.default = preferences;
/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {
/*** IMPORTS FROM imports-loader ***/
var $ = __webpack_require__(0);
'use strict';
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(function () {
_jquery2.default.fn.extend({
highlight: function highlight(color) {
if ((0, _jquery2.default)(this).hasClass('animating')) {
return (0, _jquery2.default)(this);
}
color = typeof color !== 'undefined' ? color : 'red';
var oldColor = (0, _jquery2.default)(this).css('backgroundColor');
return (0, _jquery2.default)(this).addClass('animating').stop().animate({
backgroundColor: color
}, 50, 'linear', function () {
(0, _jquery2.default)(this).stop().animate({
backgroundColor: oldColor
}, 450, 'linear', function () {
(0, _jquery2.default)(this).removeClass('animating');
});
});
}
});
})();
/***/ }),
/* 194 */
/***/ (function(module, exports, __webpack_require__) {
/*** IMPORTS FROM imports-loader ***/
var $ = __webpack_require__(0);
'use strict';
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var ids = {};
var inAction = void 0;
var charMin = 65;
var visible = void 0;
var tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>';
var defaults = {
eventName: 'click',
onShow: function onShow() {},
onBeforeShow: function onBeforeShow() {},
onHide: function onHide() {},
onChange: function onChange() {},
onSubmit: function onSubmit() {},
color: 'ff0000',
livePreview: true,
flat: false
};
var fillRGBFields = function fillRGBFields(hsb, cal) {
var rgb = _HSBToRGB(hsb);
$(cal).data('colorpicker').fields.eq(1).val(rgb.r).end().eq(2).val(rgb.g).end().eq(3).val(rgb.b).end();
};
var fillHSBFields = function fillHSBFields(hsb, cal) {
$(cal).data('colorpicker').fields.eq(4).val(hsb.h).end().eq(5).val(hsb.s).end().eq(6).val(hsb.b).end();
};
var fillHexFields = function fillHexFields(hsb, cal) {
$(cal).data('colorpicker').fields.eq(0).val(_HSBToHex(hsb)).end();
};
var setSelector = function setSelector(hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + _HSBToHex({ h: hsb.h, s: 100, b: 100 }));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s / 100, 10),
top: parseInt(150 * (100 - hsb.b) / 100, 10)
});
};
var setHue = function setHue(hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h / 360, 10));
};
var setCurrentColor = function setCurrentColor(hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + _HSBToHex(hsb));
};
var setNewColor = function setNewColor(hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + _HSBToHex(hsb));
};
var keyDown = function keyDown(ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if (pressedKey > charMin && pressedKey <= 90 || pressedKey === 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
};
var change = function change(ev) {
var cal = $(this).parent().parent();
var col = void 0;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = _HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = _RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, _HSBToHex(col), _HSBToRGB(col)]);
};
var blur = function blur(ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
};
var focus = function focus() {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
};
var downIncrement = function downIncrement(ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255,
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
};
var moveIncrement = function moveIncrement(ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
};
var upIncrement = function upIncrement(ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
};
var downHue = function downHue(ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
};
var moveHue = function moveHue(ev) {
change.apply(ev.data.cal.data('colorpicker').fields.eq(4).val(parseInt(360 * (150 - Math.max(0, Math.min(150, ev.pageY - ev.data.y))) / 150, 10)).get(0), [ev.data.preview]);
return false;
};
var upHue = function upHue(ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
};
var downSelector = function downSelector(ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
};
var moveSelector = function moveSelector(ev) {
change.apply(ev.data.cal.data('colorpicker').fields.eq(6).val(parseInt(100 * (150 - Math.max(0, Math.min(150, ev.pageY - ev.data.pos.top))) / 150, 10)).end().eq(5).val(parseInt(100 * Math.max(0, Math.min(150, ev.pageX - ev.data.pos.left)) / 150, 10)).get(0), [ev.data.preview]);
return false;
};
var upSelector = function upSelector(ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
};
var enterSubmit = function enterSubmit(ev) {
$(this).addClass('colorpicker_focus');
};
var leaveSubmit = function leaveSubmit(ev) {
$(this).removeClass('colorpicker_focus');
};
var clickSubmit = function clickSubmit(ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, _HSBToHex(col), _HSBToRGB(col), cal.data('colorpicker').el);
};
var show = function show(ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({ left: left + 'px', top: top + 'px' });
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) !== false) {
cal.show();
}
$(document).bind('mousedown', { cal: cal }, hide);
return false;
};
var hide = function hide(ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) !== false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
};
var isChildOf = function isChildOf(parentEl, el, container) {
if (parentEl === el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if (parentEl.compareDocumentPosition) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while (prEl && prEl !== container) {
if (prEl === parentEl) {
return true;
}
prEl = prEl.parentNode;
}
return false;
};
var getViewport = function getViewport() {
var m = document.compatMode === 'CSS1Compat';
return {
l: window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t: window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w: window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h: window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
};
var fixHSB = function fixHSB(hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
};
var fixRGB = function fixRGB(rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
};
var fixHex = function fixHex(hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i = 0; i < len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
};
var _HexToRGB = function _HexToRGB(hex) {
hex = parseInt(hex.indexOf('#') > -1 ? hex.substring(1) : hex, 16);
return { r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: hex & 0x0000FF };
};
var _HexToHSB = function _HexToHSB(hex) {
return _RGBToHSB(_HexToRGB(hex));
};
var _RGBToHSB = function _RGBToHSB(rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max !== 0) {}
hsb.s = max !== 0 ? 255 * delta / max : 0;
if (hsb.s !== 0) {
if (rgb.r === max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g === max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100 / 255;
hsb.b *= 100 / 255;
return hsb;
};
var _HSBToRGB = function _HSBToRGB(hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s * 255 / 100);
var v = Math.round(hsb.b * 255 / 100);
if (s === 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255 - s) * v / 255;
var t3 = (t1 - t2) * (h % 60) / 60;
if (h === 360) {
h = 0;
}
if (h < 60) {
rgb.r = t1;
rgb.b = t2;
rgb.g = t2 + t3;
} else if (h < 120) {
rgb.g = t1;
rgb.b = t2;
rgb.r = t1 - t3;
} else if (h < 180) {
rgb.g = t1;
rgb.r = t2;
rgb.b = t2 + t3;
} else if (h < 240) {
rgb.b = t1;
rgb.r = t2;
rgb.g = t1 - t3;
} else if (h < 300) {
rgb.b = t1;
rgb.g = t2;
rgb.r = t2 + t3;
} else if (h < 360) {
rgb.r = t1;
rgb.g = t2;
rgb.b = t1 - t3;
} else {
rgb.r = 0;
rgb.g = 0;
rgb.b = 0;
}
}
return { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b) };
};
var _RGBToHex = function _RGBToHex(rgb) {
var hex = [rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16)];
$.each(hex, function (nr, val) {
if (val.length === 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
};
var _HSBToHex = function _HSBToHex(hsb) {
return _RGBToHex(_HSBToRGB(hsb));
};
var restoreOriginal = function restoreOriginal() {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function init(opt) {
opt = $.extend({}, defaults, opt || {});
if (typeof opt.color === 'string') {
opt.color = _HexToHSB(opt.color);
} else if (opt.color.r !== undefined && opt.color.g !== undefined && opt.color.b !== undefined) {
opt.color = _RGBToHSB(opt.color);
} else if (opt.color.h !== undefined && opt.color.s !== undefined && opt.color.b !== undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000, 10);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal.find('input').bind('keyup', keyDown).bind('change', change).bind('blur', blur).bind('focus', focus);
cal.find('span').bind('mousedown', downIncrement).end().find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit').bind('mouseenter', enterSubmit).bind('mouseleave', leaveSubmit).bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function showPicker() {
return this.each(function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function hidePicker() {
return this.each(function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function setColor(col) {
if (typeof col === 'string') {
col = _HexToHSB(col);
} else if (col.r !== undefined && col.g !== undefined && col.b !== undefined) {
col = _RGBToHSB(col);
} else if (col.h !== undefined && col.s !== undefined && col.b !== undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function () {
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(_jquery2.default); //require('./colorpicker.scss');
/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
var _index = __webpack_require__(75);
var _index2 = _interopRequireDefault(_index);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
var _pym = __webpack_require__(17);
var _pym2 = _interopRequireDefault(_pym);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var orderItem = function orderItem(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var openModal = function openModal(orderId) {
var $dialog = _dialog2.default.create(services, {
size: 'Full'
});
_jquery2.default.ajax({
type: 'GET',
url: url + 'prod/order/' + orderId,
success: function success(data) {
$dialog.setContent(data);
_onOrderItemReady($dialog);
}
});
return true;
};
var _onOrderItemReady = function _onOrderItemReady($dialog) {
var userInfoIsVisible = false;
var itemCount = 0;
var elementsForValidation = [];
var readyForValidation = false;
var lastItemChosen = null;
var ELEMENT_TYPE = {
VALIDATED: 'validated',
DENIED: 'denied',
SELECTABLE: 'selectable',
SELECTED: 'selected',
WAITINGFORVALIDATION: 'waitingForValidation'
};
var trs = (0, _jquery2.default)('.order_list .order_row', $dialog.getDomElement());
var lastSelectedRow = void 0;
if ((0, _jquery2.default)('#notification_box').is(':visible')) {
(0, _jquery2.default)('.notification_trigger').trigger('mousedown');
}
(0, _jquery2.default)('.order_launcher', $dialog.getDomElement()).on('click', function (event) {
if (readyForValidation) {
if (confirm(window.orderItemData.translatedText.message)) {
(0, _index2.default)(services).orderModal(event);
}
} else {
(0, _index2.default)(services).orderModal(event);
}
});
(0, _jquery2.default)('#email-btn', $dialog.getDomElement()).on('click', function () {
var email = window.orderItemData.userEmail;
var subject = window.orderItemData.subject;
var body = window.orderItemData.body;
if (email !== null) {
var link = 'mailto:' + email + '?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
window.location.href = link;
}
});
(0, _jquery2.default)('input[name="select-all"]', $dialog.getDomElement()).bind('click', function () {
var checkboxElement = this;
itemCount = 0;
var selectable = [];
(0, _jquery2.default)('.table-order .order_row').each(function () {
var el = (0, _jquery2.default)(this);
if (checkboxElement.checked && el.hasClass(ELEMENT_TYPE.SELECTABLE)) {
el.addClass(ELEMENT_TYPE.SELECTED);
itemCount++;
selectable.push(el);
} else {
el.removeClass(ELEMENT_TYPE.SELECTED);
}
});
//load preview for single item selected
if (selectable.length === 1) {
loadPreviewAndCaption(selectable[0]);
}
renderOrderDetailView(itemCount);
});
(0, _jquery2.default)('.order_list .order_row', $dialog.getDomElement()).bind('click', function (event) {
var $this = (0, _jquery2.default)(this);
lastItemChosen = $this;
//disable select all checkbox if selected
if ((0, _jquery2.default)('input[name="select-all"]').is(':checked')) {
(0, _jquery2.default)('input[name="select-all"]').prop('checked', false);
}
if (appCommons.utilsModule.is_ctrl_key(event)) {
if (!$this.hasClass(ELEMENT_TYPE.SELECTABLE)) {
return;
}
if ($this.hasClass(ELEMENT_TYPE.SELECTED)) {
$this.removeClass(ELEMENT_TYPE.SELECTED);
itemCount--;
} else {
$this.addClass(ELEMENT_TYPE.SELECTED);
itemCount++;
}
} else if (appCommons.utilsModule.is_shift_key(event)) {
if (!$this.hasClass(ELEMENT_TYPE.SELECTABLE)) {
return;
}
var currentIndex = $this.index('.order_list .order_row');
var prevIndex = lastSelectedRow.index('.order_list .order_row');
(0, _jquery2.default)('.order_list .selectable.selected', $dialog.getDomElement()).removeClass(ELEMENT_TYPE.SELECTED);
itemCount = 0;
selectRowsBetweenIndexes([prevIndex, currentIndex]);
} else {
(0, _jquery2.default)('.order_list .selectable.selected', $dialog.getDomElement()).removeClass(ELEMENT_TYPE.SELECTED);
if ($this.hasClass(ELEMENT_TYPE.SELECTABLE)) {
$this.addClass(ELEMENT_TYPE.SELECTED);
lastSelectedRow = $this;
}
itemCount = 1;
}
if (itemCount === 1) {
var selected = (0, _jquery2.default)('.order_list .selected', $dialog.getDomElement());
loadPreviewAndCaption(selected);
}
renderOrderDetailView(itemCount);
});
function selectRowsBetweenIndexes(indexes) {
indexes.sort(function (a, b) {
return a - b;
});
for (var i = indexes[0]; i <= indexes[1]; i++) {
if ((0, _jquery2.default)(trs[i]).hasClass(ELEMENT_TYPE.SELECTABLE)) {
(0, _jquery2.default)(trs[i]).addClass(ELEMENT_TYPE.SELECTED);
itemCount++;
}
}
}
(0, _jquery2.default)('.captionTips, .captionRolloverTips, .infoTips', $dialog.getDomElement()).tooltip({
delay: 0
});
(0, _jquery2.default)('.previewTips', $dialog.getDomElement()).tooltip({
fixable: true
});
(0, _jquery2.default)('button.send', $dialog.getDomElement()).bind('click', function () {
updateValidation(ELEMENT_TYPE.VALIDATED);
//send_documents(order_id);
});
(0, _jquery2.default)('button.deny', $dialog.getDomElement()).bind('click', function () {
updateValidation(ELEMENT_TYPE.DENIED);
//deny_documents(order_id);
});
(0, _jquery2.default)('button.reset', $dialog.getDomElement()).bind('click', function () {
var itemsToBeReset = [];
(0, _jquery2.default)('.order_list .order_row.selected.waitingForValidation', $dialog.getDomElement()).each(function (i, n) {
itemsToBeReset.push((0, _jquery2.default)(n));
});
//if item is not selected, delete item being previewed
if (itemsToBeReset.length == 0 && lastItemChosen) {
itemsToBeReset.push(lastItemChosen);
}
resetItemForValidation(itemsToBeReset);
toggleValidationButton();
//$('.order_row.selected').removeClass('to_be_denied');
//$('.order_row.selected').removeClass('to_be_validated');
});
(0, _jquery2.default)('.force_sender', $dialog.getDomElement()).bind('click', function () {
if (confirm(localeService.t('forceSendDocument'))) {
//updateValidation('validated');
var element_id = [];
element_id.push((0, _jquery2.default)(this).closest('.order_row').find('input[name=order_element_id]').val());
var order_id = (0, _jquery2.default)('input[name=order_id]').val();
do_send_documents(order_id, element_id, true);
}
});
(0, _jquery2.default)('#userInfo').hover(function () {
var offset = (0, _jquery2.default)('#userInfo').position();
(0, _jquery2.default)('#userInfoPreview').css({
left: offset.left - (0, _jquery2.default)('#userInfoPreview').width() + 48,
top: offset.top + (0, _jquery2.default)('#userInfo').height() + 8
});
(0, _jquery2.default)('#userInfoPreview').show();
}, function () {
if (!userInfoIsVisible) {
(0, _jquery2.default)('#userInfoPreview').hide();
}
});
(0, _jquery2.default)('#userInfo').click(function () {
var offset = (0, _jquery2.default)('#userInfo').position();
if (!userInfoIsVisible) {
userInfoIsVisible = true;
(0, _jquery2.default)('#userInfoPreview').css({
left: offset.left - (0, _jquery2.default)('#userInfoPreview').width() + 48,
top: offset.top + (0, _jquery2.default)('#userInfo').height() + 8
});
(0, _jquery2.default)('#userInfoPreview').show();
} else {
userInfoIsVisible = false;
(0, _jquery2.default)('#userInfoPreview').hide();
}
});
var minimized_elements = (0, _jquery2.default)('.minimize');
(0, _jquery2.default)('.minimize').each(function () {
var t = (0, _jquery2.default)(this).text();
if (t.length < 60) return;
(0, _jquery2.default)(this).html(t.slice(0, 60) + '<span>... </span><a href="#" class="more">' + window.orderItemData.translatedText.moreText + '</a>' + '<span style="display:none;">' + t.slice(60, t.length) + ' <a href="#" class="less">' + window.orderItemData.translatedText.lessText + '</a></span>');
});
(0, _jquery2.default)('a.more', minimized_elements).click(function (event) {
event.preventDefault();
(0, _jquery2.default)(this).hide().prev().hide();
(0, _jquery2.default)(this).next().show();
});
(0, _jquery2.default)('a.less', minimized_elements).click(function (event) {
event.preventDefault();
(0, _jquery2.default)(this).parent().hide().prev().show().prev().show();
});
(0, _jquery2.default)('button.validate', $dialog.getDomElement()).bind('click', function (event) {
openValidationDialog(this, event);
return false;
});
(0, _jquery2.default)('.basket-btn').click(function (event) {
var titleCreate = window.orderItemData.translatedText.createTitle;
var type = (0, _jquery2.default)(this).attr('type');
var dialog_buttons = {};
dialog_buttons[titleCreate] = function () {
createBasket($innerDialog);
(0, _jquery2.default)(this).dialog('close');
};
var $innerDialog = (0, _jquery2.default)('#basket-window').dialog({
open: function open(event, ui) {
(0, _jquery2.default)('.ui-dialog').css('z-index', 100000);
(0, _jquery2.default)('.ui-widget-overlay').css('z-index', 100000);
},
closeOnEscape: true,
width: 450,
height: 300,
modal: true,
draggable: false,
stack: false,
title: window.orderItemData.translatedText.dialogTitle,
overlay: {
backgroundColor: '#000',
opacity: 0.7
},
buttons: dialog_buttons
}).dialog('open');
populateBasketDialog($innerDialog, type);
return false;
});
(0, _jquery2.default)('#myDropdown').on('click', function () {
if ((0, _jquery2.default)('#myDropdown').hasClass('open')) {
return;
}
if ((0, _jquery2.default)('.order_list .selected', $dialog.getDomElement()).length > 0) {
(0, _jquery2.default)('li[type="selected"]').removeClass('disabled');
} else {
//no selected item
if (!(0, _jquery2.default)('li[type="selected"]').hasClass('disabled')) {
(0, _jquery2.default)('li[type="selected"]').addClass('disabled');
}
}
});
function createBasket($innerDialog) {
var $form = (0, _jquery2.default)('form', $innerDialog);
var dialog = $innerDialog.closest('.ui-dialog');
var buttonPanel = dialog.find('.ui-dialog-buttonpane');
_jquery2.default.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serializeArray(),
dataType: 'json',
beforeSend: function beforeSend() {
(0, _jquery2.default)(":button:contains('" + localeService.t('create') + "')", buttonPanel).attr('disabled', true).addClass('ui-state-disabled');
},
success: function success(data) {
var order_id = (0, _jquery2.default)('input[name=order_id]').val();
var success = '0';
if (data.success) {
success = '1';
}
var url = '../prod/order/' + order_id + '/?success=' + success + '&action=basket' + '&message=' + encodeURIComponent(data.message);
reloadDialog(url);
appEvents.emit('workzone.refresh');
}
});
}
function populateBasketDialog($innerDialog, type) {
var lst = [];
var orderDialog = $innerDialog;
//set checkbox to true and disable it
(0, _jquery2.default)('input[name="lst"]', orderDialog).prop('checked', true);
(0, _jquery2.default)('.checkbox', orderDialog).css('visibility', 'hidden');
//set default name
var name = window.orderItemData.translatedText.defaultBasketTitle;
(0, _jquery2.default)('input[name="name"]', orderDialog).val(name);
var description = window.orderItemData.description;
var elements_ids = [];
switch (type) {
case 'denied':
(0, _jquery2.default)('.order_list .order_row.' + type, $dialog.getDomElement()).each(function (i, n) {
elements_ids.push((0, _jquery2.default)(n).attr('elementids'));
});
break;
case 'validated':
(0, _jquery2.default)('.order_list .order_row.' + type, $dialog.getDomElement()).each(function (i, n) {
elements_ids.push((0, _jquery2.default)(n).attr('elementids'));
});
break;
default:
//selected elements;
(0, _jquery2.default)('.order_list .order_row.' + type, $dialog.getDomElement()).each(function (i, n) {
elements_ids.push((0, _jquery2.default)(n).attr('elementids'));
});
}
(0, _jquery2.default)('textarea[name="description"]', orderDialog).val(description);
(0, _jquery2.default)('input[name="lst"]', orderDialog).val(elements_ids.join('; '));
}
function openValidationDialog(el, event) {
var submitTitle = window.orderItemData.translatedText.submit;
var resetTitle = window.orderItemData.translatedText.reset;
var dialog_buttons = {};
dialog_buttons[submitTitle] = function () {
//submit documents
submitDocuments((0, _jquery2.default)(this));
};
dialog_buttons[resetTitle] = function () {
if (confirm(window.orderItemData.translatedText.message)) {
resetAllItemForValidation();
toggleValidationButton();
(0, _jquery2.default)(this).dialog('close');
}
};
(0, _jquery2.default)('#validation-window').dialog({
open: function open(event, ui) {
(0, _jquery2.default)('.ui-dialog').css('z-index', 100000);
(0, _jquery2.default)('.ui-widget-overlay').css('z-index', 100000);
},
closeOnEscape: true,
resizable: false,
width: 450,
height: 500,
modal: true,
draggable: false,
stack: false,
title: window.orderItemData.translatedText.validation,
buttons: dialog_buttons,
overlay: {
backgroundColor: '#000',
opacity: 0.7
}
}).dialog('open');
createValidationTable();
}
function submitDocuments(dialogElem) {
var order_id = (0, _jquery2.default)('input[name=order_id]').val();
var validatedArrayNoForceIds = _underscore2.default.filter(elementsForValidation, function (elem) {
return elem.newState === ELEMENT_TYPE.VALIDATED && elem.oldState !== ELEMENT_TYPE.DENIED;
}).map(function (elem) {
return elem.elementId;
});
var validatedArrayWithForceIds = _underscore2.default.filter(elementsForValidation, function (elem) {
return elem.newState === ELEMENT_TYPE.VALIDATED && elem.oldState === ELEMENT_TYPE.DENIED;
}).map(function (elem) {
return elem.elementId;
});
var deniedArrayIds = _underscore2.default.filter(elementsForValidation, function (elem) {
return elem.newState === ELEMENT_TYPE.DENIED;
}).map(function (elem) {
return elem.elementId;
});
if (validatedArrayNoForceIds.length > 0) {
do_send_documents(order_id, validatedArrayNoForceIds, false);
}
if (validatedArrayWithForceIds.length > 0) {
do_send_documents(order_id, validatedArrayWithForceIds, true);
}
if (deniedArrayIds.length > 0) {
do_deny_documents(order_id, deniedArrayIds);
}
dialogElem.dialog('close');
}
function createValidationTable() {
(0, _jquery2.default)('.validation-content').empty();
var validatedArray = _underscore2.default.filter(elementsForValidation, function (elem) {
return elem.newState === ELEMENT_TYPE.VALIDATED;
});
var deniedArray = _underscore2.default.filter(elementsForValidation, function (elem) {
return elem.newState === ELEMENT_TYPE.DENIED;
});
if (validatedArray.length > 0) {
var html = '';
html += '<h5>' + window.orderItemData.translatedText.youHaveValidated + ' ' + validatedArray.length + ' ' + window.orderItemData.translatedText.item + (validatedArray.length === 1 ? '' : 's') + '</h5>';
html += '<table class="validation-table">';
_underscore2.default.each(validatedArray, function (elem) {
html += '<tr>';
html += '<td width="25%" align="center">' + elem.elementPreview[0].outerHTML + '</td>';
html += '<td width="75%">' + elem.elementTitle[0].outerHTML + '</td>';
html += '</tr>';
});
html += '</table>';
(0, _jquery2.default)('.validation-content').append(html);
}
if (deniedArray.length > 0) {
var _html = '';
_html += '<h5>' + window.orderItemData.translatedText.youHaveDenied + ' ' + deniedArray.length + ' ' + window.orderItemData.translatedText.item + (deniedArray.length === 1 ? '' : 's') + '</h5>';
_html += '<table class="validation-table">';
_underscore2.default.each(deniedArray, function (elem) {
_html += '<tr>';
_html += '<td width="25%" align="center">' + elem.elementPreview[0].outerHTML + '</td>';
_html += '<td width="75%">' + elem.elementTitle[0].outerHTML + '</td>';
_html += '</tr>';
});
_html += '</table>';
(0, _jquery2.default)('.validation-content').append(_html);
}
}
function removeItemFromArray(item) {
var elementId = item.find('input[name=order_element_id]').val();
var found = _underscore2.default.where(elementsForValidation, { elementId: elementId });
if (found.length > 0) {
item.removeClass(ELEMENT_TYPE.WAITINGFORVALIDATION);
//replace content or row with original content
item[0].innerHTML = found[0].element[0].innerHTML;
//remove from array
elementsForValidation = _underscore2.default.without(elementsForValidation, found[0]);
}
}
function resetItemForValidation(itemsToBeReset) {
var elementArrayType = [];
itemsToBeReset.forEach(function (item) {
removeItemFromArray(item);
updateButtonStatus(item.attr('class').split(/\s+/));
elementArrayType.push(item.attr('class').split(/\s+/));
});
if (elementsForValidation.length == 0) {
readyForValidation = false;
}
updateButtonStatusMultiple(elementArrayType);
toggleValidationButton();
//disable select all checkbox if selected
if ((0, _jquery2.default)('input[name="select-all"]').is(':checked')) {
(0, _jquery2.default)('input[name="select-all"]').prop('checked', false);
}
}
function resetAllItemForValidation() {
//var dialog = p4.Dialog.get(1);
(0, _jquery2.default)('.order_list .order_row', $dialog.getDomElement()).each(function (i, n) {
removeItemFromArray((0, _jquery2.default)(n));
updateButtonStatus((0, _jquery2.default)(n).attr('class').split(/\s+/));
});
readyForValidation = false;
renderOrderDetailView(0);
}
function updateValidation(newState) {
var count = 0;
(0, _jquery2.default)('.order_list .order_row', $dialog.getDomElement()).each(function (i, n) {
if ((0, _jquery2.default)(n).hasClass(ELEMENT_TYPE.SELECTED) && !(0, _jquery2.default)(n).hasClass(ELEMENT_TYPE.VALIDATED) && !(0, _jquery2.default)(n).hasClass(ELEMENT_TYPE.DENIED) && !(0, _jquery2.default)(n).hasClass(ELEMENT_TYPE.WAITINGFORVALIDATION)) {
createItemForValidation((0, _jquery2.default)(n), ELEMENT_TYPE.SELECTABLE, newState);
count++;
} else if ((0, _jquery2.default)(n).hasClass(ELEMENT_TYPE.SELECTED) && !(0, _jquery2.default)(n).hasClass(ELEMENT_TYPE.VALIDATED) && !(0, _jquery2.default)(n).hasClass(ELEMENT_TYPE.WAITINGFORVALIDATION)) {
createItemForValidation((0, _jquery2.default)(n), ELEMENT_TYPE.DENIED, newState);
count++;
}
(0, _jquery2.default)(n).removeClass(ELEMENT_TYPE.SELECTED);
});
//if item is not selected, delete item being previewed
if (count == 0 && lastItemChosen) {
createItemForValidation(lastItemChosen, ELEMENT_TYPE.SELECTABLE, newState);
count++;
}
readyForValidation = true;
toggleValidationButton();
//disable select all checkbox if selected
if ((0, _jquery2.default)('input[name="select-all"]').is(':checked')) {
(0, _jquery2.default)('input[name="select-all"]').prop('checked', false);
}
//multiple items selected
if (count > 1) {
(0, _jquery2.default)('#wrapper-padding').hide();
(0, _jquery2.default)('.external-order-action').hide();
(0, _jquery2.default)('#wrapper-multiple').hide();
(0, _jquery2.default)('#wrapper-no-item').show();
}
}
function createItemForValidation(element, oldState, newState) {
var order = {};
order.elementTitle = element.find('span');
order.elementPreview = element.find('.order_wrapper');
order.elementId = element.find('input[name=order_element_id]').val();
order.element = element.clone(true);
order.oldState = oldState;
order.newState = newState;
elementsForValidation.push(order);
//element.removeClass('to_be_denied');
//element.removeClass('to_be_validated');
element.toggleClass(ELEMENT_TYPE.WAITINGFORVALIDATION);
//element.addClass('to_be_'+order.newState);
element.find('td:first-child').empty();
element.find('td:first-child').append('<img style="cursor:help;" src="/assets/common/images/icons/to_be_' + order.newState + '.svg" title="">');
updateButtonStatus(element.attr('class').split(/\s+/));
}
function toggleValidationButton() {
if (readyForValidation) {
(0, _jquery2.default)('button.validate').prop('disabled', false);
(0, _jquery2.default)('button.validate').css('color', '#7CD21C');
} else {
(0, _jquery2.default)('button.validate').prop('disabled', true);
(0, _jquery2.default)('button.validate').css('color', '#737373');
}
}
function do_send_documents(order_id, elements_ids, force) {
var cont = $dialog.getDomElement();
(0, _jquery2.default)('button.deny, button.send', cont).prop('disabled', true);
(0, _jquery2.default)('.activity_indicator', cont).show();
_jquery2.default.ajax({
type: 'POST',
url: '../prod/order/' + order_id + '/send/',
dataType: 'json',
data: {
'elements[]': elements_ids,
force: force ? 1 : 0
},
success: function success(data) {
var success = '0';
if (data.success) {
success = '1';
}
var url = '../prod/order/' + order_id + '/?success=' + success + '&action=send';
reloadDialog(url);
},
error: function error() {
(0, _jquery2.default)('button.deny, button.send', cont).prop('disabled', false);
(0, _jquery2.default)('.activity_indicator', cont).hide();
},
timeout: function timeout() {
(0, _jquery2.default)('button.deny, button.send', cont).prop('disabled', false);
(0, _jquery2.default)('.activity_indicator', cont).hide();
}
});
}
function do_deny_documents(order_id, elements_ids) {
var cont = $dialog.getDomElement();
(0, _jquery2.default)('button.deny, button.send', cont).prop('disabled', true);
(0, _jquery2.default)('.activity_indicator', cont).show();
_jquery2.default.ajax({
type: 'POST',
url: '../prod/order/' + order_id + '/deny/',
dataType: 'json',
data: {
'elements[]': elements_ids
},
success: function success(data) {
var success = '0';
if (data.success) {
success = '1';
}
var url = '../prod/order/' + order_id + '/?success=' + success + '&action=deny';
reloadDialog(url);
},
error: function error() {
(0, _jquery2.default)('button.deny, button.send', cont).prop('disabled', false);
(0, _jquery2.default)('.activity_indicator', cont).hide();
},
timeout: function timeout() {
(0, _jquery2.default)('button.deny, button.send', cont).prop('disabled', false);
(0, _jquery2.default)('.activity_indicator', cont).hide();
}
});
}
function renderOrderDetailView(countSelected) {
if (countSelected > 1) {
(0, _jquery2.default)('#wrapper-padding').hide();
(0, _jquery2.default)('.external-order-action').hide();
(0, _jquery2.default)('#wrapper-multiple').show();
(0, _jquery2.default)('#wrapper-no-item').hide();
var elementArrayType = [];
(0, _jquery2.default)('.order_list .selectable.selected', $dialog.getDomElement()).each(function (i, n) {
//elementArrayType = _.union(elementArrayType, $(n).attr('class').split(/\s+/));
elementArrayType.push((0, _jquery2.default)(n).attr('class').split(/\s+/));
});
updateButtonStatusMultiple(elementArrayType);
//updateButtonStatus(elementArrayType);
} else if (countSelected === 1) {
(0, _jquery2.default)('#wrapper-padding').show();
(0, _jquery2.default)('.external-order-action').show();
(0, _jquery2.default)('#wrapper-multiple').hide();
(0, _jquery2.default)('#wrapper-no-item').hide();
} else {
(0, _jquery2.default)('#wrapper-padding').hide();
(0, _jquery2.default)('.external-order-action').hide();
(0, _jquery2.default)('#wrapper-multiple').hide();
(0, _jquery2.default)('#wrapper-no-item').show();
}
(0, _jquery2.default)('#preview-layout-multiple .title').html(countSelected);
}
function updateButtonStatusMultiple(elementArrayType) {
(0, _jquery2.default)('#order-action button.deny, #order-action button.send').hide();
var countObj = elementArrayType.reduce(function (m, v) {
for (var k in m) {
if (~v.indexOf(k)) m[k]++;
}
return m;
}, { validated: 0, selectable: 0, waitingForValidation: 0 });
var html = '';
if (countObj.validated > 0) {
html += '<p>' + window.orderItemData.translatedText.itemsAlreadySent + ': ' + countObj.validated + '</p>';
}
if (countObj.waitingForValidation > 0) {
html += '<p>' + window.orderItemData.translatedText.itemsWaitingValidation + ': ' + countObj.waitingForValidation + '</p>';
}
//for the remaining items
var remaining = countObj.selectable - (countObj.validated + countObj.waitingForValidation);
if (remaining > 0) {
html += '<p>' + window.orderItemData.translatedText.nonSentItems + ': ' + remaining + '</p>';
(0, _jquery2.default)('#order-action button.deny, #order-action button.send').prop('disabled', false);
(0, _jquery2.default)('#order-action button.deny, #order-action button.send').show();
}
(0, _jquery2.default)('#wrapper-multiple #text-content').empty();
(0, _jquery2.default)('#wrapper-multiple #text-content').append(html);
}
/* *
* function to update status of send and deny button
* params - array of type for each button selected
*/
function updateButtonStatus(elementArrayType) {
if (_underscore2.default.contains(elementArrayType, ELEMENT_TYPE.VALIDATED)) {
(0, _jquery2.default)('#order-action button.deny, #order-action button.send, #order-action button.reset').hide();
(0, _jquery2.default)('#order-action span.action-text').html(window.orderItemData.translatedText.alreadyValidated + '<i class="fa fa-check" aria-hidden="true"></i>');
(0, _jquery2.default)('#order-action span.action-text').show();
} else if (_underscore2.default.contains(elementArrayType, ELEMENT_TYPE.WAITINGFORVALIDATION)) {
(0, _jquery2.default)('#order-action button.deny, #order-action button.send, #order-action span.action-text').hide();
(0, _jquery2.default)('#order-action button.reset').show();
//$('#order-action button.send').show();
//$('#order-action button.send').prop('disabled', true);
} else if (_underscore2.default.contains(elementArrayType, ELEMENT_TYPE.DENIED)) {
(0, _jquery2.default)('#order-action button.deny, #order-action button.reset').hide();
(0, _jquery2.default)('#order-action span.action-text').html('window.orderItemData.translatedText.refusedPreviously');
//$('#order-action button.send').prop('disabled', false);
(0, _jquery2.default)('#order-action button.send, #order-action span.action-text').show();
} else {
// $('#order-action button.send, #order-action button.deny').prop('disabled', false);
(0, _jquery2.default)('#order-action button.send, #order-action button.deny').show();
(0, _jquery2.default)('#order-action span.action-text, #order-action button.reset').hide();
}
}
function loadPreviewAndCaption(elem) {
(0, _jquery2.default)('#preview-layout').empty();
(0, _jquery2.default)('#caption-layout').empty();
updateButtonStatus(elem.attr('class').split(/\s+/));
var elementids = elem.attr('elementids').split('_');
var sbasId = elementids[0];
var recordId = elementids[1];
var prevAjax = _jquery2.default.ajax({
type: 'GET',
url: '../prod/records/record/' + sbasId + '/' + recordId + '/',
dataType: 'json',
success: function success(data) {
if (data.error) {
return;
}
(0, _jquery2.default)('#preview-layout').append(data.html_preview);
(0, _jquery2.default)('#caption-layout').append(data.desc);
}
});
}
function reloadDialog(url) {
var baseUrl = configService.get('baseUrl');
_jquery2.default.ajax({
type: 'GET',
url: '' + baseUrl + url,
success: function success(data) {
if (data.error) {
return;
}
$dialog.setContent(data);
_onOrderItemReady($dialog);
}
});
}
};
return {
openModal: openModal
};
};
exports.default = orderItem;
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
var _emitter = __webpack_require__(15);
var _emitter2 = _interopRequireDefault(_emitter);
var _mapbox = __webpack_require__(50);
var _mapbox2 = _interopRequireDefault(_mapbox);
var _pym = __webpack_require__(17);
var _pym2 = _interopRequireDefault(_pym);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(197);
var image_enhancer = __webpack_require__(198);
__webpack_require__(14);
var previewRecordService = function previewRecordService(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var recordPreviewEvents = new _emitter2.default();
var $bodyContainer = null;
var $previewContainer = null;
var $previewTabContainer = void 0;
var prevAjax = void 0;
var prevAjaxrunning = void 0;
var activeThumbnailFrame = false;
prevAjaxrunning = false;
var stream = new Rx.Subject();
var options = {
open: false,
current: false,
slideShow: false,
navigation: {
perPage: 0,
page: 0
}
};
stream.onNext(options);
var initialize = function initialize() {
$bodyContainer = (0, _jquery2.default)('body');
$previewContainer = (0, _jquery2.default)('#PREVIEWBOX');
$previewTabContainer = (0, _jquery2.default)('#PREVIEWIMGDESC');
$previewTabContainer.tabs({
activate: function activate(event, ui) {
recordPreviewEvents.emit('tabChange');
}
});
// if contained in record editor (p4.edit.editBox):
(0, _jquery2.default)('#PREVIEWBOX .gui_vsplitter').draggable({
axis: 'x',
containment: 'parent',
drag: function drag(event, ui) {
var x = (0, _jquery2.default)(ui.position.left)[0];
if (x < 330 || x > window.bodySize.x - 400) {
return false;
}
var v = (0, _jquery2.default)(ui.position.left)[0];
(0, _jquery2.default)('#PREVIEWLEFT').width(v);
(0, _jquery2.default)('#PREVIEWRIGHT').css('left', (0, _jquery2.default)(ui.position.left)[0]);
resizePreview();
}
});
(0, _mapbox2.default)({
configService: configService,
localeService: localeService,
eventEmitter: recordPreviewEvents
}).initialize({
$container: $previewContainer,
parentOptions: options,
searchable: true,
tabOptions: {
/*tabProperties: {
classes: 'descBoxes',
},*/
position: 3
}
});
_bindEvents();
};
var _bindEvents = function _bindEvents() {
$bodyContainer.on('click', '.close-preview-action', function (event) {
event.preventDefault();
closePreview();
}).on('dblclick', '.open-preview-action', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
// env, pos, contId, reload
var reload = $el.data('reload') === true ? true : false;
_openPreview(event.currentTarget, $el.data('kind'), $el.data('position'), $el.data('id'), $el.data('kind'));
}).on('click', '.to-open-preview-action', function (event) {
event.preventDefault();
(0, _jquery2.default)('.open-preview-action').trigger("dblclick");
});
$previewContainer.on('click', '.preview-navigate-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var dir = $el.data('direction') === 'forward' ? getNext() : getPrevious();
}).on('click', '.preview-start-slideshow-action', function (event) {
event.preventDefault();
startSlide();
}).on('click', '.preview-stop-slideshow-action', function (event) {
event.preventDefault();
stopSlide();
}).on('click', '.edit-record-action', function (event) {
if (activeThumbnailFrame !== false) {
// tell child iframe to pause:
activeThumbnailFrame.sendMessage('pause', 'ok');
}
event.preventDefault();
});
};
/**
* Handle global keydown event if preview is open
* @param event
*/
var onGlobalKeydown = function onGlobalKeydown(event, specialKeyState) {
if (specialKeyState === undefined) {
var _specialKeyState = {
isCancelKey: false,
isShortcutKey: false
};
}
if (options.open) {
if ((0, _jquery2.default)('#dialog_dwnl:visible').length === 0 && (0, _jquery2.default)('#DIALOG1').length === 0 && (0, _jquery2.default)('#DIALOG2').length === 0) {
switch (event.keyCode) {
// next
case 39:
getNext();
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
// previous
case 37:
getPrevious();
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
break;
case 27:
//escape
closePreview();
break;
case 32:
var videoElement = (0, _jquery2.default)('#PREVIEWIMGCONT iframe').contents().find('video');
if (videoElement.length > 0) {
if (videoElement.get(0).paused == true) {
videoElement.get(0).play();
} else {
videoElement.get(0).pause();
}
specialKeyState.isCancelKey = specialKeyState.isShortcutKey = true;
}
break;
default:
}
}
}
return specialKeyState;
};
/**
*
* @param env
* @param pos - relative position in current page
* @param contId
* @param reload
*/
function _openPreview(event, env, pos, contId, reload) {
if (contId === undefined) {
contId = '';
}
var roll = 0;
var justOpen = false;
var options_serial = options.navigation.tot_options;
var query = options.navigation.tot_query;
var navigationContext = '';
// keep relative position for answer train:
var relativePos = pos;
var absolutePos = 0;
if (!options.open) {
(0, _jquery2.default)('#PREVIEWIMGCONT').disableSelection();
justOpen = true;
if (!navigator.userAgent.match(/msie/i)) {
(0, _jquery2.default)('#PREVIEWBOX').css({
display: 'block',
opacity: 0
}).fadeTo(500, 1);
} else {
(0, _jquery2.default)('#PREVIEWBOX').css({
display: 'block',
opacity: 1
});
}
options.open = true;
options.nCurrent = 5;
(0, _jquery2.default)('#PREVIEWCURRENT, #PREVIEWOTHERSINNER, #SPANTITLE').empty();
resizePreview();
if (env === 'BASK') {
roll = 1;
}
// if comes from story and in workzone
if (env === 'REG') {
navigationContext = 'storyFromResults';
var $source = (0, _jquery2.default)(event);
if ($source.hasClass('CHIM')) {
navigationContext = 'storyFromWorkzone';
}
}
}
if (reload === true) {
roll = 1;
}
(0, _jquery2.default)('#tooltip').css({
display: 'none'
});
(0, _jquery2.default)('#PREVIEWIMGCONT').empty();
if (navigationContext === 'storyFromWorkzone') {
// if event comes from workzone, set to relative position (CHIM == chutier image)
absolutePos = relativePos;
} else if (navigationContext === 'storyFromResults') {
absolutePos = 0;
} else {
// update real absolute position with pagination for records:
absolutePos = parseInt(options.navigation.perPage, 10) * (parseInt(options.navigation.page, 10) - 1) + parseInt(pos, 10);
}
var posAsk = null;
prevAjax = _jquery2.default.ajax({
type: 'POST',
url: url + 'prod/records/',
dataType: 'json',
data: {
env: env,
pos: absolutePos,
cont: contId,
roll: roll,
options_serial: options_serial,
query: query
},
beforeSend: function beforeSend() {
if (prevAjaxrunning) {
prevAjax.abort();
}
if (env === 'RESULT') {
(0, _jquery2.default)('#current_result_n').empty().append(parseInt(pos, 10) + 1);
}
prevAjaxrunning = true;
(0, _jquery2.default)('#PREVIEWIMGDESC, #PREVIEWOTHERS').addClass('loading');
},
error: function error(data) {
prevAjaxrunning = false;
(0, _jquery2.default)('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
},
timeout: function timeout() {
prevAjaxrunning = false;
(0, _jquery2.default)('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
},
success: function success(data) {
_cancelPreview();
prevAjaxrunning = false;
if (data.error) {
(0, _jquery2.default)('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
alert(data.error);
if (justOpen) {
closePreview();
}
return;
}
posAsk = data.pos - 1;
// transform default embed ID in order to avoid conflicts:
var customId = 'phraseanet-embed-preview-frame';
var $template = (0, _jquery2.default)(data.html_preview);
$template.find('#phraseanet-embed-frame').attr('id', customId);
(0, _jquery2.default)('#PREVIEWIMGCONT').empty().append($template.get(0));
if ((0, _jquery2.default)('#' + customId).length > 0) {
activeThumbnailFrame = new _pym2.default.Parent(customId, data.record.preview.url);
activeThumbnailFrame.iframe.setAttribute('allowfullscreen', '');
//set height of iframe to 100%
// activeThumbnailFrame.iframe.setAttribute(
// 'height',
// '100%'
// );
/*
// warning - if listening events/sendings events,
// pym instances should be destroyed when preview is closed
activeThumbnailFrame.onMessage('childReady', (child) => {
activeThumbnailFrame.sendMessage('parentReady', 'handshake');
});*/
}
(0, _jquery2.default)('#PREVIEWIMGCONT .thumb_wrapper').width('100%').height('100%').image_enhance({ zoomable: true });
resizeVideoPreview();
(0, _jquery2.default)('#PREVIEWIMGDESCINNER').empty().append(data.desc);
(0, _jquery2.default)('#HISTORICOPS').empty().append(data.history);
(0, _jquery2.default)('#popularity').empty().append(data.popularity);
if ((0, _jquery2.default)('#popularity .bitly_link').length > 0) {
if (window.BitlyCB !== undefined && window.BitlyClient !== undefined) {
window.BitlyCB.statsResponse = function (data) {
var result = data.results;
if ((0, _jquery2.default)('#popularity .bitly_link_' + result.userHash).length > 0) {
(0, _jquery2.default)('#popularity .bitly_link_' + result.userHash).append(' (' + result.clicks + ' clicks)');
}
};
window.BitlyClient.stats((0, _jquery2.default)('#popularity .bitly_link').html(), 'BitlyCB.statsResponse');
}
}
options.current = {};
options.current.width = parseInt((0, _jquery2.default)('#PREVIEWIMGCONT .thumb_wrapper').children().attr('data-original-width'), 10);
options.current.height = parseInt((0, _jquery2.default)('#PREVIEWIMGCONT .thumb_wrapper').children().attr('data-original-height'), 10);
options.current.tot = data.tot;
options.current.pos = relativePos;
options.current.captions = data.recordCaptions;
recordPreviewEvents.emit('recordSelection.changed', {
selection: [data.recordCaptions]
});
if ((0, _jquery2.default)('#PREVIEWBOX img.record.zoomable').length > 0) {
(0, _jquery2.default)('#PREVIEWBOX img.record.zoomable').draggable();
}
(0, _jquery2.default)('#SPANTITLE').empty().append(data.title);
(0, _jquery2.default)('#PREVIEWTITLE_COLLLOGO').empty().append(data.collection_logo);
(0, _jquery2.default)('#PREVIEWTITLE_COLLNAME').empty().append(data.databox_name + ' / ' + data.collection_name);
_setPreview();
if (env !== 'RESULT') {
if (justOpen || reload) {
_setCurrent(data.current);
}
_viewCurrent((0, _jquery2.default)('#PREVIEWCURRENT li.selected'));
} else {
if (!justOpen) {
(0, _jquery2.default)('#PREVIEWCURRENT li.selected').removeClass('selected');
(0, _jquery2.default)('#PREVIEWCURRENTCONT li.current' + absolutePos).addClass('selected');
}
if (justOpen || (0, _jquery2.default)('#PREVIEWCURRENTCONT li.current' + absolutePos).length === 0 || (0, _jquery2.default)('#PREVIEWCURRENTCONT li:last')[0] === (0, _jquery2.default)('#PREVIEWCURRENTCONT li.selected')[0] || (0, _jquery2.default)('#PREVIEWCURRENTCONT li:first')[0] === (0, _jquery2.default)('#PREVIEWCURRENTCONT li.selected')[0]) {
_getAnswerTrain(pos, data.tools, query, options_serial);
}
_viewCurrent((0, _jquery2.default)('#PREVIEWCURRENT li.selected'));
}
if (env === 'REG' && (0, _jquery2.default)('#PREVIEWCURRENT').html() === '') {
_getRegTrain(contId, pos, data.tools);
}
_setOthers(data.others);
_setTools(data.tools);
(0, _jquery2.default)('#tooltip').css({
display: 'none'
});
(0, _jquery2.default)('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
if (!justOpen || options.mode !== env) {
resizePreview();
}
options.mode = env;
(0, _jquery2.default)('#EDIT_query').focus();
(0, _jquery2.default)('#PREVIEWOTHERSINNER .otherBaskToolTip').tooltip();
stream.onNext(options);
return;
}
});
}
function resizeVideoPreview() {
var $sel = (0, _jquery2.default)('#phraseanet-embed-preview-frame.videoTips');
// V is for "video" ; K is for "container" ; N is for "new"
var VW = $sel.data('originalWidth');
var VH = $sel.data('originalHeight');
var KW = $sel.width();
var KH = $sel.height();
var NW, NH;
if ((NH = VH / VW * (NW = KW)) > KH) {
// try to fit exact horizontally, adjust vertically
// too bad... new height overflows container height
NW = VW / VH * (NH = KH); // so fit exact vertically, adjust horizontally
}
(0, _jquery2.default)("iframe", $sel).css('width', NW).css('height', NH);
}
function closePreview() {
options.open = false;
if (activeThumbnailFrame !== false) {
// tell child iframe to shutdown:
activeThumbnailFrame.sendMessage('dispose', 'ok');
activeThumbnailFrame = false;
}
stream.onNext(options);
(0, _jquery2.default)('#PREVIEWBOX').fadeTo(500, 0);
(0, _jquery2.default)('#PREVIEWBOX').queue(function () {
(0, _jquery2.default)(this).css({
display: 'none'
});
_cancelPreview();
(0, _jquery2.default)(this).dequeue();
});
}
function startSlide() {
if (!options.slideShow) {
options.slideShow = true;
}
if (options.slideShowCancel) {
options.slideShowCancel = false;
options.slideShow = false;
(0, _jquery2.default)('#start_slide').show();
(0, _jquery2.default)('#stop_slide').hide();
}
if (!options.open) {
options.slideShowCancel = false;
options.slideShow = false;
(0, _jquery2.default)('#start_slide').show();
(0, _jquery2.default)('#stop_slide').hide();
}
if (options.slideShow) {
(0, _jquery2.default)('#start_slide').hide();
(0, _jquery2.default)('#stop_slide').show();
getNext();
setTimeout(function () {
return startSlide();
}, configService.get('previewSlideshow.duration'));
}
}
function stopSlide() {
options.slideShowCancel = true;
(0, _jquery2.default)('#start_slide').show();
(0, _jquery2.default)('#stop_slide').hide();
}
function getNext() {
if (options.mode === 'REG' && parseInt(options.current.pos, 10) === 0) {
(0, _jquery2.default)('#PREVIEWCURRENTCONT li img:first').trigger('click');
} else {
if (options.mode === 'RESULT') {
var posAsk = parseInt(options.current.pos, 10) + 1;
posAsk = posAsk >= parseInt(options.navigation.tot, 10) || isNaN(posAsk) ? 0 : posAsk;
_openPreview(false, 'RESULT', posAsk, '', false);
} else {
if (!(0, _jquery2.default)('#PREVIEWCURRENT li.selected').is(':last-child')) {
(0, _jquery2.default)('#PREVIEWCURRENT li.selected').next().children('img').trigger('click');
} else {
(0, _jquery2.default)('#PREVIEWCURRENT li:first-child').children('img').trigger('click');
}
}
}
}
function getPrevious() {
if (options.mode === 'RESULT') {
var posAsk = parseInt(options.current.pos, 10) - 1;
if (options.navigation.page === 1) {
// may go to last result
posAsk = posAsk < 0 ? parseInt(options.navigation.tot, 10) - 1 : posAsk;
}
_openPreview(false, 'RESULT', posAsk, '', false);
} else {
if (!(0, _jquery2.default)('#PREVIEWCURRENT li.selected').is(':first-child')) {
(0, _jquery2.default)('#PREVIEWCURRENT li.selected').prev().children('img').trigger('click');
} else {
(0, _jquery2.default)('#PREVIEWCURRENT li:last-child').children('img').trigger('click');
}
}
}
function _setPreview() {
if (!options.current) {
return;
}
var zoomable = (0, _jquery2.default)('img.record.zoomable');
if (zoomable.length > 0 && zoomable.hasClass('zoomed')) {
return;
}
var h = parseInt(options.current.height, 10);
var w = parseInt(options.current.width, 10);
var t = 20;
var de = 0;
var margX = 0;
var margY = 0;
if ((0, _jquery2.default)('#PREVIEWIMGCONT .record_audio').length > 0) {
margY = 100;
de = 60;
}
var ratioP = w / h;
var ratioD = parseInt(options.width, 10) / parseInt(options.height, 10);
if (ratioD > ratioP) {
//je regle la hauteur d'abord
if (parseInt(h, 10) + margY > parseInt(options.height, 10)) {
h = Math.round(parseInt(options.height, 10) - margY);
w = Math.round(h * ratioP);
}
} else {
if (parseInt(w, 10) + margX > parseInt(options.width, 10)) {
w = Math.round(parseInt(options.width, 10) - margX);
h = Math.round(w / ratioP);
}
}
t = Math.round((parseInt(options.height, 10) - h - de) / 2);
var l = Math.round((parseInt(options.width, 10) - w) / 2);
(0, _jquery2.default)('#PREVIEWIMGCONT .record').css({
width: w,
height: h,
top: t,
left: l
}).attr('width', w).attr('height', h);
}
function _setCurrent(current) {
if (current !== '') {
var el = (0, _jquery2.default)('#PREVIEWCURRENT');
el.removeClass('loading').empty().append(current);
(0, _jquery2.default)('ul', el).width((0, _jquery2.default)('li', el).length * 80);
(0, _jquery2.default)('img.prevRegToolTip', el).tooltip();
_jquery2.default.each((0, _jquery2.default)('img.openPreview'), function (i, el) {
var jsopt = (0, _jquery2.default)(el).attr('jsargs').split('|');
(0, _jquery2.default)(el).removeAttr('jsargs');
(0, _jquery2.default)(el).removeClass('openPreview');
(0, _jquery2.default)(el).bind('click', function () {
_viewCurrent((0, _jquery2.default)(this).parent());
// convert abssolute to relative position
var absolutePos = jsopt[1];
var relativePos = parseInt(absolutePos, 10) - parseInt(options.navigation.perPage, 10) * (parseInt(options.navigation.page, 10) - 1);
// keep relative position for answer train:
_openPreview(this, jsopt[0], relativePos, jsopt[2], false);
});
});
}
}
function _viewCurrent(el) {
if (el.length === 0) {
return;
}
(0, _jquery2.default)('#PREVIEWCURRENT li.selected').removeClass('selected');
el.addClass('selected');
(0, _jquery2.default)('#PREVIEWCURRENTCONT').animate({
scrollLeft: (0, _jquery2.default)('#PREVIEWCURRENT li.selected').position().left + (0, _jquery2.default)('#PREVIEWCURRENT li.selected').width() / 2 - (0, _jquery2.default)('#PREVIEWCURRENTCONT').width() / 2
});
return;
}
function reloadPreview() {
(0, _jquery2.default)('#PREVIEWCURRENT li.selected img').trigger('click');
}
function _getAnswerTrain(pos, tools, query, options_serial) {
// keep relative position for answer train:
var relativePos = pos;
// update real absolute position with pagination:
var absolutePos = parseInt(options.navigation.perPage, 10) * (parseInt(options.navigation.page, 10) - 1) + parseInt(pos, 10);
(0, _jquery2.default)('#PREVIEWCURRENTCONT').fadeOut('fast');
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/query/answer-train/',
dataType: 'json',
data: {
pos: absolutePos,
options_serial: options_serial,
query: query
},
success: function success(data) {
_setCurrent(data.current);
_viewCurrent((0, _jquery2.default)('#PREVIEWCURRENT li.selected'));
_setTools(tools);
return;
}
});
}
function _getRegTrain(contId, pos, tools) {
_jquery2.default.ajax({
type: 'POST',
url: url + 'prod/query/reg-train/',
dataType: 'json',
data: {
cont: contId,
pos: pos
},
success: function success(data) {
_setCurrent(data.current);
_viewCurrent((0, _jquery2.default)('#PREVIEWCURRENT li.selected'));
if (typeof tools !== 'undefined') {
_setTools(tools);
}
return;
}
});
}
function _cancelPreview() {
(0, _jquery2.default)('#PREVIEWIMGDESCINNER').empty();
(0, _jquery2.default)('#PREVIEWIMGCONT').empty();
options.current = false;
}
function _setOthers(others) {
(0, _jquery2.default)('#PREVIEWOTHERSINNER').empty();
if (others !== '') {
(0, _jquery2.default)('#PREVIEWOTHERSINNER').append(others);
(0, _jquery2.default)('#PREVIEWOTHERS table.otherRegToolTip').tooltip();
}
}
function _setTools(tools) {
(0, _jquery2.default)('#PREVIEWTOOL').empty().append(tools);
if (!options.slideShowCancel && options.slideShow) {
(0, _jquery2.default)('#start_slide').hide();
(0, _jquery2.default)('#stop_slide').show();
} else {
(0, _jquery2.default)('#start_slide').show();
(0, _jquery2.default)('#stop_slide').hide();
}
}
function resizePreview() {
options.height = (0, _jquery2.default)('#PREVIEWIMGCONT').height();
options.width = (0, _jquery2.default)('#PREVIEWIMGCONT').width();
resizeVideoPreview();
_setPreview();
}
var shouldResize = function shouldResize() {
if (options.open) {
resizePreview();
}
};
var shouldReload = function shouldReload() {
if (options.open) {
reloadPreview();
}
};
var onNavigationChanged = function onNavigationChanged() {
var navigation = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
options.navigation = (0, _lodash2.default)(options.navigation, navigation);
};
var appendTab = function appendTab(params) {
var tabProperties = params.tabProperties,
position = params.position;
var $appendAfterTab = (0, _jquery2.default)('ul li:eq(' + (position - 1) + ')', $previewTabContainer);
var newTab = '<li><a href="#' + tabProperties.id + '">' + tabProperties.title + '</a></li>';
$appendAfterTab.after(newTab);
var appendAfterTabContent = (0, _jquery2.default)(' > div:eq(' + (position - 1) + ')', $previewTabContainer);
appendAfterTabContent.after('<div id="' + tabProperties.id + '" class="' + tabProperties.classes + '"></div>');
try {
$previewTabContainer.tabs('refresh');
} catch (e) {}
recordPreviewEvents.emit('appendTab.complete', {
origParams: params,
selection: []
});
};
appEvents.listenAll({
'broadcast.searchResultNavigation': onNavigationChanged,
'preview.doResize': shouldResize,
'preview.doReload': shouldReload,
'preview.close': closePreview
});
recordPreviewEvents.listenAll({
/* eslint-disable quote-props */
appendTab: appendTab
});
return {
initialize: initialize,
onGlobalKeydown: onGlobalKeydown,
getPreviewStream: function getPreviewStream() {
return stream;
},
//_openPreview,
startSlide: startSlide,
stopSlide: stopSlide,
getNext: getNext,
getPrevious: getPrevious,
reloadPreview: reloadPreview,
resizePreview: resizePreview
};
};
exports.default = previewRecordService;
/***/ }),
/* 197 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
/*** IMPORTS FROM imports-loader ***/
var $ = __webpack_require__(0);
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(199);
(function ($) {
var methods = {
init: function init(options) {
var settings = {
zoomable: false,
display_full_screen: false
};
return this.each(function () {
var $this = $(this);
var data = $(this).data('image_enhance');
if (!data) {
if (options) {
$.extend(settings, options);
}
var wrapper = $('.thumb_wrapper', $(this));
var $image = $('img', $this);
var image_width = parseInt($('input[name="width"]', $this).val(), 10);
var image_height = parseInt($('input[name="height"]', $this).val(), 10);
var ratio = image_width / image_height;
wrapper.css('position', 'relative');
reset_position($this);
if (settings.display_full_screen) {
$image.parent().append('<div class="image_enhance_titlebar" style="display:none;">\n\
<div class="image_enhance_title_options"><span class="full"><img src="/assets/common/images/icons/fullscreen.gif" /></span></div>\n\
<div class="image_enhance_title_bg"></div></div>');
var $titlebar = $('.image_enhance_titlebar', $this);
$('.image_enhance_title_bg', $titlebar).css('opacity', 0.5);
$image.parent().bind('mouseover.image_enhance', function () {
$titlebar.stop().show().animate({
height: 28
}, 150);
}).bind('mouseout.image_enhance', function () {
$titlebar.stop().animate({
height: 0
}, 150, function () {
$titlebar.hide();
});
});
$('.image_enhance_titlebar .full', wrapper).bind('click.image_enhance', function () {
$('body').append('<div class="image_enhance_theatre">\n\
\n\
<div class="image_enhance_theatre_closer_wrapper"><span class="closer">close</span></div>\n\
<img style="width:' + image_width + 'px;height:' + image_height + '" src="' + $image.attr('src') + '"/>\n\
</div>');
var $theatre = $('.image_enhance_theatre');
var $theatre_img = $('img', $theatre);
$(window).bind('resize.image_enhance dblclick.image_enhance', function (event) {
if (event.type === 'dblclick') {
$theatre_img.removeClass('zoomed');
} else {
if ($theatre_img.hasClass('zoomed')) {
return;
}
}
var datas = calculate_sizes($(this).width(), $(this).height(), image_width, image_height, 80);
$theatre_img.width(datas.width).height(datas.height).css('top', datas.top).css('left', datas.left);
});
$(window).trigger('resize.image_enhance');
$('.closer', $theatre).bind('click.image_enhance', function () {
$theatre.remove();
});
if (typeof $theatre.disableSelection !== 'function' && window.console) {
console.error('enhanced image require jquery UI\'s disableSelection');
}
$('img', $theatre).disableSelection();
});
}
if (settings.zoomable) {
if (typeof $image.draggable !== 'function' && window.console) {
console.error('zoomable require jquery UI\'s draggable');
}
if ($image.attr('ondragstart')) {
$image.removeAttr('ondragstart');
}
$image.draggable();
$image.css({
'max-width': 'none',
'max-height': 'none'
});
$this.bind('mousewheel', function (event, delta) {
$image.addClass('zoomed');
if (delta > 0) {
event.stopPropagation();
zoomPreview(true, ratio, $image, $(this));
} else {
event.stopPropagation();
zoomPreview(false, ratio, $image, $(this));
}
return false;
}).bind('dblclick', function (event) {
reset_position($this);
});
}
$(this).data('image_enhance', {
width: image_width,
height: image_height
});
}
});
},
destroy: function destroy() {
return this.each(function () {
$(this).data('image_enhance', null);
$('.image_enhance_titlebar, .image_enhance_theatre', this).remove();
});
}
};
function zoomPreview(bool, ratio, $img, $container) {
if ($img.length === 0) {
return;
}
var t1 = parseInt($img.css('top'), 10);
var l1 = parseInt($img.css('left'), 10);
var w1 = $img.width();
var h1 = $img.height();
var w2 = void 0;
if (bool) {
if (w1 * 1.08 < 32767) {
w2 = w1 * 1.08;
} else {
w2 = w1;
}
} else {
if (w1 / 1.08 > 20) {
w2 = w1 / 1.08;
} else {
w2 = w1;
}
}
var h2 = Math.round(w2 / ratio);
w2 = Math.round(w2);
var wPreview = $container.width() / 2;
var hPreview = $container.height() / 2;
var nt = Math.round(h2 / h1 * (t1 - hPreview) + hPreview);
var nl = Math.round(w2 / w1 * (l1 - wPreview) + wPreview);
$img.css({
left: nl,
top: nt
}).width(w2).height(h2);
}
function calculate_sizes(window_width, window_height, image_width, image_height, border) {
if (typeof border !== 'number') {
border = 0;
}
var width = void 0;
var height = void 0;
var ratio_display = window_width / window_height;
var ratio_image = image_width / image_height;
if (ratio_image > ratio_display) {
width = window_width - border;
height = Math.round(width / ratio_image);
} else {
height = window_height - border;
width = Math.round(height * ratio_image);
}
var top = Math.round((window_height - height) / 2);
var left = Math.round((window_width - width) / 2);
return {
top: top,
left: left,
width: width,
height: height
};
}
function reset_position($this) {
var display_width = $this.width();
var display_height = $this.height();
var image_width = parseInt($('input[name="width"]', $this).val(), 10);
var image_height = parseInt($('input[name="height"]', $this).val(), 10);
var datas = calculate_sizes(display_width, display_height, image_width, image_height);
var $image = $('img', $this);
var top = Math.round((display_height - datas.height) / 2) + 'px';
var left = Math.round((display_width - datas.width) / 2) + 'px';
$image.width(datas.width).height(datas.height).css({ top: top, left: left });
return;
}
$.fn.image_enhance = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if ((typeof method === 'undefined' ? 'undefined' : _typeof(method)) === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.image_enhance');
}
};
})(_jquery2.default);
/***/ }),
/* 199 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _ = _interopRequireWildcard(_underscore);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _alert = __webpack_require__(44);
var _alert2 = _interopRequireDefault(_alert);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
__webpack_require__(14);
var uploader = function uploader(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var UploaderManager = void 0;
var initialize = function initialize() {
dragOnModalClosed();
(0, _jquery2.default)('body').on('click', '.uploader-open-action', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(event.currentTarget);
__webpack_require__.e/* require.ensure */(2/* duplicate */).then((function () {
// load uploader manager dep
UploaderManager = __webpack_require__(88).default;
openModal($this, []);
}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
});
};
var dragOnModalClosed = function dragOnModalClosed() {
(0, _jquery2.default)('html').on('drop', function (event) {
if (event.originalEvent.dataTransfer !== undefined) {
var fileList = event.originalEvent.dataTransfer.files;
// open modal
if (fileList.length > 0) {
__webpack_require__.e/* require.ensure */(2/* duplicate */).then((function () {
// load uploader manager dep
UploaderManager = __webpack_require__(88).default;
openModal((0, _jquery2.default)('.uploader-open-action'), fileList);
}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
event.preventDefault();
event.stopPropagation();
return false;
}
}
}).on('dragover', function (event) {
event.preventDefault();
event.stopPropagation();
}).on('dragleave', function (event) {
event.preventDefault();
event.stopPropagation();
});
};
var disableDragOnModalClosed = function disableDragOnModalClosed() {
(0, _jquery2.default)('html').off('drop');
(0, _jquery2.default)('html').off('dragover');
(0, _jquery2.default)('html').off('dragleave');
};
var openModal = function openModal($this, filesList) {
var options = {
size: 'Full',
loading: true,
title: $this.attr('title'),
closeOnEscape: true,
closeCallback: function closeCallback() {
dragOnModalClosed();
}
};
var $dialog = _dialog2.default.create(services, options);
_jquery2.default.ajax({
type: 'GET',
url: $this.attr('href'),
dataType: 'html',
success: function success(data) {
disableDragOnModalClosed();
$dialog.setContent(data);
(0, _jquery2.default)(document).ready(function () {
return onOpenModal(filesList);
});
return;
}
});
};
var onOpenModal = function onOpenModal(filesList) {
// @TODO replace with feature detection:
var iev = 0;
var ieold = /MSIE (\d+\.\d+);/.test(navigator.userAgent);
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var rv = navigator.userAgent.indexOf('rv:11.0');
if (ieold) iev = new Number(RegExp.$1);
if (navigator.appVersion.indexOf('MSIE 10') !== -1) iev = 10;
if (trident && rv !== -1) iev = 11;
if (iev >= 10) {
(0, _jquery2.default)('#UPLOAD_FLASH_LINK').hide();
(0, _jquery2.default)('#upload_type option[value="flash"]').remove();
}
// Upload management
var uploaderInstance = new UploaderManager({
container: (0, _jquery2.default)('#uploadBox'),
uploadBox: (0, _jquery2.default)('#uploadBox .upload-box-addedfiles'),
settingsBox: (0, _jquery2.default)('#uploadBox .settings-box'),
downloadBox: (0, _jquery2.default)('#uploadBox .download-box')
});
var totalElement;
var maxFileSize = window.uploaderOptions.maxFileSize;
uploaderInstance.Preview.setOptions({
maxWidth: 130,
maxHeight: 120
});
(0, _jquery2.default)('#upload_type').on('change', function () {
if ((0, _jquery2.default)(this).val() === 'html') {
(0, _jquery2.default)("#UPLOAD_HTML5_LINK").trigger("click");
} else if ((0, _jquery2.default)(this).val() === 'flash') {
(0, _jquery2.default)("#UPLOAD_FLASH_LINK").trigger("click");
}
});
// Init jquery tabs
(0, _jquery2.default)('.upload-tabs', uploaderInstance.getContainer()).tabs({
beforeLoad: function beforeLoad(event, ui) {
ui.jqXHR.success(function (xhr, status, index, anchor) {
var lazaretBox = (0, _jquery2.default)('#lazaretBox');
(0, _jquery2.default)('.userTips', lazaretBox).tooltip();
});
ui.jqXHR.error(function (xhr, status, index, anchor) {
// display error message if ajax failed
(0, _jquery2.default)(anchor.hash).html(localeService.t('error'));
});
ui.tab.find('span').html(' <img src="/assets/common/images/icons/loader404040.gif"/>');
},
load: function load(event, ui) {
ui.tab.find('span').empty();
(0, _jquery2.default)('.btn.page-lazaret', uploaderInstance.getContainer()).bind('click', function () {
(0, _jquery2.default)('.lazaret-target').attr('href', (0, _jquery2.default)('a', (0, _jquery2.default)(this)).attr('href'));
(0, _jquery2.default)('.upload-tabs', uploaderInstance.getContainer()).tabs('load', 1);
(0, _jquery2.default)('#lazaretBox').empty();
return false;
});
},
create: function create() {
(0, _jquery2.default)('#tab-upload').css('overflow', 'hidden');
},
heightStyle: 'fill'
});
// Show the good collection status box
(0, _jquery2.default)('select[name="base_id"]', uploaderInstance.getSettingsBox()).bind('change', function () {
var selectedCollId = (0, _jquery2.default)(this).find('option:selected').val();
(0, _jquery2.default)('#uploadBox .settings-box .collection-status').hide();
(0, _jquery2.default)('#uploadBox #status-' + selectedCollId).show();
});
uploaderInstance.getContainer().on('file-added', function () {
(0, _jquery2.default)('.number-files').html(uploaderInstance.countData());
});
uploaderInstance.getContainer().on('file-removed', function () {
(0, _jquery2.default)('.number-files').html(uploaderInstance.countData());
});
uploaderInstance.getContainer().on('file-transmited', function () {
var domEl = (0, _jquery2.default)('.number-files-transmited');
domEl.html(parseInt(domEl.html(), 10) + 1);
});
uploaderInstance.getContainer().on('uploaded-file-removed', function () {
var domEl = (0, _jquery2.default)('.number-files-to-transmit');
domEl.html(parseInt(domEl.html(), 10) - 1);
});
// add a url
(0, _jquery2.default)('button.add-url', uploaderInstance.getContainer()).bind('click', function (e) {
e.preventDefault();
var url = (0, _jquery2.default)('#add-url', uploaderInstance.getContainer()).val();
(0, _jquery2.default)('.upload-box').show();
// perform a "head" request on the url (via php proxy) to get mime and size
var distantfileInfos = {
'content-type': '?',
'content-length': '?'
};
_jquery2.default.get('upload/head/', {
'url': url
}).done(function (data) {
distantfileInfos = data;
}).always(function () {
var fileContent = JSON.stringify({ 'url': url }, null, 2); // the content of the "micro json file" that will be uploaded
var blob = new Blob([fileContent], {
type: 'application/json'
});
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).fileupload('add', {
'files': blob, // files is an array with 1 element
'fileInfos': [distantfileInfos] // ... so we do the same with our custom data
});
});
});
// Remove all element from upload box
(0, _jquery2.default)('button.clear-queue', uploaderInstance.getContainer()).bind('click', function () {
uploaderInstance.clearUploadBox();
(0, _jquery2.default)('ul', (0, _jquery2.default)(this).closest('.upload-box')).empty();
uploaderInstance.getContainer().trigger('file-removed');
});
// Cancel all upload
(0, _jquery2.default)('#cancel-all').bind('click', function () {
//Remove all cancel
(0, _jquery2.default)('button.remove-element', uploaderInstance.getDownloadBox()).each(function (i, el) {
(0, _jquery2.default)(el).trigger('click');
});
progressbarAll.width('0%');
});
// Remove an element from the upload box
(0, _jquery2.default)(uploaderInstance.getUploadBox()).on('click', 'button.remove-element', function () {
var container = (0, _jquery2.default)(this).closest('li');
var uploadIndex = container.find('input[name=uploadIndex]').val();
uploaderInstance.removeData(uploadIndex);
container.remove();
uploaderInstance.getContainer().trigger('file-removed');
});
// Get all elements in the upload box & trigger the submit event
(0, _jquery2.default)('button.upload-submitter', uploaderInstance.getContainer()).bind('click', function () {
// Fetch all valid elements
var documents = uploaderInstance.getUploadBox().find('li.upload-valid');
totalElement = documents.length;
if (totalElement > 0) {
(0, _jquery2.default)('.number-files').html('');
(0, _jquery2.default)('.number-files-to-transmit').html(totalElement);
(0, _jquery2.default)('.transmit-box').show();
var $dialog = _dialog2.default.get(1);
// reset progressbar for iframe uploads
if (!_jquery2.default.support.xhrFileUpload && !_jquery2.default.support.xhrFormDataFileUpload) {
progressbarAll.width('0%');
}
// enabled cancel all button
(0, _jquery2.default)('#cancel-all').attr('disabled', false);
// prevent dialog box from being closed while files are being downloaded
$dialog.getDomElement().bind('dialogbeforeclose', function (event, ui) {
if (!uploaderInstance.Queue.isEmpty()) {
(0, _alert2.default)(localeService.t('warning'), localeService.t('fileBeingDownloaded'));
return false;
}
});
documents.each(function (index, el) {
var indexValue = (0, _jquery2.default)(el).find('input[name=uploadIndex]').val();
var data = uploaderInstance.getData(indexValue);
uploaderInstance.getData(indexValue).submit();
});
}
});
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).fileupload({
namespace: 'phrasea-upload',
// define our own mediatype to handle and convert the response
// to prevent errors when Iframe based uploads
// as they require text/plain or text/html Content-type
// see http://api.jquery.com/extending-ajax/#Converters
dataType: 'phrjson',
converters: {
'html phrjson': function htmlPhrjson(htmlEncodedJson) {
return _jquery2.default.parseJSON(htmlEncodedJson);
},
'iframe phrjson': function iframePhrjson(iframe) {
return _jquery2.default.parseJSON(iframe.find('body').text());
}
},
// override "on error" local ajax event to prevent global ajax event from being triggered
// as all fileupload options are passed as argument to the $.ajax jquery function
error: function error() {
return false;
},
// Set singleFileUploads, sequentialUploads to true so the files
// are upload one by one
singleFileUploads: true, // There will be ONE AND ONLY ONE file into data.files
sequentialUploads: true,
recalculateProgress: true,
// When a file is added
add: function add(e, data) {
// Since singleFileUploads & sequentialUploads are setted to true
// There is ONE AND ONLY ONE file into data.files
_jquery2.default.each(data.files, function (index, file) {
(0, _jquery2.default)('.upload-box').show();
var params = {};
var html = '';
if (file.error) {
params = _jquery2.default.extend({}, file, { error: localeService.t('errorFileApi') });
html = _.template((0, _jquery2.default)('#upload_items_error_tpl').html())(params);
uploaderInstance.getUploadBox().append(html);
} else if (file.size > maxFileSize) {
params = _jquery2.default.extend({}, file, { error: localeService.t('errorFileApiTooBig') });
html = _.template((0, _jquery2.default)('#upload_items_error_tpl').html())(params);
uploaderInstance.getUploadBox().append(html);
} else {
// Add data to Queue
uploaderInstance.addData(data);
// Check support of file.size && file.type property
var formatedFile = {
id: 'file-' + index,
size: typeof file.size !== 'undefined' ? uploaderInstance.Formater.size(file.size) : '',
name: encodeURI(file.name),
type: typeof file.type !== 'undefined' ? file.type : '',
uploadIndex: uploaderInstance.getUploadIndex()
};
// if the "file" is a blob (tiny json with url to a distant file),
// we can find infos of distant file into data, and fix html
if (typeof data.fileInfos !== 'undefined') {
formatedFile.size = uploaderInstance.Formater.size(data.fileInfos[index]['content-length']);
formatedFile.name = data.fileInfos[index]['basename'];
formatedFile.type = data.fileInfos[index]['content-type'];
}
// Set context in upload-box
html = _.template((0, _jquery2.default)('#upload_items_tpl').html())(formatedFile);
uploaderInstance.getUploadBox().append(html);
var context = (0, _jquery2.default)('li', uploaderInstance.getUploadBox()).last();
var uploadIndex = context.find('input[name=uploadIndex]').val();
uploaderInstance.addAttributeToData(uploadIndex, 'context', context);
uploaderInstance.Preview.render(file, function (img) {
context.find('.thumbnail .canva-wrapper').prepend(img);
uploaderInstance.addAttributeToData(uploadIndex, 'image', img);
});
}
});
uploaderInstance.getContainer().trigger('file-added');
},
submit: function submit(e, data) {
return false;
},
// on success upload
done: function done(e, data) {
// set progress bar to 100% for preventing mozilla bug which never reach 100%
data.context.find('.progress-bar').width('100%');
data.context.find('div.progress').removeClass('progress-striped active');
data.context.find('button.remove-element').removeClass('btn-inverse').addClass('disabled');
uploaderInstance.removeData(data.uploadIndex);
uploaderInstance.getContainer().trigger('file-transmited');
data.context.find('button.remove-element').remove();
if (!_jquery2.default.support.xhrFileUpload && !_jquery2.default.support.xhrFormDataFileUpload) {
progressbarAll.width(100 - Math.round(uploaderInstance.Queue.getLength() * (100 / totalElement)) + '%');
}
if (uploaderInstance.Queue.isEmpty()) {
progressbarAll.width('100%');
bitrateBox.empty();
(0, _jquery2.default)('#uploadBoxRight .progress').removeClass('progress-striped active');
var $dialog = _dialog2.default.get(1);
// unbind check before close event & disabled button for cancel all download
$dialog.getDomElement().unbind('dialogbeforeclose');
// disabled cancel-all button, if queue is empty and last upload success
(0, _jquery2.default)('#cancel-all').attr('disabled', true);
}
return false;
},
fail: function fail() {
// disabled cancel-all button, if queue is empty and last upload fail
if (uploaderInstance.Queue.isEmpty()) {
(0, _jquery2.default)('#cancel-all').attr('disabled', true);
}
}
});
// on submit file
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).bind('fileuploadsubmit', function (e, data) {
var $this = (0, _jquery2.default)(this);
var params = [];
data.formData = [];
// get form datas attached to the file
params.push(data.context.find('input, select').serializeArray());
params.push((0, _jquery2.default)('input', (0, _jquery2.default)('.collection-status:visible', uploaderInstance.getSettingsBox())).serializeArray());
params.push((0, _jquery2.default)('select', uploaderInstance.getSettingsBox()).serializeArray());
_jquery2.default.each(params, function (i, p) {
_jquery2.default.each(p, function (i, f) {
data.formData.push(f);
});
});
// remove current context
data.context.remove();
// Set new context in download-box
_jquery2.default.each(data.files, function (index, file) {
var params = _jquery2.default.extend({}, file, { id: 'file-' + index, name: encodeURI(file.name) });
// if the "file" is a blob (tiny json with url to a distant file),
// we can find infos of distant file into data, and fix html
if (typeof data.fileInfos !== 'undefined') {
params.name = data.fileInfos[index]['basename'];
}
var html = _.template((0, _jquery2.default)('#download_items_tpl').html())(params);
uploaderInstance.getDownloadBox().append(html);
data.context = (0, _jquery2.default)('li', uploaderInstance.getDownloadBox()).last();
// copy image
data.context.find('.upload-record .canva-wrapper').prepend(data.image);
// launch ajax request
var jqXHR = $this.fileupload('send', data).success(function (response) {
if (response.success) {
// case record
if (response.element === 'record') {
html = _.template((0, _jquery2.default)('#download_finish_tpl').html())({
heading: response.message,
reasons: response.reasons
});
data.context.find('.upload-record p.success').append(html).show();
} else {
// case quarantine
html = _.template((0, _jquery2.default)('#download_finish_tpl').html())({
heading: response.message,
reasons: response.reasons
});
data.context.find('.upload-record p.error').append(html).show();
}
} else {
// fail
html = _.template((0, _jquery2.default)('#download_finish_tpl').html())({
heading: response.message,
reasons: response.reasons
});
data.context.find('.upload-record p.error').append(html).show();
}
}).error(function (jqXHR, textStatus, errorThrown) {
// Request is aborted
if (errorThrown === 'abort') {
return false;
} else {
data.context.find('.upload-record p.error').append(jqXHR.status + ' ' + jqXHR.statusText).show();
}
// Remove data
uploaderInstance.removeData(data.uploadIndex);
// Remove cancel button
(0, _jquery2.default)('button.remove-element', data.context).remove();
});
// cancel request
(0, _jquery2.default)('button.remove-element', data.context).bind('click', function (e) {
jqXHR.abort();
data.context.remove();
uploaderInstance.getContainer().trigger('uploaded-file-removed');
});
});
return false;
});
var bitrateBox = (0, _jquery2.default)('#uploadBoxRight .bitrate-box');
// Get one file upload progress & bitrate
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).bind('fileuploadprogress', function (e, data) {
var progressbar = data.context.find('.progress-bar');
progressbar.width(Math.round(uploaderInstance.Formater.pourcent(data.loaded, data.total)) + '%');
bitrateBox.empty().append(uploaderInstance.Formater.bitrate(data.bitrate));
});
var progressbarAll = (0, _jquery2.default)('#uploadBoxRight .progress-bar-total');
// Get global upload progress
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).bind('fileuploadprogressall', function (e, data) {
progressbarAll.width(Math.round(uploaderInstance.Formater.pourcent(data.loaded, data.total)) + '%');
});
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).bind('fileuploadfail', function (e, data) {
// Remove from queue
uploaderInstance.removeData(data.uploadIndex);
});
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).bind('fileuploadsend', function (e, data) {
// IFRAME progress fix
if (!_jquery2.default.support.xhrFileUpload && !_jquery2.default.support.xhrFormDataFileUpload) {
data.context.find('.progress-bar').width('25%');
}
});
// if initialized with dropped files:
if (filesList !== undefined) {
(0, _jquery2.default)('#fileupload', uploaderInstance.getContainer()).fileupload('add', { files: filesList });
}
};
return { initialize: initialize };
};
exports.default = uploader;
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var defaultConfig = {
locale: 'fr',
basePath: '/',
translations: '/prod/language/',
previewSlideshow: {
duration: 4000
},
availableThemes: [{
name: '000000'
}, {
name: '959595'
}, {
name: 'FFFFFF'
}]
};
exports.default = defaultConfig;
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _ui = __webpack_require__(47);
var _ui2 = _interopRequireDefault(_ui);
var _notify = __webpack_require__(46);
var _notify2 = _interopRequireDefault(_notify);
var _phraseanetCommon = __webpack_require__(11);
var appCommons = _interopRequireWildcard(_phraseanetCommon);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var user = function user(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var initialize = function initialize() {};
var onUserDisconnect = function onUserDisconnect() {
// @TODO refactor - display modal in here
(0, _ui2.default)(services).showModal('disconnected', { title: localeService.t('serverDisconnected') });
};
appEvents.listenAll({
'user.disconnected': onUserDisconnect
});
var manageSession = function manageSession() {
for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
var data = params[0],
showMessages = params[1];
if (typeof showMessages === 'undefined') {
showMessages = false;
}
if (showMessages) {
// @todo: to be moved
if (_jquery2.default.trim(data.message) !== '') {
if ((0, _jquery2.default)('#MESSAGE').length === 0) {
(0, _jquery2.default)('body').append('<div id="#MESSAGE"></div>');
}
(0, _jquery2.default)('#MESSAGE').empty().append(data.message + '<div style="margin:20px;"><input type="checkbox" class="dialog_remove" />' + localeService.t('hideMessage') + '</div>').attr('title', 'Global Message').dialog({
autoOpen: false,
closeOnEscape: true,
resizable: false,
draggable: false,
modal: true,
close: function close() {
if ((0, _jquery2.default)('.dialog_remove:checked', (0, _jquery2.default)(this)).length > 0) {
// @TODO get from module
appCommons.userModule.setTemporaryPref('message', 0);
}
}
}).dialog('open');
}
}
return true;
};
return { initialize: initialize, manageSession: manageSession };
};
exports.default = user;
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _ui = __webpack_require__(47);
var _ui2 = _interopRequireDefault(_ui);
var _notify = __webpack_require__(46);
var _notify2 = _interopRequireDefault(_notify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var basket = function basket() {
var onUpdatedContent = function onUpdatedContent(data) {
if (data.changed.length > 0) {
var current_open = (0, _jquery2.default)('.SSTT.ui-state-active');
var main_open = false;
for (var i = 0; i !== data.changed.length; i++) {
var sstt = (0, _jquery2.default)('#SSTT_' + data.changed[i]);
if (sstt.size() === 0) {
if (main_open === false) {
(0, _jquery2.default)('#baskets .bloc').animate({ top: 30 }, function () {
(0, _jquery2.default)('#baskets .alert_datas_changed:first').show();
});
main_open = true;
}
} else {
if (!sstt.hasClass('active')) {
sstt.addClass('unread');
} else {
(0, _jquery2.default)('.alert_datas_changed', (0, _jquery2.default)('#SSTT_content_' + data.changed[i])).show();
}
}
}
}
};
var subscribeToEvents = {
'notification.refresh': onUpdatedContent
};
return { subscribeToEvents: subscribeToEvents };
};
exports.default = basket;
/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _lodash = __webpack_require__(4);
var _lodash2 = _interopRequireDefault(_lodash);
var _resultInfos = __webpack_require__(76);
var _resultInfos2 = _interopRequireDefault(_resultInfos);
var _index = __webpack_require__(60);
var _index2 = _interopRequireDefault(_index);
var _selectable = __webpack_require__(23);
var _selectable2 = _interopRequireDefault(_selectable);
var _searchForm = __webpack_require__(205);
var _searchForm2 = _interopRequireDefault(_searchForm);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var lazyload = __webpack_require__(58);
__webpack_require__(14);
__webpack_require__(19);
var search = function search(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var searchPromise = {};
var searchResult = {
selection: false,
navigation: {
tot: 0, // p4.tot in record preview
tot_options: false, // datas.form; // p4.tot_options common/tooltip
tot_query: false, // datas.query; // p4.tot_query
perPage: 0,
page: 0
}
};
var $searchForm = null;
var $searchResult = null;
var answAjaxrunning = false;
var resultInfoView = void 0;
var facets = null;
var lastFilterResults = [];
var savedHiddenFacetsList = configService.get('savedHiddenFacetsList') ? JSON.parse(configService.get('savedHiddenFacetsList')) : [];
var initialize = function initialize() {
$searchForm = (0, _jquery2.default)('#searchForm');
(0, _searchForm2.default)(services).initialize({
$container: $searchForm
});
$searchResult = (0, _jquery2.default)('#answers');
resultInfoView = (0, _resultInfos2.default)(services);
resultInfoView.initialize({
$container: (0, _jquery2.default)('#answers_status')
});
searchResult.selection = new _selectable2.default(services, $searchResult, {
selector: '.IMGT',
limit: 800,
selectStart: function selectStart(event, selection) {
(0, _jquery2.default)('#answercontextwrap table:visible').hide();
},
selectStop: function selectStop(event, selection) {
appEvents.emit('search.doRefreshSelection');
},
callbackSelection: function callbackSelection(element) {
var elements = (0, _jquery2.default)(element).attr('id').split('_');
return elements.slice(elements.length - 2, elements.length).join('_');
}
});
// map events to result selection:
appEvents.listenAll({
'search.selection.selectAll': function searchSelectionSelectAll() {
return searchResult.selection.selectAll();
},
'search.selection.unselectAll': function searchSelectionUnselectAll() {
return searchResult.selection.empty();
},
'search.selection.selectByType': function searchSelectionSelectByType(dataType) {
return searchResult.selection.select(dataType.type);
},
'search.selection.remove': function searchSelectionRemove(data) {
return searchResult.selection.remove(data.records);
}
});
$searchResult.on('click', '.search-navigate-action', function (event) {
event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
navigate($el.data('page'));
}).on('keypress', '.search-navigate-input-action', function (event) {
// event.preventDefault();
var $el = (0, _jquery2.default)(event.currentTarget);
var inputPage = $el.val();
var initialPage = $el.data('initial-value');
var totalPages = $el.data('total-pages');
if (isNaN(inputPage)) {
event.preventDefault();
}
if (event.keyCode === 13) {
if (inputPage > 0 && inputPage <= totalPages) {
navigate(inputPage);
} else {
navigate(totalPages);
}
}
});
window.searchResult = searchResult;
window.dialog = _dialog2.default;
};
var getResultSelectionStream = function getResultSelectionStream() {
return searchResult.selection.stream;
};
var resultNavigationStream = new Rx.Subject();
var getResultNavigationStream = function getResultNavigationStream() {
return resultNavigationStream;
}; //Rx.Observable.ofObjectChanges(searchResult.navigation);
//const getResultNavigationStream = () => Rx.Observable.ofObjectChanges(searchResult.navigation);
var newSearch = function newSearch(query) {
searchResult.selection.empty();
clearAnswers();
//$('#SENT_query').val(query);
if (query !== null) {
var histo = (0, _jquery2.default)('#history-queries ul');
histo.prepend('<li onclick="doSpecialSearch(\'' + query.replace(/\'/g, "\\'") + '\')">' + query + '</li>');
var lis = (0, _jquery2.default)('li', histo);
if (lis.length > 25) {
(0, _jquery2.default)('li:last', histo).remove();
}
}
(0, _jquery2.default)('#idFrameC li.proposals_WZ').removeClass('active');
appEvents.emit('search.doRefreshState');
return false;
};
/**
*
*/
var doRefreshState = function doRefreshState() {
// get the selectedFacets from the facets module
var selectedFacets = {};
appEvents.emit('facets.getSelectedFacets', function (v) {
selectedFacets = v;
});
var data = $searchForm.serializeArray();
// fix bug : if a sb is dual checked, both values are sent with the SAME name
// we can remove those since it means we don't care about this sb
// /!\ silly fixed bug : in sb[] we will test if a key exists using "_undefined()"
// BUT sb["sort”] EXISTS ! it is the array.sort() function !
// so the side effect in "_filter()" was that data["sort"] was removed.
// quick solution : prefix the key with "k_"
var sb = [];
_.each(data, function (v) {
var name = "k_" + v.name;
if (name.substr(0, 9) === "k_status[") {
if (_.isUndefined(sb[name])) {
sb[name] = 0;
}
sb[name]++; // so sb["k_x"] is the number of occurences of sb checkbox named "x"
}
});
// now if a sb checkbox appears 2 times, it is removed from data
data = _.filter(data, function (e) {
return _.isUndefined(sb["k_" + e.name]) || sb["k_" + e.name] === 1;
});
// end of sb fix
var jsonData = serializeJSON(data, selectedFacets);
var qry = buildQ(jsonData.query);
data.push({
name: 'jsQuery',
value: JSON.stringify(jsonData)
}, {
name: 'qry',
value: qry
});
console.log(jsonData);
var searchPromise = {};
searchPromise = _jquery2.default.ajax({
type: 'POST',
url: url + 'prod/query/',
data: data,
dataType: 'json',
beforeSend: function beforeSend(formData) {
if (answAjaxrunning && searchPromise.abort !== undefined) {
searchPromise.abort();
}
beforeSearch();
},
error: function error() {
answAjaxrunning = false;
$searchResult.removeClass('loading');
},
timeout: function timeout() {
answAjaxrunning = false;
(0, _jquery2.default)('#answers').removeClass('loading');
},
success: function success(datas) {
$searchResult.empty().append(datas.results).removeClass('loading');
(0, _jquery2.default)('img.lazyload', $searchResult).lazyload({
container: (0, _jquery2.default)('#answers')
});
//load last result collected or [] if length == 0
if (!datas.facets) {
datas.facets = [];
}
facets = datas.facets;
$searchResult.append('<div id="paginate"><div class="navigation"><div id="tool_navigate"></div></div></div>');
resultInfoView.render(datas.infos, searchResult.selection.length());
(0, _jquery2.default)('#tool_navigate').empty().append(datas.navigationTpl);
// @TODO refactor
_jquery2.default.each(searchResult.selection.get(), function (i, el) {
(0, _jquery2.default)('#IMGT_' + el).addClass('selected');
});
searchResult.navigation = (0, _lodash2.default)(searchResult.navigation, datas.navigation, {
tot: datas.total_answers,
tot_options: datas.form,
tot_query: datas.query
});
resultNavigationStream.onNext(searchResult.navigation);
if (datas.next_page) {
(0, _jquery2.default)('#NEXT_PAGE, #answersNext').bind('click', function () {
navigate(datas.next_page);
});
} else {
(0, _jquery2.default)('#NEXT_PAGE').unbind('click');
}
if (datas.prev_page) {
(0, _jquery2.default)('#PREV_PAGE').bind('click', function () {
navigate(datas.prev_page);
});
} else {
(0, _jquery2.default)('#PREV_PAGE').unbind('click');
}
updateHiddenFacetsListInPrefsScreen();
appEvents.emit('search.doAfterSearch');
appEvents.emit('search.updateFacetData');
}
});
/*script for pagination*/
setTimeout(function () {
if ((0, _jquery2.default)("#tool_navigate").length) {
(0, _jquery2.default)("#tool_navigate .btn-mini").last().addClass("last");
}
}, 5000);
};
var playFirstQuery = function playFirstQuery() {
// if defined, play the first query
//
try {
var jsq = (0, _jquery2.default)("#FIRST_QUERY_CONTAINER");
if (jsq.length > 0) {
// there is a query to play
if (jsq.data('format') === "json") {
// json
jsq = JSON.parse(jsq.text());
// restoreJsonQuery(jsq, true);
appEvents.emit('searchAdvancedForm.restoreJsonQuery', { 'jsq': jsq, 'submit': true });
} else {
// text : do it the old way : restore only fulltext and submit
_searchForm2.default.trigger('submit');;
}
}
} catch (e) {
// malformed jsonquery ?
// no-op
// console.error(e);
}
};
var updateHiddenFacetsListInPrefsScreen = function updateHiddenFacetsListInPrefsScreen() {
var $hiddenFacetsContainer = (0, _jquery2.default)('#look_box_settings').find('.hiddenFiltersListContainer');
if (savedHiddenFacetsList.length > 0) {
$hiddenFacetsContainer.empty();
_.each(savedHiddenFacetsList, function (value) {
var $html = (0, _jquery2.default)('<span class="facetFilter" data-name="' + value.name + '"><span class="facetFilter-label" title="' + value.title + '">' + value.title + '<span class="facetFilter-gradient">&nbsp;</span></span><a class="remove-btn"></a></span>');
$hiddenFacetsContainer.append($html);
(0, _jquery2.default)('.remove-btn').on('click', function () {
var name = (0, _jquery2.default)(this).parent().data('name');
savedHiddenFacetsList = _.reject(savedHiddenFacetsList, function (obj) {
return obj.name === name;
});
(0, _jquery2.default)(this).parent().remove();
appEvents.emit('searchAdvancedForm.saveHiddenFacetsList', savedHiddenFacetsList);
updateFacetData();
});
});
}
};
var beforeSearch = function beforeSearch() {
if (answAjaxrunning) {
return;
}
answAjaxrunning = true;
clearAnswers();
(0, _jquery2.default)('#tooltip').css({
display: 'none'
});
$searchResult.addClass('loading').empty();
(0, _jquery2.default)('#answercontextwrap').remove();
};
var afterSearch = function afterSearch() {
if ((0, _jquery2.default)('#answercontextwrap').length === 0) {
(0, _jquery2.default)('body').append('<div id="answercontextwrap"></div>');
}
_jquery2.default.each((0, _jquery2.default)('.contextMenuTrigger', $searchResult), function () {
var id = (0, _jquery2.default)(this).closest('.IMGT').attr('id').split('_').slice(1, 3).join('_');
(0, _jquery2.default)(this).contextMenu('#IMGT_' + id + ' .answercontextmenu', {
appendTo: '#answercontextwrap',
openEvt: 'click',
dropDown: true,
theme: 'vista',
showTransition: 'slideDown',
hideTransition: 'hide',
shadow: false
});
});
answAjaxrunning = false;
$searchResult.removeClass('loading');
(0, _jquery2.default)('.captionTips, .captionRolloverTips').tooltip({
delay: 0,
delayOptions: {},
isBrowsable: false,
extraClass: 'caption-tooltip-container'
});
(0, _jquery2.default)('.infoTips').tooltip({
delay: 0
});
(0, _jquery2.default)('.previewTips').tooltip({
fixable: true
});
(0, _jquery2.default)('.thumb .rollovable').hover(function () {
(0, _jquery2.default)('.rollover-gif-hover', this).show();
(0, _jquery2.default)('.rollover-gif-out', this).hide();
}, function () {
(0, _jquery2.default)('.rollover-gif-hover', this).hide();
(0, _jquery2.default)('.rollover-gif-out', this).show();
});
(0, _jquery2.default)('div.IMGT', $searchResult).draggable({
helper: function helper() {
(0, _jquery2.default)('body').append('<div id="dragDropCursor" style="position:absolute;z-index:9999;background:red;-moz-border-radius:8px;-webkit-border-radius:8px;"><div style="padding:2px 5px;font-weight:bold;">' + searchResult.selection.length() + '</div></div>');
return (0, _jquery2.default)('#dragDropCursor');
},
scope: 'objects',
distance: 20,
scroll: false,
cursorAt: {
top: -10,
left: -20
},
start: function start(event, ui) {
if (!(0, _jquery2.default)(this).hasClass('selected')) {
return false;
}
}
});
appEvents.emit('ui.linearizeUi');
};
var clearAnswers = function clearAnswers() {
(0, _jquery2.default)('#formAnswerPage').val('');
(0, _jquery2.default)('#searchForm input[name="nba"]').val('');
(0, _jquery2.default)($searchResult, '#dyn_tool').empty();
};
var navigate = function navigate(page) {
(0, _jquery2.default)('#searchForm input[name="sel"]').val(searchResult.selection.serialize());
(0, _jquery2.default)('#formAnswerPage').val(page);
appEvents.emit('search.doRefreshState');
};
var updateFacetData = function updateFacetData() {
appEvents.emit('facets.doLoadFacets', {
facets: facets,
filterFacet: (0, _jquery2.default)('#look_box_settings input[name=filter_facet]').prop('checked'),
facetOrder: (0, _jquery2.default)('.look_box_settings select[name=orderFacet]').val(),
facetValueOrder: (0, _jquery2.default)('.look_box_settings select[name=facetValuesOrder]').val(),
hiddenFacetsList: savedHiddenFacetsList
});
};
var reloadHiddenFacetList = function reloadHiddenFacetList(hiddenFacetsList) {
savedHiddenFacetsList = hiddenFacetsList;
updateHiddenFacetsListInPrefsScreen();
};
/**
* restore the advansearch ux from a json-query
* elements are restored thank's to custom properties ("_xxx") included in json.
* nb : for now, _ux_ facets can't be restored _before_sending_the_query_,
* but since "selectedFacets" (js) IS restored, sending the query WILL restore facets.
*
* @param jsq
* @param submit
*/
function serializeJSON(data, selectedFacets) {
var json = {},
obj = {},
bases = [],
statuses = [],
fields = [],
aggregates = [];
_jquery2.default.each(data, function (i, el) {
obj[el.name] = el.value;
var col = parseInt(el.value);
if (el.name === 'bases[]') {
bases.push(col);
}
});
var _tmpStat = [];
(0, _jquery2.default)('#ADVSRCH_SB_ZONE INPUT[type=checkbox]:checked').each(function (k, o) {
o = (0, _jquery2.default)(o);
var b = o.data('sbas_id');
var i = o.data('sb');
var v = o.val();
if (_.isUndefined(_tmpStat[b])) {
_tmpStat[b] = [];
}
if (_.isUndefined(_tmpStat[b][i])) {
// first check
_tmpStat[b][i] = v;
} else {
// both checked
_tmpStat[b][i] = -1;
}
});
_.each(_tmpStat, function (v, sbas_id) {
var status = [];
_.each(v, function (v, sb_index) {
if (v !== -1) {
// ignore both checked
status.push({
'index': sb_index,
'value': v === '1'
});
}
});
statuses.push({
'databox': sbas_id,
'status': status
});
});
(0, _jquery2.default)('.term_select_field').each(function (i, el) {
if ((0, _jquery2.default)(el).val()) {
fields.push({
'type': 'TEXT-FIELD',
'field': (0, _jquery2.default)(el).val(),
'operator': (0, _jquery2.default)(el).next().val() === ':' ? ":" : "=",
'value': (0, _jquery2.default)(el).next().next().val(),
"enabled": true
});
}
});
_.each(selectedFacets, function (facets) {
_.each(facets.values, function (facetValue) {
aggregates.push({
'type': facetValue.value.type,
'field': facetValue.value.field,
'value': facetValue.value.raw_value,
'query': facetValue.value.query,
'negated': facetValue.negated,
'enabled': facetValue.enabled
});
});
});
var date_field = (0, _jquery2.default)('#ADVSRCH_DATE_ZONE select[name=date_field]', 'form.phrasea_query .adv_options').val();
var date_from = (0, _jquery2.default)('#ADVSRCH_DATE_ZONE input[name=date_min]', 'form.phrasea_query .adv_options').val();
var date_to = (0, _jquery2.default)('#ADVSRCH_DATE_ZONE input[name=date_max]', 'form.phrasea_query .adv_options').val();
json['sort'] = {
'field': obj.sort,
'order': obj.ord
};
json['perpage'] = parseInt((0, _jquery2.default)('#nperpage_value').val());
json['page'] = obj.pag === '' ? 1 : parseInt(obj.pag);
json['use_truncation'] = obj.truncation === 'on' ? true : false;
json['phrasea_recordtype'] = obj.search_type == 1 ? 'STORY' : 'RECORD';
json['phrasea_mediatype'] = obj.record_type.toUpperCase();
json['bases'] = bases;
json['statuses'] = statuses;
json['query'] = {
'_ux_zone': (0, _jquery2.default)('.menu-bar .selectd').text().trim().toUpperCase(),
'type': 'CLAUSES',
'must_match': 'ALL',
'enabled': true,
'clauses': [{
'_ux_zone': 'FULLTEXT',
'type': 'FULLTEXT',
'value': obj.fake_qry,
'enabled': obj.fake_qry !== ''
}, {
'_ux_zone': 'FIELDS',
'type': 'CLAUSES',
'must_match': obj.must_match,
'enabled': true,
'clauses': fields
}, {
'_ux_zone': 'DATE-FIELD',
'type': 'DATE-FIELD',
'field': date_field,
'from': date_from,
'to': date_to,
"enabled": true
}, {
'_ux_zone': 'AGGREGATES',
'type': 'CLAUSES',
'must_match': 'ALL',
'enabled': true,
'clauses': aggregates
}]
};
json['_selectedFacets'] = selectedFacets;
return json;
}
var _ALL_Clause_ = "created_on>0";
function pjoin(glue, a) {
var r = a.join(glue);
return a.length === 1 ? r : '(' + r + ')';
}
function buildQ(clause) {
if (clause.enabled === false) {
return "";
}
switch (clause.type) {
case "CLAUSES":
var t_pos = [];
var t_neg = [];
for (var i = 0; i < clause.clauses.length; i++) {
var _clause = clause.clauses[i];
var _sub_q = buildQ(_clause);
if (_sub_q !== "()" && _sub_q !== "") {
if (_clause.negated === true) {
t_neg.push(_sub_q);
} else {
t_pos.push(_sub_q);
}
}
}
if (t_pos.length > 0) {
// some "yes" clauses
if (t_neg.length > 0) {
// some "yes" and and some "neg" clauses
if (clause.must_match === "ONE") {
// some "yes" and and some "neg" clauses, one is enough to match
var neg = "(" + _ALL_Clause_ + " EXCEPT " + pjoin(" OR ", t_neg) + ")";
t_pos.push(neg);
return "(" + t_pos.join(" OR ") + ")";
} else {
// some "yes" and and some "neg" clauses, all must match
return "(" + pjoin(" AND ", t_pos) + " EXCEPT " + pjoin(" OR ", t_neg) + ")";
}
} else {
// only "yes" clauses
return pjoin(clause.must_match == "ONE" ? " OR " : " AND ", t_pos);
}
} else {
// no "yes" clauses
if (t_neg.length > 0) {
// only "neg" clauses
return "(" + _ALL_Clause_ + " EXCEPT " + pjoin(clause.must_match == "ALL" ? " OR " : " AND ", t_neg) + ")";
} else {
// no clauses at all
return "";
}
}
case "FULLTEXT":
return clause.value ? "(" + clause.value + ")" : "";
case "DATE-FIELD":
var t = "";
if (clause.from) {
t = clause.field + ">=" + clause.from;
}
if (clause.to) {
t += (t ? " AND " : "") + clause.field + "<=" + clause.to;
}
return clause.from && clause.to ? "(" + t + ")" : t;
case "TEXT-FIELD":
return clause.field + clause.operator + "\"" + clause.value + "\"";
case "GEO-DISTANCE":
return clause.field + "=\"" + clause.lat + " " + clause.lon + " " + clause.distance + "\"";
/*
case "STRING-AGGREGATE":
return clause.field + ":\"" + clause.value + "\"";
case "DATE-AGGREGATE":
return clause.field + ":\"" + clause.value + "\"";
case "COLOR-AGGREGATE":
return clause.field + ":\"" + clause.value + "\"";
case "NUMBER-AGGREGATE":
return clause.field + "=" + clause.value;
case "BOOL-AGGREGATE":
return clause.field + "=" + (clause.value ? "1" : "0");
*/
case "STRING-AGGREGATE":
case "DATE-AGGREGATE":
case "COLOR-AGGREGATE":
case "NUMBER-AGGREGATE":
case "BOOLEAN-AGGREGATE":
return clause.query;
default:
console.error("Unknown clause type \"" + clause.type + "\"");
return null;
}
}
appEvents.listenAll({
'search.doRefreshState': doRefreshState,
'search.doNewSearch': newSearch,
'search.doAfterSearch': afterSearch,
'search.doClearSearch': clearAnswers,
'search.doNavigate': navigate,
'search.updateFacetData': updateFacetData,
'search.reloadHiddenFacetList': reloadHiddenFacetList,
'search.playFirstQuery': playFirstQuery
});
return {
initialize: initialize,
getResultSelectionStream: getResultSelectionStream,
getResultNavigationStream: getResultNavigationStream
};
};
exports.default = search;
/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
var _resultInfos = __webpack_require__(76);
var _resultInfos2 = _interopRequireDefault(_resultInfos);
var _user = __webpack_require__(45);
var _user2 = _interopRequireDefault(_user);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _selectable = __webpack_require__(23);
var _selectable2 = _interopRequireDefault(_selectable);
var _searchAdvancedForm = __webpack_require__(206);
var _searchAdvancedForm2 = _interopRequireDefault(_searchAdvancedForm);
var _searchGeoForm = __webpack_require__(207);
var _searchGeoForm2 = _interopRequireDefault(_searchGeoForm);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var searchForm = function searchForm(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var $container = null;
var $searchValue = null;
var $sentValue = null;
var isAdvancedDialogOpen = false;
var $dialog = null;
var geoForm = void 0;
var searchPreferences = {};
var $geoSearchTriggerImg = void 0;
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, _options);
$searchValue = (0, _jquery2.default)('#EDIT_query');
/*Remove space on 1st and last char*/
$searchValue.on('change', function (event) {
$sentValue = $searchValue.val();
while ($sentValue.charAt(0) === ' ') {
$sentValue = $sentValue.slice(1);
}
while ($sentValue.charAt($sentValue.length - 1) === ' ') {
$sentValue = $sentValue.slice(0, -1);
}
$searchValue.val($sentValue);
});
(0, _searchAdvancedForm2.default)(services).initialize({
$container: $container
});
geoForm = (0, _searchGeoForm2.default)(services);
$container.on('click', '.adv_search_button', function (event) {
event.preventDefault();
openAdvancedForm();
});
toggleSearchState();
appEvents.emit('searchAdvancedForm.checkFilters');
$container.on('click', '.geo-search-action-btn', function (event) {
event.preventDefault();
geoForm.openModal({
drawnItems: searchPreferences.drawnItems || false
});
});
$container.on('click', 'input[name=search_type]', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var $record_types = (0, _jquery2.default)('#recordtype_sel');
if ($el.hasClass('mode_type_reg')) {
$record_types.css('display', 'none'); // better than hide because does not change layout
(0, _jquery2.default)('#recordtype_sel select').find('option').removeAttr('selected');
} else {
$record_types.css('display', 'inline-block');
}
});
$container.on('submit', function (event) {
if (isAdvancedDialogOpen === true) {
$dialog.close();
isAdvancedDialogOpen = false;
}
/*appEvents.emit('facets.doResetSelectedFacets');*/
appEvents.emit('search.doNewSearch', $searchValue.val());
return false;
});
};
var toggleSearchState = function toggleSearchState() {
$geoSearchTriggerImg = (0, _jquery2.default)('.geo-search-action-btn').find('img');
$geoSearchTriggerImg.attr('src', '/assets/common/images/icons/map.png');
if (searchPreferences.drawnItems !== undefined) {
if (!_underscore2.default.isEmpty(searchPreferences.drawnItems)) {
$geoSearchTriggerImg.attr('src', '/assets/common/images/icons/map-active.png');
}
}
};
var updateSearchValue = function updateSearchValue(params) {
var searchValue = params.searchValue;
var reset = params.reset !== undefined ? params.reset : false;
var submit = params.submit !== undefined ? params.submit : false;
$searchValue.val(searchValue);
// toogle states:
toggleSearchState();
if (submit === true) {
if (reset === true) {
appEvents.emit('search.doNewSearch', $searchValue.val());
} else {
appEvents.emit('search.doRefreshState');
}
}
return searchValue;
};
var updatePreferences = function updatePreferences(preferences) {
for (var prefKey in preferences) {
if (preferences.hasOwnProperty(prefKey)) {
searchPreferences[prefKey] = preferences[prefKey];
_user2.default.setPref(prefKey, JSON.stringify(preferences[prefKey]));
}
}
};
/**
* Move entire search form into dialog
*/
var openAdvancedForm = function openAdvancedForm() {
var $searchFormContainer = $container.parent();
var options = {
title: (0, _jquery2.default)('#advanced-search-title').val(),
size: window.bodySize.x - 120 + 'x' + (window.bodySize.y - 120),
loading: false,
closeCallback: function closeCallback(dialog) {
// move back search form
$container.appendTo($searchFormContainer);
// toggle advanced search options
(0, _jquery2.default)('.adv_trigger', $container).show();
(0, _jquery2.default)('.adv_options', $container).hide();
isAdvancedDialogOpen = false;
}
};
$dialog = _dialog2.default.create(services, options);
$dialog.getDomElement().closest('.ui-dialog').addClass('advanced_search_dialog_container');
// move all content into dialog:
$dialog.getDomElement().append($container);
// toggle advanced search options
$dialog.getDomElement().find('.adv_options').show();
$dialog.getDomElement().find('.adv_trigger').hide();
isAdvancedDialogOpen = true;
};
appEvents.listenAll({
'searchForm.updateSearchValue': updateSearchValue,
'searchForm.updatePreferences': updatePreferences
});
return { initialize: initialize };
};
exports.default = searchForm;
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
var _user = __webpack_require__(45);
var _user2 = _interopRequireDefault(_user);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var searchAdvancedForm = function searchAdvancedForm(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
/**
* add "field" zone on advsearch
*
* @returns {jQuery|HTMLElement}
* @constructor
*/
function AdvSearchAddNewTerm() {
var block_template = (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE DIV.term_select_wrapper_template');
var last_block = (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE DIV.term_select_wrapper:last');
if (last_block.length === 0) {
last_block = block_template;
}
last_block = block_template.clone(true).insertAfter(last_block); // true: clone event handlers
last_block.removeClass('term_select_wrapper_template').addClass('term_select_wrapper').show();
last_block.css('background-color', '');
return last_block;
}
var initialize = function initialize(options) {
var _options;
var initWith = (_options = options, $container = _options.$container, _options);
var previousVal = void 0;
var multi_term_select_html = (0, _jquery2.default)('.term_select_wrapper').html();
// advanced
$container.on('click', '.toggle-collection', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
toggleCollection($el, (0, _jquery2.default)($el.data('toggle-content')));
});
$container.on('click', '.toggle-database', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var state = $el.data('state') || false;
toggleAllDatabase(state);
});
$container.on('change', '.select-database', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var collectionId = $el.data('database');
selectDatabase($el, collectionId);
});
$container.on('change', '.check-filters', function (event) {
var $el = (0, _jquery2.default)(event.currentTarget);
var shouldSave = $el.data('save') || false;
checkFilters(shouldSave);
});
(0, _jquery2.default)('.field_switch').on('change', function (event) {
checkFilters(true);
});
$container.on('click', '.search-reset-action', function () {
resetSearch();
});
$container.on('click', '.reload-search', function () {
resetSearch();
(0, _jquery2.default)('#searchForm').submit();
});
(0, _jquery2.default)(document).on('focus', 'select.term_select_field', function (event) {
previousVal = (0, _jquery2.default)(event.currentTarget).val();
});
(0, _jquery2.default)(document).on('change', 'select.term_select_field', function (event) {
var $this = (0, _jquery2.default)(event.currentTarget);
// if option is selected
if ($this.val()) {
$this.siblings().prop('disabled', false);
(0, _jquery2.default)('.term_select_multiple option').each(function (index, el) {
var $el = (0, _jquery2.default)(el);
if ($this.val() === $el.val()) {
$el.prop('selected', true);
} else if (previousVal === $el.val()) {
$el.prop('selected', false);
}
});
} else {
$this.siblings().prop('disabled', 'disabled');
(0, _jquery2.default)('.term_select_multiple option').each(function (index, el) {
var $el = (0, _jquery2.default)(el);
if (previousVal === $el.val()) {
$el.prop('selected', false);
}
});
}
$this.blur();
checkFilters(true);
});
(0, _jquery2.default)(document).on('click', '.term_deleter', function (event) {
event.preventDefault();
var $this = (0, _jquery2.default)(event.currentTarget);
$this.closest('.term_select_wrapper').remove();
checkFilters(true);
});
(0, _jquery2.default)('.add_new_term').on('click', function (event) {
event.preventDefault();
AdvSearchAddNewTerm(1);
});
// @TODO - check if usefull
/**
* inform global app for state
* @TODO refactor
*/
(0, _jquery2.default)('#EDIT_query').bind('focus', function () {
(0, _jquery2.default)(this).addClass('focused');
}).bind('blur', function () {
(0, _jquery2.default)(this).removeClass('focused');
});
};
/**
* adv search : check/uncheck all the collections (called by the buttons "all"/"none")
*
* @param bool
*/
var toggleAllDatabase = function toggleAllDatabase(bool) {
(0, _jquery2.default)('form.phrasea_query .sbas_list').each(function () {
var sbas_id = (0, _jquery2.default)(this).find('input[name=reference]:first').val();
if (bool) {
(0, _jquery2.default)(this).find(':checkbox').prop('checked', true);
} else {
(0, _jquery2.default)(this).find(':checkbox').prop('checked', false);
}
});
checkFilters(true);
};
var toggleCollection = function toggleCollection($el, $elContent) {
if ($el.hasClass('deployer_opened')) {
$el.removeClass('deployer_opened').addClass('deployer_closed');
$elContent.hide();
} else {
$el.removeClass('deployer_closed').addClass('deployer_opened');
$elContent.show();
}
};
var selectDatabase = function selectDatabase($el, sbas_id) {
var bool = $el.prop('checked');
_jquery2.default.each((0, _jquery2.default)('.sbascont_' + sbas_id + ' :checkbox'), function () {
this.checked = bool;
});
checkFilters(true);
};
var activateDatabase = function activateDatabase(databaseCollection) {
// disable all db,
toggleAllDatabase(false);
// then enable only provided
_underscore2.default.each(databaseCollection, function (databaseId) {
_underscore2.default.each((0, _jquery2.default)('.sbascont_' + databaseId + ' :checkbox'), function (checkbox) {
(0, _jquery2.default)(checkbox).prop('checked', true);
});
});
};
(0, _jquery2.default)('#ADVSRCH_DATE_SELECTORS input').change(function () {
checkFilters(true);
});
var checkFilters = function checkFilters(save) {
var danger = false;
var search = {
bases: {},
fields: [],
dates: {},
status: [],
elasticSort: {}
};
var adv_box = (0, _jquery2.default)('form.phrasea_query .adv_options');
var container = (0, _jquery2.default)('#ADVSRCH_OPTIONS_ZONE');
var fieldsSort = (0, _jquery2.default)('#ADVSRCH_SORT_ZONE select[name=sort]', container);
var fieldsSortOrd = (0, _jquery2.default)('#ADVSRCH_SORT_ZONE select[name=ord]', container);
var fieldsSelect = (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE select.term_select_multiple', container);
var fieldsSelectFake = (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE select.term_select_field', container);
var statusField = (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE .danger_indicator', container);
var statusFilters = (0, _jquery2.default)('#ADVSRCH_SB_ZONE .status-section-title .danger_indicator', container);
var dateFilterSelect = (0, _jquery2.default)('#ADVSRCH_DATE_ZONE select', container);
var scroll = fieldsSelect.scrollTop();
// hide all the fields in the "sort by" select, so only the relevant ones will be shown again
(0, _jquery2.default)('option.dbx', fieldsSort).hide().prop('disabled', true); // dbx is for "field of databases"
// hide all the fields in the "fields" select, so only the relevant ones will be shown again
(0, _jquery2.default)('option.dbx', fieldsSelect).hide().prop('disabled', true); // option[0] is "all fields"
(0, _jquery2.default)('option.dbx', fieldsSelectFake).hide().prop('disabled', true);
// disable the whole select
(0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE .term_select_wrapper select.term_select_field', container).prop('disabled', true);
(0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE .term_select_wrapper select.term_select_op', container).prop('disabled', true);
(0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE .term_select_wrapper input.term_select_value', container).prop('disabled', true);
// hide all the fields in the "date field" select, so only the relevant ones will be shown again
(0, _jquery2.default)('option.dbx', dateFilterSelect).hide().prop('disabled', true); // dbx = all "field" entries in the select = all except the firstt
statusFilters.removeClass('danger');
_jquery2.default.each((0, _jquery2.default)('#ADVSRCH_SB_ZONE .field_switch'), function (index, el) {
if ((0, _jquery2.default)(el).prop('checked') === true) {
danger = true;
statusFilters.addClass('danger');
}
});
// enable also the select if the first option ("choose:") was selected
statusField.removeClass('danger');
fieldsSelectFake.each(function (e) {
var $this = (0, _jquery2.default)(this);
if ($this.val() !== '') {
danger = true;
statusField.addClass('danger');
}
});
var nbTotalSelectedColls = 0;
// if one coll is not checked, show danger for ADVSRCH_SBAS_ZONE
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE').each(function () {
var $this = (0, _jquery2.default)(this);
var nbSelectedColls = 0;
$this.find('.checkbas').each(function (idx, el) {
if ((0, _jquery2.default)(this).prop('checked') === false) {
nbSelectedColls++;
}
});
if (nbSelectedColls > 0) {
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE').addClass('danger');
danger = true;
} else {
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE').removeClass('danger');
}
});
_jquery2.default.each((0, _jquery2.default)('.sbascont', adv_box), function () {
var $this = (0, _jquery2.default)(this);
var sbas_id = $this.parent().find('input[name="reference"]').val();
search.bases[sbas_id] = [];
var nbCols = 0;
var nbSelectedColls = 0;
$this.find('.checkbas').each(function (idx, el) {
nbCols++;
if ((0, _jquery2.default)(this).prop('checked')) {
nbSelectedColls++;
nbTotalSelectedColls++;
search.bases[sbas_id].push((0, _jquery2.default)(this).val());
}
});
// display the number of selected colls for the databox
if (nbSelectedColls === nbCols) {
(0, _jquery2.default)('.infos_sbas_' + sbas_id).empty().append(nbCols);
(0, _jquery2.default)(this).siblings('.clksbas').removeClass('danger');
(0, _jquery2.default)(this).siblings('.clksbas').find('.custom_checkbox_label input').prop('checked', 'checked');
} else {
(0, _jquery2.default)('.infos_sbas_' + sbas_id).empty().append('<span style="color:#2096F3;font-size: 20px;">' + nbSelectedColls + '</span> / ' + nbCols);
(0, _jquery2.default)(this).siblings('.clksbas').addClass('danger');
danger = true;
}
// if one coll is not checked, show danger
if (nbSelectedColls !== nbCols) {
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE').addClass('danger');
danger = true;
} else if (nbSelectedColls === nbCols && danger === false) {
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE').removeClass('danger');
}
if (nbSelectedColls === 0) {
// no collections checked for this databox
// hide the status bits
(0, _jquery2.default)('#ADVSRCH_SB_ZONE_' + sbas_id, container).hide();
// uncheck
(0, _jquery2.default)('#ADVSRCH_SB_ZONE_' + sbas_id + ' input:checkbox', container).prop('checked', false);
} else {
// at least one coll checked for this databox
// show again the relevant fields in "sort by" select
(0, _jquery2.default)('.db_' + sbas_id, fieldsSort).show().prop('disabled', false);
// show again the relevant fields in "from fields" select
(0, _jquery2.default)('.db_' + sbas_id, fieldsSelect).show().prop('disabled', false);
(0, _jquery2.default)('.db_' + sbas_id, fieldsSelectFake).show().prop('disabled', false);
// show the sb
(0, _jquery2.default)('#ADVSRCH_SB_ZONE_' + sbas_id, container).show();
// show again the relevant fields in "date field" select
(0, _jquery2.default)('.db_' + sbas_id, dateFilterSelect).show().prop('disabled', false);
}
});
// enable also the select if the first option ("choose:") was selected
statusField.removeClass('danger');
fieldsSelectFake.each(function (e) {
var $this = (0, _jquery2.default)(this);
var term_ok = (0, _jquery2.default)('option:selected:enabled', $this).closest(".term_select_wrapper");
(0, _jquery2.default)("select.term_select_field", term_ok).prop('disabled', false);
if ($this.val() !== "") {
(0, _jquery2.default)("select.term_select_op", term_ok).prop('disabled', false);
(0, _jquery2.default)("input.term_select_value", term_ok).prop('disabled', false);
danger = true;
statusField.addClass('danger');
}
});
if (nbTotalSelectedColls === 0) {
// no collections checked at all
// hide irrelevant filters
(0, _jquery2.default)('#ADVSRCH_OPTIONS_ZONE').hide();
} else {
// at least one collection checked
// show relevant filters
(0, _jquery2.default)('#ADVSRCH_OPTIONS_ZONE').show();
}
// --------- sort --------
// if no field is selected for sort, select the default option
if ((0, _jquery2.default)('option:selected:enabled', fieldsSort).length === 0) {
(0, _jquery2.default)('option.default-selection', fieldsSort).prop('selected', true);
(0, _jquery2.default)('option.default-selection', fieldsSortOrd).prop('selected', true);
}
search.elasticSort.by = (0, _jquery2.default)('option:selected:enabled', fieldsSort).val();
search.elasticSort.order = (0, _jquery2.default)('option:selected:enabled', fieldsSortOrd).val();
// --------- from fields filter ---------
// unselect the unavailable fields (or all fields if "all" is selected)
var optAllSelected = false;
(0, _jquery2.default)('option', fieldsSelect).each(function (idx, opt) {
if (idx === 0) {
// nb: unselect the "all" field, so it acts as a button
optAllSelected = (0, _jquery2.default)(opt).is(':selected');
}
if (idx === 0 || optAllSelected || (0, _jquery2.default)(opt).is(':disabled') || (0, _jquery2.default)(opt).css('display') === 'none') {
(0, _jquery2.default)(opt).prop('selected', false);
}
});
// --------- status bits filter ---------
// here only the relevant sb are checked
var availableDb = search.bases;
for (var sbas_id in availableDb) {
var n_checked = 0;
var n_unchecked = 0;
(0, _jquery2.default)('#ADVSRCH_SB_ZONE_' + sbas_id + ' :checkbox', container).each(function (k, o) {
var n = (0, _jquery2.default)(this).data('sb');
if ((0, _jquery2.default)(o).attr('checked')) {
search.status[n] = (0, _jquery2.default)(this).val().split('_');
n_checked++;
} else {
n_unchecked++;
}
});
if (n_checked === 0) {
(0, _jquery2.default)('#ADVSRCH_SB_ZONE_' + sbas_id, container).removeClass('danger');
} else {
(0, _jquery2.default)('#ADVSRCH_SB_ZONE_' + sbas_id, container).addClass('danger');
danger = true;
}
}
// --------- dates filter ---------
// if no date field is selected for filter, select the first option
(0, _jquery2.default)('#ADVSRCH_DATE_ZONE', adv_box).removeClass('danger');
if ((0, _jquery2.default)('option:selected:enabled', dateFilterSelect).length === 0) {
(0, _jquery2.default)('option:eq(0)', dateFilterSelect).prop('selected', true);
}
if ((0, _jquery2.default)('option:selected', dateFilterSelect).val() !== '') {
(0, _jquery2.default)('#ADVSRCH_DATE_SELECTORS', container).show();
search.dates.minbound = (0, _jquery2.default)('#ADVSRCH_DATE_ZONE input[name=date_min]', adv_box).val();
search.dates.maxbound = (0, _jquery2.default)('#ADVSRCH_DATE_ZONE input[name=date_max]', adv_box).val();
search.dates.field = (0, _jquery2.default)('#ADVSRCH_DATE_ZONE select[name=date_field]', adv_box).val();
if (_jquery2.default.trim(search.dates.minbound) || _jquery2.default.trim(search.dates.maxbound)) {
danger = true;
(0, _jquery2.default)('#ADVSRCH_DATE_ZONE', adv_box).addClass('danger');
}
} else {
(0, _jquery2.default)('#ADVSRCH_DATE_SELECTORS', container).hide();
(0, _jquery2.default)('#ADVSRCH_DATE_ZONE input[name=date_min]').val("");
(0, _jquery2.default)('#ADVSRCH_DATE_ZONE input[name=date_max]').val("");
}
fieldsSelect.scrollTop(scroll);
// if one filter shows danger, show it on the query
/* if (danger) {*/
if ((0, _jquery2.default)('#ADVSRCH_DATE_ZONE', adv_box).hasClass('danger') || (0, _jquery2.default)('#ADVSRCH_SB_ZONE .danger_indicator', adv_box).hasClass('danger') || (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE', adv_box).hasClass('danger') || (0, _jquery2.default)('#ADVSRCH_SBAS_ZONE', adv_box).hasClass('danger')) {
(0, _jquery2.default)('#EDIT_query').addClass('danger');
} else {
(0, _jquery2.default)('#EDIT_query').removeClass('danger');
}
if (save === true) {
_user2.default.setPref('search', JSON.stringify(search));
}
};
var saveHiddenFacetsList = function saveHiddenFacetsList(hiddenFacetsList) {
_user2.default.setPref('hiddenFacetsList', JSON.stringify(hiddenFacetsList));
};
function findClauseBy_ux_zone(clause, ux_zone) {
// console.log('find clause' + ux_zone);
if (typeof clause._ux_zone != 'undefined' && clause._ux_zone === ux_zone) {
return clause;
}
if (clause.type === "CLAUSES") {
for (var i = 0; i < clause.clauses.length; i++) {
var r = findClauseBy_ux_zone(clause.clauses[i], ux_zone);
if (r != null) {
return r;
}
}
}
return null;
}
/**
* add "field" zone on advsearch
*
* @returns {jQuery|HTMLElement}
* @constructor
*/
function AdvSearchFacetAddNewTerm() {
var block_template = (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE DIV.term_select_wrapper_template');
var last_block = (0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE DIV.term_select_wrapper:last');
if (last_block.length === 0) {
last_block = block_template;
}
last_block = block_template.clone(true).insertAfter(last_block); // true: clone event handlers
last_block.removeClass('term_select_wrapper_template').addClass('term_select_wrapper').show();
last_block.css('background-color', '');
return last_block;
}
function restoreJsonQuery(args) {
var jsq = args.jsq;
var submit = args.submit;
var clause;
// restore the "fulltext" input-text
clause = findClauseBy_ux_zone(jsq.query, "FULLTEXT");
if (clause) {
(0, _jquery2.default)('#EDIT_query').val(clause.value);
}
// restore the "bases" checkboxes
if (!_underscore2.default.isUndefined(jsq.bases)) {
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE .sbas_list .checkbas').prop('checked', false);
if (jsq.bases.length > 0) {
for (var k = 0; k < jsq.bases.length; k++) {
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE .sbas_list .checkbas[value="' + jsq.bases[k] + '"]').prop('checked', true);
}
} else {
// special case : EMPTY array ==> since it's a nonsense, check ALL bases
(0, _jquery2.default)('#ADVSRCH_SBAS_ZONE .sbas_list .checkbas').prop('checked', true);
}
}
// restore the status-bits (for now dual checked status are restored unchecked)
if (!_underscore2.default.isUndefined(jsq.statuses)) {
(0, _jquery2.default)('#ADVSRCH_SB_ZONE INPUT:checkbox').prop('checked', false);
_underscore2.default.each(jsq.statuses, function (db_statuses) {
var db = db_statuses.databox;
_underscore2.default.each(db_statuses.status, function (sb) {
var i = sb.index;
var v = sb.value ? '1' : '0';
(0, _jquery2.default)("#ADVSRCH_SB_ZONE INPUT[name='status[" + db_statuses.databox + '][' + sb.index + "]'][value=" + v + ']').prop('checked', true);
});
});
}
// restore the "records/stories" radios
if (!_underscore2.default.isUndefined(jsq.phrasea_recordtype)) {
(0, _jquery2.default)('#searchForm INPUT[name=search_type][value="' + (jsq.phrasea_recordtype == 'STORY' ? '1' : '0') + '"]').prop('checked', true); // check one radio will uncheck siblings
}
// restore the "record type" menu (image, video, audio, ...)
if (!_underscore2.default.isUndefined(jsq.phrasea_mediatype)) {
(0, _jquery2.default)('#searchForm SELECT[name=record_type] OPTION[value="' + jsq.phrasea_mediatype.toLowerCase() + '"]').prop('selected', true);
}
// restore the "use truncation" checkbox
if (!_underscore2.default.isUndefined(jsq.phrasea_mediatype) && jsq.phrasea_mediatype == 'true') {
(0, _jquery2.default)('#ADVSRCH_USE_TRUNCATION').prop('checked', jsq.phrasea_mediatype);
}
// restore the "sort results" menus
if (!_underscore2.default.isUndefined(jsq.sort)) {
if (!_underscore2.default.isUndefined(jsq.sort.field)) {
(0, _jquery2.default)('#ADVSRCH_SORT_ZONE SELECT[name=sort] OPTION[value="' + jsq.sort.field + '"]').prop('selected', true);
}
if (!_underscore2.default.isUndefined(jsq.sort.order)) {
(0, _jquery2.default)('#ADVSRCH_SORT_ZONE SELECT[name=ord] OPTION[value="' + jsq.sort.order + '"]').prop('selected', true);
}
}
// restore the multiples "fields" (field-menu + op-menu + value-input)
clause = findClauseBy_ux_zone(jsq.query, "FIELDS");
if (clause) {
(0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE INPUT[name=must_match][value="' + clause.must_match + '"]').attr('checked', true);
(0, _jquery2.default)('#ADVSRCH_FIELDS_ZONE DIV.term_select_wrapper').remove();
for (var j = 0; j < clause.clauses.length; j++) {
var wrapper = AdvSearchFacetAddNewTerm(); // div.term_select_wrapper
var f = (0, _jquery2.default)(".term_select_field", wrapper);
var o = (0, _jquery2.default)(".term_select_op", wrapper);
var v = (0, _jquery2.default)(".term_select_value", wrapper);
f.data('fieldtype', clause.clauses[j].type);
(0, _jquery2.default)('option[value="' + clause.clauses[j].field + '"]', f).prop('selected', true);
(0, _jquery2.default)('option[value="' + clause.clauses[j].operator + '"]', o).prop('selected', true);
o.prop('disabled', false);
v.val(clause.clauses[j].value).prop('disabled', false);
}
}
// restore the "date field" (field-menu + from + to)
clause = findClauseBy_ux_zone(jsq.query, "DATE-FIELD");
if (clause) {
(0, _jquery2.default)("#ADVSRCH_DATE_ZONE SELECT[name=date_field] option[value='" + clause.field + "']").prop('selected', true);
(0, _jquery2.default)("#ADVSRCH_DATE_ZONE INPUT[name=date_min]").val(clause.from);
(0, _jquery2.default)("#ADVSRCH_DATE_ZONE INPUT[name=date_max]").val(clause.to);
if ((0, _jquery2.default)("#ADVSRCH_DATE_ZONE SELECT[name=date_field]").val() !== '') {
(0, _jquery2.default)("#ADVSRCH_DATE_SELECTORS").show();
// $('#ADVSRCH_DATE_ZONE').addClass('danger');
}
}
// restore the selected facets (whole saved as custom property)
if (!_underscore2.default.isUndefined(jsq._selectedFacets)) {
appEvents.emit('facets.setSelectedFacets', jsq._selectedFacets);
//(0, _index2.default)(services).setSelectedFacets(jsq._selectedFacets);
// selectedFacets = jsq._selectedFacets;
}
// the ux is restored, finish the job (hide unavailable fields/status etc, display "danger" where needed)
appEvents.emit('searchAdvancedForm.checkFilters');
//loadFacets([]); // useless, facets will be restored after the query is sent
if (submit) {
appEvents.emit('search.doRefreshState');
}
}
var resetSearch = function resetSearch() {
var jsq = {
"sort": {
"field": "created_on",
"order": "desc"
},
"use_truncation": false,
"phrasea_recordtype": "RECORD",
"phrasea_mediatype": "",
"bases": [],
"statuses": [],
"query": {
"_ux_zone": "PROD",
"type": "CLAUSES",
"must_match": "ALL",
"enabled": true,
"clauses": [{
"_ux_zone": "FIELDS",
"type": "CLAUSES",
"must_match": "ALL",
"enabled": false,
"clauses": []
}, {
"_ux_zone": "DATE-FIELD",
"type": "DATE-FIELD",
"field": "",
"from": "",
"to": "",
"enabled": false
}, {
"_ux_zone": "AGGREGATES",
"type": "CLAUSES",
"must_match": "ALL",
"enabled": false,
"clauses": []
}]
},
"_selectedFacets": {}
};
restoreJsonQuery({ 'jsq': jsq, 'submit': false });
};
appEvents.listenAll({
'searchAdvancedForm.checkFilters': checkFilters,
'searchAdvancedForm.selectDatabase': selectDatabase,
'searchAdvancedForm.activateDatabase': function searchAdvancedFormActivateDatabase(params) {
return activateDatabase(params.databases);
},
'searchAdvancedForm.toggleCollection': toggleCollection,
'searchAdvancedForm.saveHiddenFacetsList': saveHiddenFacetsList,
'searchAdvancedForm.restoreJsonQuery': restoreJsonQuery
});
return { initialize: initialize };
};
exports.default = searchAdvancedForm;
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rx = __webpack_require__(7);
var Rx = _interopRequireWildcard(_rx);
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __webpack_require__(1);
var _dialog2 = _interopRequireDefault(_dialog);
var _mapbox = __webpack_require__(50);
var _mapbox2 = _interopRequireDefault(_mapbox);
var _underscore = __webpack_require__(2);
var _underscore2 = _interopRequireDefault(_underscore);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var searchGeoForm = function searchGeoForm(services) {
var configService = services.configService,
localeService = services.localeService,
appEvents = services.appEvents;
var url = configService.get('baseUrl');
var $container = null;
var $dialog = void 0;
var mapBoxService = void 0;
var searchQuery = void 0;
var drawnItems = void 0;
var $geoSearchBtn = void 0;
var mapContainerName = 'geo-search-map-container';
var openModal = function openModal(options) {
options = _underscore2.default.extend({
size: window.bodySize.x - 120 + 'x' + (window.bodySize.y - 120),
loading: false,
title: localeService.t('title-map-dialog')
}, options);
$dialog = _dialog2.default.create(services, options);
$dialog.setContent(renderModal());
$container = $dialog.getDomElement();
$container.closest('.ui-dialog').addClass('map_search_dialog');
onModalReady(options);
};
var onModalReady = function onModalReady(options) {
$container.on('click', '.submit-geo-search-action', function (event) {
event.preventDefault();
updateSearchValue();
// searchQuery
$dialog.close();
});
mapBoxService = (0, _mapbox2.default)({ configService: configService, localeService: localeService, eventEmitter: appEvents });
mapBoxService.initialize({
$container: $container.find('#' + mapContainerName),
parentOptions: {},
drawable: true,
drawnItems: options.drawnItems || false,
mapOptions: {}
});
mapBoxService.appendMapContent({ selection: [] });
(0, _jquery2.default)('.map-geo-btn').on('click', function (event) {
event.preventDefault();
if ((0, _jquery2.default)('#map-zoom-to-setting').val() != '') {
savePreferences({ map_zoom: parseFloat((0, _jquery2.default)('#map-zoom-to-setting').val()) });
(0, _jquery2.default)('#map-zoom-from-setting').val(parseFloat((0, _jquery2.default)('#map-zoom-to-setting').val()));
}
if ((0, _jquery2.default)('#map-position-to-setting').val() != '') {
var centerRes = (0, _jquery2.default)('#map-position-to-setting').val();
centerRes = centerRes.split('[');
centerRes = centerRes[1].split(']');
centerRes = centerRes[0].split(',');
var lng = centerRes[0].split('"');
lng = lng[1];
var lat = centerRes[1].split('"');
lat = lat[1];
var res = [lng, lat];
savePreferences({ map_position: res });
(0, _jquery2.default)('#map-position-from-setting').val('["' + lng + '","' + lat + '"]');
}
});
};
var updateSearchValue = function updateSearchValue() {
appEvents.emit('searchForm.updateSearchValue', {
searchValue: searchQuery,
reset: true,
submit: true
});
};
var renderModal = function renderModal() {
// @TODO cleanup styles
return '\n <div style="overflow:hidden">\n <div id="' + mapContainerName + '" style="top: 0px; left: 0; bottom: 42px; position: absolute;height: auto;width: 100%;overflow: hidden;"></div>\n <div style="position: absolute;bottom: 0; text-align:center; height: 35px; width: 98%;overflow: hidden;"><button class="submit-geo-search-action btn map-geo-btn" style="font-size: 14px">' + localeService.t('Valider') + '</button></div>\n </div>';
};
var updateCircleGeo = function updateCircleGeo(params) {
var shapes = params.shapes;
searchQuery = buildCircularSearchQuery(shapes);
var circleObjCollection = _underscore2.default.map(params.drawnItems, function (circleObj) {
var obj = {};
obj['center'] = circleObj.getCenter();
obj['radius'] = circleObj.getRadius();
return obj;
});
savePreferences({ drawnItems: circleObjCollection });
};
var onShapeCreated = function onShapeCreated(params) {
var shapes = params.shapes;
searchQuery = buildSearchQuery(shapes);
savePreferences({ drawnItems: params.drawnItems });
};
var onShapeEdited = function onShapeEdited(params) {
var shapes = params.shapes;
searchQuery = buildSearchQuery(shapes);
savePreferences({ drawnItems: params.drawnItems });
};
var onShapeDeleted = function onShapeDeleted(params) {
var shapes = params.shapes;
searchQuery = buildSearchQuery(shapes);
savePreferences({ drawnItems: params.drawnItems });
};
var buildCircularSearchQuery = function buildCircularSearchQuery(shapes) {
var queryTerms = [];
_underscore2.default.each(shapes, function (shape) {
var terms = [];
var distanceInKM = parseFloat(shape.getRadius()) / 1000;
terms.push('geolocation="' + shape.getCenter().lat + ' ' + shape.getCenter().lng + ' ' + distanceInKM.toFixed(2) + 'km"');
if (terms.length > 0) {
queryTerms.push(' (' + terms.join(' AND ') + ') ');
}
});
return queryTerms.join(' OR ');
};
var buildSearchQuery = function buildSearchQuery(shapes) {
var queryTerms = [];
_underscore2.default.each(shapes, function (shape) {
var terms = [];
if (shape.type === 'rectangle') {
var southWest = 0;
var northEst = 2;
for (var boundary in shape.bounds) {
if (shape.bounds.hasOwnProperty(boundary)) {
if (parseInt(boundary, 10) === southWest) {
// superior
for (var coordField in shape.bounds[boundary]) {
if (shape.bounds[boundary].hasOwnProperty(coordField)) {
terms.push(coordField + '>' + shape.bounds[boundary][coordField]);
}
}
} else if (parseInt(boundary, 10) === northEst) {
// inferior
for (var _coordField in shape.bounds[boundary]) {
if (shape.bounds[boundary].hasOwnProperty(_coordField)) {
terms.push(_coordField + '<' + shape.bounds[boundary][_coordField]);
}
}
}
}
}
}
if (terms.length > 0) {
queryTerms.push(' (' + terms.join(' AND ') + ') ');
}
});
return queryTerms.join(' OR ');
};
var savePreferences = function savePreferences(obj) {
//drawnItems = JSON.stringify(data);
appEvents.emit('searchForm.updatePreferences', obj);
};
appEvents.listenAll({
shapeCreated: onShapeCreated,
shapeEdited: onShapeEdited,
shapeRemoved: onShapeDeleted,
updateSearchValue: updateSearchValue,
updateCircleGeo: updateCircleGeo
});
return { openModal: openModal };
};
exports.default = searchGeoForm;
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
/*** IMPORTS FROM imports-loader ***/
var define = false;
var exports = false;
'use strict';
var _jquery = __webpack_require__(0);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
* $ Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function () {
// We override the animation for all of these color styles
_jquery2.default.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function (i, attr) {
_jquery2.default.fx.step[attr] = function (fx) {
if (fx.state === 0) {
fx.start = getColor(fx.elem, attr);
fx.end = getRGB(fx.end);
}
fx.elem.style[attr] = 'rgb(' + [Math.max(Math.min(parseInt(fx.pos * (fx.end[0] - fx.start[0]) + fx.start[0], 10), 255), 0), Math.max(Math.min(parseInt(fx.pos * (fx.end[1] - fx.start[1]) + fx.start[1], 10), 255), 0), Math.max(Math.min(parseInt(fx.pos * (fx.end[2] - fx.start[2]) + fx.start[2], 10), 255), 0)].join(',') + ')';
};
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://$.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if (color && color.constructor === Array && color.length === 3) {
return color;
}
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) {
return [parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10)];
}
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) {
return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55];
}
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) {
return [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];
}
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) {
return [parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16)];
}
// Otherwise, we're most likely dealing with a named color
return colors[_jquery2.default.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = _jquery2.default.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if (color !== '' && color !== 'transparent' || _jquery2.default.nodeName(elem, 'body')) {
break;
}
attr = 'backgroundColor';
} while (elem = elem.parentNode);
return getRGB(color);
}
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua: [0, 255, 255],
azure: [240, 255, 255],
beige: [245, 245, 220],
black: [0, 0, 0],
blue: [0, 0, 255],
brown: [165, 42, 42],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgrey: [169, 169, 169],
darkgreen: [0, 100, 0],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkviolet: [148, 0, 211],
fuchsia: [255, 0, 255],
gold: [255, 215, 0],
green: [0, 128, 0],
indigo: [75, 0, 130],
khaki: [240, 230, 140],
lightblue: [173, 216, 230],
lightcyan: [224, 255, 255],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
navy: [0, 0, 128],
olive: [128, 128, 0],
orange: [255, 165, 0],
pink: [255, 192, 203],
purple: [128, 0, 128],
violet: [128, 0, 128],
red: [255, 0, 0],
silver: [192, 192, 192],
white: [255, 255, 255],
yellow: [255, 255, 0]
};
})();
/***/ }),
/* 209 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/* Arabic Translation for jQuery UI date picker plugin. */
/* Khaled Alhourani -- me@khaledalhourani.com */
/* NOTE: monthNames are the original months names and they are the Arabic names, not the new months name فبراير - يناير and there isn't any Arabic roots for these months */
jQuery(function($){
$.datepicker.regional['ar'] = {
closeText: 'إغلاق',
prevText: '&#x3C;السابق',
nextText: 'التالي&#x3E;',
currentText: 'اليوم',
monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'مايو', 'حزيران',
'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
dayNames: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
dayNamesShort: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
dayNamesMin: ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
weekHeader: 'أسبوع',
dateFormat: 'dd/mm/yy',
firstDay: 6,
isRTL: true,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['ar']);
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
$.datepicker.regional['de'] = {
closeText: 'Schließen',
prevText: '&#x3C;Zurück',
nextText: 'Vor&#x3E;',
currentText: 'Heute',
monthNames: ['Januar','Februar','März','April','Mai','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Dez'],
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
weekHeader: 'KW',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['de']);
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/* Inicialización en español para la extensión 'UI date picker' para jQuery. */
/* Traducido por Vester (xvester@gmail.com). */
jQuery(function($){
$.datepicker.regional['es'] = {
closeText: 'Cerrar',
prevText: '&#x3C;Ant',
nextText: 'Sig&#x3E;',
currentText: 'Hoy',
monthNames: ['enero','febrero','marzo','abril','mayo','junio',
'julio','agosto','septiembre','octubre','noviembre','diciembre'],
monthNamesShort: ['ene','feb','mar','abr','may','jun',
'jul','ogo','sep','oct','nov','dic'],
dayNames: ['domingo','lunes','martes','miércoles','jueves','viernes','sábado'],
dayNamesShort: ['dom','lun','mar','mié','juv','vie','sáb'],
dayNamesMin: ['D','L','M','X','J','V','S'],
weekHeader: 'Sm',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['es']);
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood{at}iinet.com.au),
Stéphane Nahmani (sholby@sholby.net),
Stéphane Raimbault <stephane.raimbault@gmail.com> */
jQuery(function($){
$.datepicker.regional['fr'] = {
closeText: 'Fermer',
prevText: 'Précédent',
nextText: 'Suivant',
currentText: 'Aujourd\'hui',
monthNames: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
monthNamesShort: ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin',
'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
dayNames: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
dayNamesShort: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
dayNamesMin: ['D','L','M','M','J','V','S'],
weekHeader: 'Sem.',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['fr']);
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/* Dutch (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Mathias Bynens <http://mathiasbynens.be/> */
jQuery(function($){
$.datepicker.regional.nl = {
closeText: 'Sluiten',
prevText: '←',
nextText: '→',
currentText: 'Vandaag',
monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
monthNamesShort: ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun',
'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
weekHeader: 'Wk',
dateFormat: 'dd-mm-yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional.nl);
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(jQuery) {/* English/UK initialisation for the jQuery UI date picker plugin. */
/* Written by Stuart. */
jQuery(function($){
$.datepicker.regional['en-GB'] = {
closeText: 'Done',
prevText: 'Prev',
nextText: 'Next',
currentText: 'Today',
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
weekHeader: 'Wk',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['en-GB']);
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ })
],[89]);
});