code
stringlengths
2
1.05M
define({ "queries": "Запросы", "addNew": "Добавить новое", "newQuery": "Новый запрос", "queryLayer": "Запрос слоя", "setSource": "Установить", "setDataSource": "Задать источник данных", "name": "Имя канала", "querySource": "Источник данных", "queryName": "Имя задачи", "queryDefinition": "Определение фильтра", "resultsSetting": "Настройка результатов", "symbolSetting": "Настройка символов", "resultSettingTip": "Задайте способ отображения выходных результатов.", "resultItemTitle": "Заголовок каждого элемента-результата", "resultItemContent": "Эти атрибуты поля будут отображаться", "fieldsSetTip": "Отметьте поля, которые требуется отобразить. Выберите поле, чтобы изменить его псевдоним, порядок сортировки и формат.", "addField": "Добавить поле", "visibility": "Видимость", "alias": "Псевдоним", "specialType": "Особый тип", "actions": "Действия", "none": "Нет", "link": "Связь", "image": "Изображение", "noField": "Нет поля", "operationalLayerTip": "Добавить результат как операционный слой", "setLayerSymbolTip": "Задать символ для результатов запроса: ", "setSelectedSymbolTip": "Задать символ для выбранных объектов.", "notUseFilter": "Не используйте фильтр", "setSourceTip": "Задайте источник запроса.", "setFilterTip": "Задайте корректный фильтр.", "ok": "OK", "cancel": "Отмена", "noFilterTip": "Если не задано выражение для фильтра, этот запрос перечислит все объекты указанного источника данных.", "relationships": "Отношения", "addRelationshipLayer": "Добавить новое отношение", "relatedTo": "Связано с", "selectOption": "Выберите..", "resultItemSorting": "Сортировка элементов результатов", "field": "Поле", "sortingOrder": "Порядок", "configureFieldsTip": "Настройте поля, в которых будут сортироваться результаты запроса.", "setSortingFields": "Задать поля сортировки", "ascending": "По возрастанию", "descending": "По убыванию", "sortBy": "Сортировать по", "thenBy": "Далее по", "addTask": "Добавить задачу", "noTasksTip": "Нет настроенных запросов. Щелкните \"${newQuery}\", чтобы добавить новый.", "infoText": "Информация", "filters": "Фильтры", "results": "Результаты", "optionsText": "Опции", "summaryText": "Краткая информация", "attributeFilter": "Атрибутивный фильтр", "attributeFilterTip": "Задать атрибутивные выражения в виджете для фильтрации слоя запроса.", "defineWhereClause": "Задайте выражение \"where\" для запроса.", "noExpressionDefinedTip": "Выражение не задано. Будут возвращены все записи.", "setExpressions": "Задать Выражения", "spatialFilter": "Пространственные фильтры", "spatialFilterTip": "Выберите пространственные фильтры, которые будут доступны пользователям.", "defaultOption": "По умолчанию", "useCurrentExtentTip": "Возвращать объекты только в текущем экстенте карты", "useDrawGraphicTip": "Возвращать объекты, которые пересекают геометрию, нарисованную на карте", "useFeaturesTip": "Возвращать только объекты, которые имеют пространственные отношения с объектами другого слоя", "noSpatialLimitTip": "Возвращать объекты в полном экстенте карты", "drawingTools": "Выберите инструменты рисования", "bufferSettings": "Включить опцию буферизации", "defaultDistance": "Расстояние по умолчанию", "bufferDistance": "Буферное расстояние", "defaultUnit": "Единицы по умолчанию", "miles": "Мили", "kilometers": "Километры", "feet": "Футы", "meters": "Метры", "yards": "Ярды", "nauticalMiles": "Морские мили", "availableSpatialRelationships": "Выбрать правила пространственных отношений", "setSpatialRelationships": "Задать пространственные отношения", "availability": "Доступность", "relationship": "Отношение", "label": "Подпись", "intersect": "пересекают", "contain": "содержат", "areContainedIn": "содержатся в", "cross": "крест", "envelopeIntersect": "пересекает внешнюю границу", "overlap": "наложение", "areOverlapped": "перекрывается", "touch": "коснитесь", "within": "внутри", "areWithin": "находится в пределах", "indexIntersect": "пересекает индекс", "itemTitle": "Название элемента", "displayFields": "Поля отображения", "sortingFields": "Сортировка элементов-результатов", "setDisplayFields": "Задать отображаемые поля", "symbol": "Символ", "setSymbol": "Применить пользовательский символ", "changeSymbolAtRuntime": "Разрешить изменение символов при запуске", "serviceSymbolTip": "Использовать символы, заданные слоем", "exportTip": "Разрешить экспортировать результаты", "keepResultsTip": "Сохранить результаты на карте после закрытия виджета", "queryRelatedRecords": "Запрос к связанным записям", "createLayerForTaskTip": "Указать, как задача запроса будет создавать слои", "oneLayerForTaskTip": "Перезаписывать слой при каждом выполнении запроса", "multipleLayerForTaskTip": "Создавать новый слой при каждом выполнении запроса", "makeDefault": "Использовать по умолчанию", "icon": "Значок", "newTask": "Новая задача", "addTaskTip": "Добавьте в виджет один или несколько запросов и настройте их параметры.", "webMapPopupTip": "Использовать в веб-карте настройки всплывающих окон слоя", "customPopupTip": "Настроить пользовательские ресурсы", "showResultsSetActions": "Показать действия для набора результатов", "zoomTo": "Приблизить к", "openAttributeTable": "Открыть в таблице атрибутов", "content": "Ресурсы", "displaySQLTip": "Отображать SQL-выражение для пользователей", "useLayerDefaultSymbol": "Использовать символы слоя по умолчанию", "setCustomIcon": "Задать пользовательский значок", "layerDefaultSymbolTip": "Использовать символы слоя по умолчанию", "uploadImage": "Загрузить изображение", "attributeCriteira": "Критерий атрибута", "specifyFilterAtRuntimeTip": "Пользователи должны задать параметры этого выражения.", "value": "ЗНАЧЕНИЕ", "hideLayersTip": "Выключить слои результата запроса при закрытии виджета." });
'use strict'; var util = require('./util'); var isWindows = process.platform === 'win32'; function assertPath(path) { if (typeof path !== 'string') { throw new TypeError('Path must be a string. Received ' + util.inspect(path)); } } // resolves . and .. elements in a path array with directory names there // must be no slashes or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { var res = []; for (var i = 0; i < parts.length; i++) { var p = parts[i]; // ignore empty parts if (!p || p === '.') continue; if (p === '..') { if (res.length && res[res.length - 1] !== '..') { res.pop(); } else if (allowAboveRoot) { res.push('..'); } } else { res.push(p); } } return res; } // Returns an array with empty elements removed from either end of the input // array or the original array if no elements need to be removed function trimArray(arr) { var lastIndex = arr.length - 1; var start = 0; for (; start <= lastIndex; start++) { if (arr[start]) break; } var end = lastIndex; for (; end >= 0; end--) { if (arr[end]) break; } if (start === 0 && end === lastIndex) return arr; if (start > end) return []; return arr.slice(start, end + 1); } // Regex to split a windows path into three parts: [*, device, slash, // tail] windows-only var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext] var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; var win32 = {}; // Function to split a filename into [root, dir, basename, ext] function win32SplitPath(filename) { // Separate device+slash from tail var result = splitDeviceRe.exec(filename), device = (result[1] || '') + (result[2] || ''), tail = result[3]; // Split the tail into dir, basename and extension var result2 = splitTailRe.exec(tail), dir = result2[1], basename = result2[2], ext = result2[3]; return [device, dir, basename, ext]; } function win32StatPath(path) { var result = splitDeviceRe.exec(path), device = result[1] || '', isUnc = !!device && device[1] !== ':'; return { device, isUnc, isAbsolute: isUnc || !!result[2], // UNC paths are always absolute tail: result[3] }; } function normalizeUNCRoot(device) { return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\'); } // path.resolve([from ...], to) win32.resolve = function() { var resolvedDevice = '', resolvedTail = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1; i--) { var path; if (i >= 0) { path = arguments[i]; } else if (!resolvedDevice) { path = process.cwd(); } else { // Windows has the concept of drive-specific current working // directories. If we've resolved a drive letter but not yet an // absolute path, get cwd for that drive. We're sure the device is not // an unc path at this points, because unc paths are always absolute. path = process.env['=' + resolvedDevice]; // Verify that a drive-local cwd was found and that it actually points // to our drive. If not, default to the drive's root. if (!path || path.substr(0, 3).toLowerCase() !== resolvedDevice.toLowerCase() + '\\') { path = resolvedDevice + '\\'; } } assertPath(path); // Skip empty entries if (path === '') { continue; } var result = win32StatPath(path), device = result.device, isUnc = result.isUnc, isAbsolute = result.isAbsolute, tail = result.tail; if (device && resolvedDevice && device.toLowerCase() !== resolvedDevice.toLowerCase()) { // This path points to another device so it is not applicable continue; } if (!resolvedDevice) { resolvedDevice = device; } if (!resolvedAbsolute) { resolvedTail = tail + '\\' + resolvedTail; resolvedAbsolute = isAbsolute; } if (resolvedDevice && resolvedAbsolute) { break; } } // Convert slashes to backslashes when `resolvedDevice` points to an UNC // root. Also squash multiple slashes into a single one where appropriate. if (isUnc) { resolvedDevice = normalizeUNCRoot(resolvedDevice); } // At this point the path should be resolved to a full absolute path, // but handle relative paths to be safe (might happen when process.cwd() // fails) // Normalize the tail path resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/), !resolvedAbsolute).join('\\'); return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) || '.'; }; win32.normalize = function(path) { assertPath(path); var result = win32StatPath(path), device = result.device, isUnc = result.isUnc, isAbsolute = result.isAbsolute, tail = result.tail, trailingSlash = /[\\\/]$/.test(tail); // Normalize the tail path tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\'); if (!tail && !isAbsolute) { tail = '.'; } if (tail && trailingSlash) { tail += '\\'; } // Convert slashes to backslashes when `device` points to an UNC root. // Also squash multiple slashes into a single one where appropriate. if (isUnc) { device = normalizeUNCRoot(device); } return device + (isAbsolute ? '\\' : '') + tail; }; win32.isAbsolute = function(path) { assertPath(path); return win32StatPath(path).isAbsolute; }; win32.join = function() { var paths = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; assertPath(arg); if (arg) { paths.push(arg); } } var joined = paths.join('\\'); // Make sure that the joined path doesn't start with two slashes, because // normalize() will mistake it for an UNC path then. // // This step is skipped when it is very clear that the user actually // intended to point at an UNC path. This is assumed when the first // non-empty string arguments starts with exactly two slashes followed by // at least one more non-slash character. // // Note that for normalize() to treat a path as an UNC path it needs to // have at least 2 components, so we don't filter for that here. // This means that the user can use join to construct UNC paths from // a server name and a share name; for example: // path.join('//server', 'share') -> '\\\\server\\share\') if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) { joined = joined.replace(/^[\\\/]{2,}/, '\\'); } return win32.normalize(joined); }; // path.relative(from, to) // it will solve the relative path from 'from' to 'to', for instance: // from = 'C:\\orandea\\test\\aaa' // to = 'C:\\orandea\\impl\\bbb' // The output of the function should be: '..\\..\\impl\\bbb' win32.relative = function(from, to) { assertPath(from); assertPath(to); from = win32.resolve(from); to = win32.resolve(to); // windows is not case sensitive var lowerFrom = from.toLowerCase(); var lowerTo = to.toLowerCase(); var toParts = trimArray(to.split('\\')); var lowerFromParts = trimArray(lowerFrom.split('\\')); var lowerToParts = trimArray(lowerTo.split('\\')); var length = Math.min(lowerFromParts.length, lowerToParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (lowerFromParts[i] !== lowerToParts[i]) { samePartsLength = i; break; } } if (samePartsLength === 0) { return to; } var outputParts = []; for (var i = samePartsLength; i < lowerFromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('\\'); }; win32._makeLong = function(path) { // Note: this will *probably* throw somewhere. if (typeof path !== 'string') return path; if (!path) { return ''; } var resolvedPath = win32.resolve(path); if (/^[a-zA-Z]\:\\/.test(resolvedPath)) { // path is local filesystem path, which needs to be converted // to long UNC path. return '\\\\?\\' + resolvedPath; } else if (/^\\\\[^?.]/.test(resolvedPath)) { // path is network UNC path, which needs to be converted // to long UNC path. return '\\\\?\\UNC\\' + resolvedPath.substring(2); } return path; }; win32.dirname = function(path) { var result = win32SplitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; win32.basename = function(path, ext) { if (ext !== undefined && typeof ext !== 'string') throw new TypeError('ext must be a string'); var f = win32SplitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; win32.extname = function(path) { return win32SplitPath(path)[3]; }; win32.format = function(pathObject) { if (pathObject === null || typeof pathObject !== 'object') { throw new TypeError( "Parameter 'pathObject' must be an object, not " + typeof pathObject ); } var root = pathObject.root || ''; if (typeof root !== 'string') { throw new TypeError( "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root ); } var dir = pathObject.dir; var base = pathObject.base || ''; if (!dir) { return base; } if (dir[dir.length - 1] === win32.sep) { return dir + base; } return dir + win32.sep + base; }; win32.parse = function(pathString) { assertPath(pathString); var allParts = win32SplitPath(pathString); return { root: allParts[0], dir: allParts[0] + allParts[1].slice(0, -1), base: allParts[2], ext: allParts[3], name: allParts[2].slice(0, allParts[2].length - allParts[3].length) }; }; win32.sep = '\\'; win32.delimiter = ';'; // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var posix = {}; function posixSplitPath(filename) { var out = splitPathRe.exec(filename); out.shift(); return out; } // path.resolve([from ...], to) // posix version posix.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); assertPath(path); // Skip empty entries if (path === '') { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path[0] === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(resolvedPath.split('/'), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version posix.normalize = function(path) { assertPath(path); var isAbsolute = posix.isAbsolute(path), trailingSlash = path && path[path.length - 1] === '/'; // Normalize the path path = normalizeArray(path.split('/'), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version posix.isAbsolute = function(path) { assertPath(path); return !!path && path[0] === '/'; }; // posix version posix.join = function() { var path = ''; for (var i = 0; i < arguments.length; i++) { var segment = arguments[i]; assertPath(segment); if (segment) { if (!path) { path += segment; } else { path += '/' + segment; } } } return posix.normalize(path); }; // path.relative(from, to) // posix version posix.relative = function(from, to) { assertPath(from); assertPath(to); from = posix.resolve(from).substr(1); to = posix.resolve(to).substr(1); var fromParts = trimArray(from.split('/')); var toParts = trimArray(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; posix._makeLong = function(path) { return path; }; posix.dirname = function(path) { var result = posixSplitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; posix.basename = function(path, ext) { if (ext !== undefined && typeof ext !== 'string') throw new TypeError('ext must be a string'); var f = posixSplitPath(path)[2]; if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; posix.extname = function(path) { return posixSplitPath(path)[3]; }; posix.format = function(pathObject) { if (pathObject === null || typeof pathObject !== 'object') { throw new TypeError( "Parameter 'pathObject' must be an object, not " + typeof pathObject ); } var root = pathObject.root || ''; if (typeof root !== 'string') { throw new TypeError( "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root ); } var dir = pathObject.dir ? pathObject.dir + posix.sep : ''; var base = pathObject.base || ''; return dir + base; }; posix.parse = function(pathString) { assertPath(pathString); var allParts = posixSplitPath(pathString); return { root: allParts[0], dir: allParts[0] + allParts[1].slice(0, -1), base: allParts[2], ext: allParts[3], name: allParts[2].slice(0, allParts[2].length - allParts[3].length) }; }; posix.sep = '/'; posix.delimiter = ':'; if (isWindows) module.exports = win32; else /* posix */ module.exports = posix; module.exports.posix = posix; module.exports.win32 = win32;
function render(param) { return <root>{param}</root>; }
module.exports = { config: { type: 'polarArea', data: { labels: [0, 1, 2, 3, 4, 5], datasets: [ { // option in dataset data: [0, 2, 4, null, 6, 8], borderAlign: [ 'center', 'inner', 'center', 'inner', 'center', 'inner', ], borderColor: '#00ff00' }, ] }, options: { legend: false, title: false, elements: { arc: { backgroundColor: 'transparent', borderColor: '#ff0000', borderWidth: 5, } }, scale: { display: false } } }, options: { canvas: { height: 256, width: 512 } } };
 /** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'kama', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'about' : 1, 'a11yhelp' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'resize' : 1, 'toolbar' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'wysiwygarea' : 1, 'image' : 1, 'indentlist' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastetext' : 1, 'pastefromword' : 1, 'removeformat' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'scayt' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'undo' : 1, 'wsc' : 1, 'dialog' : 1, 'dialogui' : 1, 'menu' : 1, 'floatpanel' : 1, 'panel' : 1, 'button' : 1, 'popup' : 1, 'richcombo' : 1, 'listblock' : 1, 'indent' : 1, 'fakeobjects' : 1, 'menubutton' : 1 }, languages : { 'en' : 1, 'ru' : 1 } };
module.exports = config => { config.set({ basePath: __dirname, singleRun: true, frameworks: ['mocha'], reporters: ['dots'], browsers: ['Chrome'], files: [ 'test/**/*.spec.js', ], preprocessors: { 'test/**/*.spec.js': ['webpack'], }, webpack: { resolve: { extensions: ['', '.js', '.ts'], modulesDirectories: ['node_modules', 'src'], }, module: { loaders: [{ test: /\.js$/, loader: 'babel-loader', }], }, }, webpackMiddleware: { stats: { color: true, chunkModules: false, modules: false, }, }, }); };
import { fn, text } from './dep1.js'; export default class Main1 { constructor () { fn(); console.log(text); } }
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-7cdd32a */ goog.provide('ngmaterial.components.chips'); goog.require('ngmaterial.components.autocomplete'); goog.require('ngmaterial.core'); /** * @ngdoc module * @name material.components.chips */ /* * @see js folder for chips implementation */ angular.module('material.components.chips', [ 'material.core', 'material.components.autocomplete' ]); MdChipCtrl.$inject = ["$scope", "$element", "$mdConstant", "$timeout", "$mdUtil"];angular .module('material.components.chips') .controller('MdChipCtrl', MdChipCtrl); /** * Controller for the MdChip component. Responsible for handling keyboard * events and editting the chip if needed. * * @param $scope * @param $element * @param $mdConstant * @param $timeout * @param $mdUtil * @constructor */ function MdChipCtrl ($scope, $element, $mdConstant, $timeout, $mdUtil) { /** * @type {$scope} */ this.$scope = $scope; /** * @type {$element} */ this.$element = $element; /** * @type {$mdConstant} */ this.$mdConstant = $mdConstant; /** * @type {$timeout} */ this.$timeout = $timeout; /** * @type {$mdUtil} */ this.$mdUtil = $mdUtil; /** * @type {boolean} */ this.isEditting = false; /** * @type {MdChipsCtrl} */ this.parentController = undefined; /** * @type {boolean} */ this.enableChipEdit = false; } /** * @param {MdChipsCtrl} controller */ MdChipCtrl.prototype.init = function(controller) { this.parentController = controller; this.enableChipEdit = this.parentController.enableChipEdit; if (this.enableChipEdit) { this.$element.on('keydown', this.chipKeyDown.bind(this)); this.$element.on('mousedown', this.chipMouseDown.bind(this)); this.getChipContent().addClass('_md-chip-content-edit-is-enabled'); } }; /** * @return {Object} */ MdChipCtrl.prototype.getChipContent = function() { var chipContents = this.$element[0].getElementsByClassName('md-chip-content'); return angular.element(chipContents[0]); }; /** * @return {Object} */ MdChipCtrl.prototype.getContentElement = function() { return angular.element(this.getChipContent().children()[0]); }; /** * @return {number} */ MdChipCtrl.prototype.getChipIndex = function() { return parseInt(this.$element.attr('index')); }; /** * Presents an input element to edit the contents of the chip. */ MdChipCtrl.prototype.goOutOfEditMode = function() { if (!this.isEditting) return; this.isEditting = false; this.$element.removeClass('_md-chip-editing'); this.getChipContent()[0].contentEditable = 'false'; var chipIndex = this.getChipIndex(); var content = this.getContentElement().text(); if (content) { this.parentController.updateChipContents( chipIndex, this.getContentElement().text() ); this.$mdUtil.nextTick(function() { if (this.parentController.selectedChip === chipIndex) { this.parentController.focusChip(chipIndex); } }.bind(this)); } else { this.parentController.removeChipAndFocusInput(chipIndex); } }; /** * Given an HTML element. Selects contents of it. * @param node */ MdChipCtrl.prototype.selectNodeContents = function(node) { var range, selection; if (document.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(node); range.select(); } else if (window.getSelection) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(node); selection.removeAllRanges(); selection.addRange(range); } }; /** * Presents an input element to edit the contents of the chip. */ MdChipCtrl.prototype.goInEditMode = function() { this.isEditting = true; this.$element.addClass('_md-chip-editing'); this.getChipContent()[0].contentEditable = 'true'; this.getChipContent().on('blur', function() { this.goOutOfEditMode(); }.bind(this)); this.selectNodeContents(this.getChipContent()[0]); }; /** * Handles the keydown event on the chip element. If enable-chip-edit attribute is * set to true, space or enter keys can trigger going into edit mode. Enter can also * trigger submitting if the chip is already being edited. * @param event */ MdChipCtrl.prototype.chipKeyDown = function(event) { if (!this.isEditting && (event.keyCode === this.$mdConstant.KEY_CODE.ENTER || event.keyCode === this.$mdConstant.KEY_CODE.SPACE)) { event.preventDefault(); this.goInEditMode(); } else if (this.isEditting && event.keyCode === this.$mdConstant.KEY_CODE.ENTER) { event.preventDefault(); this.goOutOfEditMode(); } }; /** * Handles the double click event */ MdChipCtrl.prototype.chipMouseDown = function() { if(this.getChipIndex() == this.parentController.selectedChip && this.enableChipEdit && !this.isEditting) { this.goInEditMode(); } }; MdChip.$inject = ["$mdTheming", "$mdUtil"];angular .module('material.components.chips') .directive('mdChip', MdChip); /** * @ngdoc directive * @name mdChip * @module material.components.chips * * @description * `<md-chip>` is a component used within `<md-chips>` and is responsible for rendering individual * chips. * * * @usage * <hljs lang="html"> * <md-chip>{{$chip}}</md-chip> * </hljs> * */ // This hint text is hidden within a chip but used by screen readers to // inform the user how they can interact with a chip. var DELETE_HINT_TEMPLATE = '\ <span ng-if="!$mdChipsCtrl.readonly" class="md-visually-hidden">\ {{$mdChipsCtrl.deleteHint}}\ </span>'; /** * MDChip Directive Definition * * @param $mdTheming * @param $mdUtil * ngInject */ function MdChip($mdTheming, $mdUtil) { var hintTemplate = $mdUtil.processTemplate(DELETE_HINT_TEMPLATE); return { restrict: 'E', require: ['^?mdChips', 'mdChip'], compile: compile, controller: 'MdChipCtrl' }; function compile(element, attr) { // Append the delete template element.append($mdUtil.processTemplate(hintTemplate)); return function postLink(scope, element, attr, ctrls) { var chipsController = ctrls.shift(); var chipController = ctrls.shift(); $mdTheming(element); if (chipsController) { chipController.init(chipsController); angular .element(element[0] .querySelector('.md-chip-content')) .on('blur', function () { chipsController.resetSelectedChip(); chipsController.$scope.$applyAsync(); }); } }; } } MdChipRemove.$inject = ["$timeout"];angular .module('material.components.chips') .directive('mdChipRemove', MdChipRemove); /** * @ngdoc directive * @name mdChipRemove * @restrict A * @module material.components.chips * * @description * Designates an element to be used as the delete button for a chip. <br/> * This element is passed as a child of the `md-chips` element. * * The designated button will be just appended to the chip and removes the given chip on click.<br/> * By default the button is not being styled by the `md-chips` component. * * @usage * <hljs lang="html"> * <md-chips> * <button md-chip-remove=""> * <md-icon md-svg-icon="md-close"></md-icon> * </button> * </md-chips> * </hljs> */ /** * MdChipRemove Directive Definition. * * @param $timeout * @returns {{restrict: string, require: string[], link: Function, scope: boolean}} * @constructor */ function MdChipRemove ($timeout) { return { restrict: 'A', require: '^mdChips', scope: false, link: postLink }; function postLink(scope, element, attr, ctrl) { element.on('click', function(event) { scope.$apply(function() { ctrl.removeChip(scope.$$replacedScope.$index); }); }); // Child elements aren't available until after a $timeout tick as they are hidden by an // `ng-if`. see http://goo.gl/zIWfuw $timeout(function() { element.attr({ tabindex: -1, 'aria-hidden': true }); element.find('button').attr('tabindex', '-1'); }); } } MdChipTransclude.$inject = ["$compile"];angular .module('material.components.chips') .directive('mdChipTransclude', MdChipTransclude); function MdChipTransclude ($compile) { return { restrict: 'EA', terminal: true, link: link, scope: false }; function link (scope, element, attr) { var ctrl = scope.$parent.$mdChipsCtrl, newScope = ctrl.parent.$new(false, ctrl.parent); newScope.$$replacedScope = scope; newScope.$chip = scope.$chip; newScope.$index = scope.$index; newScope.$mdChipsCtrl = ctrl; var newHtml = ctrl.$scope.$eval(attr.mdChipTransclude); element.html(newHtml); $compile(element.contents())(newScope); } } MdChipsCtrl.$inject = ["$scope", "$attrs", "$mdConstant", "$log", "$element", "$timeout", "$mdUtil"];angular .module('material.components.chips') .controller('MdChipsCtrl', MdChipsCtrl); /** * Controller for the MdChips component. Responsible for adding to and * removing from the list of chips, marking chips as selected, and binding to * the models of various input components. * * @param $scope * @param $attrs * @param $mdConstant * @param $log * @param $element * @param $timeout * @param $mdUtil * @constructor */ function MdChipsCtrl ($scope, $attrs, $mdConstant, $log, $element, $timeout, $mdUtil) { /** @type {$timeout} **/ this.$timeout = $timeout; /** @type {Object} */ this.$mdConstant = $mdConstant; /** @type {angular.$scope} */ this.$scope = $scope; /** @type {angular.$scope} */ this.parent = $scope.$parent; /** @type {$mdUtil} */ this.$mdUtil = $mdUtil; /** @type {$log} */ this.$log = $log; /** @type {$element} */ this.$element = $element; /** @type {angular.NgModelController} */ this.ngModelCtrl = null; /** @type {angular.NgModelController} */ this.userInputNgModelCtrl = null; /** @type {MdAutocompleteCtrl} */ this.autocompleteCtrl = null; /** @type {Element} */ this.userInputElement = null; /** @type {Array.<Object>} */ this.items = []; /** @type {number} */ this.selectedChip = -1; /** @type {string} */ this.enableChipEdit = $mdUtil.parseAttributeBoolean($attrs.mdEnableChipEdit); /** @type {string} */ this.addOnBlur = $mdUtil.parseAttributeBoolean($attrs.mdAddOnBlur); /** * Hidden hint text for how to delete a chip. Used to give context to screen readers. * @type {string} */ this.deleteHint = 'Press delete to remove this chip.'; /** * Hidden label for the delete button. Used to give context to screen readers. * @type {string} */ this.deleteButtonLabel = 'Remove'; /** * Model used by the input element. * @type {string} */ this.chipBuffer = ''; /** * Whether to use the transformChip expression to transform the chip buffer * before appending it to the list. * @type {boolean} */ this.useTransformChip = false; /** * Whether to use the onAdd expression to notify of chip additions. * @type {boolean} */ this.useOnAdd = false; /** * Whether to use the onRemove expression to notify of chip removals. * @type {boolean} */ this.useOnRemove = false; /** * Whether to use the onSelect expression to notify the component's user * after selecting a chip from the list. * @type {boolean} */ } /** * Handles the keydown event on the input element: by default <enter> appends * the buffer to the chip list, while backspace removes the last chip in the * list if the current buffer is empty. * @param event */ MdChipsCtrl.prototype.inputKeydown = function(event) { var chipBuffer = this.getChipBuffer(); // If we have an autocomplete, and it handled the event, we have nothing to do if (this.autocompleteCtrl && event.isDefaultPrevented && event.isDefaultPrevented()) { return; } if (event.keyCode === this.$mdConstant.KEY_CODE.BACKSPACE) { // Only select and focus the previous chip, if the current caret position of the // input element is at the beginning. if (this.getCursorPosition(event.target) !== 0) { return; } event.preventDefault(); event.stopPropagation(); if (this.items.length) { this.selectAndFocusChipSafe(this.items.length - 1); } return; } // By default <enter> appends the buffer to the chip list. if (!this.separatorKeys || this.separatorKeys.length < 1) { this.separatorKeys = [this.$mdConstant.KEY_CODE.ENTER]; } // Support additional separator key codes in an array of `md-separator-keys`. if (this.separatorKeys.indexOf(event.keyCode) !== -1) { if ((this.autocompleteCtrl && this.requireMatch) || !chipBuffer) return; event.preventDefault(); // Only append the chip and reset the chip buffer if the max chips limit isn't reached. if (this.hasMaxChipsReached()) return; this.appendChip(chipBuffer.trim()); this.resetChipBuffer(); } }; /** * Returns the cursor position of the specified input element. * @param element HTMLInputElement * @returns {Number} Cursor Position of the input. */ MdChipsCtrl.prototype.getCursorPosition = function(element) { /* * Figure out whether the current input for the chips buffer is valid for using * the selectionStart / end property to retrieve the cursor position. * Some browsers do not allow the use of those attributes, on different input types. */ try { if (element.selectionStart === element.selectionEnd) { return element.selectionStart; } } catch (e) { if (!element.value) { return 0; } } }; /** * Updates the content of the chip at given index * @param chipIndex * @param chipContents */ MdChipsCtrl.prototype.updateChipContents = function(chipIndex, chipContents){ if(chipIndex >= 0 && chipIndex < this.items.length) { this.items[chipIndex] = chipContents; this.ngModelCtrl.$setDirty(); } }; /** * Returns true if a chip is currently being edited. False otherwise. * @return {boolean} */ MdChipsCtrl.prototype.isEditingChip = function() { return !!this.$element[0].querySelector('._md-chip-editing'); }; MdChipsCtrl.prototype.isRemovable = function() { // Return false if we have static chips if (!this.ngModelCtrl) { return false; } return this.readonly ? this.removable : angular.isDefined(this.removable) ? this.removable : true; }; /** * Handles the keydown event on the chip elements: backspace removes the selected chip, arrow * keys switch which chips is active * @param event */ MdChipsCtrl.prototype.chipKeydown = function (event) { if (this.getChipBuffer()) return; if (this.isEditingChip()) return; switch (event.keyCode) { case this.$mdConstant.KEY_CODE.BACKSPACE: case this.$mdConstant.KEY_CODE.DELETE: if (this.selectedChip < 0) return; event.preventDefault(); // Cancel the delete action only after the event cancel. Otherwise the page will go back. if (!this.isRemovable()) return; this.removeAndSelectAdjacentChip(this.selectedChip); break; case this.$mdConstant.KEY_CODE.LEFT_ARROW: event.preventDefault(); if (this.selectedChip < 0) this.selectedChip = this.items.length; if (this.items.length) this.selectAndFocusChipSafe(this.selectedChip - 1); break; case this.$mdConstant.KEY_CODE.RIGHT_ARROW: event.preventDefault(); this.selectAndFocusChipSafe(this.selectedChip + 1); break; case this.$mdConstant.KEY_CODE.ESCAPE: case this.$mdConstant.KEY_CODE.TAB: if (this.selectedChip < 0) return; event.preventDefault(); this.onFocus(); break; } }; /** * Get the input's placeholder - uses `placeholder` when list is empty and `secondary-placeholder` * when the list is non-empty. If `secondary-placeholder` is not provided, `placeholder` is used * always. */ MdChipsCtrl.prototype.getPlaceholder = function() { // Allow `secondary-placeholder` to be blank. var useSecondary = (this.items && this.items.length && (this.secondaryPlaceholder == '' || this.secondaryPlaceholder)); return useSecondary ? this.secondaryPlaceholder : this.placeholder; }; /** * Removes chip at {@code index} and selects the adjacent chip. * @param index */ MdChipsCtrl.prototype.removeAndSelectAdjacentChip = function(index) { var selIndex = this.getAdjacentChipIndex(index); this.removeChip(index); this.$timeout(angular.bind(this, function () { this.selectAndFocusChipSafe(selIndex); })); }; /** * Sets the selected chip index to -1. */ MdChipsCtrl.prototype.resetSelectedChip = function() { this.selectedChip = -1; }; /** * Gets the index of an adjacent chip to select after deletion. Adjacency is * determined as the next chip in the list, unless the target chip is the * last in the list, then it is the chip immediately preceding the target. If * there is only one item in the list, -1 is returned (select none). * The number returned is the index to select AFTER the target has been * removed. * If the current chip is not selected, then -1 is returned to select none. */ MdChipsCtrl.prototype.getAdjacentChipIndex = function(index) { var len = this.items.length - 1; return (len == 0) ? -1 : (index == len) ? index -1 : index; }; /** * Append the contents of the buffer to the chip list. This method will first * call out to the md-transform-chip method, if provided. * * @param newChip */ MdChipsCtrl.prototype.appendChip = function(newChip) { if (this.useTransformChip && this.transformChip) { var transformedChip = this.transformChip({'$chip': newChip}); // Check to make sure the chip is defined before assigning it, otherwise, we'll just assume // they want the string version. if (angular.isDefined(transformedChip)) { newChip = transformedChip; } } // If items contains an identical object to newChip, do not append if (angular.isObject(newChip)){ var identical = this.items.some(function(item){ return angular.equals(newChip, item); }); if (identical) return; } // Check for a null (but not undefined), or existing chip and cancel appending if (newChip == null || this.items.indexOf(newChip) + 1) return; // Append the new chip onto our list var index = this.items.push(newChip); // Update model validation this.ngModelCtrl.$setDirty(); this.validateModel(); // If they provide the md-on-add attribute, notify them of the chip addition if (this.useOnAdd && this.onAdd) { this.onAdd({ '$chip': newChip, '$index': index }); } }; /** * Sets whether to use the md-transform-chip expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code transformChip}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useTransformChipExpression = function() { this.useTransformChip = true; }; /** * Sets whether to use the md-on-add expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code onAdd}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useOnAddExpression = function() { this.useOnAdd = true; }; /** * Sets whether to use the md-on-remove expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code onRemove}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useOnRemoveExpression = function() { this.useOnRemove = true; }; /* * Sets whether to use the md-on-select expression. This expression is * bound to scope and controller in {@code MdChipsDirective} as * {@code onSelect}. Due to the nature of directive scope bindings, the * controller cannot know on its own/from the scope whether an expression was * actually provided. */ MdChipsCtrl.prototype.useOnSelectExpression = function() { this.useOnSelect = true; }; /** * Gets the input buffer. The input buffer can be the model bound to the * default input item {@code this.chipBuffer}, the {@code selectedItem} * model of an {@code md-autocomplete}, or, through some magic, the model * bound to any inpput or text area element found within a * {@code md-input-container} element. * @return {Object|string} */ MdChipsCtrl.prototype.getChipBuffer = function() { return !this.userInputElement ? this.chipBuffer : this.userInputNgModelCtrl ? this.userInputNgModelCtrl.$viewValue : this.userInputElement[0].value; }; /** * Resets the input buffer for either the internal input or user provided input element. */ MdChipsCtrl.prototype.resetChipBuffer = function() { if (this.userInputElement) { if (this.userInputNgModelCtrl) { this.userInputNgModelCtrl.$setViewValue(''); this.userInputNgModelCtrl.$render(); } else { this.userInputElement[0].value = ''; } } else { this.chipBuffer = ''; } }; MdChipsCtrl.prototype.hasMaxChipsReached = function() { if (angular.isString(this.maxChips)) this.maxChips = parseInt(this.maxChips, 10) || 0; return this.maxChips > 0 && this.items.length >= this.maxChips; }; /** * Updates the validity properties for the ngModel. */ MdChipsCtrl.prototype.validateModel = function() { this.ngModelCtrl.$setValidity('md-max-chips', !this.hasMaxChipsReached()); }; /** * Removes the chip at the given index. * @param index */ MdChipsCtrl.prototype.removeChip = function(index) { var removed = this.items.splice(index, 1); // Update model validation this.ngModelCtrl.$setDirty(); this.validateModel(); if (removed && removed.length && this.useOnRemove && this.onRemove) { this.onRemove({ '$chip': removed[0], '$index': index }); } }; MdChipsCtrl.prototype.removeChipAndFocusInput = function (index) { this.removeChip(index); if (this.autocompleteCtrl) { // Always hide the autocomplete dropdown before focusing the autocomplete input. // Wait for the input to move horizontally, because the chip was removed. // This can lead to an incorrect dropdown position. this.autocompleteCtrl.hidden = true; this.$mdUtil.nextTick(this.onFocus.bind(this)); } else { this.onFocus(); } }; /** * Selects the chip at `index`, * @param index */ MdChipsCtrl.prototype.selectAndFocusChipSafe = function(index) { if (!this.items.length) { this.selectChip(-1); this.onFocus(); return; } if (index === this.items.length) return this.onFocus(); index = Math.max(index, 0); index = Math.min(index, this.items.length - 1); this.selectChip(index); this.focusChip(index); }; /** * Marks the chip at the given index as selected. * @param index */ MdChipsCtrl.prototype.selectChip = function(index) { if (index >= -1 && index <= this.items.length) { this.selectedChip = index; // Fire the onSelect if provided if (this.useOnSelect && this.onSelect) { this.onSelect({'$chip': this.items[this.selectedChip] }); } } else { this.$log.warn('Selected Chip index out of bounds; ignoring.'); } }; /** * Selects the chip at `index` and gives it focus. * @param index */ MdChipsCtrl.prototype.selectAndFocusChip = function(index) { this.selectChip(index); if (index != -1) { this.focusChip(index); } }; /** * Call `focus()` on the chip at `index` */ MdChipsCtrl.prototype.focusChip = function(index) { this.$element[0].querySelector('md-chip[index="' + index + '"] .md-chip-content').focus(); }; /** * Configures the required interactions with the ngModel Controller. * Specifically, set {@code this.items} to the {@code NgModelCtrl#$viewVale}. * @param ngModelCtrl */ MdChipsCtrl.prototype.configureNgModel = function(ngModelCtrl) { this.ngModelCtrl = ngModelCtrl; var self = this; ngModelCtrl.$render = function() { // model is updated. do something. self.items = self.ngModelCtrl.$viewValue; }; }; MdChipsCtrl.prototype.onFocus = function () { var input = this.$element[0].querySelector('input'); input && input.focus(); this.resetSelectedChip(); }; MdChipsCtrl.prototype.onInputFocus = function () { this.inputHasFocus = true; this.resetSelectedChip(); }; MdChipsCtrl.prototype.onInputBlur = function () { this.inputHasFocus = false; var chipBuffer = this.getChipBuffer().trim(); // Update the custom chip validators. this.validateModel(); var isModelValid = this.ngModelCtrl.$valid; if (this.userInputNgModelCtrl) { isModelValid &= this.userInputNgModelCtrl.$valid; } // Only append the chip and reset the chip buffer if the chips and input ngModel is valid. if (this.addOnBlur && chipBuffer && isModelValid) { this.appendChip(chipBuffer); this.resetChipBuffer(); } }; /** * Configure event bindings on a user-provided input element. * @param inputElement */ MdChipsCtrl.prototype.configureUserInput = function(inputElement) { this.userInputElement = inputElement; // Find the NgModelCtrl for the input element var ngModelCtrl = inputElement.controller('ngModel'); // `.controller` will look in the parent as well. if (ngModelCtrl != this.ngModelCtrl) { this.userInputNgModelCtrl = ngModelCtrl; } var scope = this.$scope; var ctrl = this; // Run all of the events using evalAsync because a focus may fire a blur in the same digest loop var scopeApplyFn = function(event, fn) { scope.$evalAsync(angular.bind(ctrl, fn, event)); }; // Bind to keydown and focus events of input inputElement .attr({ tabindex: 0 }) .on('keydown', function(event) { scopeApplyFn(event, ctrl.inputKeydown) }) .on('focus', function(event) { scopeApplyFn(event, ctrl.onInputFocus) }) .on('blur', function(event) { scopeApplyFn(event, ctrl.onInputBlur) }) }; MdChipsCtrl.prototype.configureAutocomplete = function(ctrl) { if (ctrl) { this.autocompleteCtrl = ctrl; ctrl.registerSelectedItemWatcher(angular.bind(this, function (item) { if (item) { // Only append the chip and reset the chip buffer if the max chips limit isn't reached. if (this.hasMaxChipsReached()) return; this.appendChip(item); this.resetChipBuffer(); } })); this.$element.find('input') .on('focus',angular.bind(this, this.onInputFocus) ) .on('blur', angular.bind(this, this.onInputBlur) ); } }; MdChipsCtrl.prototype.hasFocus = function () { return this.inputHasFocus || this.selectedChip >= 0; }; MdChips.$inject = ["$mdTheming", "$mdUtil", "$compile", "$log", "$timeout", "$$mdSvgRegistry"];angular .module('material.components.chips') .directive('mdChips', MdChips); /** * @ngdoc directive * @name mdChips * @module material.components.chips * * @description * `<md-chips>` is an input component for building lists of strings or objects. The list items are * displayed as 'chips'. This component can make use of an `<input>` element or an * `<md-autocomplete>` element. * * ### Custom templates * A custom template may be provided to render the content of each chip. This is achieved by * specifying an `<md-chip-template>` element containing the custom content as a child of * `<md-chips>`. * * Note: Any attributes on * `<md-chip-template>` will be dropped as only the innerHTML is used for the chip template. The * variables `$chip` and `$index` are available in the scope of `<md-chip-template>`, representing * the chip object and its index in the list of chips, respectively. * To override the chip delete control, include an element (ideally a button) with the attribute * `md-chip-remove`. A click listener to remove the chip will be added automatically. The element * is also placed as a sibling to the chip content (on which there are also click listeners) to * avoid a nested ng-click situation. * * <h3> Pending Features </h3> * <ul style="padding-left:20px;"> * * <ul>Style * <li>Colours for hover, press states (ripple?).</li> * </ul> * * <ul>Validation * <li>allow a validation callback</li> * <li>hilighting style for invalid chips</li> * </ul> * * <ul>Item mutation * <li>Support ` * <md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double * click? * </li> * </ul> * * <ul>Truncation and Disambiguation (?) * <li>Truncate chip text where possible, but do not truncate entries such that two are * indistinguishable.</li> * </ul> * * <ul>Drag and Drop * <li>Drag and drop chips between related `<md-chips>` elements. * </li> * </ul> * </ul> * * <span style="font-size:.8em;text-align:center"> * Warning: This component is a WORK IN PROGRESS. If you use it now, * it will probably break on you in the future. * </span> * * Sometimes developers want to limit the amount of possible chips.<br/> * You can specify the maximum amount of chips by using the following markup. * * <hljs lang="html"> * <md-chips * ng-model="myItems" * placeholder="Add an item" * md-max-chips="5"> * </md-chips> * </hljs> * * In some cases, you have an autocomplete inside of the `md-chips`.<br/> * When the maximum amount of chips has been reached, you can also disable the autocomplete selection.<br/> * Here is an example markup. * * <hljs lang="html"> * <md-chips ng-model="myItems" md-max-chips="5"> * <md-autocomplete ng-hide="myItems.length > 5" ...></md-autocomplete> * </md-chips> * </hljs> * * @param {string=|object=} ng-model A model to bind the list of items to * @param {string=} placeholder Placeholder text that will be forwarded to the input. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input, * displayed when there is at least one item in the list * @param {boolean=} md-removable Enables or disables the deletion of chips through the * removal icon or the Delete/Backspace key. Defaults to true. * @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding * the input and delete buttons. If no `ng-model` is provided, the chips will automatically be * marked as readonly.<br/><br/> * When `md-removable` is not defined, the `md-remove` behavior will be overwritten and disabled. * @param {string=} md-enable-chip-edit Set this to "true" to enable editing of chip contents. The user can * go into edit mode with pressing "space", "enter", or double clicking on the chip. Chip edit is only * supported for chips with basic template. * @param {number=} md-max-chips The maximum number of chips allowed to add through user input. * <br/><br/>The validation property `md-max-chips` can be used when the max chips * amount is reached. * @param {boolean=} md-add-on-blur When set to true, remaining text inside of the input will * be converted into a new chip on blur. * @param {expression} md-transform-chip An expression of form `myFunction($chip)` that when called * expects one of the following return values: * - an object representing the `$chip` input string * - `undefined` to simply add the `$chip` input string, or * - `null` to prevent the chip from being appended * @param {expression=} md-on-add An expression which will be called when a chip has been * added. * @param {expression=} md-on-remove An expression which will be called when a chip has been * removed. * @param {expression=} md-on-select An expression which will be called when a chip is selected. * @param {boolean} md-require-match If true, and the chips template contains an autocomplete, * only allow selection of pre-defined chips (i.e. you cannot add new ones). * @param {string=} delete-hint A string read by screen readers instructing users that pressing * the delete key will remove the chip. * @param {string=} delete-button-label A label for the delete button. Also hidden and read by * screen readers. * @param {expression=} md-separator-keys An array of key codes used to separate chips. * * @usage * <hljs lang="html"> * <md-chips * ng-model="myItems" * placeholder="Add an item" * readonly="isReadOnly"> * </md-chips> * </hljs> * * <h3>Validation</h3> * When using [ngMessages](https://docs.angularjs.org/api/ngMessages), you can show errors based * on our custom validators. * <hljs lang="html"> * <form name="userForm"> * <md-chips * name="fruits" * ng-model="myItems" * placeholder="Add an item" * md-max-chips="5"> * </md-chips> * <div ng-messages="userForm.fruits.$error" ng-if="userForm.$dirty"> * <div ng-message="md-max-chips">You reached the maximum amount of chips</div> * </div> * </form> * </hljs> * */ var MD_CHIPS_TEMPLATE = '\ <md-chips-wrap\ ng-keydown="$mdChipsCtrl.chipKeydown($event)"\ ng-class="{ \'md-focused\': $mdChipsCtrl.hasFocus(), \ \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly,\ \'md-removable\': $mdChipsCtrl.isRemovable() }"\ class="md-chips">\ <md-chip ng-repeat="$chip in $mdChipsCtrl.items"\ index="{{$index}}"\ ng-class="{\'md-focused\': $mdChipsCtrl.selectedChip == $index, \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly}">\ <div class="md-chip-content"\ tabindex="-1"\ aria-hidden="true"\ ng-click="!$mdChipsCtrl.readonly && $mdChipsCtrl.focusChip($index)"\ ng-focus="!$mdChipsCtrl.readonly && $mdChipsCtrl.selectChip($index)"\ md-chip-transclude="$mdChipsCtrl.chipContentsTemplate"></div>\ <div ng-if="$mdChipsCtrl.isRemovable()"\ class="md-chip-remove-container"\ md-chip-transclude="$mdChipsCtrl.chipRemoveTemplate"></div>\ </md-chip>\ <div class="md-chip-input-container" ng-if="!$mdChipsCtrl.readonly && $mdChipsCtrl.ngModelCtrl">\ <div md-chip-transclude="$mdChipsCtrl.chipInputTemplate"></div>\ </div>\ </md-chips-wrap>'; var CHIP_INPUT_TEMPLATE = '\ <input\ class="md-input"\ tabindex="0"\ placeholder="{{$mdChipsCtrl.getPlaceholder()}}"\ aria-label="{{$mdChipsCtrl.getPlaceholder()}}"\ ng-model="$mdChipsCtrl.chipBuffer"\ ng-focus="$mdChipsCtrl.onInputFocus()"\ ng-blur="$mdChipsCtrl.onInputBlur()"\ ng-keydown="$mdChipsCtrl.inputKeydown($event)">'; var CHIP_DEFAULT_TEMPLATE = '\ <span>{{$chip}}</span>'; var CHIP_REMOVE_TEMPLATE = '\ <button\ class="md-chip-remove"\ ng-if="$mdChipsCtrl.isRemovable()"\ ng-click="$mdChipsCtrl.removeChipAndFocusInput($$replacedScope.$index)"\ type="button"\ aria-hidden="true"\ tabindex="-1">\ <md-icon md-svg-src="{{ $mdChipsCtrl.mdCloseIcon }}"></md-icon>\ <span class="md-visually-hidden">\ {{$mdChipsCtrl.deleteButtonLabel}}\ </span>\ </button>'; /** * MDChips Directive Definition */ function MdChips ($mdTheming, $mdUtil, $compile, $log, $timeout, $$mdSvgRegistry) { // Run our templates through $mdUtil.processTemplate() to allow custom start/end symbols var templates = getTemplates(); return { template: function(element, attrs) { // Clone the element into an attribute. By prepending the attribute // name with '$', Angular won't write it into the DOM. The cloned // element propagates to the link function via the attrs argument, // where various contained-elements can be consumed. attrs['$mdUserTemplate'] = element.clone(); return templates.chips; }, require: ['mdChips'], restrict: 'E', controller: 'MdChipsCtrl', controllerAs: '$mdChipsCtrl', bindToController: true, compile: compile, scope: { readonly: '=readonly', removable: '=mdRemovable', placeholder: '@', secondaryPlaceholder: '@', maxChips: '@mdMaxChips', transformChip: '&mdTransformChip', onAppend: '&mdOnAppend', onAdd: '&mdOnAdd', onRemove: '&mdOnRemove', onSelect: '&mdOnSelect', deleteHint: '@', deleteButtonLabel: '@', separatorKeys: '=?mdSeparatorKeys', requireMatch: '=?mdRequireMatch' } }; /** * Builds the final template for `md-chips` and returns the postLink function. * * Building the template involves 3 key components: * static chips * chip template * input control * * If no `ng-model` is provided, only the static chip work needs to be done. * * If no user-passed `md-chip-template` exists, the default template is used. This resulting * template is appended to the chip content element. * * The remove button may be overridden by passing an element with an md-chip-remove attribute. * * If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for * transclusion later. The transclusion happens in `postLink` as the parent scope is required. * If no user input is provided, a default one is appended to the input container node in the * template. * * Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for * transclusion in the `postLink` function. * * * @param element * @param attr * @returns {Function} */ function compile(element, attr) { // Grab the user template from attr and reset the attribute to null. var userTemplate = attr['$mdUserTemplate']; attr['$mdUserTemplate'] = null; var chipTemplate = getTemplateByQuery('md-chips>md-chip-template'); var chipRemoveSelector = $mdUtil .prefixer() .buildList('md-chip-remove') .map(function(attr) { return 'md-chips>*[' + attr + ']'; }) .join(','); // Set the chip remove, chip contents and chip input templates. The link function will put // them on the scope for transclusion later. var chipRemoveTemplate = getTemplateByQuery(chipRemoveSelector) || templates.remove, chipContentsTemplate = chipTemplate || templates.default, chipInputTemplate = getTemplateByQuery('md-chips>md-autocomplete') || getTemplateByQuery('md-chips>input') || templates.input, staticChips = userTemplate.find('md-chip'); // Warn of malformed template. See #2545 if (userTemplate[0].querySelector('md-chip-template>*[md-chip-remove]')) { $log.warn('invalid placement of md-chip-remove within md-chip-template.'); } function getTemplateByQuery (query) { if (!attr.ngModel) return; var element = userTemplate[0].querySelector(query); return element && element.outerHTML; } /** * Configures controller and transcludes. */ return function postLink(scope, element, attrs, controllers) { $mdUtil.initOptionalProperties(scope, attr); $mdTheming(element); var mdChipsCtrl = controllers[0]; if(chipTemplate) { // Chip editing functionality assumes we are using the default chip template. mdChipsCtrl.enableChipEdit = false; } mdChipsCtrl.chipContentsTemplate = chipContentsTemplate; mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate; mdChipsCtrl.chipInputTemplate = chipInputTemplate; mdChipsCtrl.mdCloseIcon = $$mdSvgRegistry.mdClose; element .attr({ 'aria-hidden': true, tabindex: -1 }) .on('focus', function () { mdChipsCtrl.onFocus(); }); if (attr.ngModel) { mdChipsCtrl.configureNgModel(element.controller('ngModel')); // If an `md-transform-chip` attribute was set, tell the controller to use the expression // before appending chips. if (attrs.mdTransformChip) mdChipsCtrl.useTransformChipExpression(); // If an `md-on-append` attribute was set, tell the controller to use the expression // when appending chips. // // DEPRECATED: Will remove in official 1.0 release if (attrs.mdOnAppend) mdChipsCtrl.useOnAppendExpression(); // If an `md-on-add` attribute was set, tell the controller to use the expression // when adding chips. if (attrs.mdOnAdd) mdChipsCtrl.useOnAddExpression(); // If an `md-on-remove` attribute was set, tell the controller to use the expression // when removing chips. if (attrs.mdOnRemove) mdChipsCtrl.useOnRemoveExpression(); // If an `md-on-select` attribute was set, tell the controller to use the expression // when selecting chips. if (attrs.mdOnSelect) mdChipsCtrl.useOnSelectExpression(); // The md-autocomplete and input elements won't be compiled until after this directive // is complete (due to their nested nature). Wait a tick before looking for them to // configure the controller. if (chipInputTemplate != templates.input) { // The autocomplete will not appear until the readonly attribute is not true (i.e. // false or undefined), so we have to watch the readonly and then on the next tick // after the chip transclusion has run, we can configure the autocomplete and user // input. scope.$watch('$mdChipsCtrl.readonly', function(readonly) { if (!readonly) { $mdUtil.nextTick(function(){ if (chipInputTemplate.indexOf('<md-autocomplete') === 0) { var autocompleteEl = element.find('md-autocomplete'); mdChipsCtrl.configureAutocomplete(autocompleteEl.controller('mdAutocomplete')); } mdChipsCtrl.configureUserInput(element.find('input')); }); } }); } // At the next tick, if we find an input, make sure it has the md-input class $mdUtil.nextTick(function() { var input = element.find('input'); input && input.toggleClass('md-input', true); }); } // Compile with the parent's scope and prepend any static chips to the wrapper. if (staticChips.length > 0) { var compiledStaticChips = $compile(staticChips.clone())(scope.$parent); $timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); }); } }; } function getTemplates() { return { chips: $mdUtil.processTemplate(MD_CHIPS_TEMPLATE), input: $mdUtil.processTemplate(CHIP_INPUT_TEMPLATE), default: $mdUtil.processTemplate(CHIP_DEFAULT_TEMPLATE), remove: $mdUtil.processTemplate(CHIP_REMOVE_TEMPLATE) }; } } angular .module('material.components.chips') .controller('MdContactChipsCtrl', MdContactChipsCtrl); /** * Controller for the MdContactChips component * @constructor */ function MdContactChipsCtrl () { /** @type {Object} */ this.selectedItem = null; /** @type {string} */ this.searchText = ''; } MdContactChipsCtrl.prototype.queryContact = function(searchText) { var results = this.contactQuery({'$query': searchText}); return this.filterSelected ? results.filter(angular.bind(this, this.filterSelectedContacts)) : results; }; MdContactChipsCtrl.prototype.itemName = function(item) { return item[this.contactName]; }; MdContactChipsCtrl.prototype.filterSelectedContacts = function(contact) { return this.contacts.indexOf(contact) == -1; }; MdContactChips.$inject = ["$mdTheming", "$mdUtil"];angular .module('material.components.chips') .directive('mdContactChips', MdContactChips); /** * @ngdoc directive * @name mdContactChips * @module material.components.chips * * @description * `<md-contact-chips>` is an input component based on `md-chips` and makes use of an * `md-autocomplete` element. The component allows the caller to supply a query expression which * returns a list of possible contacts. The user can select one of these and add it to the list of * chips. * * You may also use the `md-highlight-text` directive along with its parameters to control the * appearance of the matched text inside of the contacts' autocomplete popup. * * @param {string=|object=} ng-model A model to bind the list of items to * @param {string=} placeholder Placeholder text that will be forwarded to the input. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input, * displayed when there is at least on item in the list * @param {expression} md-contacts An expression expected to return contacts matching the search * test, `$query`. If this expression involves a promise, a loading bar is displayed while * waiting for it to resolve. * @param {string} md-contact-name The field name of the contact object representing the * contact's name. * @param {string} md-contact-email The field name of the contact object representing the * contact's email address. * @param {string} md-contact-image The field name of the contact object representing the * contact's image. * * * @param {expression=} filter-selected Whether to filter selected contacts from the list of * suggestions shown in the autocomplete. This attribute has been removed but may come back. * * * * @usage * <hljs lang="html"> * <md-contact-chips * ng-model="ctrl.contacts" * md-contacts="ctrl.querySearch($query)" * md-contact-name="name" * md-contact-image="image" * md-contact-email="email" * placeholder="To"> * </md-contact-chips> * </hljs> * */ var MD_CONTACT_CHIPS_TEMPLATE = '\ <md-chips class="md-contact-chips"\ ng-model="$mdContactChipsCtrl.contacts"\ md-require-match="$mdContactChipsCtrl.requireMatch"\ md-autocomplete-snap>\ <md-autocomplete\ md-menu-class="md-contact-chips-suggestions"\ md-selected-item="$mdContactChipsCtrl.selectedItem"\ md-search-text="$mdContactChipsCtrl.searchText"\ md-items="item in $mdContactChipsCtrl.queryContact($mdContactChipsCtrl.searchText)"\ md-item-text="$mdContactChipsCtrl.itemName(item)"\ md-no-cache="true"\ md-autoselect\ placeholder="{{$mdContactChipsCtrl.contacts.length == 0 ?\ $mdContactChipsCtrl.placeholder : $mdContactChipsCtrl.secondaryPlaceholder}}">\ <div class="md-contact-suggestion">\ <img \ ng-src="{{item[$mdContactChipsCtrl.contactImage]}}"\ alt="{{item[$mdContactChipsCtrl.contactName]}}"\ ng-if="item[$mdContactChipsCtrl.contactImage]" />\ <span class="md-contact-name" md-highlight-text="$mdContactChipsCtrl.searchText"\ md-highlight-flags="{{$mdContactChipsCtrl.highlightFlags}}">\ {{item[$mdContactChipsCtrl.contactName]}}\ </span>\ <span class="md-contact-email" >{{item[$mdContactChipsCtrl.contactEmail]}}</span>\ </div>\ </md-autocomplete>\ <md-chip-template>\ <div class="md-contact-avatar">\ <img \ ng-src="{{$chip[$mdContactChipsCtrl.contactImage]}}"\ alt="{{$chip[$mdContactChipsCtrl.contactName]}}"\ ng-if="$chip[$mdContactChipsCtrl.contactImage]" />\ </div>\ <div class="md-contact-name">\ {{$chip[$mdContactChipsCtrl.contactName]}}\ </div>\ </md-chip-template>\ </md-chips>'; /** * MDContactChips Directive Definition * * @param $mdTheming * @returns {*} * ngInject */ function MdContactChips($mdTheming, $mdUtil) { return { template: function(element, attrs) { return MD_CONTACT_CHIPS_TEMPLATE; }, restrict: 'E', controller: 'MdContactChipsCtrl', controllerAs: '$mdContactChipsCtrl', bindToController: true, compile: compile, scope: { contactQuery: '&mdContacts', placeholder: '@', secondaryPlaceholder: '@', contactName: '@mdContactName', contactImage: '@mdContactImage', contactEmail: '@mdContactEmail', contacts: '=ngModel', requireMatch: '=?mdRequireMatch', highlightFlags: '@?mdHighlightFlags' } }; function compile(element, attr) { return function postLink(scope, element, attrs, controllers) { $mdUtil.initOptionalProperties(scope, attr); $mdTheming(element); element.attr('tabindex', '-1'); }; } } ngmaterial.components.chips = angular.module("material.components.chips");
define({ "_widgetLabel": "Ruudukkomuotoinen viitegrafiikka", "newGRGFromAreaButtonLabel": "Määritä ruudukko alueesta", "newGRGFromPointButtonLabel": "Määritä ruudukko pisteestä", "newGRGFromAreaTitle": "Määritä ruudukko alueesta", "newGRGFromPointTitle": "Määritä ruudukko pisteestä", "newGRGBySizeButtonLabel": "Ulottuvuuden perusteella", "newGRGFromRefSystemButtonLabel": "Viitejärjestelmän perusteella", "newGRGByTimeLabel": "Ajan ja nopeuden perusteella", "newGRGFromNonStandardButtonLabel": "Määritä muu kuin vakiomuotoinen ruudukko", "newGRGAreaBySizeTitle": "GRG alueesta ulottuvuuden perusteella", "newGRGAreaBySizeDefineAreaLabel": "GRG-alue", "addGRGAreaPolygonToolTip": "Piirrä GRG-alue aluekohteen avulla", "addGRGAreaExtentToolTip": "Piirrä GRG-alue kartan näkymän laajuudelle", "rotation": "Ruudukon kierto", "numberRowsColumnsLabel": "Määritä rivien ja sarakkeiden määrä", "newGRGAreaByRefSystemTitle": "GRG alueesta viitejärjestelmän perusteella", "gridSize": "Ruudukon koko", "UTMZoneandBand": "Ruudukon vyöhyke", "100000m": "100 000 metriä", "10000m": "10 000 metriä", "1000m": "1 000 metriä", "100m": "100 metriä", "10m": "10 metriä", "clipGrid": "Leikkaa ruudukko GRG-alueeseen", "newGRGAreaFromNonStandardTitle": "Uusi NRG", "newGRGPointBySizeTitle": "GRG pisteestä ulottuvuuden perusteella", "newGRGPointByRefSystemTitle": "GRG pisteestä viitejärjestelmän perusteella", "newGRGPointByTimeTitle": "GRG pisteestä ajan ja nopeuden avulla", "time": "Kellonaika", "rate": "Nopeus", "hours": "Tuntia", "minutes": "Minuuttia", "seconds": "Sekuntia", "ftPerSec": "Jalkaa/sekunti", "ftPerHour": "Jalkaa/tunti", "kmPerSec": "Kilometriä/sekunti", "kmPerHour": "Kilometriä/tunti", "mPerSec": "Metriä/sekunti", "mPerHour": "Metriä/tunti", "miPerSec": "Mailia/sekunti", "miPerHour": "Mailia/tunti", "nMPerSec": "Merimailia/sekunti", "nMPerHour": "Merimailia/tunti", "settingsTitle": "Asetukset", "labelSettingsLabel": "Tunnustekstien asetukset", "labelSettingsButtonLabel": "Määritä tunnustekstien asetukset", "gridSettingsLabel": "Ruudukkoasetukset", "gridSettingsButtonLabel": "Määritä ruudukkoasetukset", "transparency": "Läpinäkyvyys", "labelStyle": "Tunnustekstin tyyli", "font": "Fontti", "textSize": "Tekstin koko", "textColor": "Tekstin väri", "halo": "Reunus", "show": "Näytä", "lockSettings": "Sovelluksen omistaja on lukinnut asetukset", "gridSettings": { "cellShape": "Solun muoto", "cellUnits": "Solun yksiköt", "cellOutline": "Solun ääriviiva-asetukset", "cellFill": "Solun täyttöasetukset", "gridReferenceSystem": "Viitejärjestelmä", "gridDatum": "Datumi: WGS84", "labelStartPosition": "Tunnustekstin alkupiste", "labelType": "Tunnustekstin tyyppi", "labelDirection": "Tunnustekstin suunta", "gridOrigin": "Ruudukon alkupiste", "default": "Suorakulmio", "hexagon": "Kuusikulmio", "miles": "Mailia", "kilometers": "Kilometriä", "feet": "Jalkaa", "meters": "Metriä", "yards": "Jaardia", "nautical-miles": "Meripeninkulmaa", "lowerLeft": "Alavasen", "lowerRight": "Alaoikea", "upperLeft": "Ylävasen", "upperRight": "Yläoikea", "center": "Keskitä", "alphaNumeric": "Aakkosnumeerinen", "alphaAlpha": "Vain kirjaimia", "numeric": "Numeerinen", "horizontal": "Vaaka", "vertical": "Pysty", "MGRS": "MGRS", "USNG": "USNG", "showLabels": "Näytä tunnustekstit", "colorPicker": "Värinvalitsin", "bold": "Lihavointi", "italic": "Kursiivi", "underline": "Alleviivaus" }, "publishTitle": "Julkaise GRG portaaliin", "publishGRGBtn": "Julkaise", "GRGLayerName": "Julkaistun GRG-karttatason nimi", "invalidGRGLayerName": "Karttatason nimi voi sisältää vain aakkosnumeerisia merkkejä ja alaviivoja", "missingGRGLayerName": "GRG:n nimi on annettava", "publishWorskpaceError": "VIRHE: virhe työtilan avauksessa", "publishToNewLayer": "Julkaise tulokset uuteen kohdekarttatasoon", "publishingFailedLayerExists": "Julkaisu epäonnistui: Sinulla on jo kohdepalvelu nimeltä {0}. Valitse toinen nimi.", "checkService": "Tarkista palvelu: {0}", "createService": "Luo palvelu: {0}", "unableToCreate": "Kohteen {0} tuonti ei onnistu", "addToDefinition": "Lisää määritykseen: {0}", "successfullyPublished": "Web-karttatason julkaisu onnistui{0}Web-karttatason hallinta", "userRole": "Palvelun luonti ei onnistu, koska käyttäjällä ei ole käyttöoikeuksia", "createGRGBtn": "Luo GRG", "clearGRGBtn": "Tyhjennä", "labelFormat": "Tunnustekstin muoto", "helpIconTooltip": "Z: ruudukon vyöhykemääritys (GZD)\nS: ruudukon 100 000 metrin neliön tunnus (GSID)\nX: itäinen (X-koordinaatti)\nY: pohjoinen (Y-koordinaatti)\n\nEsimerkit:\nZSXY on 15SWC8081751205\nZS X,Y on 15SWC 80817,51205", "addPointToolTip": "Lisää GRG:n alkupiste", "cellWidth": "Solun leveys (x)", "cellHeight": "Solun korkeus (y)", "invalidNumberMessage": "Annettu arvo ei kelpaa", "invalidRangeMessage": "Arvon on oltava suurempi kuin 0", "gridAngleInvalidRangeMessage": "Arvon on oltava välillä -89,9 ja 89,9.", "formatIconTooltip": "Muodon lähtöaineisto", "coordInputLabel": "GRG:n alkupiste", "setCoordFormat": "Määritä koordinaatin muotomerkkijono", "prefixNumbers": "Lisää etuliite +/- positiivisiin ja negatiivisiin numeroihin", "cancelBtn": "Peruuta", "applyBtn": "Käytä", "comfirmInputNotation": "Vahvista lähtöaineiston esitysmuoto", "notationsMatch": "lähtöaineistoasi vastaavia esitystapoja. Vahvista käytettävä esitystapa:", "numberOfCellsHorizontal": "Vaakasuuntaisten solujen määrä", "numberOfCellsVertical": "Pystysuuntaisten solujen määrä", "gridAngle": "Ruudukon kierto", "tooManyCellsErrorMessage": "Yrität luoda ruudukkoa, joka koostuu yli 2 000 solusta. On suositeltavaa pienentää luotavien solujen määrää muuttamalla ruudukon kokoa tai ruudukkoaluetta.", "missingParametersMessage": "<p>GRG:n luontilomakkeesta puuttuu parametreja tai ne ovat virheellisiä. Varmista seuraavat asiat:</p><ul><li>GRG-alue on piirretty.</li><li>Solun leveys ja korkeus sisältävät kelvolliset arvot.</li></ul>", "missingOriginParametersMessage": "<p>GRG:n luontilomakkeesta puuttuu parametreja tai ne ovat virheellisiä. Varmista seuraavat asiat:</p><ul><li>GRG:n alkupiste on määritetty.</li><li>Aika-, nopeus- ja kulmasyötteet sisältävät kelvolliset arvot.</li></ul>", "invalidWidthHeightParametersMessage": "<p>GRG:n luontilomakkeesta puuttuu parametreja tai ne ovat virheellisiä. Varmista, että solun leveys- ja korkeussyötteet sisältävät kelvolliset arvot.</p>", "invalidHorizontalVerticalParametersMessage": "<p>GRG:n luontilomakkeesta puuttuu parametreja tai ne ovat virheellisiä. Varmista, että vaaka- ja pystysyötteiden solujen määrät sisältävät kelvolliset arvot.<>", "drawPointToolTip": "Lisää GRG:n alkupiste napsauttamalla", "missingLayerNameMessage": "Kelvollinen karttatason nimi on annettava ennen julkaisua", "parseCoordinatesError": "Koordinaattien jäsennys ei onnistu. Tarkista lähtöaineistosi.", "grgPolarRegionError": "GRG:n laajuus on napa-alueella. Soluja, jotka osuvat napa-alueille, ei luoda.", "grgPolarOriginError": "GRG:n alkupiste ei voi olla napa-alueella, kun GRG:tä luodaan viitejärjestelmän perusteella.", "deleteBtn": "Poista", "DD": "da", "DDM": "DDM", "DMS": "DMS", "DDRev": "DDRev", "DDMRev": "DDMRev", "DMSRev": "DMSRev", "USNG": "USNG", "MGRS": "MGRS", "UTM_H": "UTM (H)", "UTM": "UTM", "GARS": "GARS", "GEOREF": "GEOREF", "DDLatLongNotation": "Desimaaliasteet – leveys-/pituusaste", "DDLongLatNotation": "Desimaaliasteet – pituus-/leveysaste", "DDMLatLongNotation": "Asteet, desimaaliminuutit – leveys-/pituusaste", "DDMLongLatNotation": "Asteet, desimaaliminuutit – pituus-/leveysaste", "DMSLatLongNotation": "Asteet, minuutit, sekunnit – leveys-/pituusaste", "DMSLongLatNotation": "Asteet, minuutit, sekunnit – pituus-/leveysaste", "GARSNotation": "GARS", "GEOREFNotation": "GEOREF", "MGRSNotation": "MGRS", "USNGNotation": "USNG", "UTMBandNotation": "UTM – kaistan kirjain", "UTMHemNotation": "UTM – pallonpuolisko (P/E)" });
var http = require('http'); var cicada = require('../'); var test = require('tap').test; var spawn = require('child_process').spawn; var mkdirp = require('mkdirp'); var basedir = '/tmp/cicada-dirmapped-test/' + Math.random().toString(16).slice(2); mkdirp.sync(basedir + '/abcdefg'); var ci; var server = http.createServer(function (req, res) { ci.handle(req, res); }); test('setup', function (t) { server.listen(0, t.end.bind(t)); }); test('dir-mapped push', function (t) { t.plan(8 + 2 + 6); ci = cicada({ repodir : function (repo) { // 8 of these should fire t.equal(repo, 'beep.git'); return basedir + '/repo-abcdefg'; }, workdir : function (commit) { // 1 of these should fire t.equal(commit.repo, 'beep.git'); t.equal(commit.cwd, basedir + '/repo-abcdefg'); return basedir + '/abcdefg'; } }); ci.on('commit', function (commit) { t.equal(commit.repo, 'beep.git'); t.equal(commit.dir, basedir + '/abcdefg'); (function () { var ps = commit.spawn('ls'); var data = ''; ps.stdout.on('data', function (buf) { data += buf }); ps.on('close', function (code) { t.equal(code, 0); t.equal(data, 'robot.txt\n'); }); })(); (function () { var ps = commit.spawn('pwd'); var data = ''; ps.stdout.on('data', function (buf) { data += buf }); ps.on('close', function (code) { t.equal(code, 0); t.equal(data, commit.dir + '\n'); }); })(); }); spawn(__dirname + '/push.sh', [ 'http://localhost:' + server.address().port + '/beep.git' ]); }); test('teardown', function (t) { server.close(); t.end(); });
import React from 'react'; class Page extends React.Component { render() { return ( <div className='page'> {this.props.children} </div> ); } } export default Page;
/* spreadsheetView Plugin * Depends: * ui.core.js * ui.view.js * Author cf AUTHORS.txt License Copyright (c) 2010-2012 Massachusetts Institute of Technology. MIT License (cf. MIT-LICENSE.txt or http://www.opensource.org/licenses/mit-license.php) */ /*global jQuery:true */ define(function(require) { var concierge = require('concierge'), view = require('view'), $ = require('jquery'); var V_OBJ = $.extend({}, $.ui.view.prototype, { _create: function () { $.ui.view.prototype._create.call(this); var self = this; self.element.addClass('spreadsheetView').html("<div class='spreadsheetView-header'/><div class='spreadsheetView-contents'/>"); self._selection = [1, 1]; //[row, column] self._files = null; self._users = null; self._rendered = false; }, _recenterMaybe: function (sel) { var self = this; var scrollby; var container = self.element; //vertical scrolling: var h = sel.height(); var H = container.height(); var delta_top = sel.offset().top - container.offset().top; var delta_bottom = delta_top + h - H; if (delta_top > 0) { if (delta_bottom > 0) {//but selection is too low... scroll down scrollby = delta_bottom + H / 2 - h; //delta_bottom is how much to scroll so that bottom of lens coincides with bottom of widget. container.stop(true).animate({ scrollTop: '+=' + scrollby + 'px' }, 300); } } else { //too high: recenter: scrollby = delta_top + (h - H) / 2; container.stop(true).animate({ scrollTop: '+=' + scrollby + 'px' }, 300); } //horizontal scrolling: var w = sel.width(); var W = container.width(); var delta_left = sel.offset().left - container.offset().left; var delta_right = delta_left + w - W; if (delta_left > 0) { if (delta_right > 0) {//but selection is too much to the right: scroll to the right scrollby = delta_right + W / 2 - w; //delta_right is how much to scroll so that right of lens coincides with right of widget. container.stop(true).animate({ scrollLeft: '+=' + scrollby + 'px' }, 300); } } else { //selection too high: recenter: scrollby = delta_left + (w - W) / 2; container.stop(true).animate({ scrollLeft: '+=' + scrollby + 'px' }, 300); } }, _defaultHandler: function (evt) { var self = this; var m = self._model; var sel; switch (evt.type){ case 'selection': $('td.selected', self.element).removeClass('selected'); self._selection = evt.value.sel; sel = $('tr:eq(' + self._selection[0] + ')', self.element).children('td:eq(' + self._selection[1] + ')').addClass('selected'); self._recenterMaybe(sel); break; case 'proxy_keydown': var moving_codes = { move_left: 37, move_right: 39, move_up: 38, move_down: 40, }; var grading_codes = { grade_A: 97, grade_B: 98, grade_C: 99, grade_D: 100, grade_F: 102 }; if (evt.value in moving_codes) { self._keydown({ keyCode: moving_codes[evt.value], charCode: 0 }); } else if (evt.value in grading_codes) { self._keydown({ keyCode: 0, charCode: grading_codes[evt.value] }); } break; } }, update: function (action, payload, items_fieldname) { if (action === 'add' && items_fieldname === 'grade' && this._rendered) { $.L('TODO re_render'); this._render(); } }, set_model: function (model, init_event) { var self = this; model.register($.ui.view.prototype.get_adapter.call(this), { grade: null }); //build view: self._model = model; self._generate_contents(); }, _update: function () { $.ui.view.prototype._update.call(this); var self = this; }, close: function () { var id = this._id_collection; delete $.concierge.features['doc_viewer'][id]; $.ui.view.prototype.close.call(this); $.L('closing spreadsheetviewer', id); }, _generate_contents: function () { this._render(); }, _keydown: function (event) { var self = this; var sel_codes = { 37: { dir: -1, idx: 1, extremum:1, msg:'At beginning of list...' }, 39: { dir: 1, idx: 1, extremum:self._files.length, msg:'At end of list...' }, 38: { dir: -1, idx: 0, extremum: 1, msg: 'Already at the top...' }, 40: { dir: 1, idx: 0, extremum: self._users.length, msg: 'Already at the bottom...' }, }; var grade_codes = { 65:4, 66:3, 67:2, 68:1, 70:0, 97: 4, 98:3, 99:2, 100:1, 102:0 }; //US GPA system. var proxy_names = { 44: 'prev', 46: 'next', 60: 'prev', 62: 'next', 188: 'prev', 190: 'next' }; //with and w/o shift and 188,190 for webkit-based browsers... var new_sel, v; var code = event.keyCode || event.charCode; //HACK: Argh, different browsers use different conventions ! if (code in sel_codes) { v = sel_codes[code]; new_sel = self._selection[v.idx] + v.dir; if (v.dir * (new_sel - v.extremum) > 0) { $.I(v.msg); } else { var _sel = self._selection.slice(); _sel[v.idx] = new_sel; $.concierge.trigger({ type:'selection', value: { sel: _sel, users: self._users, files: self._files } }); } return false; } else if (code in grade_codes) { var id_user = self._users[self._selection[0] - 1].id; var id_source = self._files[self._selection[1] - 1].id; $.concierge.get_component('set_grade_assignment')({ grade: grade_codes[code], id_user: id_user, id_source: id_source }, function (P) { self._model.add('grade', P.grades); $.I('grade added'); // self._render() }); } else if (code in proxy_names) { $.concierge.trigger({ type: 'proxy_keydown', value: proxy_names[code] }); } else { return true; // let the event be captured for other stuff } }, _lens: function (i_user, i_file) { var self = this; var m = self._model; var file = self._files[i_file]; var user = self._users[i_user]; var stat = m.o.stat[user.id + '_' + file.id]; var grade = m.get('grade', { id_user: user.id, id_source:file.id }).first(); var lens_stat = (stat !== undefined) ? "<span class='stat'>" + stat.cnt + '</span>' : ''; var lens_grade = (grade !== null) ? "<span class='grade'>" + $.concierge.get_component('grade2litt')(grade.grade) + '</span>' : ''; return lens_stat + ' ' + lens_grade; }, _render: function () { var self = this; var m = self._model; var f_sort_user = function (o1, o2) { if (o1.lastname === null) { return o2.lastname === null ? 0 : 1; } if (o1.lastname > o2.lastname) { return 1; } if (o1.lastname < o2.lastname) { return -1; } return 0; }; var f_sort_file = function (o1, o2) { return o1.id - o2.id; }; // self._users = m.get("user", {admin: false, guest: false}).sort(f_sort_user); //SACHA: Showing both admin and non-admin users. TODO: Have a switch to show/hide admins. self._users = m.get('user', { guest: false }).sort(f_sort_user); self._files = m.get('file', {}).sort(f_sort_file); var i, j, file, user, stat, lens, grade, lens_stat, lens_grade; var s = ["<table class='spreadsheet'><thead><tr><th/>"]; for (i in self._files) { file = self._files[i]; s.push("<th><a class='vertical' title='" + $.E(file.title) + "' target='_blank' href='/f/" + file.id + "'>" + $.E($.ellipsis(file.title, 12)) + '</a></th>'); } s.push('</tr></thead><tbody>'); for (j in self._users) { user = self._users[j]; lens = (user.lastname !== null) ? (user.firstname + ' ' + user.lastname) : ('<i>' + user.email + '</i>'); if (user.admin) { //TODO improve styling lens += " <i style='color: #a0a0a0'>admin</i>"; } s.push('<tr><td>' + lens + '</td>'); for (i in self._files) { /* file = self._files[i]; stat = m.o.stat[user.id+"_"+file.id]; grade = m.get("grade", {id_user: user.id, id_source:file.id}).first(); lens_stat = (stat !== undefined) ? stat.cnt : ""; lens_grade = (grade !== null) ? grade.grade: "" s.push("<td>"+lens_stat+" "+lens_grade+"</td>"); */ //TODO remove var declarations s.push('<td>' + self._lens(j, i) + '</td>'); } s.push('</tr>'); } s.push('</tbody></table>'); var contents = $('div.spreadsheetView-contents', self.element).html(s.join('')); var f_cell_click = function (event) { var td = event.currentTarget; var tr = td.parentNode; if (td.cellIndex > 0 && tr.rowIndex > 0) { var _sel = [tr.rowIndex, td.cellIndex]; $.concierge.trigger({ type:'selection', value: { sel: _sel, users: self._users, files: self._files } }); } }; $('td', contents).click(f_cell_click); $('tr:eq(' + self._selection[0] + ')', contents).children('td:eq(' + self._selection[1] + ')').addClass('selected'); self._rendered = true; }, }); $.widget('ui.spreadsheetview', V_OBJ); $.ui.spreadsheetview.prototype.options = { provides: ['spreadsheet'], listens: { selection: null, proxy_keydown: null, }, }; });
// test rightArithShift var assert = require('assert'), error = require('../../../lib/error/index'), math = require('../../../index'), bignumber = math.bignumber, rightArithShift = math.rightArithShift; describe('rightArithShift', function () { it('should right arithmetically shift a number by a given amount', function () { assert.equal(rightArithShift(0, 1000), 0); assert.equal(rightArithShift(2, 0), 2); assert.equal(rightArithShift(12, 3), 1); assert.equal(rightArithShift(32, 4), 2); assert.equal(rightArithShift(-1, 1000), -1); assert.equal(rightArithShift(-12, 2), -3); assert.equal(rightArithShift(122, 3), 15); assert.equal(rightArithShift(-13, 2), -4); assert.equal(rightArithShift(-13, 3), -2); }); it('should right arithmetically shift booleans by a boolean amount', function () { assert.equal(rightArithShift(true, true), 0); assert.equal(rightArithShift(true, false), 1); assert.equal(rightArithShift(false, true), 0); assert.equal(rightArithShift(false, false), 0); }); it('should right arithmetically shift with a mix of numbers and booleans', function () { assert.equal(rightArithShift(2, true), 1); assert.equal(rightArithShift(2, false), 2); assert.equal(rightArithShift(true, 0), 1); assert.equal(rightArithShift(true, 1), 0); assert.equal(rightArithShift(false, 2), 0); }); it('should right arithmetically shift numbers and null', function () { assert.equal(rightArithShift(1, null), 1); assert.equal(rightArithShift(null, 1), 0); }); it('should right arithmetically shift bignumbers', function () { assert.deepEqual(rightArithShift(bignumber(17), bignumber(3)), bignumber(2)); assert.deepEqual(rightArithShift(bignumber('633825300114114700748351602688000'), bignumber(100)), bignumber(500)); assert.deepEqual(rightArithShift(bignumber(-17), bignumber(3)), bignumber(-3)); assert.equal(rightArithShift(bignumber(-17), bignumber(-3)).isNaN(), true); assert.equal(rightArithShift(bignumber(Infinity), bignumber(Infinity)).isNaN(), true); assert.deepEqual(rightArithShift(bignumber(-Infinity), bignumber(Infinity)), bignumber(-1)); }); it('should right arithmetically shift mixed numbers and bignumbers', function () { assert.deepEqual(rightArithShift(bignumber(17), 3), bignumber(2)); assert.deepEqual(rightArithShift(bignumber('-633825300114114700748351602688000'), 100), bignumber(-500)); assert.equal(rightArithShift(bignumber(-17), -3).isNaN(), true); assert.deepEqual(rightArithShift(17, bignumber(3)), bignumber(2)); assert.deepEqual(rightArithShift(-17, bignumber(3)), bignumber(-3)); assert.equal(rightArithShift(-3, bignumber(-17)).isNaN(), true); assert.deepEqual(rightArithShift(bignumber(-Infinity), Infinity), bignumber(-1)); assert.equal(rightArithShift(bignumber(Infinity), Infinity).isNaN(), true); assert.equal(rightArithShift(Infinity, bignumber(Infinity)).isNaN(), true); }); it('should right arithmetically shift mixed booleans and bignumbers', function () { assert.deepEqual(rightArithShift(true, bignumber(0)), bignumber(1)); assert.deepEqual(rightArithShift(false, bignumber('1000000')), bignumber(0)); assert.deepEqual(rightArithShift(bignumber(3), false), bignumber(3)); assert.deepEqual(rightArithShift(bignumber(3), true), bignumber(1)); }); it('should throw an error if the parameters are not integers', function () { assert.throws(function () { rightArithShift(1.1, 1); }, /Parameters in function rightArithShift must be integer numbers/); assert.throws(function () { rightArithShift(1, 1.1); }, /Parameters in function rightArithShift must be integer numbers/); assert.throws(function () { rightArithShift(1.1, 1.1); }, /Parameters in function rightArithShift must be integer numbers/); assert.throws(function () { rightArithShift(bignumber(1.1), 1); }, /Parameters in function rightArithShift must be integer numbers/); assert.throws(function () { rightArithShift(1, bignumber(1.1)); }, /Parameters in function rightArithShift must be integer numbers/); assert.throws(function () { rightArithShift(bignumber(1.1), bignumber(1)); }, /Parameters in function rightArithShift must be integer numbers/); assert.throws(function () { rightArithShift(bignumber(1), bignumber(1.1)); }, /Parameters in function rightArithShift must be integer numbers/); }); it('should throw an error if used with a unit', function() { assert.throws(function () {rightArithShift(math.unit('5cm'), 2)}, error.UnsupportedTypeError); assert.throws(function () {rightArithShift(2, math.unit('5cm'))}, error.UnsupportedTypeError); assert.throws(function () {rightArithShift(math.unit('2cm'), math.unit('5cm'))}, error.UnsupportedTypeError); }); it('should element-wise right arithmetically shift a matrix', function () { var a = math.matrix([4,8]); var b = rightArithShift(a, 2); assert.ok(b instanceof math.type.Matrix); assert.deepEqual(b, math.matrix([1,2])); a = math.matrix([[4,8],[12,16]]); b = rightArithShift(a, 2); assert.ok(b instanceof math.type.Matrix); assert.deepEqual(b, math.matrix([[1,2],[3,4]])); }); it('should element-wise right arithmetically shift an array', function () { var a = [[4,8],[12,16]]; assert.deepEqual(rightArithShift(a[0], 0), a[0]); assert.deepEqual(rightArithShift(a[0], 2), [1,2]); assert.deepEqual(rightArithShift(a, 0), a); assert.deepEqual(rightArithShift(a, 2), [[1,2],[3,4]]); }); it('should throw an error if used with wrong number of arguments', function () { assert.throws(function () {rightArithShift(1)}, error.ArgumentsError); assert.throws(function () {rightArithShift(1, 2, 3)}, error.ArgumentsError); }); it('should throw an error in case of invalid type of arguments', function () { assert.throws(function () {rightArithShift(new Date(), true)}, error.UnsupportedTypeError); assert.throws(function () {rightArithShift(true, new Date())}, error.UnsupportedTypeError); assert.throws(function () {rightArithShift(true, 'foo')}, error.UnsupportedTypeError); assert.throws(function () {rightArithShift('foo', true)}, error.UnsupportedTypeError); assert.throws(function () {rightArithShift(true, undefined)}, error.UnsupportedTypeError); assert.throws(function () {rightArithShift(undefined, true)}, error.UnsupportedTypeError); }); });
import webpack from 'webpack'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import config, { postcss, COMMON_CSS } from './config'; export default { devtool: 'eval-source-map', resolve: { extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg'] }, entry: config.paths.demo, module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'], include: config.paths.demo }, ], loaders: [ { test: /\.json$/, loader: 'json', include: config.paths.packageJson }, { test: /\.png$/, loader: 'url?limit=100000&mimetype=image/png', include: config.paths.demo }, { test: /\.jpg$/, loader: 'file', include: config.paths.demo }, { test: /\.scss$/, loaders: ['style', 'css', 'postcss'], include: [config.paths.src, config.paths.demo, ...COMMON_CSS], }, { test: /\.jsx?$/, loaders: ['babel?cacheDirectory'], include: [config.paths.demo] }, ], }, postcss, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development') }), new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: config.paths.demoTemplate, title: `${config.pkg.name} - ${config.pkg.description}`, }), ], devServer: { historyApiFallback: true, hot: true, inline: true, progress: true, host: process.env.HOST, port: process.env.PORT, stats: 'errors-only', }, };
var configuredModules = []; var app;
var Bleext = { version : "1.0.0" };
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, describe, it, expect, beforeEach, afterEach, waitsFor, waits, runs, $, waitsForDone */ define(function (require, exports, module) { 'use strict'; var Editor = require("editor/Editor").Editor, EditorManager = require("editor/EditorManager"), EditorCommandHandlers = require("editor/EditorCommandHandlers"), Commands = require("command/Commands"), CommandManager = require("command/CommandManager"), LanguageManager = require("language/LanguageManager"), SpecRunnerUtils = require("spec/SpecRunnerUtils"); describe("EditorCommandHandlers", function () { var defaultContent = "function foo() {\n" + " function bar() {\n" + " \n" + " a();\n" + " \n" + " }\n" + "\n" + "}"; var myDocument, myEditor; var testPath = SpecRunnerUtils.getTestPath("/spec/EditorCommandHandlers-test-files"), testWindow; function setupFullEditor(content, languageId) { content = content || defaultContent; languageId = languageId || "javascript"; // create dummy Document and Editor var mocks = SpecRunnerUtils.createMockEditor(content, languageId); myDocument = mocks.doc; myEditor = mocks.editor; myEditor.focus(); } function makeEditorWithRange(range, content) { content = content || defaultContent; // create editor with a visible range var mocks = SpecRunnerUtils.createMockEditor(content, "javascript", range); myDocument = mocks.doc; myEditor = mocks.editor; myEditor.focus(); } afterEach(function () { if (myDocument) { SpecRunnerUtils.destroyMockEditor(myDocument); myEditor = null; myDocument = null; } }); // Helper functions for testing cursor position / selection range function expectCursorAt(pos) { var selection = myEditor.getSelection(); expect(selection.start).toEqual(selection.end); expect(selection.start).toEqual(pos); } function expectSelection(sel) { expect(myEditor.getSelection()).toEqual(sel); } // Helper function for creating a window with an inline editor function createWindowWithInlineEditor(spec) { var promise; if (!testWindow) { SpecRunnerUtils.createTestWindowAndRun(spec, function (w) { testWindow = w; // Load module instances from brackets.test CommandManager = testWindow.brackets.test.CommandManager; Commands = testWindow.brackets.test.Commands; EditorManager = testWindow.brackets.test.EditorManager; SpecRunnerUtils.loadProjectInTestWindow(testPath); }); } runs(function () { promise = CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, {fullPath: testPath + "/test.html"}); waitsForDone(promise, "Open into working set"); }); runs(function () { // Open inline editor onto test.css's ".testClass" rule promise = SpecRunnerUtils.toggleQuickEditAtOffset(EditorManager.getCurrentFullEditor(), {line: 8, ch: 11}); waitsForDone(promise, "Open inline editor"); }); runs(function () { myEditor = EditorManager.getCurrentFullEditor().getInlineWidgets()[0].editors[0]; }); } // Helper function for closing open files in the test window function closeFilesInTestWindow() { runs(function () { var promise = CommandManager.execute(Commands.FILE_CLOSE_ALL); waitsForDone(promise, "Close all open files in working set"); // Close the save dialog without saving the changes var $dlg = testWindow.$(".modal.instance"); if ($dlg.length) { SpecRunnerUtils.clickDialogButton("dontsave"); } }); } // Helper function for closing the test window. This must be used in the last spec in the suite. function closeTestWindow() { runs(function () { this.after(function () { SpecRunnerUtils.closeTestWindow(); testWindow = null; }); }); } describe("Line comment/uncomment", function () { beforeEach(setupFullEditor); it("should comment/uncomment a single line, cursor at start", function () { myEditor.setCursorPos(3, 0); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[3] = "// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 3, ch: 2}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 3, ch: 0}); }); it("should comment/uncomment a single line, cursor at end", function () { myEditor.setCursorPos(3, 12); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[3] = "// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 3, ch: 14}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 3, ch: 12}); }); it("should comment/uncomment first line in file", function () { myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[0] = "//function foo() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 0, ch: 2}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 0, ch: 0}); }); it("should comment/uncomment a single partly-selected line", function () { // select "function" on line 1 myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 12}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 6}, end: {line: 1, ch: 14}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 12}}); }); it("should comment/uncomment a single selected line", function () { // selection covers all of line's text, but not \n at end myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 1, ch: 22}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 1, ch: 20}}); }); it("should comment/uncomment a single fully-selected line (including LF)", function () { // selection including \n at end of line myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); }); it("should comment/uncomment multiple selected lines", function () { // selection including \n at end of line myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "// a();"; lines[4] = "// "; lines[5] = "// }"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); it("should comment/uncomment ragged multi-line selection", function () { myEditor.setSelection({line: 1, ch: 6}, {line: 3, ch: 9}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 8}, end: {line: 3, ch: 11}}); expect(myEditor.getSelectedText()).toEqual("nction bar() {\n// \n// a"); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 6}, end: {line: 3, ch: 9}}); }); it("should comment/uncomment when selection starts & ends on whitespace lines", function () { myEditor.setSelection({line: 2, ch: 0}, {line: 4, ch: 8}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[2] = "// "; lines[3] = "// a();"; lines[4] = "// "; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 4, ch: 10}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 2, ch: 0}, end: {line: 4, ch: 8}}); }); it("should do nothing on whitespace line", function () { myEditor.setCursorPos(2, 8); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 2, ch: 8}); }); it("should do nothing when only whitespace lines selected", function () { // Start with line 2 duplicated twice (3 copies total) var lines = defaultContent.split("\n"); lines.splice(2, 0, lines[2], lines[2]); var startingContent = lines.join("\n"); myDocument.setText(startingContent); myEditor.setSelection({line: 2, ch: 4}, {line: 4, ch: 4}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); myEditor.setSelection({line: 2, ch: 4}, {line: 4, ch: 4}); }); it("should comment/uncomment after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var expectedText = "//function foo() {\n" + "// function bar() {\n" + "// \n" + "// a();\n" + "// \n" + "// }\n" + "//\n" + "//}"; expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 3}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}}); }); it("should comment/uncomment lines that were partially commented out already, our style", function () { // Start with line 3 commented out, with "//" at column 0 var lines = defaultContent.split("\n"); lines[3] = "// a();"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-3 myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "//// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); }); it("should comment/uncomment lines that were partially commented out already, comment closer to code", function () { // Start with line 3 commented out, with "//" snug against the code var lines = defaultContent.split("\n"); lines[3] = " //a();"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-3 myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "// //a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); }); it("should uncomment indented, aligned comments", function () { // Start with lines 1-5 commented out, with "//" all aligned at column 4 var lines = defaultContent.split("\n"); lines[1] = " //function bar() {"; lines[2] = " // "; lines[3] = " // a();"; lines[4] = " // "; lines[5] = " //}"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-5 myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); it("should uncomment ragged partial comments", function () { // Start with lines 1-5 commented out, with "//" snug up against each non-blank line's code var lines = defaultContent.split("\n"); lines[1] = " //function bar() {"; lines[2] = " "; lines[3] = " //a();"; lines[4] = " "; lines[5] = " //}"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-5 myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); }); describe("Line comment in languages with mutiple line comment prefixes", function () { // Define a special version of JavaScript for testing purposes LanguageManager.defineLanguage("javascript2", { "name": "JavaScript2", "mode": "javascript", "fileExtensions": ["js2"], "lineComment": ["//", "////", "#"] }); beforeEach(function () { setupFullEditor(null, "javascript2"); }); it("should comment using the first prefix", function () { // select first 2 lines myEditor.setSelection({line: 0, ch: 4}, {line: 1, ch: 12}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[0] = "//function foo() {"; lines[1] = "// function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 6}, end: {line: 1, ch: 14}}); }); it("should uncomment every prefix", function () { // Start with lines 1-5 commented out, with multiple line comment variations var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = " // "; lines[3] = " //// a();"; lines[4] = " "; lines[5] = "# }"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-5 myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); it("should only uncomment the first prefix", function () { // Start with lines 1-3 commented out, with multiple line comment variations var lines = defaultContent.split("\n"); lines[1] = "//# function bar() {"; lines[2] = "// "; lines[3] = "////// a();"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); lines = defaultContent.split("\n"); lines[1] = "# function bar() {"; lines[2] = " "; lines[3] = "// a();"; var expectedContent = lines.join("\n"); // select lines 1-3 myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(expectedContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); }); }); /** * Invokes Toggle Block Comment, expects the given selection/cursor & document text, invokes * it a 2nd time, and then expects the original selection/cursor & document text again. * @param {!string} expectedCommentedText * @param {!{ch:number,line:number}|{start:{ch:number,line:number},end:{ch:number,line:number}}} expectedCommentedSel */ function testToggleBlock(expectedCommentedText, expectedCommentedSel) { function expectSel(sel) { if (sel.start) { expectSelection(sel); } else { expectCursorAt(sel); } } var startingContent = myDocument.getText(); var startingSel = myEditor.getSelection(); // Toggle comment on CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(expectedCommentedText); expectSel(expectedCommentedSel); // Toggle comment off // Can't immediately call BLOCK_COMMENT again to uncomment because CodeMirror might not // be done re-tokenizing in response to the first toggle, and BLOCK_COMMENT depends on // getting correct tokens. See #2335. Ideally we'd listen for onHighlightComplete() but // it's not clear that will always get called (if CM decides no async work was needed). // So we just wait until after the async tokenization must have been run. waits(200); runs(function () { CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSel(startingSel); }); } describe("Block comment/uncomment", function () { beforeEach(setupFullEditor); it("should block comment/uncomment, cursor at start of line", function () { myEditor.setCursorPos(0, 0); var lines = defaultContent.split("\n"); lines[0] = "/**/function foo() {"; var expectedText = lines.join("\n"); testToggleBlock(expectedText, {line: 0, ch: 2}); }); it("should block comment/uncomment, cursor to left of existing block comment", function () { // Start with part of line 3 wrapped in a block comment var lines = defaultContent.split("\n"); lines[3] = " /*a();*/"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // put cursor to left of block myEditor.setCursorPos(3, 4); lines[3] = " /**/ /*a();*/"; var expectedText = lines.join("\n"); testToggleBlock(expectedText, {line: 3, ch: 6}); }); it("should block comment/uncomment, subset of line selected", function () { myEditor.setSelection({line: 1, ch: 13}, {line: 1, ch: 18}); // select "bar()" var lines = defaultContent.split("\n"); lines[1] = " function /*bar()*/ {"; var expectedText = lines.join("\n"); // Selects just text within block testToggleBlock(expectedText, {start: {line: 1, ch: 15}, end: {line: 1, ch: 20}}); }); it("should block uncomment, cursor within existing sub-line block comment", function () { // Start with part of line 1 wrapped in a block comment var lines = defaultContent.split("\n"); lines[1] = " function /*bar()*/ {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // put cursor within block myEditor.setCursorPos(1, 18); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 1, ch: 16}); }); it("should block uncomment, selection covering whole sub-line block comment", function () { // Start with part of line 1 wrapped in a block comment var lines = defaultContent.split("\n"); lines[1] = " function /*bar()*/ {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select whole comment myEditor.setSelection({line: 1, ch: 13}, {line: 1, ch: 22}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 13}, end: {line: 1, ch: 18}}); // just text that was uncommented }); it("should block comment/uncomment, selection from mid-line end of line", function () { myEditor.setSelection({line: 3, ch: 8}, {line: 3, ch: 12}); var lines = defaultContent.split("\n"); lines[3] = " /*a();*/"; var expectedText = lines.join("\n"); // Selects just text within block testToggleBlock(expectedText, {start: {line: 3, ch: 10}, end: {line: 3, ch: 14}}); }); it("should block comment/uncomment, all of line selected but not newline", function () { myEditor.setSelection({line: 3, ch: 0}, {line: 3, ch: 12}); var lines = defaultContent.split("\n"); lines[3] = "/* a();*/"; var expectedText = lines.join("\n"); // Selects just text within block testToggleBlock(expectedText, {start: {line: 3, ch: 2}, end: {line: 3, ch: 14}}); }); it("should block comment/uncomment, all of line selected including newline", function () { myEditor.setSelection({line: 3, ch: 0}, {line: 4, ch: 0}); var lines = defaultContent.split("\n"); lines.splice(3, 1, "/*", lines[3], "*/"); // inserts new delimiter lines var expectedText = lines.join("\n"); // Selects original line, but not block-delimiter lines testToggleBlock(expectedText, {start: {line: 4, ch: 0}, end: {line: 5, ch: 0}}); }); it("should block comment/uncomment, multiple lines selected", function () { myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); var lines = defaultContent.split("\n"); lines.splice(6, 0, "*/"); // inserts new delimiter lines lines.splice(1, 0, "/*"); var expectedText = lines.join("\n"); // Selects original lines, but not block-delimiter lines testToggleBlock(expectedText, {start: {line: 2, ch: 0}, end: {line: 7, ch: 0}}); }); it("should block comment/uncomment, multiple partial lines selected", function () { myEditor.setSelection({line: 1, ch: 13}, {line: 3, ch: 9}); var lines = defaultContent.split("\n"); lines[1] = " function /*bar() {"; lines[3] = " a*/();"; var expectedText = lines.join("\n"); // Selects just text within block testToggleBlock(expectedText, {start: {line: 1, ch: 15}, end: {line: 3, ch: 9}}); }); // Whitespace within block comments var BLOCK_CONTAINING_WS = "function foo()\n" + "/*\n" + " a();\n" + " \n" + " b();\n" + "*/\n" + "}"; it("should block uncomment, cursor in whitespace within block comment", function () { myDocument.setText(BLOCK_CONTAINING_WS); myEditor.setCursorPos(3, 2); // middle of blank line CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = BLOCK_CONTAINING_WS.split("\n"); lines.splice(5, 1); // removes delimiter lines lines.splice(1, 1); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 2, ch: 2}); }); it("should block uncomment, selection in whitespace within block comment", function () { myDocument.setText(BLOCK_CONTAINING_WS); myEditor.setSelection({line: 3, ch: 0}, {line: 3, ch: 4}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = BLOCK_CONTAINING_WS.split("\n"); lines.splice(5, 1); // removes delimiter lines lines.splice(1, 1); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 2, ch: 4}}); }); // Selections mixing whitespace and existing block comments var WS_SURROUNDING_BLOCK = "function foo()\n" + " \n" + " /*a();\n" + " \n" + " b();*/\n" + " \n" + "}"; it("should block uncomment, selection covers block comment plus whitespace before", function () { myDocument.setText(WS_SURROUNDING_BLOCK); myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 10}); // start of blank line to end of block comment CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = WS_SURROUNDING_BLOCK.split("\n"); lines[2] = " a();"; lines[4] = " b();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 8}}); }); it("should block uncomment, selection covers block comment plus whitespace after", function () { myDocument.setText(WS_SURROUNDING_BLOCK); myEditor.setSelection({line: 2, ch: 4}, {line: 5, ch: 4}); // start of block comment to end of blank line CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = WS_SURROUNDING_BLOCK.split("\n"); lines[2] = " a();"; lines[4] = " b();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 4}, end: {line: 5, ch: 4}}); }); it("should block uncomment, selection covers part of block comment plus whitespace before", function () { myDocument.setText(WS_SURROUNDING_BLOCK); myEditor.setSelection({line: 1, ch: 0}, {line: 3, ch: 4}); // start of blank line to middle of block comment CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = WS_SURROUNDING_BLOCK.split("\n"); lines[2] = " a();"; lines[4] = " b();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 4}}); }); it("should block uncomment, selection covers part of block comment plus whitespace after", function () { myDocument.setText(WS_SURROUNDING_BLOCK); myEditor.setSelection({line: 3, ch: 4}, {line: 5, ch: 4}); // middle of block comment to end of blank line CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = WS_SURROUNDING_BLOCK.split("\n"); lines[2] = " a();"; lines[4] = " b();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 3, ch: 4}, end: {line: 5, ch: 4}}); }); it("should block uncomment, selection covers block comment plus whitespace on both sides", function () { myDocument.setText(WS_SURROUNDING_BLOCK); myEditor.setSelection({line: 1, ch: 0}, {line: 5, ch: 4}); // start of first blank line to end of last blank line CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = WS_SURROUNDING_BLOCK.split("\n"); lines[2] = " a();"; lines[4] = " b();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 5, ch: 4}}); }); // Selections mixing uncommented text and existing block comments it("should block uncomment, selection covers block comment plus other text", function () { // Start with part of line 1 wrapped in a block comment var lines = defaultContent.split("\n"); lines[1] = " function /*bar()*/ {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select more of line 1 myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 24}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 20}}); // range endpoints still align with same text }); it("should block uncomment, selection covers multi-line block comment plus other text", function () { var content = "function foo()\n" + " \n" + " /*a();\n" + " \n" + " b();*/\n" + " c();\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 0, ch: 5}, {line: 5, ch: 5}); // middle of first line of code to middle of line following comment CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[2] = " a();"; lines[4] = " b();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 5}, end: {line: 5, ch: 5}}); }); // Selections including multiple separate block comments // We no-op in these cases since it's ambiguous - can't nest block comments, but was multiple independent uncomments intended? it("should do nothing, selection covers parts of multiple block comments", function () { // Start with part of line 1 wrapped in a block comment var lines = defaultContent.split("\n"); lines[1] = " /*function*/ /*bar()*/ {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select end of 1st comment, start of 2nd comment, and the space between them myEditor.setSelection({line: 1, ch: 9}, {line: 1, ch: 22}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 9}, end: {line: 1, ch: 22}}); // no change }); it("should do nothing, selection covers all of multiple block comments", function () { // Start with part of line 1 wrapped in a block comment var lines = defaultContent.split("\n"); lines[1] = " /*function*/ /*bar()*/ {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select both block comments and the space between them, but nothing else myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 26}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 26}}); // no change }); it("should do nothing, selection covers multiple block comments & nothing else", function () { // Start with part of line 1 wrapped in a block comment var lines = defaultContent.split("\n"); lines[1] = " /*function*//*bar()*/ {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select both block comments, but nothing else myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 25}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 25}}); // no change }); it("should do nothing, selection covers multiple block comments plus other text", function () { // Start with part of line 1 wrapped in a block comment var lines = defaultContent.split("\n"); lines[1] = " /*function*/ /*bar()*/ {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select all of line 1 (but not newline) myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 28}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 1, ch: 28}}); // no change }); }); // If the cursor's/selection's lines contain nothing but line comments and whitespace, we assume the user // meant line-uncomment (i.e. delegate to Toggle Line Comment). In all other cases, we ignore the line comment // and create a new block comment. describe("Block comment around line comments", function () { beforeEach(setupFullEditor); // Selections including existing line comments (and possibly whitespace) it("should switch to line uncomment mode, cursor inside line comment (with only whitespace to left)", function () { // Start with part of line 1 line-commented var lines = defaultContent.split("\n"); lines[1] = " //function bar() {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); myEditor.setCursorPos(1, 18); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 1, ch: 16}); }); it("should switch to line uncomment, cursor in whitespace to left of line comment", function () { // #2342 // Start with part of line 1 line-commented var lines = defaultContent.split("\n"); lines[1] = " //function bar() {"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); myEditor.setCursorPos(1, 0); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 1, ch: 0}); }); it("should switch to line uncomment, some of line-comment selected (only whitespace to left)", function () { var content = "function foo()\n" + " // Comment\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 6}, {line: 1, ch: 13}); // just " Commen" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " Comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 11}}); }); it("should switch to line uncomment, some of line-comment selected including last char (only whitespace to left)", function () { // #2337 var content = "function foo()\n" + " // Comment\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 6}, {line: 1, ch: 14}); // everything but leading "//" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " Comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 12}}); }); it("should switch to line uncomment, all of line-comment selected (only whitespace to left)", function () { // #2342 var content = "function foo()\n" + " // Comment\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 14}); // include "//" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " Comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 12}}); }); // Selections that don't mix code & line-comment, but are on a line that does contain both it("should insert block comment, cursor inside line comment (with code to left)", function () { // Start with comment ending line 1 var lines = defaultContent.split("\n"); lines[1] = " function bar() { // comment"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); myEditor.setCursorPos(1, 24); // between space and "c" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); lines = defaultContent.split("\n"); lines[1] = " function bar() { // /**/comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: 26}); }); it("should insert block comment, cursor in code to left of line comment", function () { // Start with comment ending line 1 var lines = defaultContent.split("\n"); lines[1] = " function bar() { // comment"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); myEditor.setCursorPos(1, 12); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); lines[1] = " function/**/ bar() { // comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: 14}); }); it("should block comment, some of line-comment selected (with code to left)", function () { var content = "function foo()\n" + " f(); // Comment\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 11}, {line: 1, ch: 18}); // just " Commen" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " f(); ///* Commen*/t"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 13}, end: {line: 1, ch: 20}}); }); it("should block comment, some of line-comment selected including last char (with code to left)", function () { // #2337 var content = "function foo()\n" + " f(); // Comment\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 11}, {line: 1, ch: 19}); // everything but leading "//" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " f(); ///* Comment*/"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 13}, end: {line: 1, ch: 21}}); }); it("should block comment, all of line-comment selected (with code to left)", function () { // #2342 var content = "function foo()\n" + " f(); // Comment\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 9}, {line: 1, ch: 19}); // include "//" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " f(); /*// Comment*/"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 11}, end: {line: 1, ch: 21}}); }); // Full-line/multiline selections containing only line comments and whitespace it("should switch to line uncomment, all of line-comment line selected (following line is code)", function () { var content = "function foo()\n" + " // Comment\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " Comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); }); it("should switch to line uncomment, all of line-comment line selected (following line is whitespace)", function () { var content = "function foo()\n" + " // Comment\n" + " \n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " Comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); }); it("should switch to line uncomment, all of line-comment line selected (following line is line comment)", function () { var content = "function foo()\n" + " // Comment\n" + " // Comment 2\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " Comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); }); it("should switch to line uncomment, all of line-comment line selected (following line is block comment)", function () { var content = "function foo()\n" + " // Comment\n" + " /* Comment 2 */\n" + "}"; myDocument.setText(content); myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = content.split("\n"); lines[1] = " Comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); }); it("should line uncomment, multiple line comments selected", function () { // Start with all of lines 1-5 line-commented var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "// a();"; lines[4] = "// "; lines[5] = "// }"; var content = lines.join("\n"); myDocument.setText(content); myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); // Selections mixing uncommented code & line comments var lineCommentCode = "function foo() {\n" + " \n" + " // Floating comment\n" + " \n" + " // Attached comment\n" + " function bar() {\n" + " a();\n" + " b(); // post comment\n" + " }\n" + " \n" + " bar();\n" + " // Attached above\n" + " \n" + " // Final floating comment\n" + " \n" + "}"; it("should line uncomment, multiline selection covers line comment plus whitespace", function () { myDocument.setText(lineCommentCode); myEditor.setSelection({line: 1, ch: 0}, {line: 3, ch: 4}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[2] = " Floating comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 4}}); }); it("should switch to line uncomment mode, selection starts in whitespace & ends in middle of line comment", function () { // #2342 myDocument.setText(lineCommentCode); myEditor.setSelection({line: 2, ch: 2}, {line: 2, ch: 10}); // stops with "Flo" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[2] = " Floating comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 2}, end: {line: 2, ch: 8}}); }); it("should switch to line uncomment mode, selection starts in whitespace & ends at end of line comment", function () { // #2337, #2342 myDocument.setText(lineCommentCode); myEditor.setSelection({line: 2, ch: 2}, {line: 2, ch: 23}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[2] = " Floating comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 2}, end: {line: 2, ch: 21}}); }); it("should block comment, selection starts in code & ends in middle of line comment", function () { // #2342 myDocument.setText(lineCommentCode); myEditor.setSelection({line: 7, ch: 8}, {line: 7, ch: 20}); // stops at end of "post" CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[7] = " /*b(); // post*/ comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 7, ch: 10}, end: {line: 7, ch: 22}}); }); it("should block comment, selection starts in middle of code & ends at end of line comment", function () { // #2342 myDocument.setText(lineCommentCode); myEditor.setSelection({line: 7, ch: 9}, {line: 7, ch: 28}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[7] = " b/*(); // post comment*/"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 7, ch: 11}, end: {line: 7, ch: 30}}); }); it("should block comment, selection starts in code & ends at end of line comment", function () { // #2337 myDocument.setText(lineCommentCode); myEditor.setSelection({line: 7, ch: 8}, {line: 7, ch: 28}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[7] = " /*b(); // post comment*/"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 7, ch: 10}, end: {line: 7, ch: 30}}); }); it("should block comment, selection starts at col 0 of code & ends at end of line comment", function () { myDocument.setText(lineCommentCode); myEditor.setSelection({line: 7, ch: 0}, {line: 7, ch: 28}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[7] = "/* b(); // post comment*/"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 7, ch: 2}, end: {line: 7, ch: 30}}); }); it("should block comment, selection starts on line with line comment", function () { myDocument.setText(lineCommentCode); myEditor.setSelection({line: 4, ch: 0}, {line: 9, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines.splice(9, 0, "*/"); lines.splice(4, 0, "/*"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 5, ch: 0}, end: {line: 10, ch: 0}}); }); it("should block comment, selection ends on line with line comment", function () { myDocument.setText(lineCommentCode); myEditor.setSelection({line: 10, ch: 0}, {line: 12, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines.splice(12, 0, "*/"); lines.splice(10, 0, "/*"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 11, ch: 0}, end: {line: 13, ch: 0}}); }); it("should line uncomment, selection covers several line comments separated by whitespace", function () { myDocument.setText(lineCommentCode); myEditor.setSelection({line: 11, ch: 0}, {line: 14, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); var lines = lineCommentCode.split("\n"); lines[11] = " Attached above"; lines[13] = " Final floating comment"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 11, ch: 0}, end: {line: 14, ch: 0}}); }); }); // In cases where the language only supports block comments, the line comment/uncomment command may perform block comment/uncomment instead describe("Line comment auto-switching to block comment", function () { var cssContent = "div {\n" + " color: red;\n" + "}\n" + "\n" + "/*span {\n" + " color: blue;\n" + "}*/\n"; beforeEach(function () { setupFullEditor(cssContent, "css"); }); it("should block-comment entire line that cursor is in", function () { myEditor.setCursorPos(1, 4); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[1] = "/* color: red;*/"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: 6}); }); it("should block-comment entire line that sub-line selection is in", function () { myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 9}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[1] = "/* color: red;*/"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 6}, end: {line: 1, ch: 11}}); }); it("should block-comment full multi-line selection", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 3, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines.splice(3, 0, "*/"); lines.splice(0, 0, "/*"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); }); it("should block-comment partial multi-line selection as if it were full", function () { myEditor.setSelection({line: 0, ch: 3}, {line: 1, ch: 10}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines.splice(2, 0, "*/"); lines.splice(0, 0, "/*"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 3}, end: {line: 2, ch: 10}}); // range endpoints still align with same text }); it("should uncomment multi-line block comment selection, selected exactly", function () { myEditor.setSelection({line: 4, ch: 0}, {line: 6, ch: 3}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[4] = "span {"; lines[6] = "}"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 4, ch: 0}, end: {line: 6, ch: 1}}); }); it("should uncomment multi-line block comment selection, selected including trailing newline", function () { // #2339 myEditor.setSelection({line: 4, ch: 0}, {line: 7, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[4] = "span {"; lines[6] = "}"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 4, ch: 0}, end: {line: 7, ch: 0}}); }); it("should uncomment multi-line block comment selection, only start selected", function () { myEditor.setSelection({line: 4, ch: 0}, {line: 5, ch: 8}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[4] = "span {"; lines[6] = "}"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 4, ch: 0}, end: {line: 5, ch: 8}}); }); it("should uncomment multi-line block comment selection, only middle selected", function () { myEditor.setSelection({line: 5, ch: 0}, {line: 5, ch: 8}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[4] = "span {"; lines[6] = "}"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 5, ch: 0}, end: {line: 5, ch: 8}}); }); it("should uncomment multi-line block comment selection, only end selected", function () { // #2339 myEditor.setSelection({line: 5, ch: 8}, {line: 6, ch: 3}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[4] = "span {"; lines[6] = "}"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 5, ch: 8}, end: {line: 6, ch: 1}}); }); it("should uncomment multi-line block comment selection, only end selected, ends at EOF", function () { // remove trailing blank line, so end of "*/" is EOF (no newline afterward) myDocument.replaceRange("", {line: 6, ch: 3}, {line: 7, ch: 0}); var content = myDocument.getText(); myEditor.setSelection({line: 5, ch: 8}, {line: 6, ch: 3}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = content.split("\n"); lines[4] = "span {"; lines[6] = "}"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 5, ch: 8}, end: {line: 6, ch: 1}}); }); it("should uncomment multi-line block comment that cursor is in", function () { myEditor.setCursorPos(5, 4); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = cssContent.split("\n"); lines[4] = "span {"; lines[6] = "}"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 5, ch: 4}); }); }); describe("Comment/uncomment with mixed syntax modes", function () { var htmlContent = "<html>\n" + " <head>\n" + " <style type='text/css'>\n" + " body {\n" + " font-size: 15px;\n" + " }\n" + " </style>\n" + " <script type='text/javascript'>\n" + " function foo() {\n" + " function bar() {\n" + " a();\n" + " }\n" + " }\n" + " </script>\n" + " </head>\n" + " <body>\n" + " <p>Hello</p>\n" + " <p>World</p>\n" + " </body>\n" + "</html>"; beforeEach(function () { setupFullEditor(htmlContent, "html"); }); // Correct behavior for line and block comment commands it("should block comment/uncomment generic HTML code", function () { myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 10}); var lines = htmlContent.split("\n"); lines[1] = " <!--<head>-->"; var expectedText = lines.join("\n"); testToggleBlock(expectedText, {start: { line: 1, ch: 8 }, end: {line: 1, ch: 14}}); }); it("should block comment/uncomment generic CSS code", function () { myEditor.setSelection({line: 4, ch: 16}, {line: 4, ch: 32}); var lines = htmlContent.split("\n"); lines[4] = " /*font-size: 15px;*/"; var expectedText = lines.join("\n"); testToggleBlock(expectedText, {start: {line: 4, ch: 18}, end: {line: 4, ch: 34}}); }); it("should line comment/uncomment generic JS code", function () { myEditor.setCursorPos(10, 0); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = htmlContent.split("\n"); lines[10] = "// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 10, ch: 2}); // Uncomment CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(htmlContent); expectCursorAt({line: 10, ch: 0}); }); it("should block comment/uncomment generic JS code", function () { myEditor.setSelection({line: 8, ch: 0}, {line: 13, ch: 0}); var lines = htmlContent.split("\n"); lines.splice(13, 0, "*/"); lines.splice(8, 0, "/*"); var expectedText = lines.join("\n"); testToggleBlock(expectedText, {start: {line: 9, ch: 0}, end: {line: 14, ch: 0}}); }); it("should HTML comment/uncomment around outside of <style> block", function () { myEditor.setSelection({line: 2, ch: 0}, {line: 7, ch: 0}); var lines = htmlContent.split("\n"); lines.splice(7, 0, "-->"); lines.splice(2, 0, "<!--"); var expectedText = lines.join("\n"); testToggleBlock(expectedText, {start: {line: 3, ch: 0}, end: {line: 8, ch: 0}}); }); it("shouldn't comment anything when selection mixes modes", function () { myEditor.setSelection({line: 3, ch: 0}, {line: 11, ch: 0}); CommandManager.execute(Commands.EDIT_BLOCK_COMMENT, myEditor); expect(myDocument.getText()).toEqual(htmlContent); expectSelection({start: {line: 3, ch: 0}, end: {line: 11, ch: 0}}); }); }); describe("Duplicate", function () { beforeEach(setupFullEditor); it("should duplicate whole line if no selection", function () { // place cursor in middle of line 1 myEditor.setCursorPos(1, 10); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, " function bar() {"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 2, ch: 10}); }); it("should duplicate line + \n if selected line is at end of file", function () { var lines = defaultContent.split("\n"), len = lines.length; // place cursor at the beginning of the last line myEditor.setCursorPos(len - 1, 0); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); lines.push("}"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: len, ch: 0}); }); it("should duplicate first line", function () { // place cursor at start of line 0 myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(0, 0, "function foo() {"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: 0}); }); it("should duplicate empty line", function () { // place cursor on line 6 myEditor.setCursorPos(6, 0); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(6, 0, ""); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 7, ch: 0}); }); it("should duplicate selection within a line", function () { // select "bar" on line 1 myEditor.setSelection({line: 1, ch: 13}, {line: 1, ch: 16}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines[1] = " function barbar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 16}, end: {line: 1, ch: 19}}); }); it("should duplicate when entire line selected, excluding newline", function () { // select all of line 1, EXcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines[1] = " function bar() { function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 20}, end: {line: 1, ch: 40}}); }); it("should duplicate when entire line selected, including newline", function () { // select all of line 1, INcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, " function bar() {"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 3, ch: 0}}); }); it("should duplicate when multiple lines selected", function () { // select lines 1-3 myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, " function bar() {", " ", " a();"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 4, ch: 0}, end: {line: 7, ch: 0}}); }); it("should duplicate selection crossing line boundary", function () { // select from middle of line 1 to middle of line 3 myEditor.setSelection({line: 1, ch: 13}, {line: 3, ch: 11}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 3, " function bar() {", " ", " a()bar() {", " ", " a();"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 3, ch: 11}, end: {line: 5, ch: 11}}); }); it("should duplicate after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var expectedText = defaultContent + defaultContent; expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 7, ch: 1}, end: {line: 14, ch: 1}}); }); }); describe("Move Lines Up/Down", function () { beforeEach(setupFullEditor); it("should move whole line up if no selection", function () { // place cursor in middle of line 1 myEditor.setCursorPos(1, 10); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[0]; lines[0] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 0, ch: 10}); }); it("should move whole line down if no selection", function () { // place cursor in middle of line 1 myEditor.setCursorPos(1, 10); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 2, ch: 10}); }); it("shouldn't move up first line", function () { // place cursor at start of line 0 myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 0, ch: 0}); }); it("shouldn't move down last line", function () { var lines = defaultContent.split("\n"), len = lines.length; // place cursor at the beginning of the last line myEditor.setCursorPos(len - 1, 0); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: len - 1, ch: 0}); }); it("should move up empty line", function () { // place cursor on line 6 myEditor.setCursorPos(6, 0); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[5]; lines[5] = lines[6]; lines[6] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 5, ch: 0}); }); it("should move down empty line", function () { // place cursor on line 6 myEditor.setCursorPos(6, 0); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[7]; lines[7] = lines[6]; lines[6] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 7, ch: 0}); }); it("should move up when entire line selected, excluding newline", function () { // select all of line 1, EXcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[0]; lines[0] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 0}, end: {line: 0, ch: 20}}); }); it("should move down when entire line selected, excluding newline", function () { // select all of line 1, EXcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 2, ch: 20}}); }); it("should move up when entire line selected, including newline", function () { // select all of line 1, INcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[0]; lines[0] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 0}, end: {line: 1, ch: 0}}); }); it("should move down when entire line selected, including newline", function () { // select all of line 1, INcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 3, ch: 0}}); }); it("should move up when multiple lines selected", function () { // select lines 2-3 myEditor.setSelection({line: 2, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[1]; lines[1] = lines[2]; lines[2] = lines[3]; lines[3] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 0}}); }); it("should move down when multiple lines selected", function () { // select lines 2-3 myEditor.setSelection({line: 2, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[4]; lines[4] = lines[3]; lines[3] = lines[2]; lines[2] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 3, ch: 0}, end: {line: 5, ch: 0}}); }); it("should move up selection crossing line boundary", function () { // select from middle of line 2 to middle of line 3 myEditor.setSelection({line: 2, ch: 8}, {line: 3, ch: 11}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[1]; lines[1] = lines[2]; lines[2] = lines[3]; lines[3] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 8}, end: {line: 2, ch: 11}}); }); it("should move down selection crossing line boundary", function () { // select from middle of line 2 to middle of line 3 myEditor.setSelection({line: 2, ch: 8}, {line: 3, ch: 11}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[4]; lines[4] = lines[3]; lines[3] = lines[2]; lines[2] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 3, ch: 8}, end: {line: 4, ch: 11}}); }); it("should move the last line up", function () { // place cursor in last line myEditor.setCursorPos(7, 0); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[6]; lines[6] = lines[7]; lines[7] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 6, ch: 0}); }); it("should move the first line down", function () { // place cursor in first line myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[1]; lines[1] = lines[0]; lines[0] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: 0}); }); it("should move the last lines up", function () { // select lines 6-7 myEditor.setSelection({line: 6, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[5]; lines[5] = lines[6]; lines[6] = lines[7]; lines[7] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 5, ch: 0}, end: {line: 6, ch: 1}}); }); it("should move the first lines down", function () { // select lines 0-1 myEditor.setSelection({line: 0, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = lines[0]; lines[0] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 0}}); }); it("shouldn't move up after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}}); }); it("shouldn't move down after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}}); }); }); describe("Move Lines Up/Down - inline editor", function () { this.category = "integration"; var moveContent = ".testClass {\n" + " color: red;\n" + "}"; beforeEach(function () { createWindowWithInlineEditor(this); }); afterEach(function () { closeFilesInTestWindow(); }); it("should not move the first line of the inline editor up", function () { myEditor.setCursorPos({line: 0, ch: 5}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); expect(myEditor.document.getText()).toEqual(moveContent); expect(myEditor._codeMirror.doc.historySize().undo).toBe(0); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(2); }); it("should not move the last line of the inline editor down", function () { myEditor.setCursorPos({line: 2, ch: 5}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); expect(myEditor.document.getText()).toEqual(moveContent); expect(myEditor._codeMirror.doc.historySize().undo).toBe(0); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(2); }); it("should be able to move the second to last line of the inline editor down", function () { myEditor.setCursorPos({line: 1, ch: 5}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = moveContent.split("\n"); var temp = lines[1]; lines[1] = lines[2]; lines[2] = temp; var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(2); }); it("should be able to move the last line of the inline editor up", function () { myEditor.setCursorPos({line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = moveContent.split("\n"); var temp = lines[1]; lines[1] = lines[2]; lines[2] = temp; var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(2); closeTestWindow(); }); }); describe("Delete Line", function () { beforeEach(setupFullEditor); it("should delete the first line when selection is an IP in that line", function () { myEditor.setSelection({line: 0, ch: 5}, {line: 0, ch: 5}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var expectedText = defaultContent.split("\n").slice(1).join("\n"); expect(myDocument.getText()).toEqual(expectedText); }); it("should delete the first line when selection is a range in that line", function () { myEditor.setSelection({line: 0, ch: 5}, {line: 0, ch: 8}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var expectedText = defaultContent.split("\n").slice(1).join("\n"); expect(myDocument.getText()).toEqual(expectedText); }); it("should delete a middle line when selection is an IP in that line", function () { myEditor.setSelection({line: 2, ch: 5}, {line: 2, ch: 5}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var lines = defaultContent.split("\n"); lines.splice(2, 1); expect(myDocument.getText()).toEqual(lines.join("\n")); }); it("should delete a middle line when selection is a range in that line", function () { myEditor.setSelection({line: 2, ch: 5}, {line: 2, ch: 8}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var lines = defaultContent.split("\n"); lines.splice(2, 1); expect(myDocument.getText()).toEqual(lines.join("\n")); }); it("should delete the last line when selection is an IP in that line", function () { myEditor.setSelection({line: 7, ch: 0}, {line: 7, ch: 0}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var expectedText = defaultContent.split("\n").slice(0, 7).join("\n"); expect(myDocument.getText()).toEqual(expectedText); }); it("should delete the last line when selection is a range in that line", function () { myEditor.setSelection({line: 7, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var expectedText = defaultContent.split("\n").slice(0, 7).join("\n"); expect(myDocument.getText()).toEqual(expectedText); }); it("should delete multiple lines starting at the top when selection spans them", function () { myEditor.setSelection({line: 0, ch: 5}, {line: 2, ch: 4}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var expectedText = defaultContent.split("\n").slice(3).join("\n"); expect(myDocument.getText()).toEqual(expectedText); }); it("should delete multiple lines ending at the bottom when selection spans them", function () { myEditor.setSelection({line: 5, ch: 5}, {line: 7, ch: 0}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var expectedText = defaultContent.split("\n").slice(0, 5).join("\n"); expect(myDocument.getText()).toEqual(expectedText); }); it("should leave empty text when all lines are selected", function () { myEditor.setSelection({line: 0, ch: 4}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); expect(myDocument.getText()).toEqual(""); }); }); describe("Delete Line - editor with visible range", function () { it("should delete the top line of the visible range", function () { makeEditorWithRange({startLine: 1, endLine: 5}); myEditor.setSelection({line: 1, ch: 5}, {line: 1, ch: 5}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 1); expect(myDocument.getText()).toEqual(lines.join("\n")); expect(myEditor._visibleRange.startLine).toNotBe(null); expect(myEditor._visibleRange.endLine).toNotBe(null); }); it("should delete the bottom line of the visible range", function () { makeEditorWithRange({startLine: 1, endLine: 5}); myEditor.setSelection({line: 5, ch: 2}, {line: 5, ch: 2}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var lines = defaultContent.split("\n"); lines.splice(5, 1); expect(myDocument.getText()).toEqual(lines.join("\n")); expect(myEditor._visibleRange.startLine).toNotBe(null); expect(myEditor._visibleRange.endLine).toNotBe(null); }); it("should leave a single newline when all visible lines are selected", function () { makeEditorWithRange({startLine: 1, endLine: 5}); myEditor.setSelection({line: 1, ch: 5}, {line: 5, ch: 2}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 5, ""); expect(myDocument.getText()).toEqual(lines.join("\n")); expect(myEditor._visibleRange.startLine).toNotBe(null); expect(myEditor._visibleRange.endLine).toNotBe(null); }); it("should leave a single newline when only one line is visible", function () { makeEditorWithRange({startLine: 3, endLine: 3}); myEditor.setSelection({line: 3, ch: 4}, {line: 3, ch: 4}); CommandManager.execute(Commands.EDIT_DELETE_LINES, myEditor); var lines = defaultContent.split("\n"); lines.splice(3, 1, ""); expect(myDocument.getText()).toEqual(lines.join("\n")); expect(myEditor._visibleRange.startLine).toNotBe(null); expect(myEditor._visibleRange.endLine).toNotBe(null); }); }); describe("Select Line", function () { beforeEach(setupFullEditor); it("should select the first line with IP in that line", function () { myEditor.setSelection({line: 0, ch: 5}, {line: 0, ch: 5}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 0, ch: 0}, end: {line: 1, ch: 0}}); }); it("should select the last line with IP in that line", function () { myEditor.setSelection({line: 7, ch: 0}, {line: 7, ch: 0}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 7, ch: 0}, end: {line: 7, ch: 1}}); }); it("should select all in one-line file", function () { myDocument.setText("// x"); myEditor.setSelection({line: 0, ch: 0}, {line: 0, ch: 0}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 0, ch: 0}, end: {line: 0, ch: 4}}); }); it("should extend selection to whole line", function () { myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 8}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); }); it("should extend whole line selection to next line", function () { myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 0}}); }); it("should extend multi-line selection to full lines", function () { myEditor.setSelection({line: 1, ch: 4}, {line: 3, ch: 9}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); }); it("should extend full multi-line selection to one more line", function () { myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 1, ch: 0}, end: {line: 5, ch: 0}}); }); }); describe("Select Line - editor with visible range", function () { it("shouldn't select past end of visible range, IP in middle of last visible line", function () { makeEditorWithRange({startLine: 1, endLine: 5}); myEditor.setSelection({line: 5, ch: 4}, {line: 5, ch: 4}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 5, ch: 0}, end: {line: 5, ch: 5}}); }); it("shouldn't select past end of visible range, IP at start of last visible line", function () { makeEditorWithRange({startLine: 1, endLine: 5}); myEditor.setSelection({line: 5, ch: 0}, {line: 5, ch: 0}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 5, ch: 0}, end: {line: 5, ch: 5}}); }); it("should extend selection to include last line of visible range", function () { makeEditorWithRange({startLine: 1, endLine: 5}); myEditor.setSelection({line: 4, ch: 4}, {line: 4, ch: 4}); CommandManager.execute(Commands.EDIT_SELECT_LINE, myEditor); expectSelection({start: {line: 4, ch: 0}, end: {line: 5, ch: 0}}); }); }); describe("Open Line Above and Below", function () { var indentUnit = Editor.getSpaceUnits(); var indentation = (function () { // generate indent string once var spaces = []; spaces.length = indentUnit + 1; return spaces.join(" "); }()); beforeEach(setupFullEditor); it("should insert new line above if no selection", function () { // place cursor in line 1 myEditor.setCursorPos(1, 10); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: indentUnit}); }); it("should insert new line above the first line if no selection", function () { // place cursor in the first line myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = defaultContent.split("\n"); lines.splice(0, 0, ""); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 0, ch: 0}); }); it("should insert new line above the last line if no selection", function () { // place cursor in the last line myEditor.setCursorPos(7, 0); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = defaultContent.split("\n"); lines.splice(7, 0, indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 7, ch: indentUnit}); }); it("should insert new line above with no indentation if no selection", function () { // place cursor in the middle of line 0 myEditor.setCursorPos(0, 10); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = defaultContent.split("\n"); lines.splice(0, 0, ""); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 0, ch: 0}); }); it("should insert new line above when characters selected", function () { // select characters 0-10 in line 1 myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 10}); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: indentUnit}); }); it("should insert new line above when linewise selection", function () { // select all of line 1 and 2, Including trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 3, ch: 0}); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: indentUnit}); }); it("should insert new line above when multiple line selection", function () { // selection from line 2 character 6 to line 5 character 2 myEditor.setSelection({line: 2, ch: 6}, {line: 5, ch: 2}); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = defaultContent.split("\n"); lines.splice(2, 0, " " + indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 2, ch: 4 + indentUnit}); }); it("should insert new line below when no selection", function () { // place cursor in line 0 myEditor.setCursorPos(0, 10); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: indentUnit}); }); it("should insert new line below the first line if no selection", function () { // place cursor in the first line myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: indentUnit}); }); it("should insert new line below the last line if no selection", function () { // place cursor in the last line myEditor.setCursorPos(7, 0); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = defaultContent.split("\n"); lines.splice(8, 0, ""); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 8, ch: 0}); }); it("should insert new line below with no indentation if no selection", function () { // place cursor in line 7 character 1 myEditor.setCursorPos(7, 1); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = defaultContent.split("\n"); lines.splice(8, 0, ""); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 8, ch: 0}); }); it("should insert new line below when characters selected", function () { // select characters 0-10 in line 0 myEditor.setSelection({line: 0, ch: 0}, {line: 0, ch: 10}); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: indentUnit}); }); it("should insert new line below when linewise selection", function () { // select all of line 1 and 2, Including trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 3, ch: 0}); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = defaultContent.split("\n"); lines.splice(3, 0, " " + indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 3, ch: 4 + indentUnit}); }); it("should insert new line below when multiple line selection", function () { // selection from line 1 character 4 to line 4 character 2 myEditor.setSelection({line: 1, ch: 4}, {line: 4, ch: 2}); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = defaultContent.split("\n"); lines.splice(5, 0, " " + indentation); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 5, ch: 4 + indentUnit}); }); }); describe("Open Line Above and Below - inline editor", function () { this.category = "integration"; var content = ".testClass {\n" + " color: red;\n" + "}"; beforeEach(function () { createWindowWithInlineEditor(this); }); afterEach(function () { closeFilesInTestWindow(); }); it("should insert new line above the first line of the inline editor", function () { myEditor.setSelection({line: 0, ch: 4}, {line: 0, ch: 6}); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = content.split("\n"); lines.splice(0, 0, ""); var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(3); }); it("should insert new line below the first line of the inline editor", function () { myEditor.setCursorPos({line: 0, ch: 3}); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = content.split("\n"); lines.splice(1, 0, " "); var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(3); }); it("should insert new line above the last line of the inline editor", function () { myEditor.setSelection({line: 2, ch: 0}, {line: 2, ch: 1}); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = content.split("\n"); lines.splice(2, 0, " "); var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(3); }); it("should insert new line below the last line of the inline editor", function () { myEditor.setCursorPos({line: 3, ch: 0}); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = content.split("\n"); lines.splice(3, 0, ""); var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(3); }); it("should insert new indented line above the second line of the inline editor", function () { myEditor.setCursorPos({line: 1, ch: 5}); CommandManager.execute(Commands.EDIT_OPEN_LINE_ABOVE, myEditor); var lines = content.split("\n"); lines.splice(1, 0, " "); var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(3); }); it("should insert new indented line below the second line of the inline editor", function () { myEditor.setCursorPos({line: 1, ch: 5}); CommandManager.execute(Commands.EDIT_OPEN_LINE_BELOW, myEditor); var lines = content.split("\n"); lines.splice(2, 0, " "); var expectedText = lines.join("\n"); expect(myEditor.document.getText()).toEqual(expectedText); expect(myEditor.getFirstVisibleLine()).toBe(0); expect(myEditor.getLastVisibleLine()).toBe(3); closeTestWindow(); }); }); }); });
var express = require('express'); var router = express.Router(); var projectController = require('../controllers/projectController'); router.get('/', projectController.allProjects); // To add a project by curl // NOTE: Untested // curl -H "Content-Type: application/json" -X POST -d '{"name":"my task", "description":"blahblah"}' http://localhost:3000/api/projects/create router.post('/create', projectController.createProject); module.exports = router;
/** * @module ember-paper */ import $ from 'jquery'; import { computed } from '@ember/object'; import { htmlSafe } from '@ember/string'; import layout from '../templates/components/paper-menu-content'; import ContentComponent from 'ember-basic-dropdown/components/basic-dropdown/content'; import { nextTick } from 'ember-css-transitions/mixins/transition-mixin'; const MutObserver = window.MutationObserver || window.WebKitMutationObserver; function waitForAnimations(element, callback) { let computedStyle = window.getComputedStyle(element); if (computedStyle.transitionDuration && computedStyle.transitionDuration !== '0s') { let eventCallback = function() { element.removeEventListener('transitionend', eventCallback); callback(); }; element.addEventListener('transitionend', eventCallback); } else if (computedStyle.animationName !== 'none' && computedStyle.animationPlayState === 'running') { let eventCallback = function() { element.removeEventListener('animationend', eventCallback); callback(); }; element.addEventListener('animationend', eventCallback); } else { callback(); } } /** * @class PaperMenuContent * @extends ContentComponent */ export default ContentComponent.extend({ layout, // We need to overwrite this CP because: // 1. we don't want to use the width property // 2. we need additional styles style: computed('top', 'left', 'right', 'transform', 'transformOrigin', function() { let style = ''; let { top, left, right, transform, transformOrigin } = this.getProperties('top', 'left', 'right', 'transform', 'transformOrigin'); if (top) { style += `top: ${top};`; } if (left) { style += `left: ${left};`; } if (right) { style += `right: ${right};`; } if (transform) { style += `transform: ${transform};`; } if (transformOrigin) { style += `transform-origin: ${transformOrigin};`; } if (style.length > 0) { return htmlSafe(style); } }), startObservingDomMutations() { if (MutObserver) { this.mutationObserver = new MutObserver((mutations) => { // e-b-d incorrectly counts ripples as a mutation, triggering a problematic repositon // convert NodeList to Array let addedNodes = Array.prototype.slice.call(mutations[0].addedNodes).filter((node) => !$(node).hasClass('md-ripple') && (node.nodeName !== '#comment') && !(node.nodeName === '#text' && node.nodeValue === '')); let removedNodes = Array.prototype.slice.call(mutations[0].removedNodes).filter((node) => !$(node).hasClass('md-ripple') && (node.nodeName !== '#comment')); if (addedNodes.length || removedNodes.length) { this.runloopAwareReposition(); } }); this.mutationObserver.observe(this.dropdownElement, { childList: true, subtree: true }); } else { this.dropdownElement.addEventListener('DOMNodeInserted', this.runloopAwareReposition, false); this.dropdownElement.addEventListener('DOMNodeRemoved', this.runloopAwareReposition, false); } }, animateIn() { this.dropdownElement.style.transform = this.get('transform'); nextTick().then(() => { this.set('isActive', true); this.set('transform', null); }); }, animateOut(dropdownElement) { let parentElement = this.get('renderInPlace') ? dropdownElement.parentElement.parentElement : dropdownElement.parentElement; let clone = dropdownElement.cloneNode(true); clone.id = `${clone.id}--clone`; let $clone = $(clone); parentElement.appendChild(clone); nextTick().then(() => { if (!this.get('isDestroyed')) { this.set('isActive', false); $clone.addClass('md-leave'); waitForAnimations(clone, function() { $clone.removeClass('md-active'); parentElement.removeChild(clone); }); } else { parentElement.removeChild(clone); } }); } });
window.WhereAmIButton = (function() { var defaultOptions = { selector: '.whereami-button', mapInstance: null }; /** * Class that contains the behavior of the * * @class * @param {Object} options */ function WhereAmIButton(options) { this.options = $.extend({}, defaultOptions, options); this.$el = $(this.options.selector); this.map = this.options.mapInstance; this.initialize(); } /** * Initializes the classe's behavior * * @return {void} */ WhereAmIButton.prototype.initialize = function() { this.$el.on('click', this.onClickHandler.bind(this)); }; /** * The handler for the click event on the button * * @param {Event} e * @return {void} */ WhereAmIButton.prototype.onClickHandler = function(e) { e.preventDefault(); this.map.centerOnUserPosition(); }; return WhereAmIButton; })();
var mongoose = require('mongoose'); var config = require('../config'); var logger = require('../common/logger') mongoose.connect(config.db, { server: {poolSize: 20} }, function (err) { if (err) { logger.error('connect to %s error: ', config.db, err.message); process.exit(1); } }); // models require('./user'); require('./topic'); require('./reply'); require('./topic_collect'); require('./message'); exports.User = mongoose.model('User'); exports.Topic = mongoose.model('Topic'); exports.Reply = mongoose.model('Reply'); exports.TopicCollect = mongoose.model('TopicCollect'); exports.Message = mongoose.model('Message');
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.hola_videojs_hls = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var Hls = window.Hls = require('@hola.org/hls.js').default; var provider = module.exports = require('@hola.org/videojs5-hlsjs-source-handler'); provider.Hls = Hls; provider.version = '1.0.28'; provider.hls_version = provider.Hls.version; provider.provider_version = provider.VERSION; },{"@hola.org/hls.js":26,"@hola.org/videojs5-hlsjs-source-handler":42}],2:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _bufferHelper = require('../helper/buffer-helper'); var _bufferHelper2 = _interopRequireDefault(_bufferHelper); var _errors = require('../errors'); var _logger = require('../utils/logger'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * simple ABR Controller * - compute next level based on last fragment bw heuristics * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling */ var AbrController = function (_EventHandler) { _inherits(AbrController, _EventHandler); function AbrController(hls) { _classCallCheck(this, AbrController); var _this = _possibleConstructorReturn(this, (AbrController.__proto__ || Object.getPrototypeOf(AbrController)).call(this, hls, _events2.default.FRAG_LOADING, _events2.default.FRAG_LOAD_PROGRESS, _events2.default.FRAG_LOADED, _events2.default.ERROR)); _this.lastLoadedFragLevel = 0; _this._autoLevelCapping = -1; _this._nextAutoLevel = -1; _this.hls = hls; _this.onCheck = _this.abandonRulesCheck.bind(_this); return _this; } _createClass(AbrController, [{ key: 'destroy', value: function destroy() { this.clearTimer(); _eventHandler2.default.prototype.destroy.call(this); } }, { key: 'onFragLoading', value: function onFragLoading(data) { if (!this.timer) { this.timer = setInterval(this.onCheck, 100); } this.fragCurrent = data.frag; } }, { key: 'onFragLoadProgress', value: function onFragLoadProgress(data) { var stats = data.stats; // only update stats if first frag loading // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly // and leading to wrong bw estimation if (stats.aborted === undefined && data.frag.loadCounter === 1) { this.lastfetchduration = (performance.now() - stats.trequest) / 1000; this.lastbw = stats.loaded * 8 / this.lastfetchduration; //console.log(`fetchDuration:${this.lastfetchduration},bw:${(this.lastbw/1000).toFixed(0)}/${stats.aborted}`); } } }, { key: 'abandonRulesCheck', value: function abandonRulesCheck() { /* monitor fragment retrieval time... we compute expected time of arrival of the complete fragment. we compare it to expected time of buffer starvation */ var hls = this.hls, v = hls.media, frag = this.fragCurrent; // if loader has been destroyed or loading has been aborted, stop timer and return if (!frag.loader || frag.loader.stats && frag.loader.stats.aborted) { _logger.logger.warn('frag loader destroy or aborted, disarm abandonRulesCheck'); this.clearTimer(); return; } /* only monitor frag retrieval time if (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */ if (v && (!v.paused || !v.readyState) && frag.autoLevel && frag.level) { var requestDelay = performance.now() - frag.trequest; // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate if (requestDelay > 500 * frag.duration) { var loadRate = Math.max(1, frag.loaded * 1000 / requestDelay); // byte/s; at least 1 byte/s to avoid division by zero if (frag.expectedLen < frag.loaded) { frag.expectedLen = frag.loaded; } var pos = v.currentTime; var fragLoadedDelay = (frag.expectedLen - frag.loaded) / loadRate; var bufferStarvationDelay = _bufferHelper2.default.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos; // consider emergency switch down only if we have less than 2 frag buffered AND // time to finish loading current fragment is bigger than buffer starvation delay // ie if we risk buffer starvation if bw does not increase quickly if (bufferStarvationDelay < 2 * frag.duration && fragLoadedDelay > bufferStarvationDelay) { var fragLevelNextLoadedDelay = void 0, nextLoadLevel = void 0; // lets iterate through lower level and try to find the biggest one that could avoid rebuffering // we start from current level - 1 and we step down , until we find a matching level for (nextLoadLevel = frag.level - 1; nextLoadLevel >= 0; nextLoadLevel--) { // compute time to load next fragment at lower level // 0.8 : consider only 80% of current bw to be conservative // 8 = bits per byte (bps/Bps) fragLevelNextLoadedDelay = frag.duration * hls.levels[nextLoadLevel].bitrate / (8 * 0.8 * loadRate); _logger.logger.log('fragLoadedDelay/bufferStarvationDelay/fragLevelNextLoadedDelay[' + nextLoadLevel + '] :' + fragLoadedDelay.toFixed(1) + '/' + bufferStarvationDelay.toFixed(1) + '/' + fragLevelNextLoadedDelay.toFixed(1)); if (fragLevelNextLoadedDelay < bufferStarvationDelay) { // we found a lower level that be rebuffering free with current estimated bw ! break; } } // only emergency switch down if it takes less time to load new fragment at lowest level instead // of finishing loading current one ... if (fragLevelNextLoadedDelay < fragLoadedDelay) { // ensure nextLoadLevel is not negative nextLoadLevel = Math.max(0, nextLoadLevel); // force next load level in auto mode hls.nextLoadLevel = nextLoadLevel; // abort fragment loading ... _logger.logger.warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel); //abort fragment loading frag.loader.abort(); this.clearTimer(); hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag }); } } } } } }, { key: 'onFragLoaded', value: function onFragLoaded(data) { // stop monitoring bw once frag loaded this.clearTimer(); // store level id after successful fragment load this.lastLoadedFragLevel = data.frag.level; // reset forced auto level value so that next level will be selected this._nextAutoLevel = -1; } }, { key: 'onError', value: function onError(data) { // stop timer in case of frag loading error switch (data.details) { case _errors.ErrorDetails.FRAG_LOAD_ERROR: case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT: this.clearTimer(); break; default: break; } } }, { key: 'clearTimer', value: function clearTimer() { if (this.timer) { clearInterval(this.timer); this.timer = null; } } /** Return the capping/max level value that could be used by automatic level selection algorithm **/ }, { key: 'autoLevelCapping', get: function get() { return this._autoLevelCapping; } /** set the capping/max level value that could be used by automatic level selection algorithm **/ , set: function set(newLevel) { this._autoLevelCapping = newLevel; } }, { key: 'nextAutoLevel', get: function get() { var lastbw = this.lastbw, hls = this.hls, adjustedbw, i, maxAutoLevel; if (this._autoLevelCapping === -1 && hls.levels && hls.levels.length) { maxAutoLevel = hls.levels.length - 1; } else { maxAutoLevel = this._autoLevelCapping; } // in case next auto level has been forced, return it straight-away (but capped) if (this._nextAutoLevel !== -1) { return Math.min(this._nextAutoLevel, maxAutoLevel); } // follow algorithm captured from stagefright : // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp // Pick the highest bandwidth stream below or equal to estimated bandwidth. for (i = 0; i <= maxAutoLevel; i++) { // consider only 80% of the available bandwidth, but if we are switching up, // be even more conservative (70%) to avoid overestimating and immediately // switching back. if (i <= this.lastLoadedFragLevel) { adjustedbw = 0.8 * lastbw; } else { adjustedbw = 0.7 * lastbw; } if (adjustedbw < hls.levels[i].bitrate) { return Math.max(0, i - 1); } } return i - 1; }, set: function set(nextLevel) { this._nextAutoLevel = nextLevel; } }]); return AbrController; }(_eventHandler2.default); exports.default = AbrController; },{"../errors":20,"../event-handler":21,"../events":22,"../helper/buffer-helper":24,"../utils/logger":38}],3:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _logger = require('../utils/logger'); var _errors = require('../errors'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Buffer Controller */ var BufferController = function (_EventHandler) { _inherits(BufferController, _EventHandler); function BufferController(hls) { _classCallCheck(this, BufferController); // the value that we have set mediasource.duration to // (the actual duration may be tweaked slighly by the browser) var _this = _possibleConstructorReturn(this, (BufferController.__proto__ || Object.getPrototypeOf(BufferController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.BUFFER_RESET, _events2.default.BUFFER_APPENDING, _events2.default.BUFFER_CODECS, _events2.default.BUFFER_EOS, _events2.default.BUFFER_FLUSHING, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_APPENDING, _events2.default.LEVEL_UPDATED)); _this._msDuration = null; // the value that we want to set mediaSource.duration to _this._levelDuration = null; // Source Buffer listeners _this.onsbue = _this.onSBUpdateEnd.bind(_this); _this.onsbe = _this.onSBUpdateError.bind(_this); _this.tracks = {}; return _this; } _createClass(BufferController, [{ key: 'destroy', value: function destroy() { _eventHandler2.default.prototype.destroy.call(this); } }, { key: 'onFragParsingData', value: function onFragParsingData(data) { var type = data.type; var audioTrack = this.tracks.audio; // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended) // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset` // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend` // event if SB is in updating state. // More info here: https://github.com/dailymotion/hls.js/issues/332#issuecomment-257986486 if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { // Chrome audio mp3 track var audioBuffer = this.sourceBuffer.audio; var delta = Math.abs(audioBuffer.timestampOffset - data.startPTS); // adjust timestamp offset if time delta is greater than 100ms if (delta > 0.1) { var updating = audioBuffer.updating; try { audioBuffer.abort(); } catch (err) { updating = true; _logger.logger.warn('can not abort audio buffer: ' + err); } if (!updating) { _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.startPTS); audioBuffer.timestampOffset = data.startPTS; } else { this.audioTimestampOffset = data.startPTS; } } } } }, { key: 'onMediaAttaching', value: function onMediaAttaching(data) { var media = this.media = data.media; if (media) { // setup the media source var ms = this.mediaSource = new MediaSource(); //Media Source listeners this.onmso = this.onMediaSourceOpen.bind(this); this.onmse = this.onMediaSourceEnded.bind(this); this.onmsc = this.onMediaSourceClose.bind(this); ms.addEventListener('sourceopen', this.onmso); ms.addEventListener('sourceended', this.onmse); ms.addEventListener('sourceclose', this.onmsc); // link video and media Source var url = URL.createObjectURL(ms); _logger.logger.log('set object url ' + url); media.src = url; } } }, { key: 'onMediaDetaching', value: function onMediaDetaching() { _logger.logger.log('media source detaching'); var ms = this.mediaSource; if (ms) { if (ms.readyState === 'open') { try { // endOfStream could trigger exception if any sourcebuffer is in updating state // we don't really care about checking sourcebuffer state here, // as we are anyway detaching the MediaSource // let's just avoid this exception to propagate ms.endOfStream(); } catch (err) { _logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream'); } } ms.removeEventListener('sourceopen', this.onmso); ms.removeEventListener('sourceended', this.onmse); ms.removeEventListener('sourceclose', this.onmsc); try { // unlink MediaSource from video tag this.media.src = ''; this.media.removeAttribute('src'); } catch (err) { _logger.logger.warn('onMediaDetaching:' + err.message + ' while unlinking video.src'); } this.mediaSource = null; this.media = null; this.pendingTracks = null; this.tracks = {}; this.sourceBuffer = {}; this.flushRange = []; this.segments = []; this.appended = 0; } this.onmso = this.onmse = this.onmsc = null; this.waitForAppended = false; this.hls.trigger(_events2.default.MEDIA_DETACHED); } }, { key: 'onMediaSourceOpen', value: function onMediaSourceOpen() { _logger.logger.log('media source opened'); this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media }); // once received, don't listen anymore to sourceopen event this.mediaSource.removeEventListener('sourceopen', this.onmso); // if any buffer codecs pending, treat it here. var pendingTracks = this.pendingTracks; if (pendingTracks) { this.onBufferCodecs(pendingTracks); this.pendingTracks = null; this.doAppending(); } } }, { key: 'onMediaSourceClose', value: function onMediaSourceClose() { _logger.logger.log('media source closed'); } }, { key: 'onMediaSourceEnded', value: function onMediaSourceEnded() { _logger.logger.log('media source ended'); } }, { key: 'onFragAppending', value: function onFragAppending() { var segments = this.segments || []; if (!segments.length && !this.isSbUpdating()) { this.hls.trigger(_events2.default.FRAG_APPENDED); } else { this.waitForAppended = true; } } }, { key: 'isSbUpdating', value: function isSbUpdating() { var sourceBuffer = this.sourceBuffer; if (!sourceBuffer) { return; } for (var type in sourceBuffer) { if (sourceBuffer[type].updating) { return true; } } } }, { key: 'dump', value: function dump(video) { var str = '', b = video.buffered, len = b.length; for (var i = 0; i < len; i++) { str += '[' + b.start(i) + ',' + b.end(i) + ']'; } return str; } }, { key: 'clear', value: function clear(video, keepSec) { var st, sb = this.sourceBuffer, end = video.currentTime - keepSec; var b = video.buffered, len = b.length; if (end <= 0 || sb.audio && sb.audio.updating || sb.video && sb.video.updating) { return; } st = b.start(0); for (var i = 1; i < len; i++) { st = Math.min(st, b.start(i)); } if (st && st < end) { _logger.logger.log('video buffered: ' + this.dump(this.media) + ' removing: [' + st + ',' + end + ']'); if (sb.audio) { sb.audio.remove(st, end); } if (sb.video) { sb.video.remove(st, end); } } } }, { key: 'onSBUpdateEnd', value: function onSBUpdateEnd() { // update timestampOffset if (this.audioTimestampOffset) { var audioBuffer = this.sourceBuffer.audio; if (audioBuffer && !audioBuffer.updating) { _logger.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset); audioBuffer.timestampOffset = this.audioTimestampOffset; delete this.audioTimestampOffset; } } if (this._needsFlush) { this.doFlush(); } if (this._needsEos) { this.onBufferEos(); } _logger.logger.log('sb updateend'); this.updateMediaElementDuration(); this.doAppending(); if (this.waitForAppended && !this.segments.length && !this.isSbUpdating()) { this.hls.trigger(_events2.default.FRAG_APPENDED); this.waitForAppended = false; } var keep = void 0; if ((keep = this.hls.config.keepBuffered) && this.media) { try { this.clear(this.media, keep); } catch (err) { _logger.logger.log(err); } } } }, { key: 'onSBUpdateError', value: function onSBUpdateError(event) { var err = this.lastSegment ? 'last segment type:' + this.lastSegment.type + ',size:' + this.lastSegment.data.length + ')' : ''; _logger.logger.error('onSBUpdateError: sourceBuffer error:' + event + ' ' + err); this.lastSegment = undefined; this.printDump(); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error // this error might not always be fatal (it is fatal if decode error is set, in that case // it will be followed by a mediaElement error ...) this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false }); // we don't need to do more than that, as accordin to the spec, updateend will be fired just after } }, { key: 'onBufferReset', value: function onBufferReset() { var sourceBuffer = this.sourceBuffer, segments = this.segments || []; _logger.logger.log('onBufferReset: pending segments:' + segments.length); for (var type in sourceBuffer) { var sb = sourceBuffer[type]; try { this.mediaSource.removeSourceBuffer(sb); sb.removeEventListener('updateend', this.onsbue); sb.removeEventListener('error', this.onsbe); } catch (err) {} } this.sourceBuffer = {}; this.flushRange = []; this.appended = 0; this.dumpSegments = undefined; } }, { key: 'isTrackChanged', value: function isTrackChanged(tracks) { var track = void 0, sb = this.sourceBuffer; if (sb.video && !tracks.video || !sb.video && sb.audio && tracks.video) { return true; } if (sb.audio && (track = tracks.audio)) { var prev = this.tracks.audio; var codec = track.levelCodec || track.codec; var isMp3 = track.container === 'audio/mpeg' || prev.container === 'audio/mpeg' || codec === 'mp3' || prev.codec === 'mp3'; if ((track.container !== prev.container || prev.codec !== codec) && isMp3) { return true; } } } }, { key: 'onBufferCodecs', value: function onBufferCodecs(tracks) { var mediaSource = this.mediaSource; // delay sourcebuffer creation if media source not opened yet if (!mediaSource || mediaSource.readyState !== 'open') { this.pendingTracks = tracks; return; } var sourceBuffer = this.sourceBuffer; if (this.isTrackChanged(tracks)) { var media = this.media; this.hls.detachMedia(); this.hls.attachMedia(media); return; } for (var trackName in tracks) { if (!sourceBuffer[trackName]) { var track = tracks[trackName]; // use levelCodec as first priority var codec = track.levelCodec || track.codec; var mimeType = track.container + ';codecs=' + codec; _logger.logger.log('creating sourceBuffer with mimeType:' + mimeType); try { var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType); sb.addEventListener('updateend', this.onsbue); sb.addEventListener('error', this.onsbe); this.tracks[trackName] = { codec: codec, container: track.container }; } catch (err) { _logger.logger.error('error while trying to add sourceBuffer:' + err.message); this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType }); } } } } }, { key: 'onBufferAppending', value: function onBufferAppending(data) { if (!this.segments) { this.segments = [data]; } else { this.segments.push(data); } this.doAppending(); } }, { key: 'onBufferAppendFail', value: function onBufferAppendFail(data) { var err = this.lastSegment ? 'last segment type:' + this.lastSegment.type + ',size:' + this.lastSegment.data.length + ')' : ''; _logger.logger.error('onBufferAppendFail:sourceBuffer error:' + data.event + ' ' + err); this.lastSegment = undefined; this.printDump(); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error // this error might not always be fatal (it is fatal if decode error is set, in that case // it will be followed by a mediaElement error ...) this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false, frag: this.fragCurrent }); } }, { key: 'onBufferEos', value: function onBufferEos() { var sb = this.sourceBuffer, mediaSource = this.mediaSource; if (!mediaSource || mediaSource.readyState !== 'open') { return; } if (!(sb.audio && sb.audio.updating || sb.video && sb.video.updating)) { _logger.logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment'); //Notify the media element that it now has all of the media data mediaSource.endOfStream(); this._needsEos = false; } else { this._needsEos = true; } } }, { key: 'onBufferFlushing', value: function onBufferFlushing(data) { this.flushRange.push({ start: data.startOffset, end: data.endOffset }); // attempt flush immediatly this.flushBufferCounter = 0; this.doFlush(); } }, { key: 'onLevelUpdated', value: function onLevelUpdated(event) { var details = event.details; if (details.fragments.length === 0) { return; } this._levelDuration = details.totalduration + details.fragments[0].start; this.updateMediaElementDuration(); } // https://github.com/dailymotion/hls.js/issues/355 }, { key: 'updateMediaElementDuration', value: function updateMediaElementDuration() { var media = this.media, mediaSource = this.mediaSource, levelDuration = this._levelDuration; if (levelDuration === null || !media || !mediaSource || media.readyState === 0 || mediaSource.readyState !== 'open') { return; } for (var i = 0; i < mediaSource.sourceBuffers.length; i++) { if (mediaSource.sourceBuffers[i].updating) { // can't set duration whilst a buffer is updating return; } } if (this._msDuration === null) { // initialise to the value that the media source is reporting this._msDuration = mediaSource.duration; } var duration = media.duration; // levelDuration was the last value we set. // not using mediaSource.duration as the browser may tweak this value // only update mediasource duration if its value increase, this is to avoid // flushing already buffered portion when switching between quality level if (levelDuration > this._msDuration && levelDuration > duration || duration === Infinity || isNaN(duration)) { _logger.logger.log('Updating mediasource duration to ' + levelDuration.toFixed(3)); this._msDuration = mediaSource.duration = levelDuration; } } }, { key: 'doFlush', value: function doFlush() { // loop through all buffer ranges to flush while (this.flushRange.length) { var range = this.flushRange[0]; // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer if (this.flushBuffer(range.start, range.end)) { // range flushed, remove from flush array this.flushRange.shift(); this.flushBufferCounter = 0; } else { this._needsFlush = true; // avoid looping, wait for SB update end to retrigger a flush return; } } if (this.flushRange.length === 0) { // everything flushed this._needsFlush = false; // let's recompute this.appended, which is used to avoid flush looping var appended = 0; var sourceBuffer = this.sourceBuffer; for (var type in sourceBuffer) { appended += sourceBuffer[type].buffered.length; } this.appended = appended; this.hls.trigger(_events2.default.BUFFER_FLUSHED); } } }, { key: 'dumpSegment', value: function dumpSegment(segment) { var i = void 0, len = segment.data.length; var info = 'queue:' + this.segments.length + 'type:' + segment.type + ',size:' + len + ',buf:['; for (i = 0, len = Math.min(len, 10); i < len; i++) { if (i) { info += ','; } info += segment.data[i]; } info += '..]'; if (!this.dumpSegments) { this.dumpSegments = [info]; } else { this.dumpSegments.push(info); } if (this.dumpSegments.length > 10) { this.dumpSegments.shift(); } } }, { key: 'printDump', value: function printDump() { if (this.dumpSegments && this.dumpSegments.length) { _logger.logger.error(this.dumpSegments.join('|')); } } }, { key: 'doAppending', value: function doAppending() { var hls = this.hls, sourceBuffer = this.sourceBuffer, segments = this.segments; if (sourceBuffer && Object.keys(sourceBuffer).length) { if (!this.media) { return; } if (this.media.error) { this.segments = []; _logger.logger.error('trying to append although a media error occured, flush segment and abort'); return; } if (this.isSbUpdating()) { _logger.logger.log('sb update in progress'); return; } if (segments.length) { var segment = segments.shift(); this.dumpSegment(segment); try { _logger.logger.log('appending ' + segment.type + ' SB, size:' + segment.data.length); if (sourceBuffer[segment.type]) { this.lastSegment = segment; sourceBuffer[segment.type].appendBuffer(segment.data); this.appendError = 0; this.appended++; } else { // in case we don't have any source buffer matching with this segment type, // it means that Mediasource fails to create sourcebuffer // discard this segment, and trigger update end this.onSBUpdateEnd(); } } catch (err) { // in case any error occured while appending, put back segment in segments table _logger.logger.error('error while trying to append buffer: ' + err.message); segments.unshift(segment); var event = { type: _errors.ErrorTypes.MEDIA_ERROR }; if (err.code !== 22) { if (this.appendError) { this.appendError++; } else { this.appendError = 1; } event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR; event.frag = this.fragCurrent; event.reason = err.message + ' (type:' + segment.type + ',size:' + segment.data.length + ')'; /* with UHD content, we could get loop of quota exceeded error until browser is able to evict some data from sourcebuffer. retrying help recovering this */ if (this.appendError > hls.config.appendErrorMaxRetry) { _logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer'); this.segments = []; event.fatal = true; hls.trigger(_events2.default.ERROR, event); return; } else { event.fatal = false; hls.trigger(_events2.default.ERROR, event); } } else { // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror // let's stop appending any segments, and report BUFFER_FULL_ERROR error this.segments = []; event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR; hls.trigger(_events2.default.ERROR, event); } } } } } /* flush specified buffered range, return true once range has been flushed. as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end */ }, { key: 'flushBuffer', value: function flushBuffer(startOffset, endOffset) { var sb, i, bufStart, bufEnd, flushStart, flushEnd; _logger.logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime + '/' + startOffset + '/' + endOffset); // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments if (this.flushBufferCounter < this.appended && this.sourceBuffer) { for (var type in this.sourceBuffer) { sb = this.sourceBuffer[type]; if (!sb.updating) { for (i = 0; i < sb.buffered.length; i++) { bufStart = sb.buffered.start(i); bufEnd = sb.buffered.end(i); // workaround firefox not able to properly flush multiple buffered range. if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) { flushStart = startOffset; flushEnd = endOffset; } else { flushStart = Math.max(bufStart, startOffset); flushEnd = Math.min(bufEnd, endOffset); } /* sometimes sourcebuffer.remove() does not flush the exact expected time range. to avoid rounding issues/infinite loop, only flush buffer range of length greater than 500ms. */ if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) { this.flushBufferCounter++; _logger.logger.log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime); sb.remove(flushStart, flushEnd); return false; } } } else { //logger.log('abort ' + type + ' append in progress'); // this will abort any appending in progress //sb.abort(); _logger.logger.warn('cannot flush, sb updating in progress'); return false; } } } else { _logger.logger.warn('abort flushing too many retries'); } _logger.logger.log('buffer flushed'); // everything flushed ! return true; } }]); return BufferController; }(_eventHandler2.default); exports.default = BufferController; },{"../errors":20,"../event-handler":21,"../events":22,"../utils/logger":38}],4:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * cap stream level to media size dimension controller */ var CapLevelController = function (_EventHandler) { _inherits(CapLevelController, _EventHandler); function CapLevelController(hls) { _classCallCheck(this, CapLevelController); return _possibleConstructorReturn(this, (CapLevelController.__proto__ || Object.getPrototypeOf(CapLevelController)).call(this, hls, _events2.default.FPS_DROP_LEVEL_CAPPING, _events2.default.MEDIA_ATTACHING, _events2.default.MANIFEST_PARSED)); } _createClass(CapLevelController, [{ key: 'destroy', value: function destroy() { if (this.hls.config.capLevelToPlayerSize) { this.media = this.restrictedLevels = null; this.autoLevelCapping = Number.POSITIVE_INFINITY; if (this.timer) { this.timer = clearInterval(this.timer); } } } }, { key: 'onFpsDropLevelCapping', value: function onFpsDropLevelCapping(data) { if (!this.restrictedLevels) { this.restrictedLevels = []; } if (!this.isLevelRestricted(data.droppedLevel)) { this.restrictedLevels.push(data.droppedLevel); } } }, { key: 'onMediaAttaching', value: function onMediaAttaching(data) { this.media = data.media instanceof HTMLVideoElement ? data.media : null; } }, { key: 'onManifestParsed', value: function onManifestParsed(data) { if (this.hls.config.capLevelToPlayerSize) { this.autoLevelCapping = Number.POSITIVE_INFINITY; this.levels = data.levels; this.hls.firstLevel = this.getMaxLevel(data.firstLevel); clearInterval(this.timer); this.timer = setInterval(this.detectPlayerSize.bind(this), 1000); this.detectPlayerSize(); } } }, { key: 'detectPlayerSize', value: function detectPlayerSize() { if (this.media) { var levelsLength = this.levels ? this.levels.length : 0; if (levelsLength) { this.hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1); if (this.hls.autoLevelCapping > this.autoLevelCapping) { // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch // usually happen when the user go to the fullscreen mode. this.hls.streamController.nextLevelSwitch(); } this.autoLevelCapping = this.hls.autoLevelCapping; } } } /* * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled) */ }, { key: 'getMaxLevel', value: function getMaxLevel(capLevelIndex) { var result = 0, i = void 0, level = void 0, mWidth = this.mediaWidth, mHeight = this.mediaHeight, lWidth = 0, lHeight = 0; for (i = 0; i <= capLevelIndex; i++) { level = this.levels[i]; if (this.isLevelRestricted(i)) { break; } result = i; lWidth = level.width; lHeight = level.height; if (mWidth <= lWidth || mHeight <= lHeight) { break; } } return result; } }, { key: 'isLevelRestricted', value: function isLevelRestricted(level) { return this.restrictedLevels && this.restrictedLevels.indexOf(level) !== -1 ? true : false; } }, { key: 'contentScaleFactor', get: function get() { var pixelRatio = 1; try { pixelRatio = window.devicePixelRatio; } catch (e) {} return pixelRatio; } }, { key: 'mediaWidth', get: function get() { var width = void 0; if (this.media) { width = this.media.width || this.media.clientWidth || this.media.offsetWidth; width *= this.contentScaleFactor; } return width; } }, { key: 'mediaHeight', get: function get() { var height = void 0; if (this.media) { height = this.media.height || this.media.clientHeight || this.media.offsetHeight; height *= this.contentScaleFactor; } return height; } }]); return CapLevelController; }(_eventHandler2.default); exports.default = CapLevelController; },{"../event-handler":21,"../events":22}],5:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _logger = require('../utils/logger'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * FPS Controller */ var FPSController = function (_EventHandler) { _inherits(FPSController, _EventHandler); function FPSController(hls) { _classCallCheck(this, FPSController); return _possibleConstructorReturn(this, (FPSController.__proto__ || Object.getPrototypeOf(FPSController)).call(this, hls, _events2.default.MEDIA_ATTACHING)); } _createClass(FPSController, [{ key: 'destroy', value: function destroy() { if (this.timer) { clearInterval(this.timer); } this.isVideoPlaybackQualityAvailable = false; } }, { key: 'onMediaAttaching', value: function onMediaAttaching(data) { if (this.hls.config.capLevelOnFPSDrop) { this.video = data.media instanceof HTMLVideoElement ? data.media : null; if (typeof this.video.getVideoPlaybackQuality === 'function') { this.isVideoPlaybackQualityAvailable = true; } clearInterval(this.timer); this.timer = setInterval(this.checkFPSInterval.bind(this), this.hls.config.fpsDroppedMonitoringPeriod); } } }, { key: 'checkFPS', value: function checkFPS(video, decodedFrames, droppedFrames) { var currentTime = performance.now(); if (decodedFrames) { if (this.lastTime) { var currentPeriod = currentTime - this.lastTime, currentDropped = droppedFrames - this.lastDroppedFrames, currentDecoded = decodedFrames - this.lastDecodedFrames, droppedFPS = 1000 * currentDropped / currentPeriod; this.hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames }); if (droppedFPS > 0) { //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod)); if (currentDropped > this.hls.config.fpsDroppedMonitoringThreshold * currentDecoded) { var currentLevel = this.hls.currentLevel; _logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel); if (currentLevel > 0 && (this.hls.autoLevelCapping === -1 || this.hls.autoLevelCapping >= currentLevel)) { currentLevel = currentLevel - 1; this.hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: this.hls.currentLevel }); this.hls.autoLevelCapping = currentLevel; this.hls.streamController.nextLevelSwitch(); } } } } this.lastTime = currentTime; this.lastDroppedFrames = droppedFrames; this.lastDecodedFrames = decodedFrames; } } }, { key: 'checkFPSInterval', value: function checkFPSInterval() { if (this.video) { if (this.isVideoPlaybackQualityAvailable) { var videoPlaybackQuality = this.video.getVideoPlaybackQuality(); this.checkFPS(this.video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames); } else { this.checkFPS(this.video, this.video.webkitDecodedFrameCount, this.video.webkitDroppedFrameCount); } } } }]); return FPSController; }(_eventHandler2.default); exports.default = FPSController; },{"../event-handler":21,"../events":22,"../utils/logger":38}],6:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _levelHelper = require('../helper/level-helper'); var _levelHelper2 = _interopRequireDefault(_levelHelper); var _logger = require('../utils/logger'); var _errors = require('../errors'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Level Controller */ var LevelController = function (_EventHandler) { _inherits(LevelController, _EventHandler); function LevelController(hls) { _classCallCheck(this, LevelController); var _this = _possibleConstructorReturn(this, (LevelController.__proto__ || Object.getPrototypeOf(LevelController)).call(this, hls, _events2.default.MANIFEST_LOADED, _events2.default.LEVEL_LOADED, _events2.default.ERROR)); _this.ontick = _this.tick.bind(_this); _this._manualLevel = _this._autoLevelCapping = -1; return _this; } _createClass(LevelController, [{ key: 'destroy', value: function destroy() { if (this.timer) { clearTimeout(this.timer); this.timer = null; } this._manualLevel = -1; } }, { key: 'clearLevelDetails', value: function clearLevelDetails() { // clean up live level details to force reload them, and reset load errors if (this._levels) { this._levels.forEach(function (level) { level.loadError = 0; var levelDetails = level.details; if (levelDetails && levelDetails.live) { level.details = undefined; } }); } } }, { key: 'startLoad', value: function startLoad() { this.canload = true; // speed up live playlist refresh if (_levelHelper2.default.isLive(this._level, this._levels)) { this.tick(); } } }, { key: 'stopLoad', value: function stopLoad() { this.canload = false; } }, { key: 'isVideoLevel', value: function isVideoLevel(level) { return level.videoCodec || !level.audioCodec && (level.bitrate > 64000 || level.width || level.height); } }, { key: 'onManifestLoaded', value: function onManifestLoaded(data) { var _this2 = this; var levels0 = [], levels = [], bitrateStart, bitrateSet = {}, videoCodecFound = false, audioCodecFound = false, hls = this.hls, i, brokenmp4inmp3 = /chrome|firefox/.test(navigator.userAgent.toLowerCase()), checkSupported = function checkSupported(type, codec) { return MediaSource.isTypeSupported(type + '/mp4;codecs=' + codec); }; // regroup redundant level together data.levels.forEach(function (level) { if (_this2.isVideoLevel(level)) { videoCodecFound = true; } // erase audio codec info if browser does not support mp4a.40.34. demuxer will autodetect codec and fallback to mpeg/audio if (brokenmp4inmp3 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) { level.audioCodec = undefined; } if (level.audioCodec || level.attrs && level.attrs.AUDIO) { audioCodecFound = true; } var redundantLevelId = bitrateSet[level.bitrate]; if (redundantLevelId === undefined) { bitrateSet[level.bitrate] = levels0.length; level.url = [level.url]; level.urlId = 0; levels0.push(level); } else { levels0[redundantLevelId].url.push(level.url); } }); // remove audio-only level if we also have levels with audio+video codecs signalled if (videoCodecFound && audioCodecFound) { levels0.forEach(function (level) { if (_this2.isVideoLevel(level)) { levels.push(level); } }); } else { levels = levels0; } // only keep level with supported audio/video codecs levels = levels.filter(function (level) { var audioCodec = level.audioCodec, videoCodec = level.videoCodec; return (!audioCodec || checkSupported('audio', audioCodec)) && (!videoCodec || checkSupported('video', videoCodec)); }); if (levels.length) { // start bitrate is the first bitrate of the manifest bitrateStart = levels[0].bitrate; // sort level on bitrate levels.sort(function (a, b) { return a.bitrate - b.bitrate; }); this._levels = levels; // find index of first level in sorted levels for (i = 0; i < levels.length; i++) { if (levels[i].bitrate === bitrateStart) { this._firstLevel = i; _logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart); break; } } hls.trigger(_events2.default.MANIFEST_PARSED, { levels: this._levels, firstLevel: this._firstLevel, stats: data.stats }); } else { hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest' }); } return; } }, { key: 'setLevelInternal', value: function setLevelInternal(newLevel) { var levels = this._levels; // check if level idx is valid if (newLevel >= 0 && newLevel < levels.length) { // stopping live reloading timer if any if (this.timer) { clearTimeout(this.timer); this.timer = null; } if (this._level !== newLevel) { _logger.logger.log('switching to level ' + newLevel); this._level = newLevel; this.hls.trigger(_events2.default.LEVEL_SWITCH, { level: newLevel }); } var level = levels[newLevel]; // check if we need to load playlist for this level if (!level.details || level.details.live === true) { // level not retrieved yet, or live playlist we need to (re)load it _logger.logger.log('(re)loading playlist for level ' + newLevel); var urlId = level.urlId; this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId }); } } else { // invalid level id given, trigger error this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' }); } } }, { key: 'onError', value: function onError(data) { if (data.fatal) { return; } var details = data.details, hls = this.hls, levelId = void 0, level = void 0, levelError = false; // try to recover not fatal errors switch (details) { case _errors.ErrorDetails.FRAG_LOAD_ERROR: case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT: case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR: case _errors.ErrorDetails.KEY_LOAD_ERROR: case _errors.ErrorDetails.KEY_LOAD_TIMEOUT: levelId = data.frag.level; break; case _errors.ErrorDetails.LEVEL_LOAD_ERROR: case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT: levelId = data.level; levelError = true; break; default: break; } /* try to switch to a redundant stream if any available. * if no redundant stream available, emergency switch down (if in auto mode and current level not 0) * otherwise, we cannot recover this network error ... * don't raise FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT as fatal, as it is handled by mediaController */ if (levelId !== undefined) { level = this._levels[levelId]; if (level.urlId < level.url.length - 1) { level.urlId++; if (this.hls.config.clearLevelDetailsOnSwitching) { level.details = undefined; } _logger.logger.warn('level controller,' + details + ' for level ' + levelId + ': switching to redundant stream id ' + level.urlId); } else { // we could try to recover if in auto mode and current level not lowest level (0) var recoverable = this._manualLevel === -1 && levelId; if (recoverable) { _logger.logger.warn('level controller,' + details + ': emergency switch-down for next fragment'); hls.abrController.nextAutoLevel = 0; } else if (level && level.details && level.details.live) { _logger.logger.warn('level controller,' + details + ' on live stream, discard'); if (levelError) { // reset this._level so that another call to set level() will retrigger a frag load this._level = undefined; } // FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT are handled by mediaController } else if (details !== _errors.ErrorDetails.FRAG_LOAD_ERROR && details !== _errors.ErrorDetails.FRAG_LOAD_TIMEOUT) { _logger.logger.error('cannot recover ' + details + ' error'); this._level = undefined; // stopping live reloading timer if any if (this.timer) { clearTimeout(this.timer); this.timer = null; } // redispatch same error but with fatal set to true data.fatal = true; hls.trigger(_events2.default.ERROR, data); } } } } }, { key: 'onLevelLoaded', value: function onLevelLoaded(data) { // only process level loaded events matching with expected level if (data.level === this._level) { var newDetails = data.details; // if current playlist is a live playlist, arm a timer to reload it if (newDetails.live) { var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration), curLevel = this._levels[data.level], curDetails = curLevel.details; if (curDetails && newDetails.endSN === curDetails.endSN) { // follow HLS Spec, If the client reloads a Playlist file and finds that it has not // changed then it MUST wait for a period of one-half the target // duration before retrying. reloadInterval /= 2; _logger.logger.log('same live playlist, reload twice faster'); } // decrement reloadInterval with level loading delay reloadInterval -= performance.now() - data.stats.trequest; // in any case, don't reload more than every second reloadInterval = Math.max(1000, Math.round(reloadInterval)); _logger.logger.log('live playlist, reload in ' + reloadInterval + ' ms'); this.timer = setTimeout(this.ontick, reloadInterval); } else { this.timer = null; } } } }, { key: 'tick', value: function tick() { var levelId = this._level; if (levelId !== undefined && this.canload) { var level = this._levels[levelId], urlId = level.urlId; this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId }); } } }, { key: 'levels', get: function get() { return this._levels; } }, { key: 'level', get: function get() { return this._level; }, set: function set(newLevel) { var levels = this._levels; if (levels && levels.length > newLevel) { if (this._level !== newLevel || levels[newLevel].details === undefined) { this.setLevelInternal(newLevel); } } } }, { key: 'manualLevel', get: function get() { return this._manualLevel; }, set: function set(newLevel) { this._manualLevel = newLevel; if (this._startLevel === undefined) { this._startLevel = newLevel; } if (newLevel !== -1) { this.level = newLevel; } } }, { key: 'firstLevel', get: function get() { return this._firstLevel; }, set: function set(newLevel) { this._firstLevel = newLevel; } }, { key: 'startLevel', get: function get() { return this._startLevel === undefined ? this._firstLevel : this._startLevel; }, set: function set(newLevel) { this._startLevel = newLevel; } }, { key: 'nextLoadLevel', get: function get() { if (this._manualLevel !== -1) { return this._manualLevel; } else { return this.hls.abrController.nextAutoLevel; } }, set: function set(nextLevel) { this.level = nextLevel; if (this._manualLevel === -1) { this.hls.abrController.nextAutoLevel = nextLevel; } } }]); return LevelController; }(_eventHandler2.default); exports.default = LevelController; },{"../errors":20,"../event-handler":21,"../events":22,"../helper/level-helper":25,"../utils/logger":38}],7:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _demuxer = require('../demux/demuxer'); var _demuxer2 = _interopRequireDefault(_demuxer); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _logger = require('../utils/logger'); var _binarySearch = require('../utils/binary-search'); var _binarySearch2 = _interopRequireDefault(_binarySearch); var _bufferHelper = require('../helper/buffer-helper'); var _bufferHelper2 = _interopRequireDefault(_bufferHelper); var _levelHelper = require('../helper/level-helper'); var _levelHelper2 = _interopRequireDefault(_levelHelper); var _errors = require('../errors'); var _browser = require('../utils/browser'); var _browser2 = _interopRequireDefault(_browser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Stream Controller */ var State = { STOPPED: 'STOPPED', STARTING: 'STARTING', IDLE: 'IDLE', PAUSED: 'PAUSED', KEY_LOADING: 'KEY_LOADING', FRAG_LOADING: 'FRAG_LOADING', FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY', WAITING_LEVEL: 'WAITING_LEVEL', PARSING: 'PARSING', PARSED: 'PARSED', ENDED: 'ENDED', ERROR: 'ERROR' }; var StreamController = function (_EventHandler) { _inherits(StreamController, _EventHandler); function StreamController(hls) { _classCallCheck(this, StreamController); var _this = _possibleConstructorReturn(this, (StreamController.__proto__ || Object.getPrototypeOf(StreamController)).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_PARSED, _events2.default.LEVEL_LOADED, _events2.default.LEVEL_PTS_UPDATED, _events2.default.KEY_LOADED, _events2.default.FRAG_CHUNK_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_LOAD_EMERGENCY_ABORTED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.FRAG_APPENDED, _events2.default.ERROR, _events2.default.BUFFER_FLUSHED, _events2.default.DEMUXER_QUEUE_EMPTY)); _this.config = hls.config; _this.audioCodecSwap = false; _this.ticks = 0; _this.ontick = _this.tick.bind(_this); _this.noMediaCount = 0; return _this; } _createClass(StreamController, [{ key: 'destroy', value: function destroy() { this.stopLoad(); delete this.fragPreviousSaved; if (this.timer) { clearInterval(this.timer); this.timer = null; } _eventHandler2.default.prototype.destroy.call(this); this.state = State.STOPPED; } }, { key: 'startLoad', value: function startLoad() { var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; if (this.levels) { var media = this.media, lastCurrentTime = this.lastCurrentTime; this.stopLoad(); if (!this.demuxer) { this.demuxer = new _demuxer2.default(this.hls); this.fragParsing = null; } if (!this.timer) { this.timer = setInterval(this.ontick, 100); } if (this.fragPreviousSaved) { this.fragPrevious = this.fragPreviousSaved; delete this.fragPrevious; } this.level = -1; this.fragLoadError = 0; if (media && lastCurrentTime > 0) { var lastLevel = this.hls.loadLevel; if (_levelHelper2.default.isLive(lastLevel, this.levels)) { this.level = lastLevel; this.waitLiveLevel = true; } _logger.logger.log('configure startPosition @' + lastCurrentTime); this.state = this.level === -1 ? State.IDLE : State.WAITING_LEVEL; } else { this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition; _logger.logger.log('configure lastCurrentTime @' + this.lastCurrentTime + ' start:' + this.startPosition + ',' + startPosition); this.state = State.STARTING; } this.nextLoadPosition = this.startPosition = this.lastCurrentTime; this.tick(); } else { _logger.logger.warn('cannot start loading as manifest not parsed yet'); this.state = State.STOPPED; } } }, { key: 'onDemuxerQueueEmpty', value: function onDemuxerQueueEmpty() { this.fragParsing = null; } }, { key: 'stopLoad', value: function stopLoad() { var frag = this.fragCurrent; if (frag) { if (frag.loader) { frag.loader.abort(); } this.fragCurrent = null; } this.fragPreviousSaved = this.fragPrevious || this.fragPreviousSaved; this.fragPrevious = null; if (this.state === State.PARSING && this.demuxer && this.config.enableWorker) { this.fragParsing = frag; this.demuxer.waitQueue(); } this.state = State.STOPPED; } }, { key: 'tick', value: function tick() { this.ticks++; if (this.ticks === 1) { this.doTick(); if (this.ticks > 1) { setTimeout(this.tick, 1); } this.ticks = 0; } } }, { key: 'doTick', value: function doTick() { switch (this.state) { case State.STARTING: var hls = this.hls; // determine load level var startLevel = hls.startLevel; if (startLevel === -1) { startLevel = 0; } // set new level to playlist loader : this will trigger start level load // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded this.level = hls.nextLoadLevel = startLevel; this.state = State.WAITING_LEVEL; this.loadedmetadata = false; break; case State.IDLE: if (!this.media) { if (this.noMediaCount++ % 20 === 0) { var media = this.hls.bufferController.media || {}; var ms = this.hls.bufferController.mediaSource || {}; _logger.logger.log('no media ' + media + ' src=' + media.src + ' ms_state=' + ms.readyState); } } else { if (this.noMediaCount) { _logger.logger.log('media is set to ' + this.media.src); } this.noMediaCount = 0; } // when this returns false there was an error and we shall return immediatly // from current tick if (!this._doTickIdle()) { return; } break; case State.WAITING_LEVEL: var level = this.levels[this.level]; // check if playlist is already loaded if (level && level.details && !this.waitLiveLevel) { this.state = State.IDLE; } break; case State.FRAG_LOADING: try { if (this.levels[this.level].details.live && this.fragCurrent.sn < this.levels[this.level].details.startSN) { _logger.logger.log('live playlist slided forward loading segments: reload'); this.state = State.IDLE; } } catch (e) {} break; case State.FRAG_LOADING_WAITING_RETRY: var now = performance.now(); var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading if (!retryDate || now >= retryDate || this.media && this.media.seeking) { _logger.logger.log('mediaController: retryDate reached, switch back to IDLE state'); this.state = State.IDLE; } break; case State.ERROR: case State.PAUSED: case State.STOPPED: case State.PARSING: case State.PARSED: case State.ENDED: break; default: break; } // check buffer this._checkBuffer(); // check/update current fragment this._checkFragmentChanged(); } // Ironically the "idle" state is the on we do the most logic in it seems .... // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently // played segment, or on pause/play/seek instead of naively checking every 100ms? }, { key: '_doTickIdle', value: function _doTickIdle() { var hls = this.hls, config = hls.config; // if video not attached AND // start fragment already requested OR start frag prefetch disable // exit loop // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop if (this.levelLastLoaded !== undefined && !this.media && (this.startFragRequested || !config.startFragPrefetch)) { return true; } // if we have not yet loaded any fragment, start loading from start position var pos = this.loadedmetadata ? this.media.currentTime : this.nextLoadPosition; // determine next load level var level = hls.nextLoadLevel; // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s var maxBufLen = void 0; if (this.levels[level].hasOwnProperty('bitrate')) { maxBufLen = Math.max(8 * config.maxBufferSize / this.levels[level].bitrate, config.maxBufferLength); maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); } else { maxBufLen = config.maxBufferLength; } // determine next candidate fragment to be loaded, based on current position and end of buffer position // ensure up to `config.maxMaxBufferLength` of buffer upfront var bufferInfo = _bufferHelper2.default.bufferInfo(this.media, pos, config.maxBufferHole), bufferLen = bufferInfo.len; // Stay idle if we are still with buffer margins if (bufferLen >= maxBufLen) { return true; } // if buffer length is less than maxBufLen try to load a new fragment ... _logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...'); // set next load level : this will trigger a playlist load if needed this.level = hls.nextLoadLevel = level; var levelDetails = this.levels[level].details; // if level info not retrieved yet, switch state and wait for level retrieval // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist) if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) { this.state = State.WAITING_LEVEL; return true; } // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..) return this._fetchPayloadOrEos({ pos: pos, bufferInfo: bufferInfo, levelDetails: levelDetails }); } }, { key: '_fetchPayloadOrEos', value: function _fetchPayloadOrEos(_ref) { var pos = _ref.pos, bufferInfo = _ref.bufferInfo, levelDetails = _ref.levelDetails; var fragPrevious = this.fragPrevious, level = this.level, fragments = levelDetails.fragments, fragLen = fragments.length; // empty playlist if (fragLen === 0) { return false; } // find fragment index, contiguous with end of buffer position var start = fragments[0].start, end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration, bufferEnd = bufferInfo.end, frag = void 0; // in case of live playlist we need to ensure that requested position is not located before playlist start if (levelDetails.live) { frag = this._ensureFragmentAtLivePoint({ levelDetails: levelDetails, bufferEnd: bufferEnd, start: start, end: end, fragPrevious: fragPrevious, fragments: fragments, fragLen: fragLen }); // if it explicitely returns null don't load any fragment and exit function now if (frag === null) { return false; } } else { // VoD playlist: if bufferEnd before start of playlist, load first fragment if (bufferEnd < start) { frag = fragments[0]; } } if (!frag) { frag = this._findFragment({ start: start, fragPrevious: fragPrevious, fragLen: fragLen, fragments: fragments, bufferEnd: bufferEnd, end: end, levelDetails: levelDetails }); } if (frag) { return this._loadFragmentOrKey({ frag: frag, level: level, levelDetails: levelDetails, pos: pos, bufferEnd: bufferEnd }); } return true; } }, { key: '_ensureFragmentAtLivePoint', value: function _ensureFragmentAtLivePoint(_ref2) { var levelDetails = _ref2.levelDetails, bufferEnd = _ref2.bufferEnd, start = _ref2.start, end = _ref2.end, fragPrevious = _ref2.fragPrevious, fragments = _ref2.fragments, fragLen = _ref2.fragLen; var config = this.hls.config, media = this.media; var frag = void 0; // check if requested position is within seekable boundaries : //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`); var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration; if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) { var liveSyncPosition = this.computeLivePosition(start, levelDetails); _logger.logger.log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3)); bufferEnd = liveSyncPosition; if (media && media.readyState && media.duration > liveSyncPosition) { media.currentTime = liveSyncPosition; } } // if end of buffer greater than live edge, don't load any fragment // this could happen if live playlist intermittently slides in the past. // level 1 loaded [182580161,182580167] // level 1 loaded [182580162,182580169] // Loading 182580168 of [182580162 ,182580169],level 1 .. // Loading 182580169 of [182580162 ,182580169],level 1 .. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168 // level 1 loaded [182580164,182580171] // if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) { return null; } if (this.startFragRequested && !levelDetails.PTSKnown) { /* we are switching level on live playlist, but we don't have any PTS info for that quality level ... try to load frag matching with next SN. even if SN are not synchronized between playlists, loading this frag will help us compute playlist sliding and find the right one after in case it was not the right consecutive one */ if (fragPrevious) { var targetSN = fragPrevious.sn + 1; if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) { frag = fragments[targetSN - levelDetails.startSN]; _logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn); } } if (!frag) { /* we have no idea about which fragment should be loaded. so let's load mid fragment. it will help computing playlist sliding and find the right one */ frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))]; _logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn); } } return frag; } }, { key: '_findFragment', value: function _findFragment(_ref3) { var start = _ref3.start, fragPrevious = _ref3.fragPrevious, fragLen = _ref3.fragLen, fragments = _ref3.fragments, bufferEnd = _ref3.bufferEnd, end = _ref3.end, levelDetails = _ref3.levelDetails, holaSeek = _ref3.holaSeek; var config = this.hls.config; var frag = void 0, foundFrag = void 0, maxFragLookUpTolerance = config.maxFragLookUpTolerance, media = this.media, seekFlag = media && media.seeking || holaSeek; if (bufferEnd < end - (fragments[fragLen - 1].PTSDTSshift || 0) - 0.05) { if (bufferEnd > end - maxFragLookUpTolerance || seekFlag) { maxFragLookUpTolerance = 0; } foundFrag = _binarySearch2.default.search(fragments, function (candidate) { // offset should be within fragment boundary - config.maxFragLookUpTolerance // this is to cope with situations like // bufferEnd = 9.991 // frag[Ø] : [0,10] // frag[1] : [10,20] // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here // frag start frag start+duration // |-----------------------------| // <---> <---> // ...--------><-----------------------------><---------.... // previous frag matching fragment next frag // return -1 return 0 return 1 //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`); // if we are in seek, the condition will always be false if (candidate.lastGop - maxFragLookUpTolerance < bufferEnd && candidate.lastGop + maxFragLookUpTolerance > bufferEnd) { return 1; } // if we are in seek, the condition will always be false if (candidate.firstGop - maxFragLookUpTolerance < bufferEnd && candidate.firstGop + maxFragLookUpTolerance > bufferEnd) { return 0; } if (candidate.start + candidate.duration - candidate.PTSDTSshift - maxFragLookUpTolerance <= bufferEnd) { return 1; } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element if (candidate.start - candidate.PTSDTSshift - maxFragLookUpTolerance > bufferEnd && candidate.start) { return candidate.sn > levelDetails.startSN ? -1 : 0; } return 0; }); } else { // reach end of playlist foundFrag = fragments[fragLen - 1]; } if (foundFrag) { frag = foundFrag; start = foundFrag.start; _logger.logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn); if (fragPrevious && frag.sn === fragPrevious.sn) { if (frag.sn < levelDetails.endSN) { var deltaPTS = fragPrevious.deltaPTS, curSNIdx = frag.sn - levelDetails.startSN; // if there is a significant delta between audio and video, larger than max allowed hole, // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped) // let's try to load previous fragment again to get last keyframe // then we will reload again current fragment (that way we should be able to fill the buffer hole ...) if (this.loadedmetadata && deltaPTS && deltaPTS > config.maxSeekHole && fragPrevious.dropped && (!media || !_bufferHelper2.default.isBuffered(media, bufferEnd))) { frag = fragments[curSNIdx - 1]; _logger.logger.warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this'); // decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded fragPrevious.loadCounter--; } else { frag = fragments[curSNIdx + 1]; _logger.logger.log('SN just loaded, load next one: ' + frag.sn); } } else { // have we reached end of VOD playlist ? if (!levelDetails.live) { // Finalize the media stream this.hls.trigger(_events2.default.BUFFER_EOS); // We might be loading the last fragment but actually the media // is currently processing a seek command and waiting for new data to resume at another point. // Going to ended state while media is seeking can spawn an infinite buffering broken state. if (!this.media.seeking) { this.state = State.ENDED; } } frag = null; } } } return frag; } }, { key: '_loadFragmentOrKey', value: function _loadFragmentOrKey(_ref4) { var frag = _ref4.frag, level = _ref4.level, levelDetails = _ref4.levelDetails, pos = _ref4.pos, bufferEnd = _ref4.bufferEnd; var hls = this.hls, config = hls.config; //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3)); if (frag.decryptdata.uri != null && frag.decryptdata.key == null) { _logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level); this.state = State.KEY_LOADING; hls.trigger(_events2.default.KEY_LOADING, { frag: frag }); } else { _logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3)); frag.autoLevel = hls.autoLevelEnabled; if (this.levels.length > 1) { frag.expectedLen = Math.round(frag.duration * this.levels[level].bitrate / 8); frag.trequest = performance.now(); } // ensure that we are not reloading the same fragments in loop ... if (this.fragLoadIdx !== undefined) { this.fragLoadIdx++; } else { this.fragLoadIdx = 0; } if (frag.loadCounter) { frag.loadCounter++; var maxThreshold = config.fragLoadingLoopThreshold; // if this frag has already been loaded 3 times, and if it has been reloaded recently if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) { hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag }); return false; } } else { frag.loadCounter = 1; } frag.loadIdx = this.fragLoadIdx; this.fragCurrent = frag; this.fragCurrent.loaded = false; this.startFragRequested = true; this.nextLoadPosition = frag.start + frag.duration; this.fragTimeOffset = frag.start; // lazy demuxer init, as this could take some time ... do it during frag loading if (!this.demuxer) { this.demuxer = new _demuxer2.default(hls, 'main'); } this.state = State.FRAG_LOADING; hls.trigger(_events2.default.FRAG_LOADING, { frag: frag }); return true; } } }, { key: 'getBufferRange', value: function getBufferRange(position) { return _binarySearch2.default.search(this.bufferRange, function (range) { if (position < range.start) { return -1; } else if (position > range.end) { return 1; } return 0; }); } }, { key: 'followingBufferRange', value: function followingBufferRange(range) { if (range) { // try to get range of next fragment (500ms after this range) return this.getBufferRange(range.end + 0.5); } return null; } }, { key: '_checkFragmentChanged', value: function _checkFragmentChanged() { var currentTime, video = this.media; if (video && video.seeking === false) { currentTime = video.currentTime; /* if video element is in seeked state, currentTime can only increase. (assuming that playback rate is positive ...) As sometimes currentTime jumps back to zero after a media decode error, check this, to avoid seeking back to wrong position after a media decode error */ if (currentTime > video.playbackRate * this.lastCurrentTime) { this.lastCurrentTime = currentTime; } } } /* on immediate level switch : - pause playback if playing - cancel any pending load request - and trigger a buffer flush */ }, { key: 'immediateLevelSwitch', value: function immediateLevelSwitch() { _logger.logger.log('immediateLevelSwitch'); if (!this.immediateSwitch) { this.immediateSwitch = true; this.previouslyPaused = this.media.paused; this.media.pause(); } var fragCurrent = this.fragCurrent; if (fragCurrent && fragCurrent.loader) { fragCurrent.loader.abort(); } this.fragCurrent = null; // increase fragment load Index to avoid frag loop loading error after buffer flush this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; this.state = State.PAUSED; // flush everything this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY }); } /* on immediate level switch end, after new fragment has been buffered : - nudge video decoder by slightly adjusting video currentTime - resume the playback if needed */ }, { key: 'immediateLevelSwitchEnd', value: function immediateLevelSwitchEnd() { var media = this.media; if (media && media.buffered.length) { this.immediateSwitch = false; if (_bufferHelper2.default.isBuffered(media, media.currentTime)) { // only nudge if currentTime is buffered media.currentTime -= 0.0001; } if (!this.previouslyPaused) { media.play(); } } } }, { key: 'nextLevelSwitch', value: function nextLevelSwitch() { /* try to switch ASAP without breaking video playback : in order to ensure smooth but quick level switching, we need to find the next flushable buffer range we should take into account new segment fetch time */ var media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime) if (media && media.readyState) { var fetchdelay = void 0, currentRange = void 0, nextRange = void 0; // increase fragment load Index to avoid frag loop loading error after buffer flush this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; currentRange = this.getBufferRange(media.currentTime); if (currentRange && currentRange.start > 1) { // flush buffer preceding current fragment (flush until current fragment start offset) // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ... this.state = State.PAUSED; this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: currentRange.start - 1 }); } if (!media.paused) { // add a safety delay of 1s var nextLevelId = this.hls.nextLoadLevel, nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps; if (fragLastKbps && this.fragCurrent) { fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1; } else { fetchdelay = 0; } } else { fetchdelay = 0; } //logger.log('fetchdelay:'+fetchdelay); // find buffer range that will be reached once new fragment will be fetched nextRange = this.getBufferRange(media.currentTime + fetchdelay); if (nextRange) { // we can flush buffer range following this one without stalling playback nextRange = this.followingBufferRange(nextRange); if (nextRange) { // if we are here, we can also cancel any loading/demuxing in progress, as they are useless var fragCurrent = this.fragCurrent; if (fragCurrent && fragCurrent.loader) { fragCurrent.loader.abort(); } this.fragCurrent = null; // flush position is the start position of this new buffer this.state = State.PAUSED; this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: nextRange.start, endOffset: Number.POSITIVE_INFINITY }); } } } } }, { key: 'onMediaAttached', value: function onMediaAttached(data) { var media = this.media = data.media; this.onvseeking = this.onMediaSeeking.bind(this); this.onvseeked = this.onMediaSeeked.bind(this); this.onvended = this.onMediaEnded.bind(this); media.addEventListener('seeking', this.onvseeking); media.addEventListener('seeked', this.onvseeked); media.addEventListener('ended', this.onvended); if (this.demuxer) { this.demuxer.destroy(); this.demuxer = new _demuxer2.default(this.hls); this.fragParsing = null; } if (this.levels && this.config.autoStartLoad) { this.hls.startLoad(); } } }, { key: 'onMediaDetaching', value: function onMediaDetaching() { var media = this.media; if (media && media.ended || this.state === State.ENDED) { _logger.logger.log('MSE detaching and video ended, reset startPosition'); this.startPosition = this.lastCurrentTime = 0; } // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery var levels = this.levels; if (levels) { // reset fragment load counter levels.forEach(function (level) { if (level.details) { level.details.fragments.forEach(function (fragment) { fragment.loadCounter = undefined; }); } }); } // remove video listeners if (media) { media.removeEventListener('seeking', this.onvseeking); media.removeEventListener('seeked', this.onvseeked); media.removeEventListener('ended', this.onvended); this.onvseeking = this.onvseeked = this.onvended = null; } this.media = null; this.loadedmetadata = false; this.stopLoad(); this.fragParsing = null; } }, { key: 'onMediaSeeking', value: function onMediaSeeking() { var currentTime = this.media.currentTime; _logger.logger.log('media seeking to ' + currentTime); var fragCurrent = this.fragCurrent; if (this.state === State.FRAG_LOADING) { // check if currently loaded fragment is inside buffer. //if outside, cancel fragment loading, otherwise do nothing if (_bufferHelper2.default.bufferInfo(this.media, currentTime, 0).len === 0) { _logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load'); if (fragCurrent) { if (fragCurrent.loader) { fragCurrent.loader.abort(); } this.fragCurrent = null; } this.fragPrevious = null; // switch to IDLE state to load new fragment this.state = State.IDLE; } } else if (this.state === State.ENDED) { // switch to IDLE state to check for potential new fragment this.state = State.IDLE; } else if (this.state === State.PARSING && fragCurrent && !fragCurrent.loaded) { _logger.logger.log('mediaController: no final chunk, switch back to IDLE state'); this.state = State.IDLE; } if (this.media) { this.lastCurrentTime = currentTime; } // avoid reporting fragment loop loading error in case user is seeking several times on same position if (this.fragLoadIdx !== undefined) { this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; } // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target if (!this.loadedmetadata) { this.nextLoadPosition = this.startPosition = currentTime; if (this.fragCurrent && (this.fragCurrent.start > currentTime || this.fragCurrent.start + this.fragCurrent.duration < currentTime)) { this.seekDuringFirst = true; } } // tick to speed up processing this.tick(); } }, { key: 'onMediaSeeked', value: function onMediaSeeked() { _logger.logger.log('media seeked to ' + this.media.currentTime); // tick to speed up FRAGMENT_PLAYING triggering this.tick(); } }, { key: 'onMediaEnded', value: function onMediaEnded() { _logger.logger.log('media ended'); // reset startPosition and lastCurrentTime to restart playback @ stream beginning this.startPosition = this.lastCurrentTime = 0; } }, { key: 'onManifestLoading', value: function onManifestLoading() { // reset buffer on manifest loading _logger.logger.log('trigger BUFFER_RESET'); this.hls.trigger(_events2.default.BUFFER_RESET); this.bufferRange = []; this.stalled = false; this.startPosition = this.lastCurrentTime = 0; this.fragParsing = null; delete this.fragPreviousSaved; } }, { key: 'onManifestParsed', value: function onManifestParsed(data) { var aac = false, heaac = false, codec; data.levels.forEach(function (level) { // detect if we have different kind of audio codecs used amongst playlists codec = level.audioCodec; if (codec) { if (codec.indexOf('mp4a.40.2') !== -1) { aac = true; } if (codec.indexOf('mp4a.40.5') !== -1) { heaac = true; } } }); this.audioCodecSwitch = aac && heaac; if (this.audioCodecSwitch) { _logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'); } this.levels = data.levels; this.startLevelLoaded = false; this.startFragRequested = false; if (this.demuxer) { this.demuxer.destroy(); this.demuxer = new _demuxer2.default(this.hls); this.fragParsing = null; } if (this.config.autoStartLoad) { this.hls.startLoad(); } } }, { key: 'onLevelLoaded', value: function onLevelLoaded(data) { var newDetails = data.details, newLevelId = data.level, curLevel = this.levels[newLevelId], duration = newDetails.totalduration, sliding = 0, lastDetails = this.levelLastLoaded !== undefined && this.levels[this.levelLastLoaded] && this.levels[this.levelLastLoaded].details; _logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration); if (newDetails.live) { var curDetails = curLevel.details; if (lastDetails && _levelHelper2.default.canMerge(lastDetails, newDetails)) { curDetails = lastDetails; } else if (curDetails && !_levelHelper2.default.canMerge(curDetails, newDetails)) { curDetails = undefined; this.hls.clearLevelDetails(); } if (curDetails) { // we already have details for that level, merge them _levelHelper2.default.mergeDetails(curDetails, newDetails); sliding = newDetails.fragments[0].start; if (newDetails.PTSKnown) { _logger.logger.log('live playlist sliding:' + sliding.toFixed(3)); } else { _logger.logger.log('live playlist - outdated PTS, unknown sliding'); } } else { newDetails.PTSKnown = false; _logger.logger.log('live playlist - first load, unknown sliding'); } } else { newDetails.PTSKnown = false; if (lastDetails) { _levelHelper2.default.mergeDetails(lastDetails, newDetails); } } // override level info this.levelLastLoaded = newLevelId; curLevel.details = newDetails; this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId }); // compute start position if (this.startFragRequested === false) { // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3) if (newDetails.live) { this.startPosition = this.computeLivePosition(sliding, newDetails); _logger.logger.log('configure startPosition to ' + this.startPosition); } this.nextLoadPosition = this.startPosition; } // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment if (this.state === State.WAITING_LEVEL) { this.waitLiveLevel = false; this.state = State.IDLE; } //trigger handler right now this.tick(); } }, { key: 'onKeyLoaded', value: function onKeyLoaded() { if (this.state === State.KEY_LOADING) { this.state = State.IDLE; this.tick(); } } }, { key: 'onFragChunkLoaded', value: function onFragChunkLoaded(data) { var fragCurrent = this.fragCurrent; if ((this.state === State.FRAG_LOADING || this.state === State.PARSING) && fragCurrent && data.frag.level === fragCurrent.level && data.frag.sn === fragCurrent.sn) { _logger.logger.log('Loaded chunk ' + data.payload.byteLength + ' of frag ' + fragCurrent.sn + ' of level ' + fragCurrent.level); this.state = State.PARSING; // transmux the MPEG-TS data to ISO-BMFF segments this.stats = data.stats; var level = fragCurrent.level, fragLevel = this.levels[level], details = fragLevel.details, duration = details.totalduration, start = this.fragTimeOffset, sn = fragCurrent.sn, audioCodec = this.config.defaultAudioCodec || fragLevel.audioCodec; if (this.audioCodecSwap) { _logger.logger.log('swapping playlist audio codec'); if (audioCodec === undefined) { audioCodec = this.lastAudioCodec; } if (audioCodec) { if (audioCodec.indexOf('mp4a.40.5') !== -1) { audioCodec = 'mp4a.40.2'; } else { audioCodec = 'mp4a.40.5'; } } } _logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc); var demuxer = this.demuxer; if (demuxer) { // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments) var media = this.media; var mediaSeeking = media && media.seeking; var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live); demuxer.push(data.payload, audioCodec, fragLevel.videoCodec, start, fragCurrent.cc, level, sn, duration, fragCurrent.decryptdata, accurateTimeOffset, details.endSN); } if (data.payload.final) { fragCurrent.loaded = true; } } } }, { key: 'onFragLoaded', value: function onFragLoaded() { _logger.logger.log('Loaded ' + this.fragCurrent.sn + ' of level ' + this.fragCurrent.level); this.fragLoadError = 0; } }, { key: 'onFragParsingInitSegment', value: function onFragParsingInitSegment(data) { if (this.state === State.PARSING) { var tracks = data.tracks, trackName, track; // include levelCodec in audio and video tracks track = tracks.audio; if (track) { var audioCodec = this.levels[this.level].audioCodec, ua = navigator.userAgent.toLowerCase(); if (audioCodec && this.audioCodecSwap) { _logger.logger.log('swapping playlist audio codec'); if (audioCodec.indexOf('mp4a.40.5') !== -1) { audioCodec = 'mp4a.40.2'; } else { audioCodec = 'mp4a.40.5'; } } // in case AAC and HE-AAC audio codecs are signalled in manifest // force HE-AAC , as it seems that most browsers prefers that way, // except for mono streams OR on FF // these conditions might need to be reviewed ... if (this.audioCodecSwitch) { // don't force HE-AAC if mono stream if (track.metadata.channelCount !== 1 && // don't force HE-AAC if firefox ua.indexOf('firefox') === -1) { audioCodec = 'mp4a.40.5'; } } // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { audioCodec = 'mp4a.40.2'; _logger.logger.log('Android: force audio codec to ' + audioCodec); } track.levelCodec = audioCodec; } track = tracks.video; if (track) { track.levelCodec = this.levels[this.level].videoCodec; } // if remuxer specify that a unique track needs to generated, // let's merge all tracks together if (data.unique) { var mergedTrack = { codec: '', levelCodec: '' }; for (trackName in data.tracks) { track = tracks[trackName]; mergedTrack.container = track.container; if (mergedTrack.codec) { mergedTrack.codec += ','; mergedTrack.levelCodec += ','; } if (track.codec) { mergedTrack.codec += track.codec; } if (track.levelCodec) { mergedTrack.levelCodec += track.levelCodec; } } tracks = { audiovideo: mergedTrack }; } this.hls.trigger(_events2.default.BUFFER_CODECS, tracks); if (this.state !== State.STOPPED) { // loop through tracks that are going to be provided to bufferController for (trackName in tracks) { track = tracks[trackName]; var initSegment = track.initSegment; _logger.logger.log('track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']' + (initSegment ? ',init:' + initSegment.length : '')); if (initSegment) { this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment }); } } } //trigger handler right now this.tick(); } } }, { key: 'onFragParsingData', value: function onFragParsingData(data) { if (this.state === State.PARSING || this.fragParsing) { this.tparse2 = Date.now(); var frag = this.fragCurrent || this.fragParsing; _logger.logger.log('parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb + ',dropped:' + (data.dropped || 0) + ',deltaPTS:' + (data.deltaPTS || 0)); var hls = this.hls; // has remuxer dropped video frames located before first keyframe ? if (data.type === 'video') { frag.dropped = data.dropped; if (data.deltaPTS) { if (isNaN(frag.deltaPTS)) { frag.deltaPTS = data.deltaPTS; } else { frag.deltaPTS = Math.max(data.deltaPTS, frag.deltaPTS); } } } [data.data1, data.data2].forEach(function (buffer) { if (buffer) { hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer }); } }); //trigger handler right now this.tick(); } else { _logger.logger.warn('not in PARSING state but ' + this.state + ', ignoring FRAG_PARSING_DATA event'); } } }, { key: 'onFragParsed', value: function onFragParsed(data) { if (this.state === State.PARSING) { var frag = this.fragCurrent, level = this.levels[frag.level]; this.stats.tparsed = performance.now(); this.state = State.PARSED; _logger.logger.log('parsed frag sn:' + frag.sn + ',PTS:[' + (data.startPTS ? data.startPTS.toFixed(3) : 'none') + ',' + (data.endPTS ? data.endPTS.toFixed(3) : 'none') + '],PTSDTSshift:' + (data.PTSDTSshift ? data.PTSDTSshift.toFixed(3) : 'none') + ',lastGopPTS:' + (data.lastGopPTS ? data.lastGopPTS.toFixed(3) : 'none')); if (data.startPTS !== undefined && data.endPTS !== undefined) { var drift = _levelHelper2.default.updateFragPTS(level.details, frag.sn, data.startPTS, data.endPTS, data.PTSDTSshift, data.lastGopPTS); this.hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: frag.level, drift: drift }); } else { // forse reload of prev fragment if video samples not found frag.dropped = 1; frag.deltaPTS = this.config.maxSeekHole + 1; } this.hls.trigger(_events2.default.FRAG_APPENDING); } } }, { key: 'onFragAppended', value: function onFragAppended() { var _this2 = this; //trigger handler right now if (this.state === State.PARSED) { this._checkBuffer(true); var frag = this.fragCurrent; if (frag) { _logger.logger.log('media buffered : ' + this.timeRangesToString(this.media.buffered)); // filter potentially evicted bufferRange. this is to avoid memleak on live streams var bufferRange = this.bufferRange.filter(function (range) { return _bufferHelper2.default.isBuffered(_this2.media, (range.start + range.end) / 2); }); // push new range bufferRange.push({ type: frag.type, start: frag.startPTS, end: frag.endPTS, frag: frag }); // sort, as we use BinarySearch for lookup in getBufferRange ... this.bufferRange = bufferRange.sort(function (a, b) { return a.start - b.start; }); this.fragPrevious = frag; var stats = this.stats; stats.tbuffered = performance.now(); this.fragLastKbps = Math.round(8 * stats.length / (stats.tbuffered - stats.tfirst)); this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag }); this.state = State.IDLE; } this.tick(); } else { _logger.logger.warn('not in PARSED state but ' + this.state); } } }, { key: 'onError', value: function onError(data) { switch (data.details) { case _errors.ErrorDetails.FRAG_LOAD_ERROR: case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT: if (!data.fatal) { var loadError = (this.fragLoadError || 0) + 1; if (loadError <= this.config.fragLoadingMaxRetry) { this.fragLoadError = loadError; // reset load counter to avoid frag loop loading error data.frag.loadCounter = 0; // exponential backoff capped to 64s var delay = Math.min(Math.pow(2, loadError - 1) * this.config.fragLoadingRetryDelay, 64000); _logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms'); this.retryDate = performance.now() + delay; // retry loading state this.state = State.FRAG_LOADING_WAITING_RETRY; } else { _logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...'); // redispatch same error but with fatal set to true data.fatal = true; this.hls.trigger(_events2.default.ERROR, data); this.state = State.ERROR; } } break; case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR: case _errors.ErrorDetails.LEVEL_LOAD_ERROR: case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT: case _errors.ErrorDetails.KEY_LOAD_ERROR: case _errors.ErrorDetails.KEY_LOAD_TIMEOUT: // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received if (this.state !== State.ERROR) { // if fatal error, stop processing, otherwise move to IDLE to retry loading this.state = data.fatal ? State.ERROR : State.IDLE; _logger.logger.warn('mediaController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...'); } break; case _errors.ErrorDetails.BUFFER_FULL_ERROR: // trigger a smooth level switch to empty buffers // also reduce max buffer length as it might be too high. we do this to avoid loop flushing ... this.config.maxMaxBufferLength /= 2; _logger.logger.warn('reduce max buffer length to ' + this.config.maxMaxBufferLength + 's and trigger a nextLevelSwitch to flush old buffer and fix QuotaExceededError'); this.nextLevelSwitch(); break; default: break; } } }, { key: '_checkBuffer', value: function _checkBuffer(appended) { var media = this.media; if (media && media.readyState) { var currentTime; currentTime = media.currentTime; // adjust currentTime to start position on loaded metadata if (!this.loadedmetadata && media.buffered.length && appended) { if (this.seekDuringFirst) { this.seekDuringFirst = null; return; } this.loadedmetadata = true; // only adjust currentTime if different from startPosition or if startPosition not buffered // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered var startPosition = this.startPosition, startPositionBuffered = _bufferHelper2.default.isBuffered(media, startPosition); if (currentTime !== this.startPosition || !startPositionBuffered) { _logger.logger.log('target start position:' + startPosition); // if startPosition not buffered, let's seek to buffered.start(0) if (!startPositionBuffered) { // XXX pavelki: fix case when we asked to seek during the first // segment loading for (var i = 0; i < media.buffered.length; i++) { if (media.buffered.start(i) > startPosition) { startPosition = media.buffered.start(i); break; } } if (_browser2.default.isSafari()) { startPosition += 0.001; } _logger.logger.log('target start position not buffered, seek to buffered.start(' + i + ') ' + startPosition); } _logger.logger.log('adjust currentTime from ' + currentTime + ' to ' + startPosition); media.currentTime = startPosition; } } else { var hls = this.hls; var bufferInfo = _bufferHelper2.default.bufferInfo(media, currentTime, 0), expectedPlaying = !(media.paused || // not playing when media is paused media.ended || // not playing when media is ended media.buffered.length === 0), // not playing if nothing buffered jumpThreshold = 0.5, // tolerance needed as some browsers stalls playback before reaching buffered range end playheadMoving = currentTime !== this.lastCurrentTime, config = this.config; if (playheadMoving) { // played moving, but was previously stalled => now not stuck anymore if (this.stallReported) { var dur = Math.round(performance.now() - this.stalled); _logger.logger.warn('playback not stuck anymore @' + currentTime + ', after ' + dur + 'ms'); hls.trigger(_events2.default.BUF_STATISTICS, { bufNotStalled: { ts: currentTime, dur: dur, lowBuf: this.stallLowBuf } }); this.stallLowBuf = this.stallReported = false; } this.stalled = undefined; this.nudgeRetry = 0; } else { // playhead not moving if (expectedPlaying) { // playhead not moving BUT media expected to play var tnow = performance.now(); if (!this.stalled) { // stall just detected, store current time this.stalled = tnow; this.stallLowBuf = this.stallReported = false; } else { // playback already stalled, check stalling duration // if stalling for more than a given threshold, let's try to recover var stalledDuration = tnow - this.stalled; var bufferLen = bufferInfo.len; var nudgeRetry = this.nudgeRetry || 0; // have we reached stall deadline ? if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) { // report stalled error once if (!this.stallReported) { this.stallReported = true; this.stallLowBuf = true; _logger.logger.warn('playback stalling in low buffer @' + currentTime); hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); hls.trigger(_events2.default.BUF_STATISTICS, { bufStalledLow: { ts: currentTime } }); } // if buffer len is below threshold, try to jump to start of next buffer range if close // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range) var nextBufferStart = bufferInfo.nextStart, delta = nextBufferStart - currentTime; if (nextBufferStart && delta < config.maxSeekHole && delta > 0) { this.nudgeRetry = ++nudgeRetry; var nudgeOffset = nudgeRetry * config.nudgeOffset; // next buffer is close ! adjust currentTime to nextBufferStart // this will ensure effective video decoding _logger.logger.log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + nudgeOffset); media.currentTime = nextBufferStart + nudgeOffset; // reset stalled so to rearm watchdog timer this.stalled = undefined; hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole: nextBufferStart + nudgeOffset - currentTime }); hls.trigger(_events2.default.BUF_STATISTICS, { bufSeekOverHole: { ts: currentTime } }); } } else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) { if (this.stallReported && this.stallLowBuf) { // reset stalled so to rearm watchdog timer this.stalled = undefined; } else { // report stalled error once if (!this.stallReported) { this.stallReported = true; _logger.logger.warn('playback stalling in high buffer @' + currentTime); hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); hls.trigger(_events2.default.BUF_STATISTICS, { bufStalledHigh: { ts: currentTime } }); } // reset stalled so to rearm watchdog timer this.stalled = undefined; this.nudgeRetry = ++nudgeRetry; if (nudgeRetry < config.nudgeMaxRetry) { var _currentTime = media.currentTime; var targetTime = _currentTime + nudgeRetry * config.nudgeOffset; _logger.logger.log('adjust currentTime from ' + _currentTime + ' to ' + targetTime); // playback stalled in buffered area ... let's nudge currentTime to try to overcome this media.currentTime = targetTime; hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false }); hls.trigger(_events2.default.BUF_STATISTICS, { bufNudge: { ts: _currentTime } }); } else { _logger.logger.error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error'); hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: true }); } } } } } } } } } }, { key: 'onFragLoadEmergencyAborted', value: function onFragLoadEmergencyAborted() { this.state = State.IDLE; this.tick(); } }, { key: 'onBufferFlushed', value: function onBufferFlushed() { var _this3 = this; // after successful buffer flushing, filter flushed fragments from bufferRange this.bufferRange = this.bufferRange.filter(function (range) { return _bufferHelper2.default.isBuffered(_this3.media, (range.start + range.end) / 2); }); // handle end of immediate switching if needed if (this.immediateSwitch) { this.immediateLevelSwitchEnd(); } // move to IDLE once flush complete. this should trigger new fragment loading this.state = State.IDLE; // reset reference to frag this.fragPrevious = null; } }, { key: 'onLevelPtsUpdated', value: function onLevelPtsUpdated(lu) { if (!this.levels || this.levels[lu.level].details.live) { return; } for (var level = 0; level < this.levels.length; level++) { if (level !== lu.level && this.levels[level].details) { _levelHelper2.default.mergeDetails(this.levels[lu.level].details, this.levels[level].details); } } } }, { key: 'swapAudioCodec', value: function swapAudioCodec() { this.audioCodecSwap = !this.audioCodecSwap; } }, { key: 'timeRangesToString', value: function timeRangesToString(r) { if (!r) { return '[]'; } var log = '', len = r.length; for (var i = 0; i < len; i++) { log += '[' + r.start(i) + ',' + r.end(i) + ']'; } return log; } }, { key: 'computeLivePosition', value: function computeLivePosition(sliding, levelDetails) { var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration; return sliding + Math.max(0, levelDetails.totalduration - targetLatency); } }, { key: 'state', set: function set(nextState) { if (this.state !== nextState) { var previousState = this.state; this._state = nextState; _logger.logger.log('engine state transition from ' + previousState + ' to ' + nextState); if (nextState === 'IDLE') { var media = this.media || {}; _logger.logger.log('media ' + media + ' ct=' + media.currentTime + ' dur=' + media.duration + ' buf=' + this.timeRangesToString(media.buffered) + ' err=' + media.error); } this.hls.trigger(_events2.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState }); } }, get: function get() { return this._state; } }, { key: 'currentLevel', get: function get() { if (this.media) { var range = this.getBufferRange(this.media.currentTime); if (range) { return range.frag.level; } } return -1; } }, { key: 'nextBufferRange', get: function get() { if (this.media) { // first get end range of current fragment return this.followingBufferRange(this.getBufferRange(this.media.currentTime)); } else { return null; } } }, { key: 'nextLevel', get: function get() { var range = this.nextBufferRange; if (range) { return range.frag.level; } else { return -1; } } }]); return StreamController; }(_eventHandler2.default); exports.default = StreamController; },{"../demux/demuxer":16,"../errors":20,"../event-handler":21,"../events":22,"../helper/buffer-helper":24,"../helper/level-helper":25,"../utils/binary-search":34,"../utils/browser":35,"../utils/logger":38}],8:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _cea608Parser = require('../utils/cea-608-parser'); var _cea608Parser2 = _interopRequireDefault(_cea608Parser); var _cues = require('../utils/cues'); var _cues2 = _interopRequireDefault(_cues); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Timeline Controller */ var TimelineController = function (_EventHandler) { _inherits(TimelineController, _EventHandler); function TimelineController(hls) { _classCallCheck(this, TimelineController); var _this = _possibleConstructorReturn(this, (TimelineController.__proto__ || Object.getPrototypeOf(TimelineController)).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_USERDATA, _events2.default.MANIFEST_LOADING, _events2.default.FRAG_LOADED, _events2.default.LEVEL_SWITCH)); _this.hls = hls; _this.config = hls.config; _this.enabled = true; if (_this.config.enableCEA708Captions) { var self = _this; var channel1 = { 'newCue': function newCue(startTime, endTime, screen) { if (!self.textTrack1) { self.textTrack1 = self.createTextTrack('captions', 'Unknown CC1', 'en'); // self.textTrack1.mode = 'showing'; } _cues2.default.newCue(self.textTrack1, startTime, endTime, screen); } }; var channel2 = { 'newCue': function newCue(startTime, endTime, screen) { if (!self.textTrack2) { self.textTrack2 = self.createTextTrack('captions', 'Unknown CC2', 'es'); } _cues2.default.newCue(self.textTrack2, startTime, endTime, screen); } }; _this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2); } return _this; } _createClass(TimelineController, [{ key: 'clearCurrentCues', value: function clearCurrentCues(track) { if (track && track.cues) { while (track.cues.length > 0) { track.removeCue(track.cues[0]); } } } }, { key: 'createTextTrack', value: function createTextTrack(kind, label, lang) { if (this.media) { return this.media.addTextTrack(kind, label, lang); } } }, { key: 'destroy', value: function destroy() { _eventHandler2.default.prototype.destroy.call(this); } }, { key: 'onMediaAttaching', value: function onMediaAttaching(data) { this.media = data.media; } }, { key: 'onMediaDetaching', value: function onMediaDetaching() {} }, { key: 'onManifestLoading', value: function onManifestLoading() { this.lastPts = Number.NEGATIVE_INFINITY; } }, { key: 'onLevelSwitch', value: function onLevelSwitch() { if (this.hls.currentLevel.closedCaptions === 'NONE') { this.enabled = false; } else { this.enabled = true; } } }, { key: 'onFragLoaded', value: function onFragLoaded(data) { var pts = data.frag.start; // if this is a frag for a previously loaded timerange, remove all captions // TODO: consider just removing captions for the timerange if (pts <= this.lastPts) { this.clearCurrentCues(this.textTrack1); this.clearCurrentCues(this.textTrack2); } this.lastPts = pts; } }, { key: 'onFragParsingUserdata', value: function onFragParsingUserdata(data) { // push all of the CEA-708 messages into the interpreter // immediately. It will create the proper timestamps based on our PTS value if (this.enabled) { for (var i = 0; i < data.samples.length; i++) { var ccdatas = this.extractCea608Data(data.samples[i].bytes); this.cea608Parser.addData(data.samples[i].pts, ccdatas); } } } }, { key: 'extractCea608Data', value: function extractCea608Data(byteArray) { var count = byteArray[0] & 31; var position = 2; var tmpByte, ccbyte1, ccbyte2, ccValid, ccType; var actualCCBytes = []; for (var j = 0; j < count; j++) { tmpByte = byteArray[position++]; ccbyte1 = 0x7F & byteArray[position++]; ccbyte2 = 0x7F & byteArray[position++]; ccValid = (4 & tmpByte) === 0 ? false : true; ccType = 3 & tmpByte; if (ccbyte1 === 0 && ccbyte2 === 0) { continue; } if (ccValid) { if (ccType === 0) // || ccType === 1 { actualCCBytes.push(ccbyte1); actualCCBytes.push(ccbyte2); } } } return actualCCBytes; } }]); return TimelineController; }(_eventHandler2.default); exports.default = TimelineController; },{"../event-handler":21,"../events":22,"../utils/cea-608-parser":36,"../utils/cues":37}],9:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /* * * This file contains an adaptation of the AES decryption algorithm * from the Standford Javascript Cryptography Library. That work is * covered by the following copyright and permissions notice: * * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation * are those of the authors and should not be interpreted as representing * official policies, either expressed or implied, of the authors. */ var AES = function () { /** * Schedule out an AES key for both encryption and decryption. This * is a low-level class. Use a cipher mode to do bulk encryption. * * @constructor * @param key {Array} The key as an array of 4, 6 or 8 words. */ function AES(key) { _classCallCheck(this, AES); /** * The expanded S-box and inverse S-box tables. These will be computed * on the client so that we don't have to send them down the wire. * * There are two tables, _tables[0] is for encryption and * _tables[1] is for decryption. * * The first 4 sub-tables are the expanded S-box with MixColumns. The * last (_tables[01][4]) is the S-box itself. * * @private */ this._tables = [[[], [], [], [], []], [[], [], [], [], []]]; this._precompute(); var i, j, tmp, encKey, decKey, sbox = this._tables[0][4], decTable = this._tables[1], keyLen = key.length, rcon = 1; if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) { throw new Error('Invalid aes key size=' + keyLen); } encKey = key.slice(0); decKey = []; this._key = [encKey, decKey]; // schedule encryption keys for (i = keyLen; i < 4 * keyLen + 28; i++) { tmp = encKey[i - 1]; // apply sbox if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) { tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon if (i % keyLen === 0) { tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24; rcon = rcon << 1 ^ (rcon >> 7) * 283; } } encKey[i] = encKey[i - keyLen] ^ tmp; } // schedule decryption keys for (j = 0; i; j++, i--) { tmp = encKey[j & 3 ? i : i - 4]; if (i <= 4 || j < 4) { decKey[j] = tmp; } else { decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]]; } } } /** * Expand the S-box tables. * * @private */ _createClass(AES, [{ key: '_precompute', value: function _precompute() { var encTable = this._tables[0], decTable = this._tables[1], sbox = encTable[4], sboxInv = decTable[4], i, x, xInv, d = [], th = [], x2, x4, x8, s, tEnc, tDec; // Compute double and third tables for (i = 0; i < 256; i++) { th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i; } for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) { // Compute sbox s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4; s = s >> 8 ^ s & 255 ^ 99; sbox[x] = s; sboxInv[s] = x; // Compute MixColumns x8 = d[x4 = d[x2 = d[x]]]; tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100; tEnc = d[s] * 0x101 ^ s * 0x1010100; for (i = 0; i < 4; i++) { encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8; decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8; } } // Compactify. Considerable speedup on Firefox. for (i = 0; i < 5; i++) { encTable[i] = encTable[i].slice(0); decTable[i] = decTable[i].slice(0); } } /** * Decrypt 16 bytes, specified as four 32-bit words. * @param encrypted0 {number} the first word to decrypt * @param encrypted1 {number} the second word to decrypt * @param encrypted2 {number} the third word to decrypt * @param encrypted3 {number} the fourth word to decrypt * @param out {Int32Array} the array to write the decrypted words * into * @param offset {number} the offset into the output array to start * writing results * @return {Array} The plaintext. */ }, { key: 'decrypt', value: function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) { var key = this._key[1], // state variables a,b,c,d are loaded with pre-whitened data a = encrypted0 ^ key[0], b = encrypted3 ^ key[1], c = encrypted2 ^ key[2], d = encrypted1 ^ key[3], a2, b2, c2, nInnerRounds = key.length / 4 - 2, // key.length === 2 ? i, kIndex = 4, table = this._tables[1], // load up the tables table0 = table[0], table1 = table[1], table2 = table[2], table3 = table[3], sbox = table[4]; // Inner rounds. Cribbed from OpenSSL. for (i = 0; i < nInnerRounds; i++) { a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex]; b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1]; c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2]; d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3]; kIndex += 4; a = a2;b = b2;c = c2; } // Last round. for (i = 0; i < 4; i++) { out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++]; a2 = a;a = b;b = c;c = d;d = a2; } } }]); return AES; }(); exports.default = AES; },{}],10:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* * * This file contains an adaptation of the AES decryption algorithm * from the Standford Javascript Cryptography Library. That work is * covered by the following copyright and permissions notice: * * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation * are those of the authors and should not be interpreted as representing * official policies, either expressed or implied, of the authors. */ var _aes = require('./aes'); var _aes2 = _interopRequireDefault(_aes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var AES128Decrypter = function () { function AES128Decrypter(key, initVector) { _classCallCheck(this, AES128Decrypter); this.key = key; this.iv = new Uint32Array(initVector); } /** * Convert network-order (big-endian) bytes into their little-endian * representation. */ _createClass(AES128Decrypter, [{ key: 'ntoh', value: function ntoh(word) { return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24; } /** * Decrypt bytes using AES-128 with CBC and PKCS#7 padding. * @param encrypted {Uint8Array} the encrypted bytes * @param key {Uint32Array} the bytes of the decryption key * @param initVector {Uint32Array} the initialization vector (IV) to * use for the first round of CBC. * @return {Uint8Array} the decrypted bytes * * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29 * @see https://tools.ietf.org/html/rfc2315 */ }, { key: 'doDecrypt', value: function doDecrypt(encrypted, key, initVector) { var // word-level access to the encrypted bytes encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2), decipher = new _aes2.default(Array.prototype.slice.call(key)), // byte and word-level access for the decrypted output decrypted = new Uint8Array(encrypted.byteLength), decrypted32 = new Int32Array(decrypted.buffer), // temporary variables for working with the IV, encrypted, and // decrypted data init0, init1, init2, init3, encrypted0, encrypted1, encrypted2, encrypted3, // iteration variable wordIx; // pull out the words of the IV to ensure we don't modify the // passed-in reference and easier access init0 = ~~initVector[0]; init1 = ~~initVector[1]; init2 = ~~initVector[2]; init3 = ~~initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC) // to each decrypted block for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) { // convert big-endian (network order) words into little-endian // (javascript order) encrypted0 = ~~this.ntoh(encrypted32[wordIx]); encrypted1 = ~~this.ntoh(encrypted32[wordIx + 1]); encrypted2 = ~~this.ntoh(encrypted32[wordIx + 2]); encrypted3 = ~~this.ntoh(encrypted32[wordIx + 3]); // decrypt the block decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the // plaintext decrypted32[wordIx] = this.ntoh(decrypted32[wordIx] ^ init0); decrypted32[wordIx + 1] = this.ntoh(decrypted32[wordIx + 1] ^ init1); decrypted32[wordIx + 2] = this.ntoh(decrypted32[wordIx + 2] ^ init2); decrypted32[wordIx + 3] = this.ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round init0 = encrypted0; init1 = encrypted1; init2 = encrypted2; init3 = encrypted3; } return decrypted; } }, { key: 'localDecrypt', value: function localDecrypt(encrypted, key, initVector, decrypted) { var bytes = this.doDecrypt(encrypted, key, initVector); decrypted.set(bytes, encrypted.byteOffset); } }, { key: 'decrypt', value: function decrypt(encrypted) { var step = 4 * 8000, //encrypted32 = new Int32Array(encrypted.buffer), encrypted32 = new Int32Array(encrypted), decrypted = new Uint8Array(encrypted.byteLength), i = 0; // split up the encryption job and do the individual chunks asynchronously var key = this.key; var initVector = this.iv; this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted); for (i = step; i < encrypted32.length; i += step) { initVector = new Uint32Array([this.ntoh(encrypted32[i - 4]), this.ntoh(encrypted32[i - 3]), this.ntoh(encrypted32[i - 2]), this.ntoh(encrypted32[i - 1])]); this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted); } return decrypted; } }]); return AES128Decrypter; }(); exports.default = AES128Decrypter; },{"./aes":9}],11:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* * AES128 decryption. */ var _aes128Decrypter = require('./aes128-decrypter'); var _aes128Decrypter2 = _interopRequireDefault(_aes128Decrypter); var _errors = require('../errors'); var _logger = require('../utils/logger'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Decrypter = function () { function Decrypter(hls) { _classCallCheck(this, Decrypter); this.hls = hls; this.iv = null; try { var browserCrypto = window ? window.crypto : crypto; this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle; this.disableWebCrypto = !this.subtle; } catch (e) { this.disableWebCrypto = true; } } _createClass(Decrypter, [{ key: 'destroy', value: function destroy() {} }, { key: 'decrypt', value: function decrypt(data, key, iv, callback) { if (this.disableWebCrypto && this.hls.config.enableSoftwareAES) { this.decryptBySoftware(data, key, iv, callback); } else { this.decryptByWebCrypto(data, key, iv, callback); } } }, { key: 'decryptByWebCrypto', value: function decryptByWebCrypto(data, key, iv, callback) { var _this = this; _logger.logger.log('decrypting by WebCrypto API'); this.subtle.importKey('raw', key, { name: 'AES-CBC', length: 128 }, false, ['decrypt']).then(function (importedKey) { _this.subtle.decrypt({ name: 'AES-CBC', iv: iv.buffer }, importedKey, data).then(callback).catch(function (err) { _this.onWebCryptoError(err, data, key, iv, callback); }); }).catch(function (err) { _this.onWebCryptoError(err, data, key, iv, callback); }); } }, { key: 'decryptBySoftware', value: function decryptBySoftware(data, key8, iv8, callback) { _logger.logger.log('decrypting by JavaScript Implementation'); var view = new DataView(key8.buffer); var key = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]); if (iv8) { view = new DataView(iv8.buffer); this.iv = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]); } var decrypter = new _aes128Decrypter2.default(key, this.iv); var ivview = new DataView(data), len = data.byteLength; // save initvector for the next chunk this.iv = new Uint32Array([ivview.getUint32(len - 16), ivview.getUint32(len - 12), ivview.getUint32(len - 8), ivview.getUint32(len - 4)]); callback(decrypter.decrypt(data).buffer); } }, { key: 'onWebCryptoError', value: function onWebCryptoError(err, data, key, iv, callback) { if (this.hls.config.enableSoftwareAES) { _logger.logger.log('disabling to use WebCrypto API'); this.disableWebCrypto = true; this.decryptBySoftware(data, key, iv, callback); } else { _logger.logger.error('decrypting error : ' + err.message); this.hls.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message }); } } }]); return Decrypter; }(); exports.default = Decrypter; },{"../errors":20,"../utils/logger":38,"./aes128-decrypter":10}],12:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * AAC demuxer */ var _adts = require('./adts'); var _adts2 = _interopRequireDefault(_adts); var _logger = require('../utils/logger'); var _id = require('../demux/id3'); var _id2 = _interopRequireDefault(_id); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var AACDemuxer = function () { function AACDemuxer(observer, remuxerClass, config, typeSupported) { _classCallCheck(this, AACDemuxer); this.observer = observer; this.remuxerClass = remuxerClass; this.config = config; this.remuxer = new this.remuxerClass(observer, config, typeSupported); this._aacTrack = { container: 'audio/adts', type: 'audio', id: -1, sequenceNumber: 0, samples: [], len: 0 }; } _createClass(AACDemuxer, [{ key: 'push', // feed incoming data to the front of the parsing pipeline value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final) { var track = this._aacTrack, id3 = new _id2.default(data), pts = 90 * id3.timeStamp, config, frameLength, frameDuration, frameIndex, offset, headerLength, stamp, len, aacSample, startPTS, endPTS; // look for ADTS header (0xFFFx) for (offset = id3.length, len = data.length; offset < len - 1; offset++) { if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) { break; } } if (!track.audiosamplerate) { config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec); track.config = config.config; track.audiosamplerate = config.samplerate; track.channelCount = config.channelCount; track.codec = config.codec; track.duration = duration; _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount); } frameIndex = 0; frameDuration = 1024 * 90000 / track.audiosamplerate; while (offset + 5 < len) { // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9; // retrieve frame size frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5; frameLength -= headerLength; //stamp = pes.pts; if (frameLength > 0 && offset + headerLength + frameLength <= len) { stamp = pts + frameIndex * frameDuration; //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp }; track.samples.push(aacSample); track.len += frameLength; offset += frameLength + headerLength; frameIndex++; // look for ADTS header (0xFFFx) for (; offset < len - 1; offset++) { if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) { break; } } } else { break; } } if (track.samples.length && final) { var timescale = this.remuxer.PES_TIMESCALE; var initDTS = this.remuxer._initDTS === undefined ? track.samples[0].dts - timescale * timeOffset : this.remuxer._initDTS; var nextAvcDts = timeOffset * timescale; startPTS = this.remuxer._PTSNormalize(track.samples[0].pts - initDTS, nextAvcDts) / timescale; endPTS = this.remuxer._PTSNormalize(track.samples[track.samples.length - 1].pts + frameDuration - initDTS, nextAvcDts) / timescale; } this.remuxer.remux(this._aacTrack, { samples: [] }, { samples: [{ pts: pts, dts: pts, unit: id3.payload }] }, { samples: [] }, timeOffset); if (final) { this.observer.trigger(_events2.default.FRAG_PARSED, { startPTS: startPTS, endPTS: endPTS, PTSDTSshift: 0 }); } } }, { key: 'destroy', value: function destroy() {} }], [{ key: 'probe', value: function probe(data) { // check if data contains ID3 timestamp and ADTS sync worc var id3 = new _id2.default(data), offset, len; if (id3.hasTimeStamp) { // look for ADTS header (0xFFFx) for (offset = id3.length, len = data.length; offset < len - 1; offset++) { if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) { //logger.log('ADTS sync word found !'); return true; } } } return false; } }]); return AACDemuxer; }(); exports.default = AACDemuxer; },{"../demux/id3":18,"../events":22,"../utils/logger":38,"./adts":13}],13:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * ADTS parser helper */ var _logger = require('../utils/logger'); var _errors = require('../errors'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ADTS = function () { function ADTS() { _classCallCheck(this, ADTS); } _createClass(ADTS, null, [{ key: 'getAudioConfig', value: function getAudioConfig(observer, data, offset, audioCodec) { var adtsObjectType, // :int adtsSampleingIndex, // :int adtsExtensionSampleingIndex, // :int adtsChanelConfig, // :int config, userAgent = navigator.userAgent.toLowerCase(), adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2 adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1; adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2; if (adtsSampleingIndex > adtsSampleingRates.length - 1) { observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex }); return; } adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3 adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6; _logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig); // firefox: freq less than 24kHz = AAC SBR (HE-AAC) if (userAgent.indexOf('firefox') !== -1) { if (adtsSampleingIndex >= 6) { adtsObjectType = 5; config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies // there is a factor 2 between frame sample rate and output sample rate // multiply frequency by 2 (see table below, equivalent to substract 3) adtsExtensionSampleingIndex = adtsSampleingIndex - 3; } else { adtsObjectType = 2; config = new Array(2); adtsExtensionSampleingIndex = adtsSampleingIndex; } // Android : always use AAC } else if (userAgent.indexOf('android') !== -1) { adtsObjectType = 2; config = new Array(2); adtsExtensionSampleingIndex = adtsSampleingIndex; } else { /* for other browsers (chrome ...) always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...) */ adtsObjectType = 5; config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz) if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) { // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies // there is a factor 2 between frame sample rate and output sample rate // multiply frequency by 2 (see table below, equivalent to substract 3) adtsExtensionSampleingIndex = adtsSampleingIndex - 3; } else { // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio) // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || !audioCodec && adtsChanelConfig === 1) { adtsObjectType = 2; config = new Array(2); } adtsExtensionSampleingIndex = adtsSampleingIndex; } } /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig() Audio Profile / Audio Object Type 0: Null 1: AAC Main 2: AAC LC (Low Complexity) 3: AAC SSR (Scalable Sample Rate) 4: AAC LTP (Long Term Prediction) 5: SBR (Spectral Band Replication) 6: AAC Scalable sampling freq 0: 96000 Hz 1: 88200 Hz 2: 64000 Hz 3: 48000 Hz 4: 44100 Hz 5: 32000 Hz 6: 24000 Hz 7: 22050 Hz 8: 16000 Hz 9: 12000 Hz 10: 11025 Hz 11: 8000 Hz 12: 7350 Hz 13: Reserved 14: Reserved 15: frequency is written explictly Channel Configurations These are the channel configurations: 0: Defined in AOT Specifc Config 1: 1 channel: front-center 2: 2 channels: front-left, front-right */ // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1 config[0] = adtsObjectType << 3; // samplingFrequencyIndex config[0] |= (adtsSampleingIndex & 0x0E) >> 1; config[1] |= (adtsSampleingIndex & 0x01) << 7; // channelConfiguration config[1] |= adtsChanelConfig << 3; if (adtsObjectType === 5) { // adtsExtensionSampleingIndex config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1; config[2] = (adtsExtensionSampleingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ??? // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc config[2] |= 2 << 2; config[3] = 0; } return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType }; } }]); return ADTS; }(); exports.default = ADTS; },{"../errors":20,"../utils/logger":38}],14:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* inline demuxer. * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...) */ var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _errors = require('../errors'); var _aacdemuxer = require('../demux/aacdemuxer'); var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer); var _tsdemuxer = require('../demux/tsdemuxer'); var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer); var _mp4Remuxer = require('../remux/mp4-remuxer'); var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer); var _passthroughRemuxer = require('../remux/passthrough-remuxer'); var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DemuxerInline = function () { function DemuxerInline(hls, typeSupported) { var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; _classCallCheck(this, DemuxerInline); var _this = this; this.hls = hls; this.config = this.hls.config || config; this.typeSupported = typeSupported; this.timeOffset = 0; this.onFragParsingData = function (ev, data) { if (data.type === 'video' && !data.flush) { // sync on video chunks _this.timeOffset += data.endDTS - data.startDTS; } }; this.hls.on(_events2.default.FRAG_PARSING_DATA, this.onFragParsingData); } _createClass(DemuxerInline, [{ key: 'destroy', value: function destroy() { var demuxer = this.demuxer; if (demuxer) { demuxer.destroy(); } this.hls.off(_events2.default.FRAG_PARSING_DATA, this.onFragParsingData); } }, { key: 'push', value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN) { var demuxer = this.demuxer; if (!demuxer) { var hls = this.hls; // probe for content type if (_tsdemuxer2.default.probe(data)) { if (this.typeSupported.mp2t === true) { demuxer = new _tsdemuxer2.default(hls, _passthroughRemuxer2.default, this.config, this.typeSupported); } else { demuxer = new _tsdemuxer2.default(hls, _mp4Remuxer2.default, this.config, this.typeSupported); } } else if (_aacdemuxer2.default.probe(data)) { demuxer = new _aacdemuxer2.default(hls, _mp4Remuxer2.default, this.config, this.typeSupported); } else { var i = void 0, len = data.length, info = 'len:' + len + ' ['; for (i = 0, len = Math.min(len, 10); i < len; i++) { if (i) { info += ','; } info += data[i]; } info += '..]'; if (data.length >= 3 * 188) { info += ' [0]==' + data[0] + ' [188]==' + data[188] + ' [2*188]==' + data[2 * 188]; } hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found ' + info }); return; } this.demuxer = demuxer; } if (first) { this.timeOffset = timeOffset; } demuxer.push(data, audioCodec, videoCodec, this.timeOffset, cc, level, sn, duration, accurate, first, final, lastSN); } }]); return DemuxerInline; }(); exports.default = DemuxerInline; },{"../demux/aacdemuxer":12,"../demux/tsdemuxer":19,"../errors":20,"../events":22,"../remux/mp4-remuxer":31,"../remux/passthrough-remuxer":32}],15:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _demuxerInline = require('../demux/demuxer-inline'); var _demuxerInline2 = _interopRequireDefault(_demuxerInline); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _events3 = require('events'); var _events4 = _interopRequireDefault(_events3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DemuxerWorker = function DemuxerWorker(self) { // observer setup var observer = new _events4.default(); observer.trigger = function trigger(event) { for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { data[_key - 1] = arguments[_key]; } observer.emit.apply(observer, [event, event].concat(data)); }; observer.off = function off(event) { for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { data[_key2 - 1] = arguments[_key2]; } observer.removeListener.apply(observer, [event].concat(data)); }; self.addEventListener('message', function (ev) { var data = ev.data; //console.log('demuxer cmd:' + data.cmd); switch (data.cmd) { case 'init': self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, JSON.parse(data.config)); break; case 'demux': self.demuxer.push(new Uint8Array(data.data), data.audioCodec, data.videoCodec, data.timeOffset, data.cc, data.level, data.sn, data.duration, data.accurate, data.first, data.final, data.lastSN); break; case 'empty': self.postMessage({ event: _events2.default.DEMUXER_QUEUE_EMPTY }); break; default: break; } }); // listen to events triggered by Demuxer observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, function (ev, data) { self.postMessage({ event: ev, tracks: data.tracks, unique: data.unique }); }); observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) { var objData = { event: ev, type: data.type, startPTS: data.startPTS, endPTS: data.endPTS, startDTS: data.startDTS, endDTS: data.endDTS, data1: data.data1.buffer, data2: data.data2.buffer, nb: data.nb, dropped: data.dropped, deltaPTS: data.deltaPTS }; // pass data1/data2 as transferable object (no copy) self.postMessage(objData, [objData.data1, objData.data2]); }); observer.on(_events2.default.FRAG_PARSED, function (event, data) { self.postMessage({ event: event, data: data }); }); observer.on(_events2.default.FRAG_STATISTICS, function (event, data) { self.postMessage({ event: event, data: data }); }); observer.on(_events2.default.ERROR, function (event, data) { self.postMessage({ event: event, data: data }); }); observer.on(_events2.default.FRAG_PARSING_METADATA, function (event, data) { var objData = { event: event, samples: data.samples }; self.postMessage(objData); }); observer.on(_events2.default.FRAG_PARSING_USERDATA, function (event, data) { var objData = { event: event, samples: data.samples }; self.postMessage(objData); }); }; /* demuxer web worker. * - listen to worker message, and trigger DemuxerInline upon reception of Fragments. * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead. */ exports.default = DemuxerWorker; },{"../demux/demuxer-inline":14,"../events":22,"events":43}],16:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _demuxerInline = require('../demux/demuxer-inline'); var _demuxerInline2 = _interopRequireDefault(_demuxerInline); var _demuxerWorker = require('../demux/demuxer-worker'); var _demuxerWorker2 = _interopRequireDefault(_demuxerWorker); var _logger = require('../utils/logger'); var _decrypter = require('../crypt/decrypter'); var _decrypter2 = _interopRequireDefault(_decrypter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Demuxer = function () { function Demuxer(hls) { _classCallCheck(this, Demuxer); this.hls = hls; this.trail = new Uint8Array(0); var typeSupported = { mp4: MediaSource.isTypeSupported('video/mp4'), mp2t: hls.config.enableMP2TPassThrough && MediaSource.isTypeSupported('video/mp2t'), mpeg: MediaSource.isTypeSupported('audio/mpeg'), mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"') }; if (hls.config.disableMp3) { typeSupported.mpeg = typeSupported.mp3 = false; } if (hls.config.enableWorker && typeof Worker !== 'undefined') { _logger.logger.log('demuxing in webworker'); try { var work = require('webworkify'); this.w = work(_demuxerWorker2.default); this.onwmsg = this.onWorkerMessage.bind(this); this.w.addEventListener('message', this.onwmsg); this.w.postMessage({ cmd: 'init', typeSupported: typeSupported, config: JSON.stringify(hls.config) }); } catch (err) { _logger.logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline'); this.demuxer = new _demuxerInline2.default(hls, typeSupported); } } else { this.demuxer = new _demuxerInline2.default(hls, typeSupported); } this.demuxInitialized = true; } _createClass(Demuxer, [{ key: 'destroy', value: function destroy() { if (this.w) { this.w.removeEventListener('message', this.onwmsg); this.w.terminate(); this.w = null; } else { this.demuxer.destroy(); this.demuxer = null; } if (this.decrypter) { this.decrypter.destroy(); this.decrypter = null; } } }, { key: 'pushDecrypted', value: function pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN) { if (this.w) { // post fragment payload as transferable objects (no copy) this.w.postMessage({ cmd: 'demux', data: data, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, cc: cc, level: level, sn: sn, duration: duration, accurate: accurate, first: first, final: final, lastSN: lastSN }, [data]); } else { this.demuxer.push(new Uint8Array(data), audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN); } } }, { key: 'push', value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, decryptdata, accurate, lastSN) { if (data.first) { this.trail = new Uint8Array(0); this.trail.first = true; } var traillen = this.trail.length; // 752 = 4*188. We need number of bytes to be multiplier of 16 to // perform chained AES decryption if (traillen || (data.byteLength + traillen) % 752) { var final = data.final, first = data.first || this.trail.first || false; // add trailing bytes var newlen = data.byteLength + traillen; if (!final) { // at final chunk we sent all pending data newlen -= newlen % 752; } var olddata = new Uint8Array(data); var newdata = new Uint8Array(newlen); var newtrail = new Uint8Array(data.byteLength + traillen - newlen); if (newlen) { newdata.set(this.trail); newdata.set(olddata.subarray(0, newlen - traillen), traillen); } if (newtrail.length) { if (newlen) { newtrail.set(olddata.subarray(-newtrail.length)); } else { newtrail.set(this.trail); newtrail.set(olddata, traillen); newtrail.first = first; } } olddata = null; this.trail = newtrail; if (!newdata.length) { return; } data = newdata.buffer; data.final = final; data.first = first; newdata = null; } if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') { if (this.decrypter == null) { this.decrypter = new _decrypter2.default(this.hls); } var localthis = this; this.decrypter.decrypt(data, decryptdata.key, data.first && decryptdata.iv, function (decryptedData) { localthis.pushDecrypted(decryptedData, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, !!data.first, !!data.final, lastSN); }); } else { this.pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, !!data.first, !!data.final, lastSN); } } }, { key: 'onWorkerMessage', value: function onWorkerMessage(ev) { var data = ev.data; switch (data.event) { case _events2.default.FRAG_PARSING_INIT_SEGMENT: var obj = {}; obj.tracks = data.tracks; obj.unique = data.unique; this.hls.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, obj); break; case _events2.default.FRAG_PARSING_DATA: this.hls.trigger(_events2.default.FRAG_PARSING_DATA, { data1: new Uint8Array(data.data1), data2: new Uint8Array(data.data2), startPTS: data.startPTS, endPTS: data.endPTS, startDTS: data.startDTS, endDTS: data.endDTS, type: data.type, nb: data.nb, dropped: data.dropped, deltaPTS: data.deltaPTS }); break; case _events2.default.FRAG_PARSING_METADATA: this.hls.trigger(_events2.default.FRAG_PARSING_METADATA, { samples: data.samples }); break; case _events2.default.FRAG_PARSING_USERDATA: this.hls.trigger(_events2.default.FRAG_PARSING_USERDATA, { samples: data.samples }); break; default: this.hls.trigger(data.event, data.data); break; } } }, { key: 'waitQueue', value: function waitQueue() { if (this.w) { this.w.postMessage({ cmd: 'empty' }); } } }]); return Demuxer; }(); exports.default = Demuxer; },{"../crypt/decrypter":11,"../demux/demuxer-inline":14,"../demux/demuxer-worker":15,"../events":22,"../utils/logger":38,"webworkify":44}],17:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264. */ var _logger = require('../utils/logger'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ExpGolomb = function () { function ExpGolomb(data) { _classCallCheck(this, ExpGolomb); this.data = data; // the number of bytes left to examine in this.data this.bytesAvailable = this.data.byteLength; // the current word being examined this.word = 0; // :uint // the number of bits left to examine in the current word this.bitsAvailable = 0; // :uint } _createClass(ExpGolomb, [{ key: 'wholeBytesAvailable', value: function wholeBytesAvailable() { return this.bytesAvailable + (this.bitsAvailable >> 3); } // ():void }, { key: 'loadWord', value: function loadWord() { var position = this.data.byteLength - this.bytesAvailable, workingBytes = new Uint8Array(4), availableBytes = Math.min(4, this.bytesAvailable); if (availableBytes === 0) { throw new Error('no bytes available'); } workingBytes.set(this.data.subarray(position, position + availableBytes)); this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed this.bitsAvailable = availableBytes * 8; this.bytesAvailable -= availableBytes; } // (count:int):void }, { key: 'skipBits', value: function skipBits(count) { var skipBytes; // :int if (this.bitsAvailable > count) { this.word <<= count; this.bitsAvailable -= count; } else { count -= this.bitsAvailable; skipBytes = count >> 3; count -= skipBytes >> 3; this.bytesAvailable -= skipBytes; this.loadWord(); this.word <<= count; this.bitsAvailable -= count; } } // (size:int):uint }, { key: 'readBits', value: function readBits(size) { var bits = Math.min(this.bitsAvailable, size), // :uint valu = this.word >>> 32 - bits; // :uint if (size > 32) { _logger.logger.error('Cannot read more than 32 bits at a time'); } this.bitsAvailable -= bits; if (this.bitsAvailable > 0) { this.word <<= bits; } else if (this.bytesAvailable > 0) { this.loadWord(); } bits = size - bits; return bits > 0 && this.bitsAvailable ? valu << bits | this.readBits(bits) : valu; } // ():uint }, { key: 'skipLZ', value: function skipLZ() { var leadingZeroCount; // :uint for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) { // the first bit of working word is 1 this.word <<= leadingZeroCount; this.bitsAvailable -= leadingZeroCount; return leadingZeroCount; } } // we exhausted word and still have not found a 1 this.loadWord(); return leadingZeroCount + this.skipLZ(); } // ():void }, { key: 'skipUEG', value: function skipUEG() { this.skipBits(1 + this.skipLZ()); } // ():void }, { key: 'skipEG', value: function skipEG() { this.skipBits(1 + this.skipLZ()); } // ():uint }, { key: 'readUEG', value: function readUEG() { var clz = this.skipLZ(); // :uint return this.readBits(clz + 1) - 1; } // ():int }, { key: 'readEG', value: function readEG() { var valu = this.readUEG(); // :int if (0x01 & valu) { // the number is odd if the low order bit is set return 1 + valu >>> 1; // add 1 to make it even, and divide by 2 } else { return -1 * (valu >>> 1); // divide by two then make it negative } } // Some convenience functions // :Boolean }, { key: 'readBoolean', value: function readBoolean() { return 1 === this.readBits(1); } // ():int }, { key: 'readUByte', value: function readUByte() { return this.readBits(8); } // ():int }, { key: 'readUShort', value: function readUShort() { return this.readBits(16); } // ():int }, { key: 'readUInt', value: function readUInt() { return this.readBits(32); } /** * Advance the ExpGolomb decoder past a scaling list. The scaling * list is optionally transmitted as part of a sequence parameter * set and is not relevant to transmuxing. * @param count {number} the number of entries in this scaling list * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 */ }, { key: 'skipScalingList', value: function skipScalingList(count) { var lastScale = 8, nextScale = 8, j, deltaScale; for (j = 0; j < count; j++) { if (nextScale !== 0) { deltaScale = this.readEG(); nextScale = (lastScale + deltaScale + 256) % 256; } lastScale = nextScale === 0 ? lastScale : nextScale; } } /** * Read a sequence parameter set and return some interesting video * properties. A sequence parameter set is the H264 metadata that * describes the properties of upcoming video frames. * @param data {Uint8Array} the bytes of a sequence parameter set * @return {object} an object with configuration parsed from the * sequence parameter set, including the dimensions of the * associated video frames. */ }, { key: 'readSPS', value: function readSPS() { var frameCropLeftOffset = 0, frameCropRightOffset = 0, frameCropTopOffset = 0, frameCropBottomOffset = 0, sarScale = 1, profileIdc, profileCompat, levelIdc, numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1, picHeightInMapUnitsMinus1, frameMbsOnlyFlag, scalingListCount, i; this.readUByte(); profileIdc = this.readUByte(); // profile_idc profileCompat = this.readBits(5); // constraint_set[0-4]_flag, u(5) this.skipBits(3); // reserved_zero_3bits u(3), levelIdc = this.readUByte(); //level_idc u(8) this.skipUEG(); // seq_parameter_set_id // some profiles have more optional data we don't need if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) { var chromaFormatIdc = this.readUEG(); if (chromaFormatIdc === 3) { this.skipBits(1); // separate_colour_plane_flag } this.skipUEG(); // bit_depth_luma_minus8 this.skipUEG(); // bit_depth_chroma_minus8 this.skipBits(1); // qpprime_y_zero_transform_bypass_flag if (this.readBoolean()) { // seq_scaling_matrix_present_flag scalingListCount = chromaFormatIdc !== 3 ? 8 : 12; for (i = 0; i < scalingListCount; i++) { if (this.readBoolean()) { // seq_scaling_list_present_flag[ i ] if (i < 6) { this.skipScalingList(16); } else { this.skipScalingList(64); } } } } } this.skipUEG(); // log2_max_frame_num_minus4 var picOrderCntType = this.readUEG(); if (picOrderCntType === 0) { this.readUEG(); //log2_max_pic_order_cnt_lsb_minus4 } else if (picOrderCntType === 1) { this.skipBits(1); // delta_pic_order_always_zero_flag this.skipEG(); // offset_for_non_ref_pic this.skipEG(); // offset_for_top_to_bottom_field numRefFramesInPicOrderCntCycle = this.readUEG(); for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) { this.skipEG(); // offset_for_ref_frame[ i ] } } this.skipUEG(); // max_num_ref_frames this.skipBits(1); // gaps_in_frame_num_value_allowed_flag picWidthInMbsMinus1 = this.readUEG(); picHeightInMapUnitsMinus1 = this.readUEG(); frameMbsOnlyFlag = this.readBits(1); if (frameMbsOnlyFlag === 0) { this.skipBits(1); // mb_adaptive_frame_field_flag } this.skipBits(1); // direct_8x8_inference_flag if (this.readBoolean()) { // frame_cropping_flag frameCropLeftOffset = this.readUEG(); frameCropRightOffset = this.readUEG(); frameCropTopOffset = this.readUEG(); frameCropBottomOffset = this.readUEG(); } if (this.readBoolean()) { // vui_parameters_present_flag if (this.readBoolean()) { // aspect_ratio_info_present_flag var sarRatio = void 0; var aspectRatioIdc = this.readUByte(); switch (aspectRatioIdc) { case 1: sarRatio = [1, 1];break; case 2: sarRatio = [12, 11];break; case 3: sarRatio = [10, 11];break; case 4: sarRatio = [16, 11];break; case 5: sarRatio = [40, 33];break; case 6: sarRatio = [24, 11];break; case 7: sarRatio = [20, 11];break; case 8: sarRatio = [32, 11];break; case 9: sarRatio = [80, 33];break; case 10: sarRatio = [18, 11];break; case 11: sarRatio = [15, 11];break; case 12: sarRatio = [64, 33];break; case 13: sarRatio = [160, 99];break; case 14: sarRatio = [4, 3];break; case 15: sarRatio = [3, 2];break; case 16: sarRatio = [2, 1];break; case 255: { sarRatio = [this.readUByte() << 8 | this.readUByte(), this.readUByte() << 8 | this.readUByte()]; break; } } if (sarRatio) { sarScale = sarRatio[0] / sarRatio[1]; } } } return { width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale), height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset) }; } }, { key: 'readSliceType', value: function readSliceType() { // skip NALu type this.readUByte(); // discard first_mb_in_slice this.readUEG(); // return slice_type return this.readUEG(); } }]); return ExpGolomb; }(); exports.default = ExpGolomb; },{"../utils/logger":38}],18:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * ID3 parser */ var _logger = require('../utils/logger'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } //import Hex from '../utils/hex'; var ID3 = function () { function ID3(data) { _classCallCheck(this, ID3); this._hasTimeStamp = false; var offset = 0, byte1, byte2, byte3, byte4, tagSize, endPos, header, len; do { header = this.readUTF(data, offset, 3); offset += 3; // first check for ID3 header if (header === 'ID3') { // skip 24 bits offset += 3; // retrieve tag(s) length byte1 = data[offset++] & 0x7f; byte2 = data[offset++] & 0x7f; byte3 = data[offset++] & 0x7f; byte4 = data[offset++] & 0x7f; tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4; endPos = offset + tagSize; //logger.log(`ID3 tag found, size/end: ${tagSize}/${endPos}`); // read ID3 tags this._parseID3Frames(data, offset, endPos); offset = endPos; } else if (header === '3DI') { // http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer offset += 7; _logger.logger.log('3DI footer found, end: ' + offset); } else { offset -= 3; len = offset; if (len) { //logger.log(`ID3 len: ${len}`); if (!this.hasTimeStamp) { _logger.logger.warn('ID3 tag found, but no timestamp'); } this._length = len; this._payload = data.subarray(0, len); } return; } } while (true); } _createClass(ID3, [{ key: 'readUTF', value: function readUTF(data, start, len) { var result = '', offset = start, end = start + len; do { result += String.fromCharCode(data[offset++]); } while (offset < end); return result; } }, { key: '_parseID3Frames', value: function _parseID3Frames(data, offset, endPos) { var tagId, tagLen, tagStart, tagFlags, timestamp; while (offset + 8 <= endPos) { tagId = this.readUTF(data, offset, 4); offset += 4; tagLen = data[offset++] << 24 + data[offset++] << 16 + data[offset++] << 8 + data[offset++]; tagFlags = data[offset++] << 8 + data[offset++]; tagStart = offset; //logger.log("ID3 tag id:" + tagId); switch (tagId) { case 'PRIV': //logger.log('parse frame:' + Hex.hexDump(data.subarray(offset,endPos))); // owner should be "com.apple.streaming.transportStreamTimestamp" if (this.readUTF(data, offset, 44) === 'com.apple.streaming.transportStreamTimestamp') { offset += 44; // smelling even better ! we found the right descriptor // skip null character (string end) + 3 first bytes offset += 4; // timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero. var pts33Bit = data[offset++] & 0x1; this._hasTimeStamp = true; timestamp = ((data[offset++] << 23) + (data[offset++] << 15) + (data[offset++] << 7) + data[offset++]) / 45; if (pts33Bit) { timestamp += 47721858.84; // 2^32 / 90 } timestamp = Math.round(timestamp); _logger.logger.trace('ID3 timestamp found: ' + timestamp); this._timeStamp = timestamp; } break; default: break; } } } }, { key: 'hasTimeStamp', get: function get() { return this._hasTimeStamp; } }, { key: 'timeStamp', get: function get() { return this._timeStamp; } }, { key: 'length', get: function get() { return this._length; } }, { key: 'payload', get: function get() { return this._payload; } }]); return ID3; }(); exports.default = ID3; },{"../utils/logger":38}],19:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * highly optimized TS demuxer: * parse PAT, PMT * extract PES packet from audio and video PIDs * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet * trigger the remuxer upon parsing completion * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource. * it also controls the remuxing process : * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state. */ // import Hex from '../utils/hex'; var _adts = require('./adts'); var _adts2 = _interopRequireDefault(_adts); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _expGolomb = require('./exp-golomb'); var _expGolomb2 = _interopRequireDefault(_expGolomb); var _logger = require('../utils/logger'); var _errors = require('../errors'); require('../utils/polyfill'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var TSDemuxer = function () { function TSDemuxer(observer, remuxerClass, config, typeSupported) { _classCallCheck(this, TSDemuxer); this.observer = observer; this.remuxerClass = remuxerClass; this.config = config; this.typeSupported = typeSupported; this.lastCC = 0; this._setEmptyTracks(); this._clearAllData(); this.remuxer = new this.remuxerClass(observer, config, typeSupported); } _createClass(TSDemuxer, [{ key: '_setEmptyTracks', value: function _setEmptyTracks() { var track = void 0; if (track = this._avcTrack) { if (track.sps) { track.savedSps = track.sps; } if (track.pps) { track.savedPps = track.pps; } } this._avcTrack = Object.assign({}, this._avcTrack, { container: 'video/mp2t', type: 'video', samples: [], len: 0, nbNalu: 0, sps: undefined, pps: undefined }); this._aacTrack = Object.assign({}, this._aacTrack, { container: 'video/mp2t', type: 'audio', samples: [], len: 0, isAAC: true }); this._id3Track = Object.assign({}, this._id3Track, { type: 'id3', samples: [], len: 0 }); this._txtTrack = Object.assign({}, this._txtTrack, { type: 'text', samples: [], len: 0 }); this._avcTrack.sequenceNumber = this._avcTrack.sequenceNumber | 0; this._aacTrack.sequenceNumber = this._aacTrack.sequenceNumber | 0; this._id3Track.sequenceNumber = this._id3Track.sequenceNumber | 0; this._txtTrack.sequenceNumber = this._txtTrack.sequenceNumber | 0; } }, { key: '_clearIDs', value: function _clearIDs() { this._aacTrack.id = this._avcTrack.id = this._id3Track.id = this._txtTrack.id = -1; } }, { key: 'switchLevel', value: function switchLevel() { // flush end of previous segment if (this._avcTrack.samples.length) { this.remux(null, false, true, false); } this.pmtParsed = false; this._pmtId = -1; this._setEmptyTracks(); this._clearAllData(); this._clearIDs(); // flush any partial content this.aacOverFlow = null; this.lastAacPTS = null; this.remuxer.switchLevel(); } }, { key: '_clearAvcData', value: function _clearAvcData() { return this._avcData = { data: [], size: 0 }; } }, { key: '_clearAacData', value: function _clearAacData() { return this._aacData = { data: [], size: 0 }; } }, { key: '_clearID3Data', value: function _clearID3Data() { return this._id3Data = { data: [], size: 0 }; } }, { key: '_clearAllData', value: function _clearAllData() { this._clearAvcData(); this._clearAacData(); this._clearID3Data(); } }, { key: 'insertDiscontinuity', value: function insertDiscontinuity() { this.switchLevel(); this.remuxer.insertDiscontinuity(); } // feed incoming data to the front of the parsing pipeline }, { key: 'push', value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurate, first, final, lastSN) { var avcData = this._avcData, aacData = this._aacData, pes, id3Data = this._id3Data, start, len = data.length, stt, pid, atf, info, num, offset, codecsOnly = this.remuxer.passthrough, unknownPIDs = false; this.audioCodec = audioCodec; this.videoCodec = videoCodec; this.timeOffset = timeOffset; this.accurate = accurate; this._duration = duration; this.contiguous = false; this.firstSample = first; if (cc !== this.lastCC) { _logger.logger.log('discontinuity detected'); this.insertDiscontinuity(); this.lastCC = cc; } if (level !== this.lastLevel) { _logger.logger.log('level switch detected'); this.switchLevel(); this.lastLevel = level; } if (sn === this.lastSN + 1 || !first) { this.contiguous = true; } else { // flush any partial content if (this._avcTrack.samples.length) { this.remux(null, false, true, false); } this.aacOverFlow = null; this._clearAllData(); this._setEmptyTracks(); } if (first) { this.lastContiguous = sn === this.lastSN + 1; this.fragStats = { keyFrames: 0, dropped: 0, segment: sn, level: level, notFirstKeyframe: 0 }; this.remuxAVCCount = this.remuxAACCount = 0; this.fragStartPts = this.fragStartDts = this.gopStartDTS = undefined; this.fragStartAVCPos = this._avcTrack.samples.length; this.fragStartAACPos = this._aacTrack.samples.length; this.nextAvcDts = this.contiguous ? this.remuxer.nextAvcDts : this.timeOffset * this.remuxer.PES_TIMESCALE; } this.currentSN = sn; var avcId = this._avcTrack.id, aacId = this._aacTrack.id, id3Id = this._id3Track.id; // don't parse last TS packet if incomplete len -= len % 188; // loop through TS packets for (start = 0, num = 0; start < len; start += 188) { if (data[start] === 0x47) { stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1] pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2]; atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header. if (atf > 1) { offset = start + 5 + data[start + 4]; // continue if there is only adaptation field if (offset === start + 188) { continue; } } else { offset = start + 4; } switch (pid) { case avcId: if (stt) { if (pes = this._parsePES(avcData)) { this._parseAVCPES(pes); if (codecsOnly) { // if we have video codec info AND // if audio PID is undefined OR if we have audio codec info, // we have all codec info ! if (this._avcTrack.codec && (aacId === -1 || this._aacTrack.codec)) { this.remux(data); return; } } } avcData = this._clearAvcData(); } avcData.data.push(data.subarray(offset, start + 188)); avcData.size += start + 188 - offset; break; case aacId: if (stt) { if (pes = this._parsePES(aacData)) { if (this._aacTrack.isAAC) { this._parseAACPES(pes); } else { this._parseMPEGPES(pes); } if (codecsOnly) { // here we now that we have audio codec info // if video PID is undefined OR if we have video codec info, // we have all codec infos ! if (this._aacTrack.codec && (avcId === -1 || this._avcTrack.codec)) { this.remux(data); return; } } } aacData = this._clearAacData(); } aacData.data.push(data.subarray(offset, start + 188)); aacData.size += start + 188 - offset; break; case id3Id: if (stt) { if (pes = this._parsePES(id3Data)) { this._parseID3PES(pes); } id3Data = this._clearID3Data(); } id3Data.data.push(data.subarray(offset, start + 188)); id3Data.size += start + 188 - offset; break; case 0: if (stt) { offset += data[offset] + 1; } this._parsePAT(data, offset); break; case this._pmtId: if (stt) { offset += data[offset] + 1; } this._parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true); avcId = this._avcTrack.id; aacId = this._aacTrack.id; id3Id = this._id3Track.id; if (unknownPIDs && !this.pmtParsed) { _logger.logger.log('reparse from beginning'); unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0 start = -188; } this.pmtParsed = true; break; case 17: case 0x1fff: break; default: unknownPIDs = true; break; } } else { if (num === 0) { var i = void 0, _len = data.length; info = 'len:' + _len + ' ['; for (i = 0, _len = Math.min(_len, 10); i < _len; i++) { if (i) { info += ','; } info += data[start + i]; } info += '..]'; } num++; } } if (num) { this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47 sn:' + sn + ' samples: ' + num + ' ' + info }); } // parse last PES packet if (final) { if (avcData.size && (pes = this._parsePES(avcData))) { this._parseAVCPES(pes); this._clearAvcData(); } if (aacData.size && (pes = this._parsePES(aacData))) { if (this._aacTrack.isAAC) { this._parseAACPES(pes); } else { this._parseMPEGPES(pes); } this._clearAacData(); } if (id3Data.size && (pes = this._parsePES(id3Data))) { this._parseID3PES(pes); this._clearID3Data(); } this.lastSN = sn; } if (this.fragStartPts === undefined && this._avcTrack.samples.length > this.fragStartAVCPos) { this.fragStartPts = this._avcTrack.samples[this.fragStartAVCPos].pts; this.fragStartDts = this._avcTrack.samples[this.fragStartAVCPos].dts; } if (this.gopStartDTS === undefined && this._avcTrack.samples.length) { this.gopStartDTS = this._avcTrack.samples[0].dts; } this.remux(null, final, final && sn === lastSN, true); if (final) { this.observer.trigger(_events2.default.FRAG_STATISTICS, this.fragStats); } } }, { key: '_recalcTrack', value: function _recalcTrack(track) { if (track.hasOwnProperty('nbNalu')) { track.nbNalu = 0; } track.len = 0; for (var i = 0; i < track.samples.length; i++) { var sample = track.samples[i]; track.len += ((sample.units && sample.units.length) | 0) + ((sample.unit && sample.unit.length) | 0) + (sample.len | 0) + ((sample.bytes && sample.bytes.length) | 0); if (track.hasOwnProperty('nbNalu')) { track.nbNalu += sample.units.units.length; } } } }, { key: '_filterSamples', value: function _filterSamples(track, end, _save) { var _new = []; for (var i = 0; i < track.samples.length; i++) { var sample = track.samples[i]; var sampleTime = sample.dts || sample.pts; if (sampleTime <= end) { _new.push(sample); } else { _save.push(sample); } } track.samples = _new; this._recalcTrack(track); } }, { key: 'remux', value: function remux(data, final, flush, lastSegment) { var _saveAVCSamples = [], _saveAACSamples = [], _saveID3Samples = [], _saveTextSamples = [], maxk, samples = this._avcTrack.samples, startPTS, endPTS, gopEndDTS, initDTS; var timescale = this.remuxer.PES_TIMESCALE; if (samples.length && final) { this.fragStats.PTSDTSshift = ((this.fragStartPts === undefined ? samples[0].pts : this.fragStartPts) - (this.fragStartDts === undefined ? samples[0].dts : this.fragStartDts)) / timescale; initDTS = this.remuxer._initDTS === undefined ? samples[0].dts - timescale * this.timeOffset : this.remuxer._initDTS; var startDTS = Math.max(this.remuxer._PTSNormalize((this.gopStartDTS === undefined ? samples[0].dts : this.gopStartDTS) - initDTS, this.nextAvcDts), 0); var sample = samples[samples.length - 1]; var videoStartPTS = Math.max(this.remuxer._PTSNormalize((this.fragStartPts === undefined ? samples[0].pts : this.fragStartPts) - initDTS, this.nextAvcDts), 0) / timescale; var videoEndPTS = Math.max(this.remuxer._PTSNormalize(sample.pts - initDTS, this.nextAvcDts), 0) / timescale; if (this.accurate && Math.abs(startDTS - this.nextAvcDts) > 90) { videoStartPTS -= (startDTS - this.nextAvcDts) / timescale; } if (samples.length + this.remuxAVCCount > this.fragStartAVCPos + 1 && this.fragStartDts !== undefined) { var fragStartDts = this.remuxer._PTSNormalize(this.fragStartDts, this.nextAvcDts); var sampleDts = this.remuxer._PTSNormalize(sample.dts, this.nextAvcDts); videoEndPTS += (sampleDts - fragStartDts) / (samples.length + this.remuxAVCCount - this.fragStartAVCPos - 1) / timescale; } startPTS = videoStartPTS; endPTS = videoEndPTS; if (this._aacTrack.audiosamplerate) { var expectedSampleDuration = 1024 / this._aacTrack.audiosamplerate; var remuxAACCount = this._aacTrack.samples.length; var nextAacPTS = (this.lastContiguous !== undefined && this.lastContiguous || this.contiguous && this.remuxAACCount) && this.remuxer.nextAacPts ? this.remuxer.nextAacPts / timescale : this.accurate ? this.timeOffset : startPTS; startPTS = Math.max(startPTS, nextAacPTS + (this.fragStartAACPos - this.remuxAACCount) * expectedSampleDuration); if (remuxAACCount) { endPTS = Math.min(endPTS, nextAacPTS + expectedSampleDuration * remuxAACCount); } var AVUnsync = void 0; if ((AVUnsync = endPTS - startPTS + videoStartPTS - videoEndPTS) > 0.2) { this.fragStats.AVUnsync = AVUnsync; } } // console.log(`parsed total ${startPTS}/${endPTS} video ${videoStartPTS}/${videoEndPTS} shift ${this.fragStats.PTSDTSshift}`); } if (!flush) { // save samples and break by GOP for (maxk = samples.length - 1; maxk > 0; maxk--) { if (samples[maxk].key) { if (maxk && (samples[maxk - 1].dts - initDTS) / timescale < startPTS) { maxk = 0; } break; } } if (maxk > 0) { _saveAVCSamples = samples.slice(maxk); this._avcTrack.samples = samples.slice(0, maxk); gopEndDTS = this._avcTrack.samples[maxk - 1].dts; this._recalcTrack(this._avcTrack); this._filterSamples(this._aacTrack, gopEndDTS, _saveAACSamples); this._filterSamples(this._id3Track, gopEndDTS, _saveID3Samples); this._filterSamples(this._txtTrack, gopEndDTS, _saveTextSamples); } } if ((flush || final && !this.remuxAVCCount) && this._avcTrack.samples.length + this._aacTrack.samples.length || maxk > 0) { this.remuxAVCCount += this._avcTrack.samples.length; this.remuxAACCount += this._aacTrack.samples.length; this.remuxer.remux(this._aacTrack, this._avcTrack, this._id3Track, this._txtTrack, flush && this.nextStartPts ? this.nextStartPts : this.timeOffset, flush && !lastSegment || (this.lastContiguous !== undefined ? this.lastContiguous : this.contiguous), this.accurate, data, flush, this.fragStats); this.lastContiguous = undefined; this.nextStartPts = this.remuxer.endPTS; this._avcTrack.samples = _saveAVCSamples; this._aacTrack.samples = _saveAACSamples; this._id3Track.samples = _saveID3Samples; this._txtTrack.samples = _saveTextSamples; this._recalcTrack(this._avcTrack); this._recalcTrack(this._aacTrack); this._recalcTrack(this._id3Track); this._recalcTrack(this._txtTrack); } //notify end of parsing if (final) { var lastGopPTS = Math.min(this.remuxer.nextAvcDts, this.remuxer.nextAacPts) / timescale; this.observer.trigger(_events2.default.FRAG_PARSED, { startPTS: startPTS, endPTS: endPTS, PTSDTSshift: this.fragStats.PTSDTSshift, lastGopPTS: lastGopPTS }); } } }, { key: 'destroy', value: function destroy() { this.switchLevel(); this._initPTS = this._initDTS = undefined; this._duration = 0; } }, { key: '_parsePAT', value: function _parsePAT(data, offset) { // skip the PSI header and parse the first PMT entry this._pmtId = (data[offset + 10] & 0x1F) << 8 | data[offset + 11]; //logger.log('PMT PID:' + this._pmtId); } }, { key: '_parsePMT', value: function _parsePMT(data, offset, mpegSupported) { var sectionLength, tableEnd, programInfoLength, pid; sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2]; tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how // long the program info descriptors are programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table offset += 12 + programInfoLength; while (offset < tableEnd) { pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2]; switch (data[offset]) { // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio) case 0x0f: //logger.log('AAC PID:' + pid); if (this._aacTrack.id === -1) { this._aacTrack.id = pid; } break; // Packetized metadata (ID3) case 0x15: //logger.log('ID3 PID:' + pid); if (this._id3Track.id === -1) { this._id3Track.id = pid; } break; // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video) case 0x1b: //logger.log('AVC PID:' + pid); if (this._avcTrack.id === -1) { this._avcTrack.id = pid; } break; // ISO/IEC 11172-3 (MPEG-1 audio) // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio) case 0x03: case 0x04: _logger.logger.log('MPEG PID:' + pid); if (!mpegSupported) { _logger.logger.log('MPEG audio found, not supported in this browser for now'); } else { if (this._aacTrack.id === -1) { this._aacTrack.id = pid; } this._aacTrack.isAAC = false; } break; case 0x24: this.fragStats.HEVC = (this.fragStats.HEVC | 0) + 1; _logger.logger.warn('HEVC stream type found, not supported for now'); break; default: this.fragStats.unknownStream = (this.fragStats.unknownStream | 0) + 1; _logger.logger.log('unkown stream type:' + data[offset]); break; } // move to the next table entry // skip past the elementary stream descriptors, if present offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5; } } }, { key: '_parsePES', value: function _parsePES(stream) { var i = 0, frag, pesFlags, pesPrefix, pesLen, pesHdrLen, pesData, pesPts, pesDts, payloadStartOffset, data = stream.data; // safety check if (!stream || stream.size === 0) { return null; } // we might need up to 19 bytes to read PES header // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes // usually only one merge is needed (and this is rare ...) while (data[0].length < 19 && data.length > 1) { var newData = new Uint8Array(data[0].length + data[1].length); newData.set(data[0]); newData.set(data[1], data[0].length); data[0] = newData; data.splice(1, 1); } //retrieve PTS/DTS from first fragment frag = data[0]; pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2]; if (pesPrefix === 1) { pesLen = (frag[4] << 8) + frag[5]; if (pesLen && pesLen > stream.size - 6) { return null; } pesFlags = frag[7]; if (pesFlags & 0xC0) { /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html as PTS / DTS is 33 bit we cannot use bitwise operator in JS, as Bitwise operators treat their operands as a sequence of 32 bits */ pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29 (frag[10] & 0xFF) * 4194304 + // 1 << 22 (frag[11] & 0xFE) * 16384 + // 1 << 14 (frag[12] & 0xFF) * 128 + // 1 << 7 (frag[13] & 0xFE) / 2; // check if greater than 2^32 -1 if (pesPts > 4294967295) { // decrement 2^33 pesPts -= 8589934592; } if (pesFlags & 0x40) { pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29 (frag[15] & 0xFF) * 4194304 + // 1 << 22 (frag[16] & 0xFE) * 16384 + // 1 << 14 (frag[17] & 0xFF) * 128 + // 1 << 7 (frag[18] & 0xFE) / 2; // check if greater than 2^32 -1 if (pesDts > 4294967295) { // decrement 2^33 pesDts -= 8589934592; } if (pesPts - pesDts > 60 * 90000) { _logger.logger.warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them'); pesPts = pesDts; } } else { pesDts = pesPts; } } pesHdrLen = frag[8]; payloadStartOffset = pesHdrLen + 9; stream.size -= payloadStartOffset; //reassemble PES packet pesData = new Uint8Array(stream.size); while (data.length) { frag = data.shift(); var len = frag.byteLength; if (payloadStartOffset) { if (payloadStartOffset > len) { // trim full frag if PES header bigger than frag payloadStartOffset -= len; continue; } else { // trim partial frag if PES header smaller than frag frag = frag.subarray(payloadStartOffset); len -= payloadStartOffset; payloadStartOffset = 0; } } pesData.set(frag, i); i += len; } if (pesLen) { // payload size : remove PES header + PES extension pesLen -= pesHdrLen + 3; } return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen }; } else { return null; } } }, { key: '_parseAVCPES', value: function _parseAVCPES(pes) { var _this = this; var track = this._avcTrack, samples = track.samples, units = this._parseAVCNALu(pes.data), units2 = [], debug = false, key = false, length = 0, expGolombDecoder, avcSample, push, hlsConfig = this.config, i; // no NALu found if (units.length === 0 && samples.length > 0) { // append pes.data to previous NAL unit var lastavcSample = samples[samples.length - 1]; var lastUnit = lastavcSample.units.units[lastavcSample.units.units.length - 1]; var tmp = new Uint8Array(lastUnit.data.byteLength + pes.data.byteLength); tmp.set(lastUnit.data, 0); tmp.set(pes.data, lastUnit.data.byteLength); lastUnit.data = tmp; lastavcSample.units.length += pes.data.byteLength; track.len += pes.data.byteLength; } //free pes.data to save up some memory pes.data = null; var debugString = ''; units.forEach(function (unit) { switch (unit.type) { //NDR case 1: push = true; if (debug) { debugString += 'NDR '; } // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR var data = unit.data; if (data.length > 1) { var sliceType = new _expGolomb2.default(data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice. // I slice: A slice that is not an SI slice that is decoded using intra prediction only. //if (sliceType === 2 || sliceType === 7) { if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) { key = true; } } break; //IDR case 5: push = true; if (debug) { debugString += 'IDR '; } key = true; break; //SEI case 6: push = true; if (debug) { debugString += 'SEI '; } expGolombDecoder = new _expGolomb2.default(_this.discardEPB(unit.data)); // skip frameType expGolombDecoder.readUByte(); var payloadType = 0; var payloadSize = 0; var endOfCaptions = false; var b = 0; while (!endOfCaptions && expGolombDecoder.wholeBytesAvailable() > 1) { payloadType = 0; do { b = expGolombDecoder.readUByte(); payloadType += b; } while (b === 0xFF); // Parse payload size. payloadSize = 0; do { b = expGolombDecoder.readUByte(); payloadSize += b; } while (b === 0xFF); // if SEI recovery_point has been found mark as keyframe if (!hlsConfig.disableSEIkeyframes) { key = key || payloadType === 6; } if (key && !track.sps && track.savedSps) { track.sps = track.savedSps; if (!track.pps && track.savedPps) { track.pps = track.savedPps; } } // TODO: there can be more than one payload in an SEI packet... // TODO: need to read type and size in a while loop to get them all if (payloadType === 4 && expGolombDecoder.wholeBytesAvailable() !== 0) { endOfCaptions = true; var countryCode = expGolombDecoder.readUByte(); if (countryCode === 181) { var providerCode = expGolombDecoder.readUShort(); if (providerCode === 49) { var userStructure = expGolombDecoder.readUInt(); if (userStructure === 0x47413934) { var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet if (userDataType === 3) { var firstByte = expGolombDecoder.readUByte(); var secondByte = expGolombDecoder.readUByte(); var totalCCs = 31 & firstByte; var byteArray = [firstByte, secondByte]; for (i = 0; i < totalCCs; i++) { // 3 bytes per CC byteArray.push(expGolombDecoder.readUByte()); byteArray.push(expGolombDecoder.readUByte()); byteArray.push(expGolombDecoder.readUByte()); } _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray }); } } } } } else if (payloadSize < expGolombDecoder.wholeBytesAvailable()) { for (i = 0; i < payloadSize; i++) { expGolombDecoder.readUByte(); } } } break; //SPS case 7: push = true; if (debug) { debugString += 'SPS '; } if (!track.sps || track.sps === track.savedSps) { track.savedSps = undefined; expGolombDecoder = new _expGolomb2.default(unit.data); var config = expGolombDecoder.readSPS(); track.width = config.width; track.height = config.height; track.sps = [unit.data]; track.duration = _this._duration; var codecarray = unit.data.subarray(1, 4); var codecstring = 'avc1.'; for (i = 0; i < 3; i++) { var h = codecarray[i].toString(16); if (h.length < 2) { h = '0' + h; } codecstring += h; } track.codec = codecstring; } break; //PPS case 8: push = true; if (debug) { debugString += 'PPS '; } if (!track.pps || track.pps === track.savedPps) { track.savedPps = undefined; track.pps = [unit.data]; } break; case 9: push = false; if (debug) { debugString += 'AUD '; } break; // Filler Data case 12: push = false; break; default: push = false; debugString += 'unknown NAL ' + unit.type + ' '; break; } if (push) { units2.push(unit); length += unit.data.byteLength; } }); if (debug || debugString.length) { _logger.logger.log(debugString); } //build sample from PES // Annex B to MP4 conversion to be done if (units2.length) { // only push AVC sample if keyframe already found in this fragment OR // keyframe found in last fragment (track.sps) AND // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous if (key === true || track.sps && (samples.length || this.contiguous)) { avcSample = { units: { units: units2, length: length }, pts: pes.pts, dts: pes.dts, key: key }; if (key) { this.fragStats.keyFrames++; } // logger.log(`avcSample ${units2.length} ${length} ${pes.dts} ${key}`); samples.push(avcSample); track.len += length; track.nbNalu += units2.length; } else { this.fragStats.dropped++; } if (this.firstSample && !key) { this.fragStats.notFirstKeyframe++; } this.firstSample = false; } } }, { key: '_insertSampleInOrder', value: function _insertSampleInOrder(arr, data) { var len = arr.length; if (len > 0) { if (data.pts >= arr[len - 1].pts) { arr.push(data); } else { for (var pos = len - 1; pos >= 0; pos--) { if (data.pts < arr[pos].pts) { arr.splice(pos, 0, data); break; } } } } else { arr.push(data); } } }, { key: '_parseAVCNALu', value: function _parseAVCNALu(array) { var i = 0, len = array.byteLength, value, overflow, state = 0; var units = [], unit, unitType, lastUnitStart, lastUnitType; //logger.log('PES:' + Hex.hexDump(array)); while (i < len) { value = array[i++]; // finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01) switch (state) { case 0: if (value === 0) { state = 1; } break; case 1: if (value === 0) { state = 2; } else { state = 0; } break; case 2: case 3: if (value === 0) { state = 3; } else if (value === 1 && i < len) { unitType = array[i] & 0x1f; //logger.log('find NALU @ offset:' + i + ',type:' + unitType); if (lastUnitStart) { unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType }; //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength); units.push(unit); } else { // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit. overflow = i - state - 1; if (overflow) { var track = this._avcTrack, samples = track.samples; //logger.log('first NALU found with overflow:' + overflow); if (samples.length) { var lastavcSample = samples[samples.length - 1], lastUnits = lastavcSample.units.units, lastUnit = lastUnits[lastUnits.length - 1], tmp = new Uint8Array(lastUnit.data.byteLength + overflow); tmp.set(lastUnit.data, 0); tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength); lastUnit.data = tmp; lastavcSample.units.length += overflow; track.len += overflow; } } } lastUnitStart = i; lastUnitType = unitType; state = 0; } else { state = 0; } break; default: break; } } if (lastUnitStart) { unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType }; units.push(unit); //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength); } return units; } /** * remove Emulation Prevention bytes from a RBSP */ }, { key: 'discardEPB', value: function discardEPB(data) { var length = data.byteLength, EPBPositions = [], i = 1, newLength, newData; // Find all `Emulation Prevention Bytes` while (i < length - 2) { if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) { EPBPositions.push(i + 2); i += 2; } else { i++; } } // If no Emulation Prevention Bytes were found just return the original // array if (EPBPositions.length === 0) { return data; } // Create a new array to hold the NAL unit data newLength = length - EPBPositions.length; newData = new Uint8Array(newLength); var sourceIndex = 0; for (i = 0; i < newLength; sourceIndex++, i++) { if (sourceIndex === EPBPositions[0]) { // Skip this byte sourceIndex++; // Remove this position index EPBPositions.shift(); } newData[i] = data[sourceIndex]; } return newData; } }, { key: '_parseAACPES', value: function _parseAACPES(pes) { var track = this._aacTrack, data = pes.data, pts = pes.pts, startOffset = 0, duration = this._duration, audioCodec = this.audioCodec, aacOverFlow = this.aacOverFlow, lastAacPTS = this.lastAacPTS, config, frameLength, frameDuration, frameIndex, offset, headerLength, stamp, len, aacSample; if (aacOverFlow) { var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength); tmp.set(aacOverFlow, 0); tmp.set(data, aacOverFlow.byteLength); //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`); data = tmp; } // look for ADTS header (0xFFFx) for (offset = startOffset, len = data.length; offset < len - 1; offset++) { if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) { break; } } // if ADTS header does not start straight from the beginning of the PES payload, raise an error if (offset) { var reason, fatal; if (offset < len - 1) { reason = 'AAC PES did not start with ADTS header,offset:' + offset; fatal = false; } else { reason = 'no ADTS header found in AAC PES'; fatal = true; } this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason }); if (fatal) { return; } } config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec); if (track.audiosamplerate !== config.samplerate || track.codec !== config.codec) { track.config = config.config; track.audiosamplerate = config.samplerate; track.channelCount = config.channelCount; track.codec = config.codec; track.duration = duration; _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount); } frameIndex = 0; frameDuration = 1024 * 90000 / track.audiosamplerate; // if last AAC frame is overflowing, we should ensure timestamps are contiguous: // first sample PTS should be equal to last sample PTS + frameDuration if (aacOverFlow && lastAacPTS) { var newPTS = lastAacPTS + frameDuration; if (Math.abs(newPTS - pts) > 1) { _logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90)); pts = newPTS; } } while (offset + 5 < len) { // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9; // retrieve frame size frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5; frameLength -= headerLength; //stamp = pes.pts; if (frameLength > 0 && offset + headerLength + frameLength <= len) { stamp = pts + frameIndex * frameDuration; //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp }; track.samples.push(aacSample); track.len += frameLength; offset += frameLength + headerLength; frameIndex++; // look for ADTS header (0xFFFx) for (; offset < len - 1; offset++) { if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) { break; } } } else { break; } } if (offset < len) { aacOverFlow = data.subarray(offset, len); //logger.log(`AAC: overflow detected:${len-offset}`); } else { aacOverFlow = null; } this.aacOverFlow = aacOverFlow; this.lastAacPTS = stamp; } }, { key: '_parseMPEGPES', value: function _parseMPEGPES(pes) { var data = pes.data; var pts = pes.pts; var length = data.length; var frameIndex = 0; var offset = 0; var parsed; while (offset < length && (parsed = this._parseMpeg(data, offset, length, frameIndex++, pts)) > 0) { offset += parsed; } } }, { key: '_onMpegFrame', value: function _onMpegFrame(data, bitRate, sampleRate, channelCount, frameIndex, pts) { var frameDuration = 1152 / sampleRate * 1000; var stamp = pts + frameIndex * frameDuration; var track = this._aacTrack; track.config = []; track.channelCount = channelCount; track.audiosamplerate = sampleRate; track.duration = this._duration; track.samples.push({ unit: data, pts: stamp, dts: stamp }); track.len += data.length; } }, { key: '_onMpegNoise', value: function _onMpegNoise(data) { _logger.logger.warn('mpeg audio has noise: ' + data.length + ' bytes'); } }, { key: '_parseMpeg', value: function _parseMpeg(data, start, end, frameIndex, pts) { var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000]; if (start + 2 > end) { return -1; // we need at least 2 bytes to detect sync pattern } if (data[start] === 0xFF || (data[start + 1] & 0xE0) === 0xE0) { // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference if (start + 24 > end) { return -1; } var headerB = data[start + 1] >> 3 & 3; var headerC = data[start + 1] >> 1 & 3; var headerE = data[start + 2] >> 4 & 15; var headerF = data[start + 2] >> 2 & 3; var headerG = !!(data[start + 2] & 2); if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) { var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4; var bitRate = BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000; var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2; var sampleRate = SamplingRateMap[columnInSampleRates * 3 + headerF]; var padding = headerG ? 1 : 0; var channelCount = data[start + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) var frameLength = headerC === 3 ? (headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding << 2 : (headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding | 0; if (start + frameLength > end) { return -1; } if (this._onMpegFrame) { this._onMpegFrame(data.subarray(start, start + frameLength), bitRate, sampleRate, channelCount, frameIndex, pts); } return frameLength; } } // noise or ID3, trying to skip var offset = start + 2; while (offset < end) { if (data[offset - 1] === 0xFF && (data[offset] & 0xE0) === 0xE0) { // sync pattern is found if (this._onMpegNoise) { this._onMpegNoise(data.subarray(start, offset - 1)); } return offset - start - 1; } offset++; } return -1; } }, { key: '_parseID3PES', value: function _parseID3PES(pes) { this._id3Track.samples.push(pes); } }], [{ key: 'probe', value: function probe(data) { // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47 return data.length >= 3 * 188 && data[0] === 0x47 && data[188] === 0x47 && data[2 * 188] === 0x47; } }]); return TSDemuxer; }(); exports.default = TSDemuxer; },{"../errors":20,"../events":22,"../utils/logger":38,"../utils/polyfill":39,"./adts":13,"./exp-golomb":17}],20:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var ErrorTypes = exports.ErrorTypes = { // Identifier for a network error (loading error / timeout ...) NETWORK_ERROR: 'networkError', // Identifier for a media Error (video/parsing/mediasource error) MEDIA_ERROR: 'mediaError', // Identifier for all other errors OTHER_ERROR: 'otherError' }; var ErrorDetails = exports.ErrorDetails = { // Identifier for a manifest load error - data: { url : faulty URL, response : XHR response} MANIFEST_LOAD_ERROR: 'manifestLoadError', // Identifier for a manifest load timeout - data: { url : faulty URL, response : XHR response} MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut', // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason} MANIFEST_PARSING_ERROR: 'manifestParsingError', // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason} MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError', // Identifier for playlist load error - data: { url : faulty URL, response : XHR response} LEVEL_LOAD_ERROR: 'levelLoadError', // Identifier for playlist load timeout - data: { url : faulty URL, response : XHR response} LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut', // Identifier for a level switch error - data: { level : faulty level Id, event : error description} LEVEL_SWITCH_ERROR: 'levelSwitchError', // Identifier for fragment load error - data: { frag : fragment object, response : XHR response} FRAG_LOAD_ERROR: 'fragLoadError', // Identifier for fragment loop loading error - data: { frag : fragment object} FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError', // Identifier for fragment load timeout error - data: { frag : fragment object} FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut', // Identifier for a fragment decryption error event - data: parsing error description FRAG_DECRYPT_ERROR: 'fragDecryptError', // Identifier for a fragment parsing error event - data: parsing error description FRAG_PARSING_ERROR: 'fragParsingError', // Identifier for decrypt key load error - data: { frag : fragment object, response : XHR response} KEY_LOAD_ERROR: 'keyLoadError', // Identifier for decrypt key load timeout error - data: { frag : fragment object} KEY_LOAD_TIMEOUT: 'keyLoadTimeOut', // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType } BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError', // Identifier for a buffer append error - data: append error description BUFFER_APPEND_ERROR: 'bufferAppendError', // Identifier for a buffer appending error event - data: appending error description BUFFER_APPENDING_ERROR: 'bufferAppendingError', // Identifier for a buffer stalled error event BUFFER_STALLED_ERROR: 'bufferStalledError', // Identifier for a buffer full event BUFFER_FULL_ERROR: 'bufferFullError', // Identifier for a buffer seek over hole event BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole', // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area) BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall', // Identifier for an internal exception happening inside hls.js while handling an event INTERNAL_EXCEPTION: 'internalException' }; },{}],21:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* * * All objects in the event handling chain should inherit from this class * */ var _logger = require('./utils/logger'); var _errors = require('./errors'); var _events = require('./events'); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var EventHandler = function () { function EventHandler(hls) { _classCallCheck(this, EventHandler); this.hls = hls; this.onEvent = this.onEvent.bind(this); for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { events[_key - 1] = arguments[_key]; } this.handledEvents = events; this.useGenericHandler = true; this.registerListeners(); } _createClass(EventHandler, [{ key: 'destroy', value: function destroy() { this.unregisterListeners(); } }, { key: 'isEventHandler', value: function isEventHandler() { return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function'; } }, { key: 'registerListeners', value: function registerListeners() { if (this.isEventHandler()) { this.handledEvents.forEach(function (event) { if (event === 'hlsEventGeneric') { throw new Error('Forbidden event name: ' + event); } this.hls.on(event, this.onEvent); }.bind(this)); } } }, { key: 'unregisterListeners', value: function unregisterListeners() { if (this.isEventHandler()) { this.handledEvents.forEach(function (event) { this.hls.off(event, this.onEvent); }.bind(this)); } } /** * arguments: event (string), data (any) */ }, { key: 'onEvent', value: function onEvent(event, data) { this.onEventGeneric(event, data); } }, { key: 'onEventGeneric', value: function onEventGeneric(event, data) { var eventToFunction = function eventToFunction(event, data) { var funcName = 'on' + event.replace('hls', ''); if (typeof this[funcName] !== 'function') { throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')'); } return this[funcName].bind(this, data); }; try { eventToFunction.call(this, event, data).call(); } catch (err) { _logger.logger.error('internal error happened while processing ' + event + ':' + err.message); this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err }); } } }]); return EventHandler; }(); exports.default = EventHandler; },{"./errors":20,"./events":22,"./utils/logger":38}],22:[function(require,module,exports){ 'use strict'; module.exports = { // fired by api when new player instance created - data: { instance } PLAYER_CREATED: 'hlsPlayerCreated', // fired by api when player instance gets destroyed - data: { instance } PLAYER_DESTROYED: 'hlsPlayerDestroyed', // fired before MediaSource is attaching to media element - data: { media } MEDIA_ATTACHING: 'hlsMediaAttaching', // fired when MediaSource has been succesfully attached to media element - data: { } MEDIA_ATTACHED: 'hlsMediaAttached', // fired before detaching MediaSource from media element - data: { } MEDIA_DETACHING: 'hlsMediaDetaching', // fired when MediaSource has been detached from media element - data: { } MEDIA_DETACHED: 'hlsMediaDetached', // fired when we buffer is going to be resetted BUFFER_RESET: 'hlsBufferReset', // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }} BUFFER_CODECS: 'hlsBufferCodecs', // fired when we append a segment to the buffer - data: { segment: segment object } BUFFER_APPENDING: 'hlsBufferAppending', // fired when the stream is finished and we want to notify the media buffer that there will be no more data BUFFER_EOS: 'hlsBufferEos', // fired when the media buffer should be flushed - data {startOffset, endOffset} BUFFER_FLUSHING: 'hlsBufferFlushing', // fired when the media has been flushed BUFFER_FLUSHED: 'hlsBufferFlushed', // fired to signal that a manifest loading starts - data: { url : manifestURL} MANIFEST_LOADING: 'hlsManifestLoading', // fired after manifest has been loaded - data: { levels : [available quality levels] , url : manifestURL, stats : { trequest, tfirst, tload, mtime}} MANIFEST_LOADED: 'hlsManifestLoaded', // fired after manifest has been parsed - data: { levels : [available quality levels] , firstLevel : index of first quality level appearing in Manifest} MANIFEST_PARSED: 'hlsManifestParsed', // fired when a level playlist loading starts - data: { url : level URL level : id of level being loaded} LEVEL_LOADING: 'hlsLevelLoading', // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} } LEVEL_LOADED: 'hlsLevelLoaded', // fired when a level's details have been updated based on previous details, after it has been loaded. - data: { details : levelDetails object, level : id of updated level } LEVEL_UPDATED: 'hlsLevelUpdated', // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment } LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated', // fired when a level switch is requested - data: { level : id of new level } LEVEL_SWITCH: 'hlsLevelSwitch', // fired when a fragment loading starts - data: { frag : fragment object} FRAG_LOADING: 'hlsFragLoading', // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded}} FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress', // Identifier for fragment load aborting for emergency switch down - data: {frag : fragment object} FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted', // fired when a fragment chunk loading is completed - data: { frag : fragment object, payload : fragment payload} FRAG_CHUNK_LOADED: 'hlsFragChunkLoaded', // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}} FRAG_LOADED: 'hlsFragLoaded', // fired when Init Segment has been extracted from fragment - data: { moov : moov MP4 box, codecs : codecs found while parsing fragment} FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment', // fired when parsing sei text is completed - data: { samples : [ sei samples pes ] } FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata', // fired when parsing id3 is completed - data: { samples : [ id3 samples pes ] } FRAG_PARSING_METADATA: 'hlsFragParsingMetadata', // fired when data have been extracted from fragment - data: { data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null} FRAG_PARSING_DATA: 'hlsFragParsingData', // fired when fragment parsing is completed - data: undefined FRAG_PARSED: 'hlsFragParsed', // fired when there are skipped frames in the beginning of frag FRAG_STATISTICS: 'hlsFragStatistics', // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} } FRAG_BUFFERED: 'hlsFragBuffered', // fired when fragment matching with current media position is changing - data : { frag : fragment object } FRAG_CHANGED: 'hlsFragChanged', // fired when fragment chunks passed to media buffer FRAG_APPENDING: 'hlsFragAppending', // fired when fragment appended to media buffer FRAG_APPENDED: 'hlsFragAppended', // Identifier for a FPS drop event - data: {curentDropped, currentDecoded, totalDroppedFrames} FPS_DROP: 'hlsFpsDrop', //triggered when FPS drop triggers auto level capping - data: {level, droppedlevel} FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping', // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data} ERROR: 'hlsError', // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example DESTROYING: 'hlsDestroying', // fired when a decrypt key loading starts - data: { frag : fragment object} KEY_LOADING: 'hlsKeyLoading', // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length}} KEY_LOADED: 'hlsKeyLoaded', // fired upon stream controller state transitions - data: {previousState, nextState} STREAM_STATE_TRANSITION: 'hlsStreamStateTransition', DEMUXER_QUEUE_EMPTY: 'hlsDemuxerQueueEmpty', // fired when playback is stalled on low/high buffer BUF_STATISTICS: 'hlsBufStatistics' }; },{}],23:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * AAC helper */ var AAC = function () { function AAC() { _classCallCheck(this, AAC); } _createClass(AAC, null, [{ key: "getSilentFrame", value: function getSilentFrame(channelCount) { if (channelCount === 1) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]); } else if (channelCount === 2) { return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]); } else if (channelCount === 3) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]); } else if (channelCount === 4) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]); } else if (channelCount === 5) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]); } else if (channelCount === 6) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]); } return null; } }]); return AAC; }(); exports.default = AAC; },{}],24:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Buffer Helper class, providing methods dealing buffer length retrieval */ var BufferHelper = function () { function BufferHelper() { _classCallCheck(this, BufferHelper); } _createClass(BufferHelper, null, [{ key: "isBuffered", value: function isBuffered(media, position) { if (media) { var buffered = media.buffered; for (var i = 0; i < buffered.length; i++) { if (position >= buffered.start(i) && position <= buffered.end(i)) { return true; } } } return false; } }, { key: "bufferInfo", value: function bufferInfo(media, pos, maxHoleDuration) { if (media) { var vbuffered = media.buffered, buffered = [], i; for (i = 0; i < vbuffered.length; i++) { buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) }); } return this.bufferedInfo(buffered, pos, maxHoleDuration); } else { return { len: 0, start: 0, end: 0, nextStart: undefined }; } } }, { key: "bufferedInfo", value: function bufferedInfo(buffered, pos, maxHoleDuration) { var buffered2 = [], // bufferStart and bufferEnd are buffer boundaries around current video position bufferLen, bufferStart, bufferEnd, bufferStartNext, i; // sort on buffer.start/smaller end (IE does not always return sorted buffered range) buffered.sort(function (a, b) { var diff = a.start - b.start; if (diff) { return diff; } else { return b.end - a.end; } }); // there might be some small holes between buffer time range // consider that holes smaller than maxHoleDuration are irrelevant and build another // buffer time range representations that discards those holes for (i = 0; i < buffered.length; i++) { var buf2len = buffered2.length; if (buf2len) { var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative) if (buffered[i].start - buf2end < maxHoleDuration) { // merge overlapping time ranges // update lastRange.end only if smaller than item.end // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end) // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15]) if (buffered[i].end > buf2end) { buffered2[buf2len - 1].end = buffered[i].end; } } else { // big hole buffered2.push(buffered[i]); } } else { // first value buffered2.push(buffered[i]); } } for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) { var start = buffered2[i].start, end = buffered2[i].end; //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i)); if (pos + maxHoleDuration >= start && pos < end) { // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length bufferStart = start; bufferEnd = end; bufferLen = bufferEnd - pos; } else if (pos + maxHoleDuration < start) { bufferStartNext = start; break; } } return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext }; } }]); return BufferHelper; }(); exports.default = BufferHelper; },{}],25:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * Level Helper class, providing methods dealing with playlist sliding and drift */ var _logger = require('../utils/logger'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var LevelHelper = function () { function LevelHelper() { _classCallCheck(this, LevelHelper); } _createClass(LevelHelper, null, [{ key: 'isLive', value: function isLive(level, levels) { return !!(level !== undefined && levels && levels[level] && levels[level].details && levels[level].details.live); } }, { key: 'canMerge', value: function canMerge(oldDetails, newDetails) { var _LevelHelper$probeDet = LevelHelper.probeDetails(oldDetails, newDetails), start = _LevelHelper$probeDet.start, end = _LevelHelper$probeDet.end; return end >= start; } }, { key: 'probeDetails', value: function probeDetails(oldDetails, newDetails) { function getTimes(details) { var startTS = 0, endTS = 0, i = 0; for (; i < details.fragments.length; i++) { if (details.fragments[i].programDateTime) { break; } } if (i !== details.fragments.length) { startTS = endTS = details.fragments[i].programDateTime.getTime(); for (var j = 0; j < details.fragments.length - 1; j++) { if (j < i) { startTS -= details.fragments[j].duration * 1000; } else { endTS += details.fragments[j].duration * 1000; } } return { start: startTS, end: endTS }; } } var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN; var end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN; var delta = newDetails.startSN - oldDetails.startSN; if (end >= start) { return { start: start, end: end, delta: delta }; } var oldTimes = getTimes(oldDetails), newTimes = getTimes(newDetails); if (oldTimes && newTimes && oldTimes.start <= newTimes.start && oldTimes.end >= newTimes.start) { start = delta = 0; end = Math.min(newDetails.fragments.length, oldDetails.fragments.length) - 1; var ts = oldTimes.start; // 0.1 sec grace while (newTimes.start - ts > 100) { ts += oldDetails.fragments[delta++].duration * 1000; end--; } return { start: start, end: end, delta: delta }; } return { start: 1, end: 0, delta: 0 }; } }, { key: 'mergeDetails', value: function mergeDetails(oldDetails, newDetails) { var oldfragments = oldDetails.fragments, newfragments = newDetails.fragments, ccOffset = 0, PTSFrag; var _LevelHelper$probeDet2 = LevelHelper.probeDetails(oldDetails, newDetails), start = _LevelHelper$probeDet2.start, end = _LevelHelper$probeDet2.end, delta = _LevelHelper$probeDet2.delta; // check if old/new playlists have fragments in common if (end < start) { newDetails.PTSKnown = false; return; } // loop through overlapping SN and update startPTS , cc, and duration if any found for (var i = start; i <= end; i++) { var oldFrag = oldfragments[delta + i], newFrag = newfragments[i]; ccOffset = oldFrag.cc - newFrag.cc; if (!isNaN(oldFrag.startPTS)) { newFrag.start = newFrag.startPTS = oldFrag.startPTS; newFrag.endPTS = oldFrag.endPTS; newFrag.duration = oldFrag.duration; newFrag.PTSDTSshift = oldFrag.PTSDTSshift; newFrag.lastGop = oldFrag.lastGop; PTSFrag = newFrag; } if (oldFrag.firstGop) { newFrag.firstGop = oldFrag.firstGop; } } if (ccOffset) { _logger.logger.log('discontinuity sliding from playlist, take drift into account'); for (i = 0; i < newfragments.length; i++) { newfragments[i].cc += ccOffset; } } // if at least one fragment contains PTS info, recompute PTS information for all fragments if (PTSFrag) { LevelHelper.updateFragPTS(newDetails, PTSFrag.sn, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.PTSDTSshift || 0, PTSFrag.lastGop); } else { // ensure that delta is within oldfragments range // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61]) // in that case we also need to adjust start offset of all fragments if (delta >= 0 && delta < oldfragments.length) { // adjust start by sliding offset var sliding = oldfragments[delta].start; for (i = 0; i < newfragments.length; i++) { newfragments[i].start += sliding; } } } // if we are here, it means we have fragments overlapping between // old and new level. reliable PTS info is thus relying on old level newDetails.PTSKnown = oldDetails.PTSKnown; return; } }, { key: 'updateFragPTS', value: function updateFragPTS(details, sn, startPTS, endPTS, PTSDTSshift, lastGop) { var fragIdx, fragments, frag, i; // exit if sn out of range if (sn < details.startSN || sn > details.endSN) { return 0; } fragIdx = sn - details.startSN; fragments = details.fragments; frag = fragments[fragIdx]; if (!isNaN(frag.startPTS)) { startPTS = Math.min(startPTS, frag.startPTS); endPTS = Math.max(endPTS, frag.endPTS); } var drift = startPTS - frag.start; frag.start = frag.startPTS = startPTS; frag.endPTS = endPTS; frag.duration = endPTS - startPTS; frag.PTSDTSshift = PTSDTSshift || 0; if (lastGop) { frag.lastGop = lastGop; } // adjust fragment PTS/duration from seqnum-1 to frag 0 for (i = fragIdx; i > 0; i--) { LevelHelper.updatePTS(fragments, i, i - 1); } // adjust fragment PTS/duration from seqnum to last frag for (i = fragIdx; i < fragments.length - 1; i++) { LevelHelper.updatePTS(fragments, i, i + 1); } details.PTSKnown = true; //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`); return drift; } }, { key: 'updatePTS', value: function updatePTS(fragments, fromIdx, toIdx) { var fragFrom = fragments[fromIdx], fragTo = fragments[toIdx], fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx] if (!isNaN(fragToPTS)) { // update fragment duration. // it helps to fix drifts between playlist reported duration and fragment real duration if (toIdx > fromIdx) { fragFrom.duration = fragToPTS - fragFrom.start; if (fragFrom.duration < 0) { _logger.logger.warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!'); } } else { fragTo.duration = fragFrom.start - fragToPTS; if (fragTo.duration < 0) { _logger.logger.warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!'); } } } else { // we dont know startPTS[toIdx] if (toIdx > fromIdx) { fragTo.start = fragFrom.start + fragFrom.duration; } else { fragTo.start = fragFrom.start - fragTo.duration; } } if (toIdx > fromIdx) { if (!fragTo.PTSDTSshift) { fragTo.PTSDTSshift = fragFrom.PTSDTSshift || 0; } if (fragFrom.lastGop) { fragTo.firstGop = fragFrom.lastGop; } } } }]); return LevelHelper; }(); exports.default = LevelHelper; },{"../utils/logger":38}],26:[function(require,module,exports){ /** * HLS interface */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('./events'); var _events2 = _interopRequireDefault(_events); var _errors = require('./errors'); var _playlistLoader = require('./loader/playlist-loader'); var _playlistLoader2 = _interopRequireDefault(_playlistLoader); var _fragmentLoader = require('./loader/fragment-loader'); var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader); var _abrController = require('./controller/abr-controller'); var _abrController2 = _interopRequireDefault(_abrController); var _bufferController = require('./controller/buffer-controller'); var _bufferController2 = _interopRequireDefault(_bufferController); var _capLevelController = require('./controller/cap-level-controller'); var _capLevelController2 = _interopRequireDefault(_capLevelController); var _streamController = require('./controller/stream-controller'); var _streamController2 = _interopRequireDefault(_streamController); var _levelController = require('./controller/level-controller'); var _levelController2 = _interopRequireDefault(_levelController); var _timelineController = require('./controller/timeline-controller'); var _timelineController2 = _interopRequireDefault(_timelineController); var _fpsController = require('./controller/fps-controller'); var _fpsController2 = _interopRequireDefault(_fpsController); var _logger = require('./utils/logger'); var _xhrLoader = require('./utils/xhr-loader'); var _xhrLoader2 = _interopRequireDefault(_xhrLoader); var _events3 = require('events'); var _events4 = _interopRequireDefault(_events3); var _keyLoader = require('./loader/key-loader'); var _keyLoader2 = _interopRequireDefault(_keyLoader); var _cues = require('./utils/cues'); var _cues2 = _interopRequireDefault(_cues); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Hls = function () { _createClass(Hls, null, [{ key: 'isSupported', value: function isSupported() { return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); } }, { key: 'isIe', value: function isIe() { var res = void 0, ua = typeof window !== 'undefined' && window.navigator && navigator.userAgent; if (res = /[( ]MSIE ([6789]|10).\d[);]/.exec(ua)) { return { browser: 'ie', version: res[1] }; } if (res = /[( ]Trident\/\d+(\.\d)+.*rv:(\d\d)(\.\d)+[);]/.exec(ua)) { return { browser: 'ie', version: res[2] }; } } }, { key: 'version', get: function get() { // replaced with browserify-versionify transform return '0.6.1-122'; } }, { key: 'Events', get: function get() { return _events2.default; } }, { key: 'ErrorTypes', get: function get() { return _errors.ErrorTypes; } }, { key: 'ErrorDetails', get: function get() { return _errors.ErrorDetails; } }, { key: 'DefaultConfig', get: function get() { if (!Hls.defaultConfig) { Hls.defaultConfig = { autoStartLoad: true, debug: false, capLevelOnFPSDrop: false, capLevelToPlayerSize: false, maxBufferLength: 40, maxBufferSize: 60 * 1000 * 1000, maxBufferHole: 0.5, maxSeekHole: 2, lowBufferWatchdogPeriod: 0, highBufferWatchdogPeriod: 3, nudgeOffset: 0.1, nudgeMaxRetry: 5, maxFragLookUpTolerance: 0.2, liveSyncDurationCount: 3, liveMaxLatencyDurationCount: Infinity, liveSyncDuration: undefined, liveMaxLatencyDuration: undefined, maxMaxBufferLength: 40, enableWorker: !Hls.isIe(), enableSoftwareAES: true, manifestLoadingTimeOut: 20000, manifestLoadingMaxRetry: 4, manifestLoadingRetryDelay: 1000, levelLoadingTimeOut: 20000, levelLoadingMaxRetry: 4, levelLoadingRetryDelay: 1000, fragLoadingTimeOut: 20000, fragLoadingMaxRetry: 6, fragLoadingRetryDelay: 1000, fragLoadingLoopThreshold: 1000, clearLevelDetailsOnSwitching: false, startFragPrefetch: false, fpsDroppedMonitoringPeriod: 5000, fpsDroppedMonitoringThreshold: 0.2, appendErrorMaxRetry: 3, loader: _xhrLoader2.default, fLoader: undefined, pLoader: undefined, abrController: _abrController2.default, bufferController: _bufferController2.default, capLevelController: _capLevelController2.default, fpsController: _fpsController2.default, streamController: _streamController2.default, timelineController: _timelineController2.default, cueHandler: _cues2.default, enableCEA708Captions: true, enableMP2TPassThrough: false, stretchShortVideoTrack: false }; } return Hls.defaultConfig; }, set: function set(defaultConfig) { Hls.defaultConfig = defaultConfig; } }]); function Hls() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Hls); var defaultConfig = Hls.DefaultConfig; if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) { throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration'); } for (var prop in defaultConfig) { if (prop in config) { continue; } config[prop] = defaultConfig[prop]; } if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) { throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"'); } if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) { throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"'); } (0, _logger.enableLogs)(config.debug); this.config = config; // observer setup var observer = this.observer = new _events4.default(); observer.trigger = function trigger(event) { for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { data[_key - 1] = arguments[_key]; } observer.emit.apply(observer, [event, event].concat(data)); }; observer.off = function off(event) { for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { data[_key2 - 1] = arguments[_key2]; } observer.removeListener.apply(observer, [event].concat(data)); }; this.on = observer.on.bind(observer); this.off = observer.off.bind(observer); this.trigger = observer.trigger.bind(observer); this.playlistLoader = new _playlistLoader2.default(this); this.fragmentLoader = new _fragmentLoader2.default(this); this.levelController = new _levelController2.default(this); this.abrController = new config.abrController(this); this.bufferController = new config.bufferController(this); this.capLevelController = new config.capLevelController(this); this.fpsController = new config.fpsController(this); this.streamController = new config.streamController(this); this.timelineController = new config.timelineController(this); this.keyLoader = new _keyLoader2.default(this); Hls.api.players.push(this); Hls.api.emit(_events2.default.PLAYER_CREATED, this); } _createClass(Hls, [{ key: 'destroy', value: function destroy() { _logger.logger.log('destroy'); this.trigger(_events2.default.DESTROYING); this.detachMedia(); this.playlistLoader.destroy(); this.fragmentLoader.destroy(); this.levelController.destroy(); this.abrController.destroy(); this.bufferController.destroy(); this.capLevelController.destroy(); this.fpsController.destroy(); this.streamController.destroy(); this.timelineController.destroy(); this.keyLoader.destroy(); this.url = null; this.observer.removeAllListeners(); var globalId = Hls.api.players.indexOf(this); if (globalId < 0) { return; } Hls.api.players.splice(globalId, 1); Hls.api.emit(_events2.default.PLAYER_DESTROYED, this); } }, { key: 'attachMedia', value: function attachMedia(media) { _logger.logger.log('attachMedia'); this.media = media; this.trigger(_events2.default.MEDIA_ATTACHING, { media: media }); } }, { key: 'detachMedia', value: function detachMedia() { _logger.logger.log('detachMedia'); this.trigger(_events2.default.MEDIA_DETACHING); this.media = null; } }, { key: 'loadSource', value: function loadSource(url) { _logger.logger.log('loadSource:' + url); this.url = url; // when attaching to a source URL, trigger a playlist load this.trigger(_events2.default.MANIFEST_LOADING, { url: url }); } }, { key: 'startLoad', value: function startLoad() { var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; _logger.logger.log('startLoad(' + startPosition + ')'); this.levelController.startLoad(); this.streamController.startLoad(startPosition); } }, { key: 'stopLoad', value: function stopLoad() { _logger.logger.log('stopLoad'); this.levelController.stopLoad(); this.streamController.stopLoad(); } }, { key: 'clearLevelDetails', value: function clearLevelDetails() { _logger.logger.log('clearing level details'); this.levelController.clearLevelDetails(); } }, { key: 'swapAudioCodec', value: function swapAudioCodec() { _logger.logger.log('swapAudioCodec'); this.streamController.swapAudioCodec(); } }, { key: 'recoverMediaError', value: function recoverMediaError() { _logger.logger.log('recoverMediaError'); var media = this.media; this.detachMedia(); this.attachMedia(media); } /** Return all quality levels **/ }, { key: 'levels', get: function get() { return this.levelController.levels; } /** Return current playback quality level **/ }, { key: 'currentLevel', get: function get() { return this.streamController.currentLevel; } /* set quality level immediately (-1 for automatic level selection) */ , set: function set(newLevel) { _logger.logger.log('set currentLevel:' + newLevel); this.loadLevel = newLevel; this.streamController.immediateLevelSwitch(); } /** Return next playback quality level (quality level of next fragment) **/ }, { key: 'nextLevel', get: function get() { return this.streamController.nextLevel; } /* set quality level for next fragment (-1 for automatic level selection) */ , set: function set(newLevel) { _logger.logger.log('set nextLevel:' + newLevel); this.levelController.manualLevel = newLevel; this.streamController.nextLevelSwitch(); } /** Return the quality level of current/last loaded fragment **/ }, { key: 'loadLevel', get: function get() { return this.levelController.level; } /* set quality level for current/next loaded fragment (-1 for automatic level selection) */ , set: function set(newLevel) { _logger.logger.log('set loadLevel:' + newLevel); this.levelController.manualLevel = newLevel; } /** Return the quality level of next loaded fragment **/ }, { key: 'nextLoadLevel', get: function get() { return this.levelController.nextLoadLevel; } /** set quality level of next loaded fragment **/ , set: function set(level) { this.levelController.nextLoadLevel = level; } /** Return first level (index of first level referenced in manifest) **/ }, { key: 'firstLevel', get: function get() { return this.levelController.firstLevel; } /** set first level (index of first level referenced in manifest) **/ , set: function set(newLevel) { _logger.logger.log('set firstLevel:' + newLevel); this.levelController.firstLevel = newLevel; } /** Return start level (level of first fragment that will be played back) if not overrided by user, first level appearing in manifest will be used as start level if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) **/ }, { key: 'startLevel', get: function get() { return this.levelController.startLevel; } /** set start level (level of first fragment that will be played back) if not overrided by user, first level appearing in manifest will be used as start level if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) **/ , set: function set(newLevel) { _logger.logger.log('set startLevel:' + newLevel); this.levelController.startLevel = newLevel; } /** Return the capping/max level value that could be used by automatic level selection algorithm **/ }, { key: 'autoLevelCapping', get: function get() { return this.abrController.autoLevelCapping; } /** set the capping/max level value that could be used by automatic level selection algorithm **/ , set: function set(newLevel) { _logger.logger.log('set autoLevelCapping:' + newLevel); this.abrController.autoLevelCapping = newLevel; } /* check if we are in automatic level selection mode */ }, { key: 'autoLevelEnabled', get: function get() { return this.levelController.manualLevel === -1; } /* return manual level */ }, { key: 'manualLevel', get: function get() { return this.levelController.manualLevel; } }]); return Hls; }(); Hls.api = new _events4.default(); Hls.api.players = []; exports.default = Hls; },{"./controller/abr-controller":2,"./controller/buffer-controller":3,"./controller/cap-level-controller":4,"./controller/fps-controller":5,"./controller/level-controller":6,"./controller/stream-controller":7,"./controller/timeline-controller":8,"./errors":20,"./events":22,"./loader/fragment-loader":27,"./loader/key-loader":28,"./loader/playlist-loader":29,"./utils/cues":37,"./utils/logger":38,"./utils/xhr-loader":41,"events":43}],27:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _errors = require('../errors'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Fragment Loader */ var FragmentLoader = function (_EventHandler) { _inherits(FragmentLoader, _EventHandler); function FragmentLoader(hls) { _classCallCheck(this, FragmentLoader); return _possibleConstructorReturn(this, (FragmentLoader.__proto__ || Object.getPrototypeOf(FragmentLoader)).call(this, hls, _events2.default.FRAG_LOADING)); } _createClass(FragmentLoader, [{ key: 'destroy', value: function destroy() { if (this.loader) { this.loader.destroy(); this.loader = null; } this.firstChunk = true; _eventHandler2.default.prototype.destroy.call(this); } }, { key: 'onFragLoading', value: function onFragLoading(data) { var frag = data.frag; this.frag = frag; this.frag.loaded = 0; this.firstChunk = true; var config = this.hls.config; frag.loader = this.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config); this.loader.load(frag.url, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, 1, 0, this.loadprogress.bind(this), frag, this.loadchunk.bind(this)); } }, { key: 'loadchunk', value: function loadchunk(event, stats) { var payload = event.currentTarget.response; payload.first = this.firstChunk; this.firstChunk = false; this.hls.trigger(_events2.default.FRAG_CHUNK_LOADED, { payload: payload, frag: this.frag, stats: stats }); } }, { key: 'loadsuccess', value: function loadsuccess(event, stats) { var payload = event.currentTarget.response; payload.final = true; stats.length = payload.byteLength; this.hls.trigger(_events2.default.FRAG_LOADED, { frag: this.frag, stats: stats }); // we cannot add new property to xhr response object in IE this.loadchunk({ currentTarget: { response: payload } }, stats); this.firstChunk = true; // detach fragment loader on load success this.frag.loader = undefined; } }, { key: 'loaderror', value: function loaderror(event) { if (this.loader) { this.loader.abort(); } this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: this.frag, response: event }); } }, { key: 'loadtimeout', value: function loadtimeout() { if (this.loader) { this.loader.abort(); } this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: this.frag }); } }, { key: 'loadprogress', value: function loadprogress(stats) { this.frag.loaded = stats.loaded; this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: this.frag, stats: stats }); } }]); return FragmentLoader; }(_eventHandler2.default); exports.default = FragmentLoader; },{"../errors":20,"../event-handler":21,"../events":22}],28:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _errors = require('../errors'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Decrypt key Loader */ var KeyLoader = function (_EventHandler) { _inherits(KeyLoader, _EventHandler); function KeyLoader(hls) { _classCallCheck(this, KeyLoader); var _this = _possibleConstructorReturn(this, (KeyLoader.__proto__ || Object.getPrototypeOf(KeyLoader)).call(this, hls, _events2.default.KEY_LOADING)); _this.decryptkey = null; _this.decrypturl = null; return _this; } _createClass(KeyLoader, [{ key: 'destroy', value: function destroy() { if (this.loader) { this.loader.destroy(); this.loader = null; } _eventHandler2.default.prototype.destroy.call(this); } }, { key: 'onKeyLoading', value: function onKeyLoading(data) { var frag = this.frag = data.frag, decryptdata = frag.decryptdata, uri = decryptdata.uri; // if uri is different from previous one or if decrypt key not retrieved yet if (uri !== this.decrypturl || this.decryptkey === null) { var config = this.hls.config; frag.loader = this.loader = new config.loader(config); this.decrypturl = uri; this.decryptkey = null; frag.loader.load(uri, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, config.fragLoadingMaxRetry, config.fragLoadingRetryDelay, this.loadprogress.bind(this), frag); } else if (this.decryptkey) { // we already loaded this key, return it decryptdata.key = this.decryptkey; this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag }); } } }, { key: 'loadsuccess', value: function loadsuccess(event) { var frag = this.frag; this.decryptkey = frag.decryptdata.key = new Uint8Array(event.currentTarget.response); // detach fragment loader on load success frag.loader = undefined; this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag }); } }, { key: 'loaderror', value: function loaderror(event) { if (this.loader) { this.loader.abort(); } this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: this.frag, response: event.currentTarget }); } }, { key: 'loadtimeout', value: function loadtimeout() { if (this.loader) { this.loader.abort(); } this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: this.frag }); } }, { key: 'loadprogress', value: function loadprogress() {} }]); return KeyLoader; }(_eventHandler2.default); exports.default = KeyLoader; },{"../errors":20,"../event-handler":21,"../events":22}],29:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _eventHandler = require('../event-handler'); var _eventHandler2 = _interopRequireDefault(_eventHandler); var _errors = require('../errors'); var _url = require('../utils/url'); var _url2 = _interopRequireDefault(_url); var _attrList = require('../utils/attr-list'); var _attrList2 = _interopRequireDefault(_attrList); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Playlist Loader */ //import {logger} from '../utils/logger'; var PlaylistLoader = function (_EventHandler) { _inherits(PlaylistLoader, _EventHandler); function PlaylistLoader(hls) { _classCallCheck(this, PlaylistLoader); return _possibleConstructorReturn(this, (PlaylistLoader.__proto__ || Object.getPrototypeOf(PlaylistLoader)).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.LEVEL_LOADING)); } _createClass(PlaylistLoader, [{ key: 'destroy', value: function destroy() { if (this.loader) { this.loader.destroy(); this.loader = null; } this.url = this.id = null; _eventHandler2.default.prototype.destroy.call(this); } }, { key: 'onManifestLoading', value: function onManifestLoading(data) { this.load(data.url, null); } }, { key: 'onLevelLoading', value: function onLevelLoading(data) { this.load(data.url, data.level, data.id); } }, { key: 'reloadCurrentRequests', value: function reloadCurrentRequests() { // we only reload manifest requests, level requests will be retried anyway if (this.loading && this.loader && this.id === null) { this.loader.abort(); this.loading = false; this.load(this.url, this.id, this.id2); } } }, { key: 'load', value: function load(url, id1, id2) { var config = this.hls.config, retry, timeout, retryDelay; if (this.loading && this.loader) { if (this.url === url && this.id === id1 && this.id2 === id2) { // same request than last pending one, don't do anything return; } else { // one playlist load request is pending, but with different params, abort it before loading new playlist this.loader.abort(); } } this.url = url; this.id = id1; this.id2 = id2; if (this.id === null) { retry = config.manifestLoadingMaxRetry; timeout = config.manifestLoadingTimeOut; retryDelay = config.manifestLoadingRetryDelay; } else { retry = config.levelLoadingMaxRetry; timeout = config.levelLoadingTimeOut; retryDelay = config.levelLoadingRetryDelay; } this.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config); this.loading = true; this.loader.load(url, '', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), timeout, retry, retryDelay); } }, { key: 'resolve', value: function resolve(url, baseUrl) { return _url2.default.buildAbsoluteURL(baseUrl, url); } }, { key: 'parseMasterPlaylist', value: function parseMasterPlaylist(string, baseurl) { var levels = [], result = void 0; // https://regex101.com is your friend var re = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g; while ((result = re.exec(string)) != null) { var level = {}; var attrs = level.attrs = new _attrList2.default(result[1]); level.url = this.resolve(result[2], baseurl); var resolution = attrs.decimalResolution('RESOLUTION'); if (resolution) { level.width = resolution.width; level.height = resolution.height; } level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'); level.name = attrs.NAME; var closedCaptions = attrs.enumeratedString('CLOSED-CAPTIONS'); if (closedCaptions) { level.closedCaptions = closedCaptions; } var codecs = attrs.CODECS; if (codecs) { codecs = codecs.split(','); for (var i = 0; i < codecs.length; i++) { var codec = codecs[i]; if (codec.indexOf('avc1') !== -1) { level.videoCodec = this.avc1toavcoti(codec); } else { level.audioCodec = codec; } } } levels.push(level); } return levels; } /** * Utility method for parseLevelPlaylist to create an initialization vector for a given segment * @returns {Uint8Array} */ }, { key: 'createInitializationVector', value: function createInitializationVector(segmentNumber) { var uint8View = new Uint8Array(16); for (var i = 12; i < 16; i++) { uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff; } return uint8View; } /** * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data * @param levelkey - a playlist's encryption info * @param segmentNumber - the fragment's segment number * @returns {*} - an object to be applied as a fragment's decryptdata */ }, { key: 'fragmentDecryptdataFromLevelkey', value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) { var decryptdata = levelkey; if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) { decryptdata = this.cloneObj(levelkey); decryptdata.iv = this.createInitializationVector(segmentNumber); } return decryptdata; } }, { key: 'avc1toavcoti', value: function avc1toavcoti(codec) { var result, avcdata = codec.split('.'); if (avcdata.length > 2) { result = avcdata.shift() + '.'; result += parseInt(avcdata.shift()).toString(16); result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4); } else { result = codec; } return result; } }, { key: 'cloneObj', value: function cloneObj(obj) { return JSON.parse(JSON.stringify(obj)); } }, { key: 'parseLevelPlaylist', value: function parseLevelPlaylist(string, baseurl, id) { var currentSN = 0, fragdecryptdata, totalduration = 0, level = { url: baseurl, fragments: [], live: true, startSN: 0 }, levelkey = { method: null, key: null, iv: null, uri: null }, cc = 0, programDateTime = null, frag = null, result, regexp, byteRangeEndOffset, byteRangeStartOffset, tagList = []; regexp = /(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*)[\r\n]+([^#|\r\n]+)?)|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*))|(?:#EXT-X-(VERSION):(.*))|(?:#(.*):(.*))|(?:#(.*))/g; while ((result = regexp.exec(string)) !== null) { result.shift(); result = result.filter(function (n) { return n !== undefined; }); switch (result[0]) { case 'MEDIA-SEQUENCE': currentSN = level.startSN = parseInt(result[1]); break; case 'TARGETDURATION': level.targetduration = parseFloat(result[1]); break; case 'VERSION': break; case 'EXTM3U': break; case 'ENDLIST': level.live = false; break; case 'DIS': cc++; tagList.push(result.map(function (e) { return (' ' + e).slice(1); })); break; case 'BYTERANGE': var params = result[1].split('@'); if (params.length === 1) { byteRangeStartOffset = byteRangeEndOffset; } else { byteRangeStartOffset = parseInt(params[1]); } byteRangeEndOffset = parseInt(params[0]) + byteRangeStartOffset; if (frag && !frag.url) { frag.byteRangeStartOffset = byteRangeStartOffset; frag.byteRangeEndOffset = byteRangeEndOffset; frag.url = this.resolve(result[2], baseurl); tagList.push(result.map(function (e) { return (' ' + e).slice(1); })); } break; case 'INF': var duration = parseFloat(result[1]); if (!isNaN(duration)) { var sn = currentSN++; fragdecryptdata = this.fragmentDecryptdataFromLevelkey(levelkey, sn); var url = result[2] ? this.resolve(result[2], baseurl) : null; tagList.push(result.map(function (e) { return (' ' + e).slice(1); })); frag = { url: url, duration: duration, start: totalduration, sn: sn, level: id, cc: cc, byteRangeStartOffset: byteRangeStartOffset, byteRangeEndOffset: byteRangeEndOffset, decryptdata: fragdecryptdata, programDateTime: programDateTime, tagList: tagList, PTSDTSshift: 0 }; level.fragments.push(frag); totalduration += duration; byteRangeStartOffset = null; programDateTime = null; tagList = []; } break; case 'KEY': // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4 var decryptparams = result[1]; var keyAttrs = new _attrList2.default(decryptparams); var decryptmethod = keyAttrs.enumeratedString('METHOD'), decrypturi = keyAttrs.URI, decryptiv = keyAttrs.hexadecimalInteger('IV'); if (decryptmethod) { levelkey = { method: null, key: null, iv: null, uri: null }; if (decrypturi && decryptmethod === 'AES-128') { levelkey.method = decryptmethod; // URI to get the key levelkey.uri = this.resolve(decrypturi, baseurl); levelkey.key = null; // Initialization Vector (IV) levelkey.iv = decryptiv; } } //issue #425, applying url and decrypt data in instances where EXT-KEY immediately follow EXT-INF if (frag && !frag.url && result.length >= 3) { frag.url = this.resolve(result[2], baseurl); //we have not moved onto another segment, we are still parsing one fragdecryptdata = this.fragmentDecryptdataFromLevelkey(levelkey, currentSN - 1); frag.decryptdata = fragdecryptdata; tagList.push(result.map(function (e) { return (' ' + e).slice(1); })); } break; case 'PROGRAM-DATE-TIME': programDateTime = new Date(Date.parse(result[1])); tagList.push(result.map(function (e) { return (' ' + e).slice(1); })); break; default: tagList.push(result.map(function (e) { return (' ' + e).slice(1); })); break; } } //logger.log('found ' + level.fragments.length + ' fragments'); if (frag && !frag.url) { level.fragments.pop(); totalduration -= frag.duration; } level.totalduration = totalduration; level.averagetargetduration = totalduration / level.fragments.length; level.endSN = currentSN - 1; return level; } }, { key: 'loadsuccess', value: function loadsuccess(event, stats) { var target = event.currentTarget, string = target.responseText, url = target.responseURL, id = this.id, id2 = this.id2, hls = this.hls, levels; this.loading = false; // responseURL not supported on some browsers (it is used to detect URL redirection) // data-uri mode also not supported (but no need to detect redirection) if (url === undefined || url.indexOf('data:') === 0) { // fallback to initial URL url = this.url; } stats.tload = performance.now(); stats.mtime = new Date(target.getResponseHeader('Last-Modified')); if (string.indexOf('#EXTM3U') === 0) { if (string.indexOf('#EXTINF:') > 0) { // 1 level playlist // if first request, fire manifest loaded event, level will be reloaded afterwards // (this is to have a uniform logic for 1 level/multilevel playlists) if (this.id === null) { hls.trigger(_events2.default.MANIFEST_LOADED, { levels: [{ url: url }], url: url, stats: stats }); } else { var levelDetails = this.parseLevelPlaylist(string, url, id); stats.tparsed = performance.now(); hls.trigger(_events2.default.LEVEL_LOADED, { details: levelDetails, level: id, id: id2, stats: stats }); } } else { levels = this.parseMasterPlaylist(string, url); // multi level playlist, parse level info if (levels.length) { hls.trigger(_events2.default.MANIFEST_LOADED, { levels: levels, url: url, stats: stats }); } else { hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest' }); } } } else { hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter' }); } } }, { key: 'loaderror', value: function loaderror(event) { var details, fatal; if (this.id === null) { details = _errors.ErrorDetails.MANIFEST_LOAD_ERROR; fatal = true; } else { details = _errors.ErrorDetails.LEVEL_LOAD_ERROR; fatal = false; } if (this.loader) { this.loader.abort(); } this.loading = false; this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, response: event.currentTarget, level: this.id, id: this.id2 }); } }, { key: 'loadtimeout', value: function loadtimeout() { var details, fatal; if (this.id === null) { details = _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT; fatal = true; } else { details = _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT; fatal = false; } if (this.loader) { this.loader.abort(); } this.loading = false; this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, level: this.id, id: this.id2 }); } }]); return PlaylistLoader; }(_eventHandler2.default); exports.default = PlaylistLoader; },{"../errors":20,"../event-handler":21,"../events":22,"../utils/attr-list":33,"../utils/url":40}],30:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Generate MP4 Box */ var UINT32_MAX = Math.pow(2, 32) - 1; //import Hex from '../utils/hex'; var MP4 = function () { function MP4() { _classCallCheck(this, MP4); } _createClass(MP4, null, [{ key: 'init', value: function init() { MP4.types = { avc1: [], // codingname avcC: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], '.mp3': [], mvex: [], mvhd: [], sdtp: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [], smhd: [] }; var i; for (i in MP4.types) { if (MP4.types.hasOwnProperty(i)) { MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)]; } } var videoHdlr = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler' ]); var audioHdlr = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler' ]); MP4.HDLR_TYPES = { 'video': videoHdlr, 'audio': audioHdlr }; var dref = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01, // entry_count 0x00, 0x00, 0x00, 0x0c, // entry_size 0x75, 0x72, 0x6c, 0x20, // 'url' type 0x00, // version 0 0x00, 0x00, 0x01 // entry_flags ]); var stco = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00 // entry_count ]); MP4.STTS = MP4.STSC = MP4.STCO = stco; MP4.STSZ = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // sample_size 0x00, 0x00, 0x00, 0x00]); MP4.VMHD = new Uint8Array([0x00, // version 0x00, 0x00, 0x01, // flags 0x00, 0x00, // graphicsmode 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor ]); MP4.SMHD = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, // balance 0x00, 0x00 // reserved ]); MP4.STSD = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01]); // entry_count var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1 var minorVersion = new Uint8Array([0, 0, 0, 1]); MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand); MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref)); } }, { key: 'box', value: function box(type) { var payload = Array.prototype.slice.call(arguments, 1), size = 8, i = payload.length, len = i, result; // calculate the total size we need to allocate while (i--) { size += payload[i].byteLength; } result = new Uint8Array(size); result[0] = size >> 24 & 0xff; result[1] = size >> 16 & 0xff; result[2] = size >> 8 & 0xff; result[3] = size & 0xff; result.set(type, 4); // copy the payload into the result for (i = 0, size = 8; i < len; i++) { // copy payload[i] array @ offset size result.set(payload[i], size); size += payload[i].byteLength; } return result; } }, { key: 'hdlr', value: function hdlr(type) { return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]); } }, { key: 'mdat', value: function mdat(data) { return MP4.box(MP4.types.mdat, data); } }, { key: 'mdhd', value: function mdhd(timescale, duration) { duration *= timescale; return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x03, // modification_time timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration 0x55, 0xc4, // 'und' language (undetermined) 0x00, 0x00])); } }, { key: 'mdia', value: function mdia(track) { return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track)); } }, { key: 'mfhd', value: function mfhd(sequenceNumber) { return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF])); } }, { key: 'minf', value: function minf(track) { if (track.type === 'audio') { return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track)); } else { return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track)); } } }, { key: 'moof', value: function moof(sn, baseMediaDecodeTime, track) { return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime)); } /** * @param tracks... (optional) {array} the tracks associated with this movie */ }, { key: 'moov', value: function moov(tracks) { var i = tracks.length, boxes = []; while (i--) { boxes[i] = MP4.trak(tracks[i]); } return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks))); } }, { key: 'mvex', value: function mvex(tracks) { var i = tracks.length, boxes = []; while (i--) { boxes[i] = MP4.trex(tracks[i]); } return MP4.box.apply(null, [MP4.types.mvex].concat(boxes)); } }, { key: 'mvhd', value: function mvhd(timescale, duration) { duration *= timescale; var bytes = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01, // creation_time 0x00, 0x00, 0x00, 0x02, // modification_time timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale duration >> 24 & 0xFF, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration 0x00, 0x01, 0x00, 0x00, // 1.0 rate 0x01, 0x00, // 1.0 volume 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined 0xff, 0xff, 0xff, 0xff // next_track_ID ]); return MP4.box(MP4.types.mvhd, bytes); } }, { key: 'sdtp', value: function sdtp(track) { var samples = track.samples || [], bytes = new Uint8Array(4 + samples.length), flags, i; // leave the full box header (4 bytes) all zero // write the sample table for (i = 0; i < samples.length; i++) { flags = samples[i].flags; bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy; } return MP4.box(MP4.types.sdtp, bytes); } }, { key: 'stbl', value: function stbl(track) { return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO)); } }, { key: 'avc1', value: function avc1(track) { var sps = [], pps = [], i, data, len; // assemble the SPSs for (i = 0; i < track.sps.length; i++) { data = track.sps[i]; len = data.byteLength; sps.push(len >>> 8 & 0xFF); sps.push(len & 0xFF); sps = sps.concat(Array.prototype.slice.call(data)); // SPS } // assemble the PPSs for (i = 0; i < track.pps.length; i++) { data = track.pps[i]; len = data.byteLength; pps.push(len >>> 8 & 0xFF); pps.push(len & 0xFF); pps = pps.concat(Array.prototype.slice.call(data)); } var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version sps[3], // profile sps[4], // profile compat sps[5], // level 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets ].concat(sps).concat([track.pps.length // numOfPictureParameterSets ]).concat(pps))), // "PPS" width = track.width, height = track.height; //console.log('avcc:' + Hex.hexDump(avcc)); return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, // pre_defined 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined width >> 8 & 0xFF, width & 0xff, // width height >> 8 & 0xFF, height & 0xff, // height 0x00, 0x48, 0x00, 0x00, // horizresolution 0x00, 0x48, 0x00, 0x00, // vertresolution 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // frame_count 0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js 0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname 0x00, 0x18, // depth = 24 0x11, 0x11]), // pre_defined = -1 avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate 0x00, 0x2d, 0xc6, 0xc0])) // avgBitrate ); } }, { key: 'esds', value: function esds(track) { var configlen = track.config.length; return new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x03, // descriptor_type 0x17 + configlen, // length 0x00, 0x01, //es_id 0x00, // stream_priority 0x04, // descriptor_type 0x0f + configlen, // length 0x40, //codec : mpeg4_audio 0x15, // stream_type 0x00, 0x00, 0x00, // buffer_size 0x00, 0x00, 0x00, 0x00, // maxBitrate 0x00, 0x00, 0x00, 0x00, // avgBitrate 0x05 // descriptor_type ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor } }, { key: 'mp4a', value: function mp4a(track) { var audiosamplerate = track.audiosamplerate; return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, track.channelCount, // channelcount 0x00, 0x10, // sampleSize:16bits 0x00, 0x00, 0x00, 0x00, // reserved2 audiosamplerate >> 8 & 0xFF, audiosamplerate & 0xff, // 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track))); } }, { key: 'mp3', value: function mp3(track) { var audiosamplerate = track.audiosamplerate; return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, track.channelCount, // channelcount 0x00, 0x10, // sampleSize:16bits 0x00, 0x00, 0x00, 0x00, // reserved2 audiosamplerate >> 8 & 0xFF, audiosamplerate & 0xff, // 0x00, 0x00])); } }, { key: 'stsd', value: function stsd(track) { if (track.type === 'audio') { if (!track.isAAC && track.codec === 'mp3') { return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track)); } return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track)); } else { return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track)); } } }, { key: 'tkhd', value: function tkhd(track) { var id = track.id, duration = track.duration * track.timescale, width = track.width, height = track.height; return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x07, // flags 0x00, 0x00, 0x00, 0x00, // creation_time 0x00, 0x00, 0x00, 0x00, // modification_time id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID 0x00, 0x00, 0x00, 0x00, // reserved duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, // layer 0x00, 0x00, // alternate_group 0x00, 0x00, // non-audio track volume 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height ])); } }, { key: 'traf', value: function traf(track, baseMediaDecodeTime) { var sampleDependencyTable = MP4.sdtp(track), id = track.id; var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1 0x00, 0x00, 0x00, // flags upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd 20 + // tfdt 8 + // traf header 16 + // mfhd 8 + // moof header 8), // mdat header sampleDependencyTable); } /** * Generate a track box. * @param track {object} a track definition * @return {Uint8Array} the track box */ }, { key: 'trak', value: function trak(track) { track.duration = track.duration || 0xffffffff; return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track)); } }, { key: 'trex', value: function trex(track) { var id = track.id; return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID 0x00, 0x00, 0x00, 0x01, // default_sample_description_index 0x00, 0x00, 0x00, 0x00, // default_sample_duration 0x00, 0x00, 0x00, 0x00, // default_sample_size 0x00, 0x01, 0x00, 0x01 // default_sample_flags ])); } }, { key: 'trun', value: function trun(track, offset) { var samples = track.samples || [], len = samples.length, arraylen = 12 + 16 * len, array = new Uint8Array(arraylen), i, sample, duration, size, flags, cts; offset += 8 + arraylen; array.set([0x00, // version 0 0x00, 0x0f, 0x01, // flags len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset ], 0); for (i = 0; i < len; i++) { sample = samples[i]; duration = sample.duration; size = sample.size; flags = sample.flags; cts = sample.cts; array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset ], 12 + 16 * i); } return MP4.box(MP4.types.trun, array); } }, { key: 'initSegment', value: function initSegment(tracks) { if (!MP4.types) { MP4.init(); } var movie = MP4.moov(tracks), result; result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength); result.set(MP4.FTYP); result.set(movie, MP4.FTYP.byteLength); return result; } }]); return MP4; }(); exports.default = MP4; },{}],31:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * fMP4 remuxer */ var _aac = require('../helper/aac'); var _aac2 = _interopRequireDefault(_aac); var _events = require('../events'); var _events2 = _interopRequireDefault(_events); var _logger = require('../utils/logger'); var _mp4Generator = require('../remux/mp4-generator'); var _mp4Generator2 = _interopRequireDefault(_mp4Generator); var _errors = require('../errors'); require('../utils/polyfill'); var _browser = require('../utils/browser'); var _browser2 = _interopRequireDefault(_browser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var MP4Remuxer = function () { function MP4Remuxer(observer, config, typeSupported) { _classCallCheck(this, MP4Remuxer); this.observer = observer; this.config = config; this.typeSupported = typeSupported; this.ISGenerated = false; this.PES2MP4SCALEFACTOR = 4; this.PES_TIMESCALE = 90000; this.MP4_TIMESCALE = this.PES_TIMESCALE / this.PES2MP4SCALEFACTOR; } _createClass(MP4Remuxer, [{ key: 'destroy', value: function destroy() {} }, { key: 'insertDiscontinuity', value: function insertDiscontinuity() { this._initPTS = this._initDTS = undefined; } }, { key: 'switchLevel', value: function switchLevel() { this.ISGenerated = false; } }, { key: 'remux', value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurate, data, flush, stats) { // dummy data = null; // generate Init Segment if needed if (!this.ISGenerated) { this.generateIS(audioTrack, videoTrack, timeOffset); } if (this.ISGenerated) { // Purposefully remuxing audio before video, so that remuxVideo can use nextAacPts, which is // calculated in remuxAudio. //logger.log('nb AAC samples:' + audioTrack.samples.length); if (audioTrack.samples.length) { var audioData = this.remuxAudio(audioTrack, timeOffset, contiguous, accurate, stats); //logger.log('nb AVC samples:' + videoTrack.samples.length); if (videoTrack.samples.length) { var audioTrackLength = void 0, audioStartPTS = void 0; if (audioData) { audioStartPTS = audioData.startPTS; audioTrackLength = audioData.endPTS - audioStartPTS; } this.remuxVideo(videoTrack, timeOffset, contiguous, audioTrackLength, audioStartPTS, flush, stats); } else if (!contiguous) { this.nextAvcDts = undefined; } } else { var videoData = void 0; //logger.log('nb AVC samples:' + videoTrack.samples.length); if (videoTrack.samples.length) { videoData = this.remuxVideo(videoTrack, timeOffset, contiguous, undefined, undefined, flush, stats); } if (videoData && audioTrack.codec) { this.remuxEmptyAudio(audioTrack, timeOffset, contiguous, videoData, stats); } } } //logger.log('nb ID3 samples:' + audioTrack.samples.length); if (id3Track.samples.length) { this.remuxID3(id3Track, timeOffset); } //logger.log('nb ID3 samples:' + audioTrack.samples.length); if (textTrack.samples.length) { this.remuxText(textTrack, timeOffset); } } }, { key: 'generateIS', value: function generateIS(audioTrack, videoTrack, timeOffset) { var observer = this.observer, audioSamples = audioTrack.samples, videoSamples = videoTrack.samples, pesTimeScale = this.PES_TIMESCALE, tracks = {}, data = { tracks: tracks, unique: false }, computePTSDTS = this._initPTS === undefined, initPTS, initDTS; if (computePTSDTS) { initPTS = initDTS = Infinity; } if (audioTrack.config && audioSamples.length) { audioTrack.timescale = audioTrack.audiosamplerate; // MP4 duration (track duration in seconds multiplied by timescale) is coded on 32 bits // we know that each AAC sample contains 1024 frames.... // in order to avoid overflowing the 32 bit counter for large duration, we use smaller timescale (timescale/gcd) // we just need to ensure that AAC sample duration will still be an integer (will be 1024/gcd) if (audioTrack.timescale * audioTrack.duration > Math.pow(2, 32)) { var greatestCommonDivisor = function greatestCommonDivisor(a, b) { if (!b) { return a; } return greatestCommonDivisor(b, a % b); }; audioTrack.timescale = audioTrack.audiosamplerate / greatestCommonDivisor(audioTrack.audiosamplerate, audioTrack.isAAC ? 1024 : 1152); } _logger.logger.log('audio mp4 timescale :' + audioTrack.timescale); var container = 'audio/mp4'; if (!audioTrack.isAAC) { if (this.typeSupported.mpeg) { // Chrome and Safari container = 'audio/mpeg'; audioTrack.codec = ''; } else if (this.typeSupported.mp3 === true) { // Firefox audioTrack.codec = 'mp3'; } } tracks.audio = { container: container, codec: audioTrack.codec, initSegment: !audioTrack.isAAC && this.typeSupported.mpeg ? new Uint8Array() : _mp4Generator2.default.initSegment([audioTrack]), metadata: { channelCount: audioTrack.channelCount } }; if (computePTSDTS) { // remember first PTS of this demuxing context. for audio, PTS = DTS initPTS = initDTS = audioSamples[0].pts - pesTimeScale * timeOffset; } } if (videoTrack.sps && videoTrack.pps && videoSamples.length) { videoTrack.timescale = this.MP4_TIMESCALE; tracks.video = { container: 'video/mp4', codec: videoTrack.codec, initSegment: _mp4Generator2.default.initSegment([videoTrack]), metadata: { width: videoTrack.width, height: videoTrack.height } }; if (computePTSDTS) { initPTS = Math.min(initPTS, videoSamples[0].pts - pesTimeScale * timeOffset); initDTS = Math.min(initDTS, videoSamples[0].dts - pesTimeScale * timeOffset); } } if (Object.keys(tracks).length) { observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data); this.ISGenerated = true; if (computePTSDTS) { this._initPTS = initPTS; this._initDTS = initDTS; } } else { observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' }); } } }, { key: 'remuxVideo', value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength, audioStartPTS, flush, stats) { var offset = 8, pesTimeScale = this.PES_TIMESCALE, pes2mp4ScaleFactor = this.PES2MP4SCALEFACTOR, mp4SampleDuration, mdat, moof, firstPTS, firstDTS, nextDTS, lastPTS, lastDTS, inputSamples = track.samples, outputSamples = []; // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale) var PTSDTSshift = inputSamples.reduce(function (prev, curr) { return Math.max(Math.min(prev, curr.pts - curr.dts), -18000); }, 0); if (PTSDTSshift < 0) { _logger.logger.warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue'); for (var i = 0; i < inputSamples.length; i++) { inputSamples[i].dts += PTSDTSshift; } } contiguous |= inputSamples.length && this.nextAvcDts && Math.abs(timeOffset - this.nextAvcDts / pesTimeScale) < 0.1; // PTS is coded on 33bits, and can loop from -2^32 to 2^32 // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value // if parsed fragment is contiguous with last one, let's use last DTS value as reference // if not contiguous, let's use target timeOffset var nextAvcDts = contiguous ? this.nextAvcDts : timeOffset * pesTimeScale; // compute first DTS and last DTS, normalize them against reference value var sample = inputSamples[0]; firstDTS = Math.max(this._PTSNormalize(sample.dts - this._initDTS, nextAvcDts), 0); firstPTS = Math.max(this._PTSNormalize(sample.pts - this._initDTS, nextAvcDts), 0); // check timestamp continuity (to remove inter-fragment gap/hole) var delta = Math.round((firstDTS - nextAvcDts) / 90); if (contiguous && delta) { _logger.logger.log('AVC:' + Math.abs(delta) + ' ms ' + (delta > 0 ? 'hole' : 'overlapping') + ' between fragments detected'); // remove hole/gap : set DTS to next expected DTS firstDTS = nextAvcDts; inputSamples[0].dts = firstDTS + this._initDTS; // offset PTS as well, ensure that PTS is smaller or equal than new DTS firstPTS = Math.max(firstPTS - delta * 90, nextAvcDts); inputSamples[0].pts = firstPTS + this._initDTS; _logger.logger.log('Video/PTS/DTS adjusted: ' + firstPTS + '/' + firstDTS + ',delta:' + delta); stats.videoGap = stats.videoGap || []; stats.videoGap.push(delta); } nextDTS = firstDTS; // compute lastPTS/lastDTS sample = inputSamples[inputSamples.length - 1]; lastDTS = Math.max(this._PTSNormalize(sample.dts - this._initDTS, nextAvcDts), 0); lastPTS = Math.max(this._PTSNormalize(sample.pts - this._initDTS, nextAvcDts), 0); lastPTS = Math.max(lastPTS, lastDTS); // on Safari let's signal the same sample duration for all samples // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS // set this constant duration as being the avg delta between consecutive DTS. if (_browser2.default.isSafari()) { mp4SampleDuration = Math.round((lastDTS - firstDTS) / (pes2mp4ScaleFactor * (inputSamples.length - 1))); } // normalize all PTS/DTS now ... for (var _i = 0; _i < inputSamples.length; _i++) { var _sample = inputSamples[_i]; if (_browser2.default.isSafari()) { // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples _sample.dts = firstDTS + _i * pes2mp4ScaleFactor * mp4SampleDuration; } else { // ensure sample monotonic DTS _sample.dts = Math.max(this._PTSNormalize(_sample.dts - this._initDTS, nextAvcDts), firstDTS); // ensure dts is a multiple of scale factor to avoid rounding issues _sample.dts = Math.round(_sample.dts / pes2mp4ScaleFactor) * pes2mp4ScaleFactor; } // we normalize PTS against nextAvcDts, we also substract initDTS (some streams don't start @ PTS O) // and we ensure that computed value is greater or equal than sample DTS _sample.pts = Math.max(this._PTSNormalize(_sample.pts - this._initDTS, nextAvcDts), _sample.dts); // ensure pts is a multiple of scale factor to avoid rounding issues _sample.pts = Math.round(_sample.pts / pes2mp4ScaleFactor) * pes2mp4ScaleFactor; } /* concatenate the video data and construct the mdat in place (need 8 more bytes to fill length and mpdat type) */ mdat = new Uint8Array(track.len + 4 * track.nbNalu + 8); var view = new DataView(mdat.buffer); view.setUint32(0, mdat.byteLength); mdat.set(_mp4Generator2.default.types.mdat, 4); for (var _i2 = 0; _i2 < inputSamples.length; _i2++) { var avcSample = inputSamples[_i2], mp4SampleLength = 0, compositionTimeOffset = void 0; // convert NALU bitstream to MP4 format (prepend NALU with size field) while (avcSample.units.units.length) { var unit = avcSample.units.units.shift(); view.setUint32(offset, unit.data.byteLength); offset += 4; mdat.set(unit.data, offset); offset += unit.data.byteLength; mp4SampleLength += 4 + unit.data.byteLength; } if (!_browser2.default.isSafari()) { // expected sample duration is the Decoding Timestamp diff of consecutive samples if (_i2 < inputSamples.length - 1) { mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts; } else { var config = this.config, lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts; if (config.stretchShortVideoTrack) { // In some cases, a segment's audio track duration may exceed the video track duration. // Since we've already remuxed audio, and we know how long the audio track is, we look to // see if the delta to the next segment is longer than the minimum of maxBufferHole and // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate // the duration of the last frame to minimize any potential gap between segments. var maxBufferHole = config.maxBufferHole, maxSeekHole = config.maxSeekHole, gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * pesTimeScale), deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * pesTimeScale : this.nextAacPts) - avcSample.pts; if (deltaToFrameEnd > gapTolerance) { // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration; if (mp4SampleDuration < 0) { mp4SampleDuration = lastFrameDuration; } _logger.logger.log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.'); } else { mp4SampleDuration = lastFrameDuration; } } else { mp4SampleDuration = lastFrameDuration; } } mp4SampleDuration /= pes2mp4ScaleFactor; compositionTimeOffset = Math.round((avcSample.pts - avcSample.dts) / pes2mp4ScaleFactor); } else { compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / (pes2mp4ScaleFactor * mp4SampleDuration))); } //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}'); outputSamples.push({ size: mp4SampleLength, // constant duration duration: mp4SampleDuration, cts: compositionTimeOffset, flags: { isLeading: 0, isDependedOn: 0, hasRedundancy: 0, degradPrio: 0, dependsOn: avcSample.key ? 2 : 1, isNonSync: avcSample.key ? 0 : 1 } }); } // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale) this.nextAvcDts = lastDTS + mp4SampleDuration * pes2mp4ScaleFactor; track.len = 0; track.nbNalu = 0; if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { var flags = outputSamples[0].flags; // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue // https://code.google.com/p/chromium/issues/detail?id=229412 flags.dependsOn = 2; flags.isNonSync = 0; } track.samples = outputSamples; moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track); track.samples = []; var data = { data1: moof, data2: mdat, startPTS: firstPTS / pesTimeScale, endPTS: (lastPTS + pes2mp4ScaleFactor * mp4SampleDuration) / pesTimeScale, startDTS: firstDTS / pesTimeScale, endDTS: this.nextAvcDts / pesTimeScale, type: 'video', flush: flush, nb: outputSamples.length, dropped: stats.dropped }; // delta PTS between audio and video data.deltaPTS = Math.abs(data.startPTS - audioStartPTS); this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data); return data; } }, { key: 'remuxAudio', value: function remuxAudio(track, timeOffset, contiguous, accurate, stats) { var pesTimeScale = this.PES_TIMESCALE, mp4timeScale = track.timescale, pes2mp4ScaleFactor = pesTimeScale / mp4timeScale, expectedSampleDuration = track.timescale * (track.isAAC ? 1024 : 1152) / track.audiosamplerate, rawMPEG = !track.isAAC && this.typeSupported.mpeg; var view, offset = rawMPEG ? 0 : 8, aacSample, mp4Sample, unit, mdat, moof, firstPTS, firstDTS, lastDTS, pts, dts, ptsnorm, dtsnorm, samples = [], samples0 = track.samples, fillFrame, newStamp; // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs), // for sake of clarity: // consecutive fragments are frags with less than 100ms gaps between new time offset and next expected PTS // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) // this helps ensuring audio continuity // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame contiguous |= samples0.length && this.nextAacPts && Math.abs(timeOffset - this.nextAacPts / pesTimeScale) < 0.1; var nextAacPts = contiguous && this.nextAacPts !== undefined ? this.nextAacPts : timeOffset * pesTimeScale; // If the audio track is missing samples, the frames seem to get "left-shifted" within the // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment. // In an effort to prevent this from happening, we inject frames here where there are gaps. // When possible, we inject a silent frame; when that's not possible, we duplicate the last // frame. var pesFrameDuration = expectedSampleDuration * pes2mp4ScaleFactor; var nextPtsNorm = nextAacPts; for (var i = 0; i < samples0.length; i++) { samples0[i].ptsNorm = this._PTSNormalize(samples0[i].pts - this._initDTS, nextAacPts); } samples0.sort(function (a, b) { return a.ptsNorm - b.ptsNorm; }); // only inject/drop audio frames in case time offset is accurate if (accurate && track.isAAC) { for (var _i3 = 0; _i3 < samples0.length;) { // First, let's see how far off this frame is from where we expect it to be var sample = samples0[_i3], ptsNorm = sample.ptsNorm, delta = ptsNorm - nextPtsNorm; if (Math.abs(delta) > pesFrameDuration / 2) { stats.audioGap = stats.audioGap || []; stats.audioGap.push(delta / 90); } // If we're overlapping by more than a duration, drop this sample if (delta < -pesFrameDuration) { _logger.logger.log('Dropping frame due to ' + Math.abs(delta / 90) + ' ms overlap.'); samples0.splice(_i3, 1); track.len -= sample.unit.length; // Don't touch nextPtsNorm or i } // Otherwise, if we're more than a frame away from where we should be, insert missing frames else if (delta > pesFrameDuration) { var missing = Math.round(delta / pesFrameDuration); _logger.logger.log('Injecting ' + missing + ' frame' + (missing > 1 ? 's' : '') + ' of missing audio due to ' + Math.round(delta / 90) + ' ms gap.'); for (var j = 0; j < missing; j++) { newStamp = nextPtsNorm + this._initDTS; newStamp = Math.max(newStamp, this._initDTS); fillFrame = _aac2.default.getSilentFrame(track.channelCount); if (!fillFrame) { _logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.'); fillFrame = sample.unit.slice(0); } samples0.splice(_i3, 0, { unit: fillFrame, pts: newStamp, dts: newStamp }); track.len += fillFrame.length; nextPtsNorm += pesFrameDuration; _i3 += 1; } // Adjust sample to next expected pts sample.pts = sample.dts = nextPtsNorm + this._initDTS; nextPtsNorm += pesFrameDuration; _i3 += 1; } // Otherwise, we're within half a frame duration, so just adjust pts else { nextPtsNorm += pesFrameDuration; if (_i3 === 0) { sample.pts = sample.dts = this._initDTS + nextAacPts; } else { sample.pts = sample.dts = samples0[_i3 - 1].pts + pesFrameDuration; } _i3 += 1; } } } while (samples0.length) { aacSample = samples0.shift(); unit = aacSample.unit; pts = aacSample.pts - this._initDTS; dts = aacSample.dts - this._initDTS; //logger.log(`Audio/PTS:${Math.round(pts/90)}`); // if not first sample if (lastDTS !== undefined) { ptsnorm = this._PTSNormalize(pts, lastDTS); dtsnorm = this._PTSNormalize(dts, lastDTS); mp4Sample.duration = Math.round((dtsnorm - lastDTS) / pes2mp4ScaleFactor); } else { ptsnorm = this._PTSNormalize(pts, nextAacPts); dtsnorm = this._PTSNormalize(dts, nextAacPts); var _delta = Math.round(1000 * (ptsnorm - nextAacPts) / pesTimeScale), numMissingFrames = 0; // log delta if (contiguous && _delta && track.isAAC) { if (_delta > 0) { numMissingFrames = Math.round((ptsnorm - nextAacPts) / pesFrameDuration); _logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it'); if (numMissingFrames > 0) { fillFrame = _aac2.default.getSilentFrame(track.channelCount); if (!fillFrame) { fillFrame = unit.slice(0); } track.len += numMissingFrames * fillFrame.length; } // if we have frame overlap, overlapping for more than half a frame duraion } else if (_delta < -12) { // drop overlapping audio frames... browser will deal with it _logger.logger.log(-_delta + ' ms overlapping between AAC samples detected, drop frame'); track.len -= unit.byteLength; continue; } // set PTS/DTS to expected PTS/DTS ptsnorm = dtsnorm = nextAacPts; } // remember first PTS of our aacSamples, ensure value is positive firstPTS = Math.max(0, ptsnorm); firstDTS = Math.max(0, dtsnorm); if (track.len <= 0) { return; } /* concatenate the audio data and construct the mdat in place (need 8 more bytes to fill length and mdat type) */ if (rawMPEG) { mdat = new Uint8Array(track.len); } else { mdat = new Uint8Array(track.len + 8); view = new DataView(mdat.buffer); view.setUint32(0, mdat.byteLength); mdat.set(_mp4Generator2.default.types.mdat, 4); } for (var _i4 = 0; _i4 < numMissingFrames; _i4++) { newStamp = ptsnorm - (numMissingFrames - _i4) * pesFrameDuration; fillFrame = _aac2.default.getSilentFrame(track.channelCount); if (!fillFrame) { _logger.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.'); fillFrame = unit.slice(0); } mdat.set(fillFrame, offset); offset += fillFrame.byteLength; mp4Sample = { size: fillFrame.byteLength, cts: 0, duration: 1024, flags: { isLeading: 0, isDependedOn: 0, hasRedundancy: 0, degradPrio: 0, dependsOn: 1 } }; samples.push(mp4Sample); } } mdat.set(unit, offset); offset += unit.byteLength; //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${aacSample.pts}/${aacSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(aacSample.pts/4294967296).toFixed(3)}'); mp4Sample = { size: unit.byteLength, cts: 0, duration: 0, flags: { isLeading: 0, isDependedOn: 0, hasRedundancy: 0, degradPrio: 0, dependsOn: 1 } }; samples.push(mp4Sample); lastDTS = dtsnorm; } var lastSampleDuration = 0; var nbSamples = samples.length; //set last sample duration as being identical to previous sample if (nbSamples >= 2) { lastSampleDuration = samples[nbSamples - 2].duration; mp4Sample.duration = lastSampleDuration; } if (nbSamples) { // next aac sample PTS should be equal to last sample PTS + duration this.nextAacPts = ptsnorm + pes2mp4ScaleFactor * lastSampleDuration; //logger.log('Audio/PTS/PTSend:' + aacSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0)); track.len = 0; track.samples = samples; if (rawMPEG) { moof = new Uint8Array(); } else { moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track); } track.samples = []; var audioData = { data1: moof, data2: mdat, startPTS: firstPTS / pesTimeScale, endPTS: this.nextAacPts / pesTimeScale, startDTS: firstDTS / pesTimeScale, endDTS: (dtsnorm + pes2mp4ScaleFactor * lastSampleDuration) / pesTimeScale, type: 'audio', nb: nbSamples }; this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData); return audioData; } return null; } }, { key: 'remuxEmptyAudio', value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData, stats) { var pesTimeScale = this.PES_TIMESCALE, mp4timeScale = track.timescale ? track.timescale : track.audiosamplerate, pes2mp4ScaleFactor = pesTimeScale / mp4timeScale, startDTS = (contiguous ? this.nextAacPts : videoData.startDTS * pesTimeScale) + this._initDTS, endDTS = videoData.endDTS * pesTimeScale + this._initDTS, // one sample's duration value sampleDuration = 1024, frameDuration = pes2mp4ScaleFactor * sampleDuration, // samples count of this segment's duration nbSamples = Math.ceil((endDTS - startDTS) / frameDuration), // silent frame silentFrame = _aac2.default.getSilentFrame(track.channelCount); // Can't remux if we can't generate a silent frame... if (!silentFrame) { stats.noSilentFrame = (stats.noSilentFrame | 0) + 1; _logger.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!'); return; } var samples = []; for (var i = 0; i < nbSamples; i++) { var stamp = startDTS + i * frameDuration; samples.push({ unit: silentFrame.slice(0), pts: stamp, dts: stamp }); track.len += silentFrame.length; } track.samples = samples; this.remuxAudio(track, timeOffset, contiguous, undefined, stats); } }, { key: 'remuxID3', value: function remuxID3(track, timeOffset) { var length = track.samples.length, sample; // consume samples if (length) { for (var index = 0; index < length; index++) { sample = track.samples[index]; // setting id3 pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE; sample.dts = (sample.dts - this._initDTS) / this.PES_TIMESCALE; } this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, { samples: track.samples }); } track.samples = []; timeOffset = timeOffset; } }, { key: 'remuxText', value: function remuxText(track, timeOffset) { track.samples.sort(function (a, b) { return a.pts - b.pts; }); var length = track.samples.length, sample; // consume samples if (length) { for (var index = 0; index < length; index++) { sample = track.samples[index]; // setting text pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE; } this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, { samples: track.samples }); } track.samples = []; timeOffset = timeOffset; } }, { key: '_PTSNormalize', value: function _PTSNormalize(value, reference) { var offset; if (reference === undefined) { return value; } if (reference < value) { // - 2^33 offset = -8589934592; } else { // + 2^33 offset = 8589934592; } /* PTS is 33bit (from 0 to 2^33 -1) if diff between value and reference is bigger than half of the amplitude (2^32) then it means that PTS looping occured. fill the gap */ while (Math.abs(value - reference) > 4294967296) { value += offset; } return value; } }, { key: 'passthrough', get: function get() { return false; } }]); return MP4Remuxer; }(); exports.default = MP4Remuxer; },{"../errors":20,"../events":22,"../helper/aac":23,"../remux/mp4-generator":30,"../utils/browser":35,"../utils/logger":38,"../utils/polyfill":39}],32:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * passthrough remuxer */ var _events = require('../events'); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PassThroughRemuxer = function () { function PassThroughRemuxer(observer) { _classCallCheck(this, PassThroughRemuxer); this.observer = observer; this.ISGenerated = false; } _createClass(PassThroughRemuxer, [{ key: 'destroy', value: function destroy() {} }, { key: 'insertDiscontinuity', value: function insertDiscontinuity() {} }, { key: 'switchLevel', value: function switchLevel() { this.ISGenerated = false; } }, { key: 'remux', value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, rawData) { var observer = this.observer; // generate Init Segment if needed if (!this.ISGenerated) { var tracks = {}, data = { tracks: tracks, unique: true }, track = videoTrack, codec = track.codec; if (codec) { data.tracks.video = { container: track.container, codec: codec, metadata: { width: track.width, height: track.height } }; } track = audioTrack; codec = track.codec; if (codec) { data.tracks.audio = { container: track.container, codec: codec, metadata: { channelCount: track.channelCount } }; } this.ISGenerated = true; observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data); } observer.trigger(_events2.default.FRAG_PARSING_DATA, { data1: rawData, startPTS: timeOffset, startDTS: timeOffset, type: 'audiovideo', nb: 1, dropped: 0, deltaPTS: 0 }); } }, { key: 'passthrough', get: function get() { return true; } }]); return PassThroughRemuxer; }(); exports.default = PassThroughRemuxer; },{"../events":22}],33:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js var AttrList = function () { function AttrList(attrs) { _classCallCheck(this, AttrList); if (typeof attrs === 'string') { attrs = AttrList.parseAttrList(attrs); } for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { this[attr] = attrs[attr]; } } } _createClass(AttrList, [{ key: 'decimalInteger', value: function decimalInteger(attrName) { var intValue = parseInt(this[attrName], 10); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; } }, { key: 'hexadecimalInteger', value: function hexadecimalInteger(attrName) { if (this[attrName]) { var stringValue = (this[attrName] || '0x').slice(2); stringValue = (stringValue.length & 1 ? '0' : '') + stringValue; var value = new Uint8Array(stringValue.length / 2); for (var i = 0; i < stringValue.length / 2; i++) { value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16); } return value; } else { return null; } } }, { key: 'hexadecimalIntegerAsNumber', value: function hexadecimalIntegerAsNumber(attrName) { var intValue = parseInt(this[attrName], 16); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; } }, { key: 'decimalFloatingPoint', value: function decimalFloatingPoint(attrName) { return parseFloat(this[attrName]); } }, { key: 'enumeratedString', value: function enumeratedString(attrName) { return this[attrName]; } }, { key: 'decimalResolution', value: function decimalResolution(attrName) { var res = /^(\d+)x(\d+)$/.exec(this[attrName]); if (res === null) { return undefined; } return { width: parseInt(res[1], 10), height: parseInt(res[2], 10) }; } }], [{ key: 'parseAttrList', value: function parseAttrList(input) { var re = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; var match, attrs = {}; while ((match = re.exec(input)) !== null) { var value = match[2], quote = '"'; if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) { value = value.slice(1, -1); } attrs[match[1]] = value; } return attrs; } }]); return AttrList; }(); exports.default = AttrList; },{}],34:[function(require,module,exports){ "use strict"; var BinarySearch = { /** * Searches for an item in an array which matches a certain condition. * This requires the condition to only match one item in the array, * and for the array to be ordered. * * @param {Array} list The array to search. * @param {Function} comparisonFunction * Called and provided a candidate item as the first argument. * Should return: * > -1 if the item should be located at a lower index than the provided item. * > 1 if the item should be located at a higher index than the provided item. * > 0 if the item is the item you're looking for. * * @return {*} The object if it is found or null otherwise. */ search: function search(list, comparisonFunction) { var minIndex = 0; var maxIndex = list.length - 1; var currentIndex = null; var currentElement = null; while (minIndex <= maxIndex) { currentIndex = (minIndex + maxIndex) / 2 | 0; currentElement = list[currentIndex]; var comparisonResult = comparisonFunction(currentElement); if (comparisonResult > 0) { minIndex = currentIndex + 1; } else if (comparisonResult < 0) { maxIndex = currentIndex - 1; } else { return currentElement; } } return null; } }; module.exports = BinarySearch; },{}],35:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var browser = { isSafari: function isSafari() { var vendor = navigator.vendor, userAgent = navigator.userAgent; return vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS'); } }; exports.default = browser; },{}],36:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * * This code was ported from the dash.js project at: * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2 * * The original copyright appears below: * * The copyright in this software is being made available under the BSD License, * included below. This software may be subject to other third party and contributor * rights, including patent rights, and no such rights are granted under this license. * * Copyright (c) 2015-2016, DASH Industry Forum. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * 2. Neither the name of Dash Industry Forum nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes */ var specialCea608CharsCodes = { 0x2a: 0xe1, // lowercase a, acute accent 0x5c: 0xe9, // lowercase e, acute accent 0x5e: 0xed, // lowercase i, acute accent 0x5f: 0xf3, // lowercase o, acute accent 0x60: 0xfa, // lowercase u, acute accent 0x7b: 0xe7, // lowercase c with cedilla 0x7c: 0xf7, // division symbol 0x7d: 0xd1, // uppercase N tilde 0x7e: 0xf1, // lowercase n tilde 0x7f: 0x2588, // Full block // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES 0x80: 0xae, // Registered symbol (R) 0x81: 0xb0, // degree sign 0x82: 0xbd, // 1/2 symbol 0x83: 0xbf, // Inverted (open) question mark 0x84: 0x2122, // Trademark symbol (TM) 0x85: 0xa2, // Cents symbol 0x86: 0xa3, // Pounds sterling 0x87: 0x266a, // Music 8'th note 0x88: 0xe0, // lowercase a, grave accent 0x89: 0x20, // transparent space (regular) 0x8a: 0xe8, // lowercase e, grave accent 0x8b: 0xe2, // lowercase a, circumflex accent 0x8c: 0xea, // lowercase e, circumflex accent 0x8d: 0xee, // lowercase i, circumflex accent 0x8e: 0xf4, // lowercase o, circumflex accent 0x8f: 0xfb, // lowercase u, circumflex accent // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F 0x90: 0xc1, // capital letter A with acute 0x91: 0xc9, // capital letter E with acute 0x92: 0xd3, // capital letter O with acute 0x93: 0xda, // capital letter U with acute 0x94: 0xdc, // capital letter U with diaresis 0x95: 0xfc, // lowercase letter U with diaeresis 0x96: 0x2018, // opening single quote 0x97: 0xa1, // inverted exclamation mark 0x98: 0x2a, // asterisk 0x99: 0x2019, // closing single quote 0x9a: 0x2501, // box drawings heavy horizontal 0x9b: 0xa9, // copyright sign 0x9c: 0x2120, // Service mark 0x9d: 0x2022, // (round) bullet 0x9e: 0x201c, // Left double quotation mark 0x9f: 0x201d, // Right double quotation mark 0xa0: 0xc0, // uppercase A, grave accent 0xa1: 0xc2, // uppercase A, circumflex 0xa2: 0xc7, // uppercase C with cedilla 0xa3: 0xc8, // uppercase E, grave accent 0xa4: 0xca, // uppercase E, circumflex 0xa5: 0xcb, // capital letter E with diaresis 0xa6: 0xeb, // lowercase letter e with diaresis 0xa7: 0xce, // uppercase I, circumflex 0xa8: 0xcf, // uppercase I, with diaresis 0xa9: 0xef, // lowercase i, with diaresis 0xaa: 0xd4, // uppercase O, circumflex 0xab: 0xd9, // uppercase U, grave accent 0xac: 0xf9, // lowercase u, grave accent 0xad: 0xdb, // uppercase U, circumflex 0xae: 0xab, // left-pointing double angle quotation mark 0xaf: 0xbb, // right-pointing double angle quotation mark // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F 0xb0: 0xc3, // Uppercase A, tilde 0xb1: 0xe3, // Lowercase a, tilde 0xb2: 0xcd, // Uppercase I, acute accent 0xb3: 0xcc, // Uppercase I, grave accent 0xb4: 0xec, // Lowercase i, grave accent 0xb5: 0xd2, // Uppercase O, grave accent 0xb6: 0xf2, // Lowercase o, grave accent 0xb7: 0xd5, // Uppercase O, tilde 0xb8: 0xf5, // Lowercase o, tilde 0xb9: 0x7b, // Open curly brace 0xba: 0x7d, // Closing curly brace 0xbb: 0x5c, // Backslash 0xbc: 0x5e, // Caret 0xbd: 0x5f, // Underscore 0xbe: 0x7c, // Pipe (vertical line) 0xbf: 0x223c, // Tilde operator 0xc0: 0xc4, // Uppercase A, umlaut 0xc1: 0xe4, // Lowercase A, umlaut 0xc2: 0xd6, // Uppercase O, umlaut 0xc3: 0xf6, // Lowercase o, umlaut 0xc4: 0xdf, // Esszett (sharp S) 0xc5: 0xa5, // Yen symbol 0xc6: 0xa4, // Generic currency sign 0xc7: 0x2503, // Box drawings heavy vertical 0xc8: 0xc5, // Uppercase A, ring 0xc9: 0xe5, // Lowercase A, ring 0xca: 0xd8, // Uppercase O, stroke 0xcb: 0xf8, // Lowercase o, strok 0xcc: 0x250f, // Box drawings heavy down and right 0xcd: 0x2513, // Box drawings heavy down and left 0xce: 0x2517, // Box drawings heavy up and right 0xcf: 0x251b // Box drawings heavy up and left }; /** * Utils */ var getCharForByte = function getCharForByte(byte) { var charCode = byte; if (specialCea608CharsCodes.hasOwnProperty(byte)) { charCode = specialCea608CharsCodes[byte]; } return String.fromCharCode(charCode); }; var NR_ROWS = 15, NR_COLS = 32; // Tables to look up row from PAC data var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 }; var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 }; var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 }; var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 }; var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent']; /** * Simple logger class to be able to write with time-stamps and filter on level. */ var logger = { verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 }, time: null, verboseLevel: 0, // Only write errors setTime: function setTime(newTime) { this.time = newTime; }, log: function log(severity, msg) { var minLevel = this.verboseFilter[severity]; if (this.verboseLevel >= minLevel) { console.log(this.time + ' [' + severity + '] ' + msg); } } }; var numArrayToHexArray = function numArrayToHexArray(numArray) { var hexArray = []; for (var j = 0; j < numArray.length; j++) { hexArray.push(numArray[j].toString(16)); } return hexArray; }; var PenState = function () { function PenState(foreground, underline, italics, background, flash) { _classCallCheck(this, PenState); this.foreground = foreground || 'white'; this.underline = underline || false; this.italics = italics || false; this.background = background || 'black'; this.flash = flash || false; } _createClass(PenState, [{ key: 'reset', value: function reset() { this.foreground = 'white'; this.underline = false; this.italics = false; this.background = 'black'; this.flash = false; } }, { key: 'setStyles', value: function setStyles(styles) { var attribs = ['foreground', 'underline', 'italics', 'background', 'flash']; for (var i = 0; i < attribs.length; i++) { var style = attribs[i]; if (styles.hasOwnProperty(style)) { this[style] = styles[style]; } } } }, { key: 'isDefault', value: function isDefault() { return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash; } }, { key: 'equals', value: function equals(other) { return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash; } }, { key: 'copy', value: function copy(newPenState) { this.foreground = newPenState.foreground; this.underline = newPenState.underline; this.italics = newPenState.italics; this.background = newPenState.background; this.flash = newPenState.flash; } }, { key: 'toString', value: function toString() { return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash; } }]); return PenState; }(); /** * Unicode character with styling and background. * @constructor */ var StyledUnicodeChar = function () { function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) { _classCallCheck(this, StyledUnicodeChar); this.uchar = uchar || ' '; // unicode character this.penState = new PenState(foreground, underline, italics, background, flash); } _createClass(StyledUnicodeChar, [{ key: 'reset', value: function reset() { this.uchar = ' '; this.penState.reset(); } }, { key: 'setChar', value: function setChar(uchar, newPenState) { this.uchar = uchar; this.penState.copy(newPenState); } }, { key: 'setPenState', value: function setPenState(newPenState) { this.penState.copy(newPenState); } }, { key: 'equals', value: function equals(other) { return this.uchar === other.uchar && this.penState.equals(other.penState); } }, { key: 'copy', value: function copy(newChar) { this.uchar = newChar.uchar; this.penState.copy(newChar.penState); } }, { key: 'isEmpty', value: function isEmpty() { return this.uchar === ' ' && this.penState.isDefault(); } }]); return StyledUnicodeChar; }(); /** * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar. * @constructor */ var Row = function () { function Row() { _classCallCheck(this, Row); this.chars = []; for (var i = 0; i < NR_COLS; i++) { this.chars.push(new StyledUnicodeChar()); } this.pos = 0; this.currPenState = new PenState(); } _createClass(Row, [{ key: 'equals', value: function equals(other) { var equal = true; for (var i = 0; i < NR_COLS; i++) { if (!this.chars[i].equals(other.chars[i])) { equal = false; break; } } return equal; } }, { key: 'copy', value: function copy(other) { for (var i = 0; i < NR_COLS; i++) { this.chars[i].copy(other.chars[i]); } } }, { key: 'isEmpty', value: function isEmpty() { var empty = true; for (var i = 0; i < NR_COLS; i++) { if (!this.chars[i].isEmpty()) { empty = false; break; } } return empty; } /** * Set the cursor to a valid column. */ }, { key: 'setCursor', value: function setCursor(absPos) { if (this.pos !== absPos) { this.pos = absPos; } if (this.pos < 0) { logger.log('ERROR', 'Negative cursor position ' + this.pos); this.pos = 0; } else if (this.pos > NR_COLS) { logger.log('ERROR', 'Too large cursor position ' + this.pos); this.pos = NR_COLS; } } /** * Move the cursor relative to current position. */ }, { key: 'moveCursor', value: function moveCursor(relPos) { var newPos = this.pos + relPos; if (relPos > 1) { for (var i = this.pos + 1; i < newPos + 1; i++) { this.chars[i].setPenState(this.currPenState); } } this.setCursor(newPos); } /** * Backspace, move one step back and clear character. */ }, { key: 'backSpace', value: function backSpace() { this.moveCursor(-1); this.chars[this.pos].setChar(' ', this.currPenState); } }, { key: 'insertChar', value: function insertChar(byte) { if (byte >= 0x90) { //Extended char this.backSpace(); } var char = getCharForByte(byte); if (this.pos >= NR_COLS) { logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!'); return; } this.chars[this.pos].setChar(char, this.currPenState); this.moveCursor(1); } }, { key: 'clearFromPos', value: function clearFromPos(startPos) { var i; for (i = startPos; i < NR_COLS; i++) { this.chars[i].reset(); } } }, { key: 'clear', value: function clear() { this.clearFromPos(0); this.pos = 0; this.currPenState.reset(); } }, { key: 'clearToEndOfRow', value: function clearToEndOfRow() { this.clearFromPos(this.pos); } }, { key: 'getTextString', value: function getTextString() { var chars = []; var empty = true; for (var i = 0; i < NR_COLS; i++) { var char = this.chars[i].uchar; if (char !== ' ') { empty = false; } chars.push(char); } if (empty) { return ''; } else { return chars.join(''); } } }, { key: 'setPenStyles', value: function setPenStyles(styles) { this.currPenState.setStyles(styles); var currChar = this.chars[this.pos]; currChar.setPenState(this.currPenState); } }]); return Row; }(); /** * Keep a CEA-608 screen of 32x15 styled characters * @constructor */ var CaptionScreen = function () { function CaptionScreen() { _classCallCheck(this, CaptionScreen); this.rows = []; for (var i = 0; i < NR_ROWS; i++) { this.rows.push(new Row()); // Note that we use zero-based numbering (0-14) } this.currRow = NR_ROWS - 1; this.nrRollUpRows = null; this.reset(); } _createClass(CaptionScreen, [{ key: 'reset', value: function reset() { for (var i = 0; i < NR_ROWS; i++) { this.rows[i].clear(); } this.currRow = NR_ROWS - 1; } }, { key: 'equals', value: function equals(other) { var equal = true; for (var i = 0; i < NR_ROWS; i++) { if (!this.rows[i].equals(other.rows[i])) { equal = false; break; } } return equal; } }, { key: 'copy', value: function copy(other) { for (var i = 0; i < NR_ROWS; i++) { this.rows[i].copy(other.rows[i]); } } }, { key: 'isEmpty', value: function isEmpty() { var empty = true; for (var i = 0; i < NR_ROWS; i++) { if (!this.rows[i].isEmpty()) { empty = false; break; } } return empty; } }, { key: 'backSpace', value: function backSpace() { var row = this.rows[this.currRow]; row.backSpace(); } }, { key: 'clearToEndOfRow', value: function clearToEndOfRow() { var row = this.rows[this.currRow]; row.clearToEndOfRow(); } /** * Insert a character (without styling) in the current row. */ }, { key: 'insertChar', value: function insertChar(char) { var row = this.rows[this.currRow]; row.insertChar(char); } }, { key: 'setPen', value: function setPen(styles) { var row = this.rows[this.currRow]; row.setPenStyles(styles); } }, { key: 'moveCursor', value: function moveCursor(relPos) { var row = this.rows[this.currRow]; row.moveCursor(relPos); } }, { key: 'setCursor', value: function setCursor(absPos) { logger.log('INFO', 'setCursor: ' + absPos); var row = this.rows[this.currRow]; row.setCursor(absPos); } }, { key: 'setPAC', value: function setPAC(pacData) { logger.log('INFO', 'pacData = ' + JSON.stringify(pacData)); var newRow = pacData.row - 1; if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) { newRow = this.nrRollUpRows - 1; } this.currRow = newRow; var row = this.rows[this.currRow]; if (pacData.indent !== null) { var indent = pacData.indent; var prevPos = Math.max(indent - 1, 0); row.setCursor(pacData.indent); pacData.color = row.chars[prevPos].penState.foreground; } var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false }; this.setPen(styles); } /** * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility). */ }, { key: 'setBkgData', value: function setBkgData(bkgData) { logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData)); this.backSpace(); this.setPen(bkgData); this.insertChar(0x20); //Space } }, { key: 'setRollUpRows', value: function setRollUpRows(nrRows) { this.nrRollUpRows = nrRows; } }, { key: 'rollUp', value: function rollUp() { if (this.nrRollUpRows === null) { logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet'); return; //Not properly setup } logger.log('TEXT', this.getDisplayText()); var topRowIndex = this.currRow + 1 - this.nrRollUpRows; var topRow = this.rows.splice(topRowIndex, 1)[0]; topRow.clear(); this.rows.splice(this.currRow, 0, topRow); logger.log('INFO', 'Rolling up'); //logger.log('TEXT', this.get_display_text()) } /** * Get all non-empty rows with as unicode text. */ }, { key: 'getDisplayText', value: function getDisplayText(asOneRow) { asOneRow = asOneRow || false; var displayText = []; var text = ''; var rowNr = -1; for (var i = 0; i < NR_ROWS; i++) { var rowText = this.rows[i].getTextString(); if (rowText) { rowNr = i + 1; if (asOneRow) { displayText.push('Row ' + rowNr + ': \'' + rowText + '\''); } else { displayText.push(rowText.trim()); } } } if (displayText.length > 0) { if (asOneRow) { text = '[' + displayText.join(' | ') + ']'; } else { text = displayText.join('\n'); } } return text; } }, { key: 'getTextAndFormat', value: function getTextAndFormat() { return this.rows; } }]); return CaptionScreen; }(); //var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT']; var Cea608Channel = function () { function Cea608Channel(channelNumber, outputFilter) { _classCallCheck(this, Cea608Channel); this.chNr = channelNumber; this.outputFilter = outputFilter; this.mode = null; this.verbose = 0; this.displayedMemory = new CaptionScreen(); this.nonDisplayedMemory = new CaptionScreen(); this.lastOutputScreen = new CaptionScreen(); this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; this.writeScreen = this.displayedMemory; this.mode = null; this.cueStartTime = null; // Keeps track of where a cue started. } _createClass(Cea608Channel, [{ key: 'reset', value: function reset() { this.mode = null; this.displayedMemory.reset(); this.nonDisplayedMemory.reset(); this.lastOutputScreen.reset(); this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; this.writeScreen = this.displayedMemory; this.mode = null; this.cueStartTime = null; this.lastCueEndTime = null; } }, { key: 'getHandler', value: function getHandler() { return this.outputFilter; } }, { key: 'setHandler', value: function setHandler(newHandler) { this.outputFilter = newHandler; } }, { key: 'setPAC', value: function setPAC(pacData) { this.writeScreen.setPAC(pacData); } }, { key: 'setBkgData', value: function setBkgData(bkgData) { this.writeScreen.setBkgData(bkgData); } }, { key: 'setMode', value: function setMode(newMode) { if (newMode === this.mode) { return; } this.mode = newMode; logger.log('INFO', 'MODE=' + newMode); if (this.mode === 'MODE_POP-ON') { this.writeScreen = this.nonDisplayedMemory; } else { this.writeScreen = this.displayedMemory; this.writeScreen.reset(); } if (this.mode !== 'MODE_ROLL-UP') { this.displayedMemory.nrRollUpRows = null; this.nonDisplayedMemory.nrRollUpRows = null; } this.mode = newMode; } }, { key: 'insertChars', value: function insertChars(chars) { for (var i = 0; i < chars.length; i++) { this.writeScreen.insertChar(chars[i]); } var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP'; logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true)); if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') { logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)); this.outputDataUpdate(); } } }, { key: 'ccRCL', value: function ccRCL() { // Resume Caption Loading (switch mode to Pop On) logger.log('INFO', 'RCL - Resume Caption Loading'); this.setMode('MODE_POP-ON'); } }, { key: 'ccBS', value: function ccBS() { // BackSpace logger.log('INFO', 'BS - BackSpace'); if (this.mode === 'MODE_TEXT') { return; } this.writeScreen.backSpace(); if (this.writeScreen === this.displayedMemory) { this.outputDataUpdate(); } } }, { key: 'ccAOF', value: function ccAOF() { // Reserved (formerly Alarm Off) return; } }, { key: 'ccAON', value: function ccAON() { // Reserved (formerly Alarm On) return; } }, { key: 'ccDER', value: function ccDER() { // Delete to End of Row logger.log('INFO', 'DER- Delete to End of Row'); this.writeScreen.clearToEndOfRow(); this.outputDataUpdate(); } }, { key: 'ccRU', value: function ccRU(nrRows) { //Roll-Up Captions-2,3,or 4 Rows logger.log('INFO', 'RU(' + nrRows + ') - Roll Up'); this.writeScreen = this.displayedMemory; this.setMode('MODE_ROLL-UP'); this.writeScreen.setRollUpRows(nrRows); } }, { key: 'ccFON', value: function ccFON() { //Flash On logger.log('INFO', 'FON - Flash On'); this.writeScreen.setPen({ flash: true }); } }, { key: 'ccRDC', value: function ccRDC() { // Resume Direct Captioning (switch mode to PaintOn) logger.log('INFO', 'RDC - Resume Direct Captioning'); this.setMode('MODE_PAINT-ON'); } }, { key: 'ccTR', value: function ccTR() { // Text Restart in text mode (not supported, however) logger.log('INFO', 'TR'); this.setMode('MODE_TEXT'); } }, { key: 'ccRTD', value: function ccRTD() { // Resume Text Display in Text mode (not supported, however) logger.log('INFO', 'RTD'); this.setMode('MODE_TEXT'); } }, { key: 'ccEDM', value: function ccEDM() { // Erase Displayed Memory logger.log('INFO', 'EDM - Erase Displayed Memory'); this.displayedMemory.reset(); this.outputDataUpdate(); } }, { key: 'ccCR', value: function ccCR() { // Carriage Return logger.log('CR - Carriage Return'); this.writeScreen.rollUp(); this.outputDataUpdate(); } }, { key: 'ccENM', value: function ccENM() { //Erase Non-Displayed Memory logger.log('INFO', 'ENM - Erase Non-displayed Memory'); this.nonDisplayedMemory.reset(); } }, { key: 'ccEOC', value: function ccEOC() { //End of Caption (Flip Memories) logger.log('INFO', 'EOC - End Of Caption'); if (this.mode === 'MODE_POP-ON') { var tmp = this.displayedMemory; this.displayedMemory = this.nonDisplayedMemory; this.nonDisplayedMemory = tmp; this.writeScreen = this.nonDisplayedMemory; logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText()); } this.outputDataUpdate(); } }, { key: 'ccTO', value: function ccTO(nrCols) { // Tab Offset 1,2, or 3 columns logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset'); this.writeScreen.moveCursor(nrCols); } }, { key: 'ccMIDROW', value: function ccMIDROW(secondByte) { // Parse MIDROW command var styles = { flash: false }; styles.underline = secondByte % 2 === 1; styles.italics = secondByte >= 0x2e; if (!styles.italics) { var colorIndex = Math.floor(secondByte / 2) - 0x10; var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta']; styles.foreground = colors[colorIndex]; } else { styles.foreground = 'white'; } logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles)); this.writeScreen.setPen(styles); } }, { key: 'outputDataUpdate', value: function outputDataUpdate() { var t = logger.time; if (t === null) { return; } if (this.outputFilter) { if (this.outputFilter.updateData) { this.outputFilter.updateData(t, this.displayedMemory); } if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue this.cueStartTime = t; } else { if (!this.displayedMemory.equals(this.lastOutputScreen)) { if (this.outputFilter.newCue) { this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen); } this.cueStartTime = this.displayedMemory.isEmpty() ? null : t; } } this.lastOutputScreen.copy(this.displayedMemory); } } }, { key: 'cueSplitAtTime', value: function cueSplitAtTime(t) { if (this.outputFilter) { if (!this.displayedMemory.isEmpty()) { if (this.outputFilter.newCue) { this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory); } this.cueStartTime = t; } } } }]); return Cea608Channel; }(); var Cea608Parser = function () { function Cea608Parser(field, out1, out2) { _classCallCheck(this, Cea608Parser); this.field = field || 1; this.outputs = [out1, out2]; this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)]; this.currChNr = -1; // Will be 1 or 2 this.lastCmdA = null; // First byte of last command this.lastCmdB = null; // Second byte of last command this.bufferedData = []; this.startTime = null; this.lastTime = null; this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 }; } _createClass(Cea608Parser, [{ key: 'getHandler', value: function getHandler(index) { return this.channels[index].getHandler(); } }, { key: 'setHandler', value: function setHandler(index, newHandler) { this.channels[index].setHandler(newHandler); } /** * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs. */ }, { key: 'addData', value: function addData(t, byteList) { var cmdFound, a, b, charsFound = false; this.lastTime = t; logger.setTime(t); for (var i = 0; i < byteList.length; i += 2) { a = byteList[i] & 0x7f; b = byteList[i + 1] & 0x7f; if (a === 0 && b === 0) { this.dataCounters.padding += 2; continue; } else { logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')'); } cmdFound = this.parseCmd(a, b); if (!cmdFound) { cmdFound = this.parseMidrow(a, b); } if (!cmdFound) { cmdFound = this.parsePAC(a, b); } if (!cmdFound) { cmdFound = this.parseBackgroundAttributes(a, b); } if (!cmdFound) { charsFound = this.parseChars(a, b); if (charsFound) { if (this.currChNr && this.currChNr >= 0) { var channel = this.channels[this.currChNr - 1]; channel.insertChars(charsFound); } else { logger.log('WARNING', 'No channel found yet. TEXT-MODE?'); } } } if (cmdFound) { this.dataCounters.cmd += 2; } else if (charsFound) { this.dataCounters.char += 2; } else { this.dataCounters.other += 2; logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]])); } } } /** * Parse Command. * @returns {Boolean} Tells if a command was found */ }, { key: 'parseCmd', value: function parseCmd(a, b) { var chNr = null; var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F; var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23; if (!(cond1 || cond2)) { return false; } if (a === this.lastCmdA && b === this.lastCmdB) { this.lastCmdA = null; this.lastCmdB = null; // Repeated commands are dropped (once) logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped'); return true; } if (a === 0x14 || a === 0x17) { chNr = 1; } else { chNr = 2; // (a === 0x1C || a=== 0x1f) } var channel = this.channels[chNr - 1]; if (a === 0x14 || a === 0x1C) { if (b === 0x20) { channel.ccRCL(); } else if (b === 0x21) { channel.ccBS(); } else if (b === 0x22) { channel.ccAOF(); } else if (b === 0x23) { channel.ccAON(); } else if (b === 0x24) { channel.ccDER(); } else if (b === 0x25) { channel.ccRU(2); } else if (b === 0x26) { channel.ccRU(3); } else if (b === 0x27) { channel.ccRU(4); } else if (b === 0x28) { channel.ccFON(); } else if (b === 0x29) { channel.ccRDC(); } else if (b === 0x2A) { channel.ccTR(); } else if (b === 0x2B) { channel.ccRTD(); } else if (b === 0x2C) { channel.ccEDM(); } else if (b === 0x2D) { channel.ccCR(); } else if (b === 0x2E) { channel.ccENM(); } else if (b === 0x2F) { channel.ccEOC(); } } else { //a == 0x17 || a == 0x1F channel.ccTO(b - 0x20); } this.lastCmdA = a; this.lastCmdB = b; this.currChNr = chNr; return true; } /** * Parse midrow styling command * @returns {Boolean} */ }, { key: 'parseMidrow', value: function parseMidrow(a, b) { var chNr = null; if ((a === 0x11 || a === 0x19) && 0x20 <= b && b <= 0x2f) { if (a === 0x11) { chNr = 1; } else { chNr = 2; } if (chNr !== this.currChNr) { logger.log('ERROR', 'Mismatch channel in midrow parsing'); return false; } var channel = this.channels[chNr - 1]; channel.ccMIDROW(b); logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')'); return true; } return false; } /** * Parse Preable Access Codes (Table 53). * @returns {Boolean} Tells if PAC found */ }, { key: 'parsePAC', value: function parsePAC(a, b) { var chNr = null; var row = null; var case1 = (0x11 <= a && a <= 0x17 || 0x19 <= a && a <= 0x1F) && 0x40 <= b && b <= 0x7F; var case2 = (a === 0x10 || a === 0x18) && 0x40 <= b && b <= 0x5F; if (!(case1 || case2)) { return false; } if (a === this.lastCmdA && b === this.lastCmdB) { this.lastCmdA = null; this.lastCmdB = null; return true; // Repeated commands are dropped (once) } chNr = a <= 0x17 ? 1 : 2; if (0x40 <= b && b <= 0x5F) { row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a]; } else { // 0x60 <= b <= 0x7F row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a]; } var pacData = this.interpretPAC(row, b); var channel = this.channels[chNr - 1]; channel.setPAC(pacData); this.lastCmdA = a; this.lastCmdB = b; this.currChNr = chNr; return true; } /** * Interpret the second byte of the pac, and return the information. * @returns {Object} pacData with style parameters. */ }, { key: 'interpretPAC', value: function interpretPAC(row, byte) { var pacIndex = byte; var pacData = { color: null, italics: false, indent: null, underline: false, row: row }; if (byte > 0x5F) { pacIndex = byte - 0x60; } else { pacIndex = byte - 0x40; } pacData.underline = (pacIndex & 1) === 1; if (pacIndex <= 0xd) { pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)]; } else if (pacIndex <= 0xf) { pacData.italics = true; pacData.color = 'white'; } else { pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4; } return pacData; // Note that row has zero offset. The spec uses 1. } /** * Parse characters. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise. */ }, { key: 'parseChars', value: function parseChars(a, b) { var channelNr = null, charCodes = null, charCode1 = null; if (a >= 0x19) { channelNr = 2; charCode1 = a - 8; } else { channelNr = 1; charCode1 = a; } if (0x11 <= charCode1 && charCode1 <= 0x13) { // Special character var oneCode = b; if (charCode1 === 0x11) { oneCode = b + 0x50; } else if (charCode1 === 0x12) { oneCode = b + 0x70; } else { oneCode = b + 0x90; } logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr); charCodes = [oneCode]; } else if (0x20 <= a && a <= 0x7f) { charCodes = b === 0 ? [a] : [a, b]; } if (charCodes) { var hexCodes = numArrayToHexArray(charCodes); logger.log('DEBUG', 'Char codes = ' + hexCodes.join(',')); this.lastCmdA = null; this.lastCmdB = null; } return charCodes; } /** * Parse extended background attributes as well as new foreground color black. * @returns{Boolean} Tells if background attributes are found */ }, { key: 'parseBackgroundAttributes', value: function parseBackgroundAttributes(a, b) { var bkgData, index, chNr, channel; var case1 = (a === 0x10 || a === 0x18) && 0x20 <= b && b <= 0x2f; var case2 = (a === 0x17 || a === 0x1f) && 0x2d <= b && b <= 0x2f; if (!(case1 || case2)) { return false; } bkgData = {}; if (a === 0x10 || a === 0x18) { index = Math.floor((b - 0x20) / 2); bkgData.background = backgroundColors[index]; if (b % 2 === 1) { bkgData.background = bkgData.background + '_semi'; } } else if (b === 0x2d) { bkgData.background = 'transparent'; } else { bkgData.foreground = 'black'; if (b === 0x2f) { bkgData.underline = true; } } chNr = a < 0x18 ? 1 : 2; channel = this.channels[chNr - 1]; channel.setBkgData(bkgData); this.lastCmdA = null; this.lastCmdB = null; return true; } /** * Reset state of parser and its channels. */ }, { key: 'reset', value: function reset() { for (var i = 0; i < this.channels.length; i++) { if (this.channels[i]) { this.channels[i].reset(); } } this.lastCmdA = null; this.lastCmdB = null; } /** * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty. */ }, { key: 'cueSplitAtTime', value: function cueSplitAtTime(t) { for (var i = 0; i < this.channels.length; i++) { if (this.channels[i]) { this.channels[i].cueSplitAtTime(t); } } } }]); return Cea608Parser; }(); exports.default = Cea608Parser; },{}],37:[function(require,module,exports){ 'use strict'; var Cues = { newCue: function newCue(track, startTime, endTime, captionScreen) { var row; var cue; var indenting; var indent; var text; var VTTCue = window.VTTCue || window.TextTrackCue; for (var r = 0; r < captionScreen.rows.length; r++) { row = captionScreen.rows[r]; indenting = true; indent = 0; text = ''; if (!row.isEmpty()) { for (var c = 0; c < row.chars.length; c++) { if (row.chars[c].uchar.match(/\s/) && indenting) { indent++; } else { text += row.chars[c].uchar; indenting = false; } } cue = new VTTCue(startTime, endTime, text.trim()); if (indent >= 16) { indent--; } else { indent++; } // VTTCue.line get's flakey when using controls, so let's now include line 13&14 // also, drop line 1 since it's to close to the top if (navigator.userAgent.match(/Firefox\//)) { cue.line = r + 1; } else { cue.line = r > 7 ? r - 2 : r + 1; } cue.align = 'left'; cue.position = 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0); track.addCue(cue); } } } }; module.exports = Cues; },{}],38:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function noop() {} var fakeLogger = { trace: noop, debug: noop, log: noop, warn: noop, info: noop, error: noop }; var exportedLogger = fakeLogger; //let lastCallTime; // function formatMsgWithTimeInfo(type, msg) { // const now = Date.now(); // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0'; // lastCallTime = now; // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )'; // return msg; // } var lastMsg = ''; function formatMsg(type, msg) { msg = '[' + type + '] > ' + msg; return msg; } function consolePrintFn(type) { var func = window.console[type]; if (func) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args[0]) { args[0] = formatMsg(type, args[0]); if (args.join(' ') === lastMsg) { return; } lastMsg = args.join(' '); } func.apply(window.console, args); }; } return noop; } function exportLoggerFunctions(debugConfig) { for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { functions[_key2 - 1] = arguments[_key2]; } functions.forEach(function (type) { exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type); }); } var enableLogs = exports.enableLogs = function enableLogs(debugConfig) { if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') { exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level //'trace', 'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway // fallback to default if needed try { exportedLogger.log(); } catch (e) { exportedLogger = fakeLogger; } } else { exportedLogger = fakeLogger; } }; var logger = exports.logger = exportedLogger; },{}],39:[function(require,module,exports){ "use strict"; if (!ArrayBuffer.prototype.slice) { ArrayBuffer.prototype.slice = function (start, end) { var that = new Uint8Array(this); if (end === undefined) { end = that.length; } var result = new ArrayBuffer(end - start); var resultArray = new Uint8Array(result); for (var i = 0; i < resultArray.length; i++) { resultArray[i] = that[i + start]; } return result; }; } if (!Object.assign) { Object.assign = function (obj) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; if (!source) { continue; } for (var prop in source) { if (source.hasOwnProperty(prop)) { obj[prop] = source[prop]; } } } return obj; }; } },{}],40:[function(require,module,exports){ 'use strict'; var URLHelper = { // build an absolute URL from a relative one using the provided baseURL // if relativeURL is an absolute URL it will be returned as is. buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL) { // remove any remaining space and CRLF relativeURL = relativeURL.trim(); if (/^[a-z]+:/i.test(relativeURL)) { // complete url, not relative return (' ' + relativeURL).slice(1); } var relativeURLQuery = null; var relativeURLHash = null; var relativeURLHashSplit = /^([^#]*)(.*)$/.exec(relativeURL); if (relativeURLHashSplit) { relativeURLHash = relativeURLHashSplit[2]; relativeURL = relativeURLHashSplit[1]; } var relativeURLQuerySplit = /^([^\?]*)(.*)$/.exec(relativeURL); if (relativeURLQuerySplit) { relativeURLQuery = relativeURLQuerySplit[2]; relativeURL = relativeURLQuerySplit[1]; } var baseURLHashSplit = /^([^#]*)(.*)$/.exec(baseURL); if (baseURLHashSplit) { baseURL = baseURLHashSplit[1]; } var baseURLQuerySplit = /^([^\?]*)(.*)$/.exec(baseURL); if (baseURLQuerySplit) { baseURL = baseURLQuerySplit[1]; } var baseURLDomainSplit = /^(([a-z]+:)?\/\/[a-z0-9\.\-_~]+(:[0-9]+)?)?(\/.*)$/i.exec(baseURL); if (!baseURLDomainSplit) { throw new Error('Error trying to parse base URL.'); } // e.g. 'http:', 'https:', '' var baseURLProtocol = baseURLDomainSplit[2] || ''; // e.g. 'http://example.com', '//example.com', '' var baseURLProtocolDomain = baseURLDomainSplit[1] || ''; // e.g. '/a/b/c/playlist.m3u8' var baseURLPath = baseURLDomainSplit[4]; var builtURL = null; if (/^\/\//.test(relativeURL)) { // relative url starts wth '//' so copy protocol (which may be '' if baseUrl didn't provide one) builtURL = baseURLProtocol + '//' + URLHelper.buildAbsolutePath('', relativeURL.substring(2)); } else if (/^\//.test(relativeURL)) { // relative url starts with '/' so start from root of domain builtURL = baseURLProtocolDomain + '/' + URLHelper.buildAbsolutePath('', relativeURL.substring(1)); } else { builtURL = URLHelper.buildAbsolutePath(baseURLProtocolDomain + baseURLPath, relativeURL); } // put the query and hash parts back if (relativeURLQuery) { builtURL += relativeURLQuery; } if (relativeURLHash) { builtURL += relativeURLHash; } return builtURL; }, // build an absolute path using the provided basePath // adapted from https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Using_relative_URLs_in_the_path_parameter // this does not handle the case where relativePath is "/" or "//". These cases should be handled outside this. buildAbsolutePath: function buildAbsolutePath(basePath, relativePath) { var sRelPath = relativePath; var nUpLn, sDir = '', sPath = basePath.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, '$1')); for (var nEnd, nStart = 0; nEnd = sPath.indexOf('/../', nStart), nEnd > -1; nStart = nEnd + nUpLn) { nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length; sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp('(?:\\\/+[^\\\/]*){0,' + (nUpLn - 1) / 3 + '}$'), '/'); } return sDir + sPath.substr(nStart); } }; module.exports = URLHelper; },{}],41:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * XHR based logger */ var _logger = require('../utils/logger'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var XhrLoader = function () { function XhrLoader(config) { _classCallCheck(this, XhrLoader); if (config && config.xhrSetup) { this.xhrSetup = config.xhrSetup; } } _createClass(XhrLoader, [{ key: 'destroy', value: function destroy() { this.abort(); this.loader = null; } }, { key: 'abort', value: function abort() { var loader = this.loader, timeoutHandle = this.timeoutHandle, retryHandle = this.retryHandle; if (loader && loader.readyState !== 4) { this.stats.aborted = true; loader.abort(); } if (timeoutHandle) { window.clearTimeout(timeoutHandle); } if (retryHandle) { window.clearTimeout(retryHandle); } } }, { key: 'load', value: function load(url, responseType, onSuccess, onError, onTimeout, timeout, maxRetry, retryDelay) { var onProgress = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; var frag = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null; this.url = url; if (frag && !isNaN(frag.byteRangeStartOffset) && !isNaN(frag.byteRangeEndOffset)) { this.byteRange = frag.byteRangeStartOffset + '-' + (frag.byteRangeEndOffset - 1); } this.responseType = responseType; this.onSuccess = onSuccess; this.onProgress = onProgress; this.onTimeout = onTimeout; this.onError = onError; this.stats = { trequest: performance.now(), retry: 0 }; this.timeout = timeout; this.maxRetry = maxRetry; this.retryDelay = retryDelay; this.loadInternal(); } }, { key: 'loadInternal', value: function loadInternal() { var xhr; if (typeof XDomainRequest !== 'undefined') { xhr = this.loader = new XDomainRequest(); } else { xhr = this.loader = new XMLHttpRequest(); } xhr.onloadend = this.loadend.bind(this); xhr.onprogress = this.loadprogress.bind(this); var url = this.url; if (location.protocol === 'https:' && /^http:\/\//.test(url)) { url = url.replace(/^http:\/\//, 'https://'); } xhr.open('GET', url, true); if (this.byteRange) { xhr.setRequestHeader('Range', 'bytes=' + this.byteRange); } xhr.responseType = this.responseType; this.stats.tfirst = null; this.stats.loaded = 0; if (this.xhrSetup) { this.xhrSetup(xhr, url); } this.timeoutHandle = window.setTimeout(this.loadtimeout.bind(this), this.timeout); xhr.send(); } }, { key: 'loadend', value: function loadend(event) { var xhr = event.currentTarget, status = xhr.status, stats = this.stats; // don't proceed if xhr has been aborted if (!stats.aborted) { // http status between 200 to 299 are all successful if (status >= 200 && status < 300) { window.clearTimeout(this.timeoutHandle); stats.tload = performance.now(); this.onSuccess(event, stats); } else { // error ... if (stats.retry < this.maxRetry) { _logger.logger.warn(status + ' while loading ' + this.url + ', retrying in ' + this.retryDelay + '...'); this.destroy(); this.retryHandle = window.setTimeout(this.loadInternal.bind(this), this.retryDelay); // exponential backoff this.retryDelay = Math.min(2 * this.retryDelay, 64000); stats.retry++; } else { window.clearTimeout(this.timeoutHandle); _logger.logger.error(status + ' while loading ' + this.url); this.onError(event); } } } } }, { key: 'loadtimeout', value: function loadtimeout(event) { _logger.logger.warn('timeout while loading ' + this.url); this.onTimeout(event, this.stats); } }, { key: 'loadprogress', value: function loadprogress(event) { var stats = this.stats; if (stats.tfirst === null) { stats.tfirst = performance.now(); } stats.loaded = event.loaded; if (event.lengthComputable) { stats.total = event.total; } if (this.onProgress) { this.onProgress(stats); } } }]); return XhrLoader; }(); exports.default = XhrLoader; },{"../utils/logger":38}],42:[function(require,module,exports){ 'use strict'; var E = module.exports; var hlsjsConfig; var ls = window.localStorage; var attached = false, disabled = false; E.Hls = window.Hls; E.videojs = window.videojs; E.VERSION = '0.0.8-31'; E.name = 'HolaProviderHLS'; var script_conf = (function script_conf_init(){ var attrs = {register: 'register-percent', manual_init: 'manual-init'}; var script = document.currentScript|| document.querySelector('#hola_videojs_hls_provider'); if (!script) return {}; var rpercent = '{[=it.HOLA_REGISTER_PERCENT]}'; if (rpercent.startsWith('{[')) { if (!script.hasAttribute(attrs.register)) return {}; rpercent = +script.getAttribute(attrs.register); } if (isNaN(rpercent)||rpercent<0||rpercent>100) { console.error(E.name+': invalid '+attrs.register+' attribute, '+ 'expected a value between 0 and 100 but '+ script.getAttribute(attrs.register)+' found'); return {disabled: true}; } if (ls && ls.getItem('hola_provider_register_percent')) { rpercent = +ls.getItem('hola_provider_register_percent'); console.info(E.name+': '+attrs.register+' forced to '+rpercent+ '% by localStorage configuration'); } return {autoinit: !script.hasAttribute(attrs.manual_init), disabled: !rpercent||Math.random()*100>rpercent}; })(); E.attach = function(obsolete_param, videojs, Hls, hlsjsConfig_){ if (Hls) E.Hls = Hls; if (videojs) E.videojs = videojs; if (hlsjsConfig_) hlsjsConfig = hlsjsConfig_; if (attached) disabled = false; else if (E.Hls.isSupported()) { attached = true; disabled = false; var tech = E.videojs.getTech('Html5'); // XXX yurij hack: some customers register their own provider and // prevent other from being registered with 0 index (rge related) if (tech.sourceHandlers instanceof Array) tech.sourceHandlers.splice(0, 0, E); else tech.registerSourceHandler(E, 0); // XXX yurij: prevent others handlers being registered with 0 index var r = tech.registerSourceHandler; tech.registerSourceHandler = function(e, i){ return r.call(tech, e, i===0 ? 1 : i); }; E.videojs.HolaProviderHLS = HolaProviderHLS; console.log('HolaProviderHLS registered as Html5 SourceHandler'); } else console.error('Hls.js is not supported in this browser!'); }; E.detach = function(){ // we don't unregister source handler, just set it as disabled so it will // return false in canHandleSource() disabled = true; }; E.canPlayType = function(type){ if (disabled) return ''; if (/^application\/x-mpegURL$/i.test(type)) return 'probably'; return ''; }; E.canHandleSource = function(source){ var _can_play_type; if (disabled) return ''; if (_can_play_type = E.canPlayType(source.type)) return _can_play_type; if (/\.m3u8/i.test(source.src)) return 'maybe'; return ''; }; E.handleSource = function(source, tech){ if (tech.hlsProvider) tech.hlsProvider.dispose(); return tech.hlsProvider = new HolaProviderHLS(source, tech); }; function HolaProviderHLS(source, tech){ tech.name_ = 'holaHLS'; var _video = tech.el(); var _hls; var _errorCounts = {}; var _duration = null; var _seekableStart = 0; var _seekableEnd = 0; _video.addEventListener('error', function(evt){ var errorTxt, mediaError = evt.currentTarget.error; switch(mediaError.code) { case mediaError.MEDIA_ERR_ABORTED: errorTxt = 'You aborted the video playback'; break; case mediaError.MEDIA_ERR_DECODE: errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support'; _handleMediaError(mediaError); break; case mediaError.MEDIA_ERR_NETWORK: errorTxt = 'A network error caused the video download to fail part-way'; break; case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED: errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported'; break; } console.error('MEDIA_ERROR: ', errorTxt); }); function initialize(){ tech.hls_obj = _hls = new E.Hls(E.videojs.mergeOptions( tech.options_.hlsjsConfig, hlsjsConfig)); _hls.manual_level = -1; _hls.on(E.Hls.Events.ERROR, function(event, data){ _onError(event, data, tech, _errorCounts); }); _hls.on(E.Hls.Events.LEVEL_SWITCH, updateQuality); _hls.on(E.Hls.Events.LEVEL_LOADED, function(event, data){ _duration = data.details.live ? Infinity : data.details.totalduration; }); _hls.on(E.Hls.Events.LEVEL_UPDATED, function(event, data){ _seekableStart = data.details.live ? data.details.fragments[0].start : 0; _seekableEnd = data.details.live ? _hls.streamController.computeLivePosition(_seekableStart, data.details) : data.details.totalduration; }); _hls.on(E.Hls.Events.FRAG_PARSING_METADATA, function(event, data){ tech.trigger('parsedmetadata', data); }); _hls.attachMedia(_video); } this.duration = function(){ return _duration || _video.duration || 0; }; this.seekable = function(){ return E.videojs.createTimeRanges([[_seekableStart, _seekableEnd]]); }; this.dispose = function(){ _hls.destroy(); }; function load(source){ _hls.loadSource(source.src); } function switchQuality(qualityId){ _hls.manual_level = qualityId; if (_hls.hola_adaptive) { (_video.player||E.videojs.getPlayers()[_video.playerId]) .trigger('mediachange'); } else _hls.loadLevel = qualityId; updateQuality(); } function _handleMediaError(error){ if (_errorCounts[E.Hls.ErrorTypes.MEDIA_ERROR] === 1) { console.info('trying to recover media error'); _hls.recoverMediaError(); } else if (_errorCounts[E.Hls.ErrorTypes.MEDIA_ERROR] === 2) { console.info('2nd try to recover media error (by swapping audio codec'); _hls.swapAudioCodec(); _hls.recoverMediaError(); } else if (_errorCounts[E.Hls.ErrorTypes.MEDIA_ERROR] > 2) { console.info('bubbling media error up to VIDEOJS'); error.code = 3; tech.error = function(){ return error; }; tech.trigger('error'); } } function _onError(event, data){ var level = 'error'; var error = { message: ('HLS.js error: ' + data.type + ' - fatal: ' + data.fatal + ' - ' + data.details), }; if (!data.fatal && data.details === E.Hls.ErrorDetails.BUFFER_STALLED_ERROR) { level = 'warn'; } console[level](error.message); // increment/set error count _errorCounts[data.type] ? _errorCounts[data.type] += 1 : _errorCounts[data.type] = 1; // implement simple error handling based on hls.js documentation // (https://github.com/dailymotion/hls.js/blob/master/API.md#fifth-step-error-handling) if (data.fatal) { switch (data.type) { case E.Hls.ErrorTypes.NETWORK_ERROR: console.info('bubbling network error up to VIDEOJS'); error.code = 2; tech.error = function() { return error; }; tech.trigger('error'); break; case E.Hls.ErrorTypes.MEDIA_ERROR: _handleMediaError(error); break; default: // cannot recover _hls.destroy(); console.info('bubbling error up to VIDEOJS'); tech.error = function() { return error; }; tech.trigger('error'); break; } } } function scaledNumber(num){ if (num===undefined) return ''; if (!num) return '0'; var k = 1024; var sizes = ['', 'K', 'M', 'G', 'T', 'P']; var i = Math.floor(Math.log(num)/Math.log(k)); num /= Math.pow(k, i); if (num<0.001) return '0'; if (num>=k-1) num = Math.trunc(num); var str = num.toFixed(num<1 ? 3 : num<10 ? 2 : num<100 ? 1 : 0); return str.replace(/\.0*$/, '')+sizes[i]; } function heightLabel(level){ var height = level.height || Math.round(level.width * 9 / 16); return height ? height + 'p' : ''; } function bitrateLabel(level){ return level.bitrate ? scaledNumber(level.bitrate) + 'bps' : ''; } function levelLabel(level, levels){ var label = heightLabel(level); if (!label) return bitrateLabel(level); var duplicated = levels.some(function(l){ return l!=level && heightLabel(l)==label; }); return duplicated ? label+' '+bitrateLabel(level) : label; } function updateQuality(){ var list = [], levels = _hls.levels; if (levels.length > 1) list.push({id: -1, label: 'Auto'}); levels.forEach(function(level, index){ list.push({id: index, label: levelLabel(level, levels)}); }); tech.trigger('loadedqualitydata', { quality: { list: list, selected: _hls.manual_level, current: _hls.loadLevel, }, callback: switchQuality, }); } initialize(); load(source); } if (script_conf.disabled) E.attach = E.detach = function(){}; else if (script_conf.autoinit) E.attach(); },{}],43:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],44:[function(require,module,exports){ var bundleFn = arguments[3]; var sources = arguments[4]; var cache = arguments[5]; var stringify = JSON.stringify; module.exports = function (fn, options) { var wkey; var cacheKeys = Object.keys(cache); for (var i = 0, l = cacheKeys.length; i < l; i++) { var key = cacheKeys[i]; var exp = cache[key].exports; // Using babel as a transpiler to use esmodule, the export will always // be an object with the default export as a property of it. To ensure // the existing api and babel esmodule exports are both supported we // check for both if (exp === fn || exp && exp.default === fn) { wkey = key; break; } } if (!wkey) { wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); var wcache = {}; for (var i = 0, l = cacheKeys.length; i < l; i++) { var key = cacheKeys[i]; wcache[key] = key; } sources[wkey] = [ Function(['require','module','exports'], '(' + fn + ')(self)'), wcache ]; } var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); var scache = {}; scache[wkey] = wkey; sources[skey] = [ Function(['require'], ( // try to call default if defined to also support babel esmodule // exports 'var f = require(' + stringify(wkey) + ');' + '(f.default ? f.default : f)(self);' )), scache ]; var workerSources = {}; resolveSources(skey); function resolveSources(key) { workerSources[key] = true; for (var depPath in sources[key][1]) { var depKey = sources[key][1][depPath]; if (!workerSources[depKey]) { resolveSources(depKey); } } } var src = '(' + bundleFn + ')({' + Object.keys(workerSources).map(function (key) { return stringify(key) + ':[' + sources[key][0] + ',' + stringify(sources[key][1]) + ']' ; }).join(',') + '},{},[' + stringify(skey) + '])' ; var URL = window.URL || window.webkitURL || window.mozURL || window.msURL; var blob = new Blob([src], { type: 'text/javascript' }); if (options && options.bare) { return blob; } var workerUrl = URL.createObjectURL(blob); var worker = new Worker(workerUrl); worker.objectURL = workerUrl; return worker; }; },{}]},{},[1])(1) }); //# sourceMappingURL=hola_videojs_hls.js.map
"use strict"; var sinon = require("sinon"), assert = require("assert"), path = require("path"), cli = require("../../lib/cli"), cjs = require("../../lib/capturejs"); describe("cli", function () { describe("#start()", function () { var sandbox = sinon.sandbox.create(), argv; before(function () { sandbox.stub(cjs, "capture"); sandbox.stub(process, "exit"); sandbox.stub(console, "error"); }); beforeEach(function () { sandbox.reset(); cli.start(argv); }); after(function () { sandbox.restore(); }); describe("no argument", function () { before(function () { argv = []; }); it("should print 'Missing required' error message", function () { assert(console.error.calledWith("Missing required: --uri\nMissing required: --output")); }); it("should exit process with 1", function () { assert(process.exit.calledWith(1)); }); }); describe("--help", function () { before(function () { argv = ["--help"]; }); it("should print help message", function () { assert(console.error.calledWithMatch(/^Usage: capturejs/)); }); it("should exit process with 0", function () { assert(process.exit.calledWith(0)); }); }); describe("--version", function () { before(function () { argv = ["--version"]; }); it("should print version number", function () { assert(console.error.calledWith(require("../../package.json").version)); }); it("should exit process with 0", function () { assert(process.exit.calledWith(0)); }); }); describe("--uri", function () { before(function () { argv = ["--uri", "http://www.example.com/", "--output", "example.com.png"]; }); it("should call cjs.capture with uri", function () { var arg = cjs.capture.lastCall.args[0]; assert.equal(arg.uri, "http://www.example.com/"); }); describe("when uri is not URI", function () { before(function () { argv = ["--uri", "this is not URI", "--output", "example.com.png"]; }); it("should print 'Invalid' error message", function () { assert(console.error.calledWith("Invalid: --uri=this is not URI")); }); it("should exit process with 1", function () { assert(process.exit.calledWith(1)); }); }); }); describe("--output", function () { var fullpath = path.resolve(process.cwd(), "example.com.png"); before(function () { argv = ["--uri", "http://www.example.com/", "--output", "example.com.png"]; }); it("should call cjs.capture with uri", function () { var arg = cjs.capture.lastCall.args[0]; assert.equal(arg.output, fullpath); }); }); }); }); // vim: set fenc=utf-8 ts=4 sts=4 sw=4 :
/*! jQuery UI - v1.12.1 - 2018-02-14 * http://jqueryui.com * Includes: widget.js, position.js, keycode.js, unique-id.js, widgets/autocomplete.js, widgets/menu.js * Copyright jQuery Foundation and other contributors; Licensed MIT */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.ui = $.ui || {}; var version = $.ui.version = "1.12.1"; /*! * jQuery UI Widget 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Widget //>>group: Core //>>description: Provides a factory for creating stateful widgets with a common API. //>>docs: http://api.jqueryui.com/jQuery.widget/ //>>demos: http://jqueryui.com/widget/ var widgetUuid = 0; var widgetSlice = Array.prototype.slice; $.cleanData = ( function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // Http://bugs.jquery.com/ticket/8235 } catch ( e ) {} } orig( elems ); }; } )( $.cleanData ); $.widget = function( name, base, prototype ) { var existingConstructor, constructor, basePrototype; // ProxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) var proxiedPrototype = {}; var namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; var fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } if ( $.isArray( prototype ) ) { prototype = $.extend.apply( null, [ {} ].concat( prototype ) ); } // Create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // Allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // Allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // Extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // Copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // Track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] } ); basePrototype = new base(); // We need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = ( function() { function _super() { return base.prototype[ prop ].apply( this, arguments ); } function _superApply( args ) { return base.prototype[ prop ].apply( this, args ); } return function() { var __super = this._super; var __superApply = this._superApply; var returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; } )(); } ); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName } ); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // Redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); } ); // Remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widgetSlice.call( arguments, 1 ); var inputIndex = 0; var inputLength = input.length; var key; var value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string"; var args = widgetSlice.call( arguments, 1 ); var returnValue = this; if ( isMethodCall ) { // If this is an empty collection, we need to have the instance method // return undefined instead of the jQuery instance if ( !this.length && options === "instance" ) { returnValue = undefined; } else { this.each( function() { var methodValue; var instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } } ); } } else { // Allow multiple hashes to be passed on init if ( args.length ) { options = $.widget.extend.apply( null, [ options ].concat( args ) ); } this.each( function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } } ); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { classes: {}, disabled: false, // Callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widgetUuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.bindings = $(); this.hoverable = $(); this.focusable = $(); this.classesElementLookup = {}; if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } } ); this.document = $( element.style ? // Element within the document element.ownerDocument : // Element is window or document element.document || element ); this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow ); } this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this._create(); if ( this.options.disabled ) { this._setOptionDisabled( this.options.disabled ); } this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: function() { return {}; }, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { var that = this; this._destroy(); $.each( this.classesElementLookup, function( key, value ) { that._removeClass( value, key ); } ); // We can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .off( this.eventNamespace ) .removeData( this.widgetFullName ); this.widget() .off( this.eventNamespace ) .removeAttr( "aria-disabled" ); // Clean up events and states this.bindings.off( this.eventNamespace ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key; var parts; var curOption; var i; if ( arguments.length === 0 ) { // Don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { if ( key === "classes" ) { this._setOptionClasses( value ); } this.options[ key ] = value; if ( key === "disabled" ) { this._setOptionDisabled( value ); } return this; }, _setOptionClasses: function( value ) { var classKey, elements, currentElements; for ( classKey in value ) { currentElements = this.classesElementLookup[ classKey ]; if ( value[ classKey ] === this.options.classes[ classKey ] || !currentElements || !currentElements.length ) { continue; } // We are doing this to create a new jQuery object because the _removeClass() call // on the next line is going to destroy the reference to the current elements being // tracked. We need to save a copy of this collection so that we can add the new classes // below. elements = $( currentElements.get() ); this._removeClass( currentElements, classKey ); // We don't use _addClass() here, because that uses this.options.classes // for generating the string of classes. We want to use the value passed in from // _setOption(), this is the new value of the classes option which was passed to // _setOption(). We pass this value directly to _classes(). elements.addClass( this._classes( { element: elements, keys: classKey, classes: value, add: true } ) ); } }, _setOptionDisabled: function( value ) { this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this._removeClass( this.hoverable, null, "ui-state-hover" ); this._removeClass( this.focusable, null, "ui-state-focus" ); } }, enable: function() { return this._setOptions( { disabled: false } ); }, disable: function() { return this._setOptions( { disabled: true } ); }, _classes: function( options ) { var full = []; var that = this; options = $.extend( { element: this.element, classes: this.options.classes || {} }, options ); function processClassString( classes, checkOption ) { var current, i; for ( i = 0; i < classes.length; i++ ) { current = that.classesElementLookup[ classes[ i ] ] || $(); if ( options.add ) { current = $( $.unique( current.get().concat( options.element.get() ) ) ); } else { current = $( current.not( options.element ).get() ); } that.classesElementLookup[ classes[ i ] ] = current; full.push( classes[ i ] ); if ( checkOption && options.classes[ classes[ i ] ] ) { full.push( options.classes[ classes[ i ] ] ); } } } this._on( options.element, { "remove": "_untrackClassesElement" } ); if ( options.keys ) { processClassString( options.keys.match( /\S+/g ) || [], true ); } if ( options.extra ) { processClassString( options.extra.match( /\S+/g ) || [] ); } return full.join( " " ); }, _untrackClassesElement: function( event ) { var that = this; $.each( that.classesElementLookup, function( key, value ) { if ( $.inArray( event.target, value ) !== -1 ) { that.classesElementLookup[ key ] = $( value.not( event.target ).get() ); } } ); }, _removeClass: function( element, keys, extra ) { return this._toggleClass( element, keys, extra, false ); }, _addClass: function( element, keys, extra ) { return this._toggleClass( element, keys, extra, true ); }, _toggleClass: function( element, keys, extra, add ) { add = ( typeof add === "boolean" ) ? add : extra; var shift = ( typeof element === "string" || element === null ), options = { extra: shift ? keys : extra, keys: shift ? element : keys, element: shift ? this.element : element, add: add }; options.element.toggleClass( this._classes( options ), add ); return this; }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement; var instance = this; // No suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // No element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // Allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // Copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ); var eventName = match[ 1 ] + instance.eventNamespace; var selector = match[ 2 ]; if ( selector ) { delegateElement.on( eventName, selector, handlerProxy ); } else { element.on( eventName, handlerProxy ); } } ); }, _off: function( element, eventName ) { eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.off( eventName ).off( eventName ); // Clear the stack to avoid memory leaks (#10056) this.bindings = $( this.bindings.not( element ).get() ); this.focusable = $( this.focusable.not( element ).get() ); this.hoverable = $( this.hoverable.not( element ).get() ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { this._addClass( $( event.currentTarget ), null, "ui-state-hover" ); }, mouseleave: function( event ) { this._removeClass( $( event.currentTarget ), null, "ui-state-hover" ); } } ); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { this._addClass( $( event.currentTarget ), null, "ui-state-focus" ); }, focusout: function( event ) { this._removeClass( $( event.currentTarget ), null, "ui-state-focus" ); } } ); }, _trigger: function( type, event, data ) { var prop, orig; var callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // The original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // Copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions; var effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue( function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); } ); } }; } ); var widget = $.widget; /*! * jQuery UI Position 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/position/ */ //>>label: Position //>>group: Core //>>description: Positions elements relative to other elements. //>>docs: http://api.jqueryui.com/position/ //>>demos: http://jqueryui.com/position/ ( function() { var cachedScrollbarWidth, max = Math.max, abs = Math.abs, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[ 0 ]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div " + "style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" + "<div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[ 0 ]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[ 0 ].clientWidth; } div.remove(); return ( cachedScrollbarWidth = w1 - w2 ); }, getScrollInfo: function( within ) { var overflowX = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[ 0 ] ), isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9, hasOffset = !isWindow && !isDocument; return { element: withinElement, isWindow: isWindow, isDocument: isDocument, offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: withinElement.outerWidth(), height: withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // Make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[ 0 ].preventDefault ) { // Force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // Clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // Force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1 ) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // Calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // Reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; } ); // Normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each( function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem: elem } ); } } ); if ( options.using ) { // Adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); } ); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // Element is wider than within if ( data.collisionWidth > outerWidth ) { // Element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // Element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // Element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // Too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // Too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // Adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // Element is taller than within if ( data.collisionHeight > outerHeight ) { // Element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // Element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // Element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // Too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // Too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // Adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; } )(); var position = $.ui.position; /*! * jQuery UI Keycode 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Keycode //>>group: Core //>>description: Provide keycodes as keynames //>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/ var keycode = $.ui.keyCode = { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 }; /*! * jQuery UI Unique ID 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: uniqueId //>>group: Core //>>description: Functions to generate and remove uniqueId's //>>docs: http://api.jqueryui.com/uniqueId/ var uniqueId = $.fn.extend( { uniqueId: ( function() { var uuid = 0; return function() { return this.each( function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } } ); }; } )(), removeUniqueId: function() { return this.each( function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } } ); } } ); var safeActiveElement = $.ui.safeActiveElement = function( document ) { var activeElement; // Support: IE 9 only // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { activeElement = document.activeElement; } catch ( error ) { activeElement = document.body; } // Support: IE 9 - 11 only // IE may return null instead of an element // Interestingly, this only seems to occur when NOT in an iframe if ( !activeElement ) { activeElement = document.body; } // Support: IE 11 only // IE11 returns a seemingly empty object in some cases when accessing // document.activeElement from an <iframe> if ( !activeElement.nodeName ) { activeElement = document.body; } return activeElement; }; /*! * jQuery UI Menu 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Menu //>>group: Widgets //>>description: Creates nestable menus. //>>docs: http://api.jqueryui.com/menu/ //>>demos: http://jqueryui.com/menu/ //>>css.structure: ../../themes/base/core.css //>>css.structure: ../../themes/base/menu.css //>>css.theme: ../../themes/base/theme.css var widgetsMenu = $.widget( "ui.menu", { version: "1.12.1", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-caret-1-e" }, items: "> *", menus: "ul", position: { my: "left top", at: "right top" }, role: "menu", // Callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; // Flag used to prevent firing of the click handler // as the event bubbles up through nested menus this.mouseHandled = false; this.element .uniqueId() .attr( { role: this.options.role, tabIndex: 0 } ); this._addClass( "ui-menu", "ui-widget ui-widget-content" ); this._on( { // Prevent focus from sticking to links inside menu after clicking // them (focus should always stay on UL during navigation). "mousedown .ui-menu-item": function( event ) { event.preventDefault(); }, "click .ui-menu-item": function( event ) { var target = $( event.target ); var active = $( $.ui.safeActiveElement( this.document[ 0 ] ) ); if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) { this.select( event ); // Only set the mouseHandled flag if the event will bubble, see #9469. if ( !event.isPropagationStopped() ) { this.mouseHandled = true; } // Open submenu on click if ( target.has( ".ui-menu" ).length ) { this.expand( event ); } else if ( !this.element.is( ":focus" ) && active.closest( ".ui-menu" ).length ) { // Redirect focus to the menu this.element.trigger( "focus", [ true ] ); // If the active item is on the top level, let it stay active. // Otherwise, blur the active item since it is no longer visible. if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { clearTimeout( this.timer ); } } } }, "mouseenter .ui-menu-item": function( event ) { // Ignore mouse events while typeahead is active, see #10458. // Prevents focusing the wrong item when typeahead causes a scroll while the mouse // is over an item in the menu if ( this.previousFilter ) { return; } var actualTarget = $( event.target ).closest( ".ui-menu-item" ), target = $( event.currentTarget ); // Ignore bubbled events on parent items, see #11641 if ( actualTarget[ 0 ] !== target[ 0 ] ) { return; } // Remove ui-state-active class from siblings of the newly focused menu item // to avoid a jump caused by adjacent elements both having a class with a border this._removeClass( target.siblings().children( ".ui-state-active" ), null, "ui-state-active" ); this.focus( event, target ); }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function( event, keepActiveItem ) { // If there's already an active item, keep it active // If not, activate the first item var item = this.active || this.element.find( this.options.items ).eq( 0 ); if ( !keepActiveItem ) { this.focus( event, item ); } }, blur: function( event ) { this._delay( function() { var notContained = !$.contains( this.element[ 0 ], $.ui.safeActiveElement( this.document[ 0 ] ) ); if ( notContained ) { this.collapseAll( event ); } } ); }, keydown: "_keydown" } ); this.refresh(); // Clicks outside of a menu collapse any open menus this._on( this.document, { click: function( event ) { if ( this._closeOnDocumentClick( event ) ) { this.collapseAll( event ); } // Reset the mouseHandled flag this.mouseHandled = false; } } ); }, _destroy: function() { var items = this.element.find( ".ui-menu-item" ) .removeAttr( "role aria-disabled" ), submenus = items.children( ".ui-menu-item-wrapper" ) .removeUniqueId() .removeAttr( "tabIndex role aria-haspopup" ); // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).addBack() .removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " + "tabIndex" ) .removeUniqueId() .show(); submenus.children().each( function() { var elem = $( this ); if ( elem.data( "ui-menu-submenu-caret" ) ) { elem.remove(); } } ); }, _keydown: function( event ) { var match, prev, character, skip, preventDefault = true; switch ( event.keyCode ) { case $.ui.keyCode.PAGE_UP: this.previousPage( event ); break; case $.ui.keyCode.PAGE_DOWN: this.nextPage( event ); break; case $.ui.keyCode.HOME: this._move( "first", "first", event ); break; case $.ui.keyCode.END: this._move( "last", "last", event ); break; case $.ui.keyCode.UP: this.previous( event ); break; case $.ui.keyCode.DOWN: this.next( event ); break; case $.ui.keyCode.LEFT: this.collapse( event ); break; case $.ui.keyCode.RIGHT: if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { this.expand( event ); } break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: this._activate( event ); break; case $.ui.keyCode.ESCAPE: this.collapse( event ); break; default: preventDefault = false; prev = this.previousFilter || ""; skip = false; // Support number pad values character = event.keyCode >= 96 && event.keyCode <= 105 ? ( event.keyCode - 96 ).toString() : String.fromCharCode( event.keyCode ); clearTimeout( this.filterTimer ); if ( character === prev ) { skip = true; } else { character = prev + character; } match = this._filterMenuItems( character ); match = skip && match.index( this.active.next() ) !== -1 ? this.active.nextAll( ".ui-menu-item" ) : match; // If no matches on the current filter, reset to the last character pressed // to move down the menu to the first item that starts with that character if ( !match.length ) { character = String.fromCharCode( event.keyCode ); match = this._filterMenuItems( character ); } if ( match.length ) { this.focus( event, match ); this.previousFilter = character; this.filterTimer = this._delay( function() { delete this.previousFilter; }, 1000 ); } else { delete this.previousFilter; } } if ( preventDefault ) { event.preventDefault(); } }, _activate: function( event ) { if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { if ( this.active.children( "[aria-haspopup='true']" ).length ) { this.expand( event ); } else { this.select( event ); } } }, refresh: function() { var menus, items, newSubmenus, newItems, newWrappers, that = this, icon = this.options.icons.submenu, submenus = this.element.find( this.options.menus ); this._toggleClass( "ui-menu-icons", null, !!this.element.find( ".ui-icon" ).length ); // Initialize nested menus newSubmenus = submenus.filter( ":not(.ui-menu)" ) .hide() .attr( { role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" } ) .each( function() { var menu = $( this ), item = menu.prev(), submenuCaret = $( "<span>" ).data( "ui-menu-submenu-caret", true ); that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon ); item .attr( "aria-haspopup", "true" ) .prepend( submenuCaret ); menu.attr( "aria-labelledby", item.attr( "id" ) ); } ); this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" ); menus = submenus.add( this.element ); items = menus.find( this.options.items ); // Initialize menu-items containing spaces and/or dashes only as dividers items.not( ".ui-menu-item" ).each( function() { var item = $( this ); if ( that._isDivider( item ) ) { that._addClass( item, "ui-menu-divider", "ui-widget-content" ); } } ); // Don't refresh list items that are already adapted newItems = items.not( ".ui-menu-item, .ui-menu-divider" ); newWrappers = newItems.children() .not( ".ui-menu" ) .uniqueId() .attr( { tabIndex: -1, role: this._itemRole() } ); this._addClass( newItems, "ui-menu-item" ) ._addClass( newWrappers, "ui-menu-item-wrapper" ); // Add aria-disabled attribute to any disabled menu item items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); // If the active item has been removed, blur the menu if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { this.blur(); } }, _itemRole: function() { return { menu: "menuitem", listbox: "option" }[ this.options.role ]; }, _setOption: function( key, value ) { if ( key === "icons" ) { var icons = this.element.find( ".ui-menu-icon" ); this._removeClass( icons, null, this.options.icons.submenu ) ._addClass( icons, null, value.submenu ); } this._super( key, value ); }, _setOptionDisabled: function( value ) { this._super( value ); this.element.attr( "aria-disabled", String( value ) ); this._toggleClass( null, "ui-state-disabled", !!value ); }, focus: function( event, item ) { var nested, focused, activeParent; this.blur( event, event && event.type === "focus" ); this._scrollIntoView( item ); this.active = item.first(); focused = this.active.children( ".ui-menu-item-wrapper" ); this._addClass( focused, null, "ui-state-active" ); // Only update aria-activedescendant if there's a role // otherwise we assume focus is managed elsewhere if ( this.options.role ) { this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); } // Highlight active parent menu item, if any activeParent = this.active .parent() .closest( ".ui-menu-item" ) .children( ".ui-menu-item-wrapper" ); this._addClass( activeParent, null, "ui-state-active" ); if ( event && event.type === "keydown" ) { this._close(); } else { this.timer = this._delay( function() { this._close(); }, this.delay ); } nested = item.children( ".ui-menu" ); if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) { this._startOpening( nested ); } this.activeMenu = item.parent(); this._trigger( "focus", event, { item: item } ); }, _scrollIntoView: function( item ) { var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; if ( this._hasScroll() ) { borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0; paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0; offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; scroll = this.activeMenu.scrollTop(); elementHeight = this.activeMenu.height(); itemHeight = item.outerHeight(); if ( offset < 0 ) { this.activeMenu.scrollTop( scroll + offset ); } else if ( offset + itemHeight > elementHeight ) { this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); } } }, blur: function( event, fromFocus ) { if ( !fromFocus ) { clearTimeout( this.timer ); } if ( !this.active ) { return; } this._removeClass( this.active.children( ".ui-menu-item-wrapper" ), null, "ui-state-active" ); this._trigger( "blur", event, { item: this.active } ); this.active = null; }, _startOpening: function( submenu ) { clearTimeout( this.timer ); // Don't open if already open fixes a Firefox bug that caused a .5 pixel // shift in the submenu position when mousing over the caret icon if ( submenu.attr( "aria-hidden" ) !== "true" ) { return; } this.timer = this._delay( function() { this._close(); this._open( submenu ); }, this.delay ); }, _open: function( submenu ) { var position = $.extend( { of: this.active }, this.options.position ); clearTimeout( this.timer ); this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) .hide() .attr( "aria-hidden", "true" ); submenu .show() .removeAttr( "aria-hidden" ) .attr( "aria-expanded", "true" ) .position( position ); }, collapseAll: function( event, all ) { clearTimeout( this.timer ); this.timer = this._delay( function() { // If we were passed an event, look for the submenu that contains the event var currentMenu = all ? this.element : $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); // If we found no valid submenu ancestor, use the main menu to close all // sub menus anyway if ( !currentMenu.length ) { currentMenu = this.element; } this._close( currentMenu ); this.blur( event ); // Work around active item staying active after menu is blurred this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" ); this.activeMenu = currentMenu; }, this.delay ); }, // With no arguments, closes the currently active menu - if nothing is active // it closes all menus. If passed an argument, it will search for menus BELOW _close: function( startMenu ) { if ( !startMenu ) { startMenu = this.active ? this.active.parent() : this.element; } startMenu.find( ".ui-menu" ) .hide() .attr( "aria-hidden", "true" ) .attr( "aria-expanded", "false" ); }, _closeOnDocumentClick: function( event ) { return !$( event.target ).closest( ".ui-menu" ).length; }, _isDivider: function( item ) { // Match hyphen, em dash, en dash return !/[^\-\u2014\u2013\s]/.test( item.text() ); }, collapse: function( event ) { var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element ); if ( newItem && newItem.length ) { this._close(); this.focus( event, newItem ); } }, expand: function( event ) { var newItem = this.active && this.active .children( ".ui-menu " ) .find( this.options.items ) .first(); if ( newItem && newItem.length ) { this._open( newItem.parent() ); // Delay so Firefox will not hide activedescendant change in expanding submenu from AT this._delay( function() { this.focus( event, newItem ); } ); } }, next: function( event ) { this._move( "next", "first", event ); }, previous: function( event ) { this._move( "prev", "last", event ); }, isFirstItem: function() { return this.active && !this.active.prevAll( ".ui-menu-item" ).length; }, isLastItem: function() { return this.active && !this.active.nextAll( ".ui-menu-item" ).length; }, _move: function( direction, filter, event ) { var next; if ( this.active ) { if ( direction === "first" || direction === "last" ) { next = this.active [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) .eq( -1 ); } else { next = this.active [ direction + "All" ]( ".ui-menu-item" ) .eq( 0 ); } } if ( !next || !next.length || !this.active ) { next = this.activeMenu.find( this.options.items )[ filter ](); } this.focus( event, next ); }, nextPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isLastItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.nextAll( ".ui-menu-item" ).each( function() { item = $( this ); return item.offset().top - base - height < 0; } ); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ) [ !this.active ? "first" : "last" ]() ); } }, previousPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isFirstItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.prevAll( ".ui-menu-item" ).each( function() { item = $( this ); return item.offset().top - base + height > 0; } ); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ).first() ); } }, _hasScroll: function() { return this.element.outerHeight() < this.element.prop( "scrollHeight" ); }, select: function( event ) { // TODO: It should never be possible to not have an active item at this // point, but the tests don't trigger mouseenter before click. this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); var ui = { item: this.active }; if ( !this.active.has( ".ui-menu" ).length ) { this.collapseAll( event, true ); } this._trigger( "select", event, ui ); }, _filterMenuItems: function( character ) { var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ), regex = new RegExp( "^" + escapedCharacter, "i" ); return this.activeMenu .find( this.options.items ) // Only match on items, not dividers or other content (#10571) .filter( ".ui-menu-item" ) .filter( function() { return regex.test( $.trim( $( this ).children( ".ui-menu-item-wrapper" ).text() ) ); } ); } } ); /*! * jQuery UI Autocomplete 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Autocomplete //>>group: Widgets //>>description: Lists suggested words as the user is typing. //>>docs: http://api.jqueryui.com/autocomplete/ //>>demos: http://jqueryui.com/autocomplete/ //>>css.structure: ../../themes/base/core.css //>>css.structure: ../../themes/base/autocomplete.css //>>css.theme: ../../themes/base/theme.css $.widget( "ui.autocomplete", { version: "1.12.1", defaultElement: "<input>", options: { appendTo: null, autoFocus: false, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, // Callbacks change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, requestIndex: 0, pending: 0, _create: function() { // Some browsers only repeat keydown events, not keypress events, // so we use the suppressKeyPress flag to determine if we've already // handled the keydown event. #7269 // Unfortunately the code for & in keypress is the same as the up arrow, // so we use the suppressKeyPressRepeat flag to avoid handling keypress // events when we know the keydown event was used to modify the // search term. #7799 var suppressKeyPress, suppressKeyPressRepeat, suppressInput, nodeName = this.element[ 0 ].nodeName.toLowerCase(), isTextarea = nodeName === "textarea", isInput = nodeName === "input"; // Textareas are always multi-line // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable // All other element types are determined by whether or not they're contentEditable this.isMultiLine = isTextarea || !isInput && this._isContentEditable( this.element ); this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ]; this.isNewMenu = true; this._addClass( "ui-autocomplete-input" ); this.element.attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { if ( this.element.prop( "readOnly" ) ) { suppressKeyPress = true; suppressInput = true; suppressKeyPressRepeat = true; return; } suppressKeyPress = false; suppressInput = false; suppressKeyPressRepeat = false; var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: suppressKeyPress = true; this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: suppressKeyPress = true; this._move( "nextPage", event ); break; case keyCode.UP: suppressKeyPress = true; this._keyEvent( "previous", event ); break; case keyCode.DOWN: suppressKeyPress = true; this._keyEvent( "next", event ); break; case keyCode.ENTER: // when menu is open and has focus if ( this.menu.active ) { // #6055 - Opera still allows the keypress to occur // which causes forms to submit suppressKeyPress = true; event.preventDefault(); this.menu.select( event ); } break; case keyCode.TAB: if ( this.menu.active ) { this.menu.select( event ); } break; case keyCode.ESCAPE: if ( this.menu.element.is( ":visible" ) ) { if ( !this.isMultiLine ) { this._value( this.term ); } this.close( event ); // Different browsers have different default behavior for escape // Single press can mean undo or clear // Double press in IE means clear the whole form event.preventDefault(); } break; default: suppressKeyPressRepeat = true; // search timeout should be triggered before the input value is changed this._searchTimeout( event ); break; } }, keypress: function( event ) { if ( suppressKeyPress ) { suppressKeyPress = false; if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { event.preventDefault(); } return; } if ( suppressKeyPressRepeat ) { return; } // Replicate some key handlers to allow them to repeat in Firefox and Opera var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: this._move( "nextPage", event ); break; case keyCode.UP: this._keyEvent( "previous", event ); break; case keyCode.DOWN: this._keyEvent( "next", event ); break; } }, input: function( event ) { if ( suppressInput ) { suppressInput = false; event.preventDefault(); return; } this._searchTimeout( event ); }, focus: function() { this.selectedItem = null; this.previous = this._value(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } clearTimeout( this.searching ); this.close( event ); this._change( event ); } } ); this._initSource(); this.menu = $( "<ul>" ) .appendTo( this._appendTo() ) .menu( { // disable ARIA support, the live region takes care of that role: null } ) .hide() .menu( "instance" ); this._addClass( this.menu.element, "ui-autocomplete", "ui-front" ); this._on( this.menu.element, { mousedown: function( event ) { // prevent moving focus out of the text field event.preventDefault(); // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event this.cancelBlur = true; this._delay( function() { delete this.cancelBlur; // Support: IE 8 only // Right clicking a menu item or selecting text from the menu items will // result in focus moving out of the input. However, we've already received // and ignored the blur event because of the cancelBlur flag set above. So // we restore focus to ensure that the menu closes properly based on the user's // next actions. if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) { this.element.trigger( "focus" ); } } ); }, menufocus: function( event, ui ) { var label, item; // support: Firefox // Prevent accidental activation of menu items in Firefox (#7024 #9118) if ( this.isNewMenu ) { this.isNewMenu = false; if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { this.menu.blur(); this.document.one( "mousemove", function() { $( event.target ).trigger( event.originalEvent ); } ); return; } } item = ui.item.data( "ui-autocomplete-item" ); if ( false !== this._trigger( "focus", event, { item: item } ) ) { // use value to match what will end up in the input, if it was a key event if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { this._value( item.value ); } } // Announce the value in the liveRegion label = ui.item.attr( "aria-label" ) || item.value; if ( label && $.trim( label ).length ) { this.liveRegion.children().hide(); $( "<div>" ).text( label ).appendTo( this.liveRegion ); } }, menuselect: function( event, ui ) { var item = ui.item.data( "ui-autocomplete-item" ), previous = this.previous; // Only trigger when focus was lost (click on menu) if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) { this.element.trigger( "focus" ); this.previous = previous; // #6109 - IE triggers two focus events and the second // is asynchronous, so we need to reset the previous // term synchronously and asynchronously :-( this._delay( function() { this.previous = previous; this.selectedItem = item; } ); } if ( false !== this._trigger( "select", event, { item: item } ) ) { this._value( item.value ); } // reset the term after the select event // this allows custom select handling to work properly this.term = this._value(); this.close( event ); this.selectedItem = item; } } ); this.liveRegion = $( "<div>", { role: "status", "aria-live": "assertive", "aria-relevant": "additions" } ) .appendTo( this.document[ 0 ].body ); this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" ); // Turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } } ); }, _destroy: function() { clearTimeout( this.searching ); this.element.removeAttr( "autocomplete" ); this.menu.element.remove(); this.liveRegion.remove(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "source" ) { this._initSource(); } if ( key === "appendTo" ) { this.menu.element.appendTo( this._appendTo() ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _isEventTargetInWidget: function( event ) { var menuElement = this.menu.element[ 0 ]; return event.target === this.element[ 0 ] || event.target === menuElement || $.contains( menuElement, event.target ); }, _closeOnClickOutside: function( event ) { if ( !this._isEventTargetInWidget( event ) ) { this.close(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front, dialog" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _initSource: function() { var array, url, that = this; if ( $.isArray( this.options.source ) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax( { url: url, data: request, dataType: "json", success: function( data ) { response( data ); }, error: function() { response( [] ); } } ); }; } else { this.source = this.options.source; } }, _searchTimeout: function( event ) { clearTimeout( this.searching ); this.searching = this._delay( function() { // Search if the value has changed, or if the user retypes the same value (see #7434) var equalValues = this.term === this._value(), menuVisible = this.menu.element.is( ":visible" ), modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) { this.selectedItem = null; this.search( null, event ); } }, this.options.delay ); }, search: function( value, event ) { value = value != null ? value : this._value(); // Always save the actual value, not the one passed as an argument this.term = this._value(); if ( value.length < this.options.minLength ) { return this.close( event ); } if ( this._trigger( "search", event ) === false ) { return; } return this._search( value ); }, _search: function( value ) { this.pending++; this._addClass( "ui-autocomplete-loading" ); this.cancelSearch = false; this.source( { term: value }, this._response() ); }, _response: function() { var index = ++this.requestIndex; return $.proxy( function( content ) { if ( index === this.requestIndex ) { this.__response( content ); } this.pending--; if ( !this.pending ) { this._removeClass( "ui-autocomplete-loading" ); } }, this ); }, __response: function( content ) { if ( content ) { content = this._normalize( content ); } this._trigger( "response", null, { content: content } ); if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { this._suggest( content ); this._trigger( "open" ); } else { // use ._close() instead of .close() so we don't cancel future searches this._close(); } }, close: function( event ) { this.cancelSearch = true; this._close( event ); }, _close: function( event ) { // Remove the handler that closes the menu on outside clicks this._off( this.document, "mousedown" ); if ( this.menu.element.is( ":visible" ) ) { this.menu.element.hide(); this.menu.blur(); this.isNewMenu = true; this._trigger( "close", event ); } }, _change: function( event ) { if ( this.previous !== this._value() ) { this._trigger( "change", event, { item: this.selectedItem } ); } }, _normalize: function( items ) { // assume all items have the right format when the first item is complete if ( items.length && items[ 0 ].label && items[ 0 ].value ) { return items; } return $.map( items, function( item ) { if ( typeof item === "string" ) { return { label: item, value: item }; } return $.extend( {}, item, { label: item.label || item.value, value: item.value || item.label } ); } ); }, _suggest: function( items ) { var ul = this.menu.element.empty(); this._renderMenu( ul, items ); this.isNewMenu = true; this.menu.refresh(); // Size and position menu ul.show(); this._resizeMenu(); ul.position( $.extend( { of: this.element }, this.options.position ) ); if ( this.options.autoFocus ) { this.menu.next(); } // Listen for interactions outside of the widget (#6642) this._on( this.document, { mousedown: "_closeOnClickOutside" } ); }, _resizeMenu: function() { var ul = this.menu.element; ul.outerWidth( Math.max( // Firefox wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping (#7513) ul.width( "" ).outerWidth() + 1, this.element.outerWidth() ) ); }, _renderMenu: function( ul, items ) { var that = this; $.each( items, function( index, item ) { that._renderItemData( ul, item ); } ); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); }, _renderItem: function( ul, item ) { return $( "<li>" ) .append( $( "<div>" ).text( item.label ) ) .appendTo( ul ); }, _move: function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.isFirstItem() && /^previous/.test( direction ) || this.menu.isLastItem() && /^next/.test( direction ) ) { if ( !this.isMultiLine ) { this._value( this.term ); } this.menu.blur(); return; } this.menu[ direction ]( event ); }, widget: function() { return this.menu.element; }, _value: function() { return this.valueMethod.apply( this.element, arguments ); }, _keyEvent: function( keyEvent, event ) { if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { this._move( keyEvent, event ); // Prevents moving cursor to beginning/end of the text field in some browsers event.preventDefault(); } }, // Support: Chrome <=50 // We should be able to just use this.element.prop( "isContentEditable" ) // but hidden elements always report false in Chrome. // https://code.google.com/p/chromium/issues/detail?id=313082 _isContentEditable: function( element ) { if ( !element.length ) { return false; } var editable = element.prop( "contentEditable" ); if ( editable === "inherit" ) { return this._isContentEditable( element.parent() ); } return editable === "true"; } } ); $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); }, filter: function( array, term ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" ); return $.grep( array, function( value ) { return matcher.test( value.label || value.value || value ); } ); } } ); // Live region extension, adding a `messages` option // NOTE: This is an experimental API. We are still investigating // a full solution for string manipulation and internationalization. $.widget( "ui.autocomplete", $.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function( amount ) { return amount + ( amount > 1 ? " results are" : " result is" ) + " available, use up and down arrow keys to navigate."; } } }, __response: function( content ) { var message; this._superApply( arguments ); if ( this.options.disabled || this.cancelSearch ) { return; } if ( content && content.length ) { message = this.options.messages.results( content.length ); } else { message = this.options.messages.noResults; } this.liveRegion.children().hide(); $( "<div>" ).text( message ).appendTo( this.liveRegion ); } } ); var widgetsAutocomplete = $.ui.autocomplete; }));
version https://git-lfs.github.com/spec/v1 oid sha256:699e7cdff3e513f13c0e6959449480c0a7f843ddcd0dbe904606634802cbe114 size 164
/** * StringWriter.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { /** * This class writes nodes into a string. * @class tinymce.dom.StringWriter */ tinymce.create('tinymce.dom.StringWriter', { str : null, tags : null, count : 0, settings : null, indent : null, /** * Constructs a new StringWriter. * * @constructor * @method StringWriter * @param {Object} s Optional settings object. */ StringWriter : function(s) { this.settings = tinymce.extend({ indent_char : ' ', indentation : 0 }, s); this.reset(); }, /** * Resets the writer so it can be reused the contents of the writer is cleared. * * @method reset */ reset : function() { this.indent = ''; this.str = ""; this.tags = []; this.count = 0; }, /** * Writes the start of an element like for example: <tag. * * @method writeStartElement * @param {String} n Name of element to write. */ writeStartElement : function(n) { this._writeAttributesEnd(); this.writeRaw('<' + n); this.tags.push(n); this.inAttr = true; this.count++; this.elementCount = this.count; }, /** * Writes an attrubute like for example: myattr="valie" * * @method writeAttribute * @param {String} n Attribute name to write. * @param {String} v Attribute value to write. */ writeAttribute : function(n, v) { var t = this; t.writeRaw(" " + t.encode(n) + '="' + t.encode(v) + '"'); }, /** * Write the end of a element. This will add a short end for elements with out children like for example a img element. * * @method writeEndElement */ writeEndElement : function() { var n; if (this.tags.length > 0) { n = this.tags.pop(); if (this._writeAttributesEnd(1)) this.writeRaw('</' + n + '>'); if (this.settings.indentation > 0) this.writeRaw('\n'); } }, /** * Writes the end of a element. This will add a full end to the element even if it didn't have any children. * * @method writeFullEndElement */ writeFullEndElement : function() { if (this.tags.length > 0) { this._writeAttributesEnd(); this.writeRaw('</' + this.tags.pop() + '>'); if (this.settings.indentation > 0) this.writeRaw('\n'); } }, /** * Writes a text node value. * * @method writeText * @param {String} v Value to append as a text node. */ writeText : function(v) { this._writeAttributesEnd(); this.writeRaw(this.encode(v)); this.count++; }, /** * Writes a CDATA section. * * @method writeCDATA * @param {String} v Value to write in CDATA. */ writeCDATA : function(v) { this._writeAttributesEnd(); this.writeRaw('<![CDATA[' + v + ']]>'); this.count++; }, /** * Writes a comment. * * @method writeComment * @param {String} v Value of the comment. */ writeComment : function(v) { this._writeAttributesEnd(); this.writeRaw('<!-- ' + v + '-->'); this.count++; }, /** * String writer specific function. Enables you to write raw contents to the string. * * @method writeRaw * @param {String} v String with raw contents to write. */ writeRaw : function(v) { this.str += v; }, /** * String writer specific method. This encodes the raw entities of a string. * * @method encode * @param {String} s String to encode. * @return {String} String with entity encoding of the raw elements like <>&". */ encode : function(s) { return s.replace(/[<>&"]/g, function(v) { switch (v) { case '<': return '&lt;'; case '>': return '&gt;'; case '&': return '&amp;'; case '"': return '&quot;'; } return v; }); }, /** * Returns a string representation of the elements/nodes written. * * @method getContent * @return {String} String representation of the written elements/nodes. */ getContent : function() { return this.str; }, _writeAttributesEnd : function(s) { if (!this.inAttr) return; this.inAttr = false; if (s && this.elementCount == this.count) { this.writeRaw(' />'); return false; } this.writeRaw('>'); return true; } }); })(tinymce);
const x = (n) => do { switch (n) { case 0: 'a'; case 1: 'b'; break; default: 'd'; case 2: 'c'; case 3: case 4: } }
YUI.add('perfcolumnseriesgroup-benchmark', function (Y) { Y.BenchmarkSuite = new Benchmark.Suite(); var suite = Y.BenchmarkSuite, container, graphic, mockChart, mockGraph, xAxis, yAxis, dataProvider = Y.GeneratePerfTestDataProvider.getData(), seriesObject, seriesKeys = ["expenses", "revenue"]; container = document.createElement('div'); container.style.left = "10px"; container.style.top = "10px"; container.style.width = "600px"; container.style.height = "300px"; container.id = "container"; document.body.appendChild(container); suite.add("PerfColumnSeriesGroup", function() { var i, key, series, seriesTypeCollection = [], len = seriesKeys.length; seriesObject = {}; for(i = 0; i < len; i = i + 1) { key = seriesKeys[i]; series = new Y.ColumnSeries({ graphOrder: i, groupMarkers: true, xAxis: xAxis, yAxis: yAxis, graph: mockGraph, xKey: "date", seriesTypeCollection: seriesTypeCollection, yKey: key }); seriesTypeCollection.push(series); series.render(); seriesObject[key] = series; } graphic._redraw(); for(key in seriesObject) { if(seriesObject.hasOwnProperty(key)) { seriesObject[key].destroy(true); } } }, { onStart: function() { xAxis = new Y.TimeAxis({ dataProvider: dataProvider, keys: ["date"], position: "none" }); yAxis = new Y.NumericAxis({ dataProvider: dataProvider, keys: ["expenses", "revenue"], position: "none" }); mockGraph = { seriesTypes: { column: [] } }; graphic = new Y.Graphic({ render: container, width: 600, height: 300 }); mockChart = {}; mockChart.get = function(attr) { var val = "yuichart"; return val; }; mockGraph.get = function(attr) { var val; switch(attr) { case "width" : val = 600; break; case "height" : val = 300; break; case "graphic" : val = graphic; break; case "chart" : val = mockChart; break; } return val; }; } }); }, '@VERSION@', {requires: ['charts']});
var jsdom = require('jsdom'); global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = document.defaultView; global.navigator = global.window.navigator; propagateToGlobal(window); function propagateToGlobal (window) { var key; for (key in window) { if (!window.hasOwnProperty(key)) continue; if (key in global) continue; global[key] = window[key] } } require('babel-core/register'); require('babel-polyfill'); process.on('unhandledRejection', function (error) { console.error('Unhandled Promise Rejection:'); console.error(error && error.stack || error); });
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<0eb506171883c5911943baafaa0fefa8>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disable */ 'use strict'; /*:: import type { ConcreteRequest, Query } from 'relay-runtime'; type RelayResponseNormalizerTest11Fragment$fragmentType = any; export type RelayResponseNormalizerTest14Query$variables = {| id: string, |}; export type RelayResponseNormalizerTest14Query$data = {| +node: ?{| +$fragmentSpreads: RelayResponseNormalizerTest11Fragment$fragmentType, |}, |}; export type RelayResponseNormalizerTest14Query = {| variables: RelayResponseNormalizerTest14Query$variables, response: RelayResponseNormalizerTest14Query$data, |}; */ var node/*: ConcreteRequest*/ = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "id" } ], v1 = [ { "kind": "Variable", "name": "id", "variableName": "id" } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "RelayResponseNormalizerTest14Query", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "RelayResponseNormalizerTest11Fragment" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "RelayResponseNormalizerTest14Query", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v2/*: any*/), (v3/*: any*/), { "kind": "InlineFragment", "selections": [ { "if": null, "kind": "Stream", "label": "RelayResponseNormalizerTest11Fragment$stream$actors", "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "actors", "plural": true, "selections": [ (v2/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, (v3/*: any*/) ], "storageKey": null } ] } ], "type": "Feedback", "abstractKey": null } ], "storageKey": null } ] }, "params": { "cacheID": "f9a6357998563d895e3fb767d8458630", "id": null, "metadata": {}, "name": "RelayResponseNormalizerTest14Query", "operationKind": "query", "text": "query RelayResponseNormalizerTest14Query(\n $id: ID!\n) {\n node(id: $id) {\n __typename\n ...RelayResponseNormalizerTest11Fragment\n id\n }\n}\n\nfragment RelayResponseNormalizerTest11Fragment on Feedback {\n id\n actors @stream(label: \"RelayResponseNormalizerTest11Fragment$stream$actors\", initial_count: 0) {\n __typename\n name\n id\n }\n}\n" } }; })(); if (__DEV__) { (node/*: any*/).hash = "c173a8d4e918b5aaecb1da24d9f8f854"; } module.exports = ((node/*: any*/)/*: Query< RelayResponseNormalizerTest14Query$variables, RelayResponseNormalizerTest14Query$data, >*/);
"use strict"; function parseWithFlow(text) { // Inline the require to avoid loading all the JS if we don't use it const flowParser = require("flow-parser"); const ast = flowParser.parse(text, { esproposal_class_instance_fields: true, esproposal_class_static_fields: true, esproposal_export_star_as: true }); if (ast.errors.length > 0) { // Construct an error similar to the ones thrown by Babylon. const loc = { line: ast.errors[0].loc.start.line, column: ast.errors[0].loc.start.column }; const msg = ast.errors[0].message + " (" + loc.line + ":" + loc.column + ")"; const error = new SyntaxError(msg); error.loc = loc; throw error; } return ast; } function parseWithBabylon(text) { // Inline the require to avoid loading all the JS if we don't use it const babylon = require("babylon"); return babylon.parse(text, { sourceType: "module", allowImportExportEverywhere: false, allowReturnOutsideFunction: false, plugins: [ "jsx", "flow", "doExpressions", "objectRestSpread", "decorators", "classProperties", "exportExtensions", "asyncGenerators", "functionBind", "functionSent", "dynamicImport" ] }); } function parseWithTypeScript(text) { // While we are working on typescript, we are putting it in devDependencies // so it shouldn't be picked up by static analysis const r = require; const parser = r("typescript-eslint-parser"); return parser.parse(text, { loc: true, range: true, tokens: true, attachComment: true, ecmaFeatures: { jsx: true } }); } module.exports = { parseWithFlow, parseWithBabylon, parseWithTypeScript };
import BasePlugin from './../_base'; import {arrayEach, arrayFilter} from './../../helpers/array'; import {cancelAnimationFrame, requestAnimationFrame} from './../../helpers/feature'; import {isVisible} from './../../helpers/dom/element'; import {GhostTable} from './../../utils/ghostTable'; import {isObject, objectEach} from './../../helpers/object'; import {valueAccordingPercent, rangeEach} from './../../helpers/number'; import {registerPlugin} from './../../plugins'; import {SamplesGenerator} from './../../utils/samplesGenerator'; import {isPercentValue} from './../../helpers/string'; /** * @plugin AutoRowSize * * @description * This plugin allows to set row heights based on their highest cells. * * By default, the plugin is declared as `undefined`, which makes it disabled (same as if it was declared as `false`). * Enabling this plugin may decrease the overall table performance, as it needs to calculate the heights of all cells to * resize the rows accordingly. * If you experience problems with the performance, try turning this feature off and declaring the row heights manually. * * Row height calculations are divided into sync and async part. Each of this parts has their own advantages and * disadvantages. Synchronous calculations are faster but they block the browser UI, while the slower asynchronous operations don't * block the browser UI. * * To configure the sync/async distribution, you can pass an absolute value (number of columns) or a percentage value to a config object: * ```js * ... * // as a number (300 columns in sync, rest async) * autoRowSize: {syncLimit: 300}, * ... * * ... * // as a string (percent) * autoRowSize: {syncLimit: '40%'}, * ... * ``` * * To configure this plugin see {@link Options#autoRowSize}. * * @example * * ```js * ... * var hot = new Handsontable(document.getElementById('example'), { * date: getData(), * autoRowSize: true * }); * // Access to plugin instance: * var plugin = hot.getPlugin('autoRowSize'); * * plugin.getRowHeight(4); * * if (plugin.isEnabled()) { * // code... * } * ... * ``` */ class AutoRowSize extends BasePlugin { static get CALCULATION_STEP() { return 50; } static get SYNC_CALCULATION_LIMIT() { return 500; } constructor(hotInstance) { super(hotInstance); /** * Cached rows heights. * * @type {Array} */ this.heights = []; /** * Instance of {@link GhostTable} for rows and columns size calculations. * * @type {GhostTable} */ this.ghostTable = new GhostTable(this.hot); /** * Instance of {@link SamplesGenerator} for generating samples necessary for rows height calculations. * * @type {SamplesGenerator} */ this.samplesGenerator = new SamplesGenerator((row, col) => { if (row >= 0) { return this.hot.getDataAtCell(row, col); } else if (row === -1) { return this.hot.getColHeader(col); } else { return null; } }); /** * `true` if only the first calculation was performed. * * @type {Boolean} */ this.firstCalculation = true; /** * `true` if the size calculation is in progress. * * @type {Boolean} */ this.inProgress = false; // moved to constructor to allow auto-sizing the rows when the plugin is disabled this.addHook('beforeRowResize', (row, size, isDblClick) => this.onBeforeRowResize(row, size, isDblClick)); } /** * Check if the plugin is enabled in the Handsontable settings. * * @returns {Boolean} */ isEnabled() { return this.hot.getSettings().autoRowSize === true || isObject(this.hot.getSettings().autoRowSize); } /** * Enable plugin for this Handsontable instance. */ enablePlugin() { if (this.enabled) { return; } let setting = this.hot.getSettings().autoRowSize; let samplingRatio = setting && setting.hasOwnProperty('samplingRatio') ? this.hot.getSettings().autoRowSize.samplingRatio : void 0; if (samplingRatio && !isNaN(samplingRatio)) { this.samplesGenerator.customSampleCount = parseInt(samplingRatio, 10); } this.addHook('afterLoadData', () => this.onAfterLoadData()); this.addHook('beforeChange', (changes) => this.onBeforeChange(changes)); this.addHook('beforeColumnMove', () => this.recalculateAllRowsHeight()); this.addHook('beforeColumnResize', () => this.recalculateAllRowsHeight()); this.addHook('beforeColumnSort', () => this.clearCache()); this.addHook('beforeRender', (force) => this.onBeforeRender(force)); this.addHook('beforeRowMove', (rowStart, rowEnd) => this.onBeforeRowMove(rowStart, rowEnd)); this.addHook('modifyRowHeight', (height, row) => this.getRowHeight(row, height)); this.addHook('modifyColumnHeaderHeight', () => this.getColumnHeaderHeight()); super.enablePlugin(); } /** * Disable plugin for this Handsontable instance. */ disablePlugin() { super.disablePlugin(); } /** * Calculate rows height. * * @param {Number|Object} rowRange Row range object. * @param {Number|Object} colRange Column range object. * @param {Boolean} [force=false] If `true` force calculate height even when value was cached earlier. */ calculateRowsHeight(rowRange = {from: 0, to: this.hot.countRows() - 1}, colRange = {from: 0, to: this.hot.countCols() - 1}, force = false) { if (typeof rowRange === 'number') { rowRange = {from: rowRange, to: rowRange}; } if (typeof colRange === 'number') { colRange = {from: colRange, to: colRange}; } if (this.hot.getColHeader(0) !== null) { const samples = this.samplesGenerator.generateRowSamples(-1, colRange); this.ghostTable.addColumnHeadersRow(samples.get(-1)); } rangeEach(rowRange.from, rowRange.to, (row) => { // For rows we must calculate row height even when user had set height value manually. // We can shrink column but cannot shrink rows! if (force || this.heights[row] === void 0) { const samples = this.samplesGenerator.generateRowSamples(row, colRange); samples.forEach((sample, row) => this.ghostTable.addRow(row, sample)); } }); if (this.ghostTable.rows.length) { this.ghostTable.getHeights((row, height) => this.heights[row] = height); this.ghostTable.clean(); } } /** * Calculate all rows height. * * @param {Object|Number} colRange Column range object. */ calculateAllRowsHeight(colRange = {from: 0, to: this.hot.countCols() - 1}) { let current = 0; let length = this.hot.countRows() - 1; let timer = null; this.inProgress = true; let loop = () => { // When hot was destroyed after calculating finished cancel frame if (!this.hot) { cancelAnimationFrame(timer); this.inProgress = false; return; } this.calculateRowsHeight({from: current, to: Math.min(current + AutoRowSize.CALCULATION_STEP, length)}, colRange); current = current + AutoRowSize.CALCULATION_STEP + 1; if (current < length) { timer = requestAnimationFrame(loop); } else { cancelAnimationFrame(timer); this.inProgress = false; // @TODO Should call once per render cycle, currently fired separately in different plugins this.hot.view.wt.wtOverlays.adjustElementsSize(true); // tmp if (this.hot.view.wt.wtOverlays.leftOverlay.needFullRender) { this.hot.view.wt.wtOverlays.leftOverlay.clone.draw(); } } }; // sync if (this.firstCalculation && this.getSyncCalculationLimit()) { this.calculateRowsHeight({from: 0, to: this.getSyncCalculationLimit()}, colRange); this.firstCalculation = false; current = this.getSyncCalculationLimit() + 1; } // async if (current < length) { loop(); } else { this.inProgress = false; } } /** * Recalculate all rows height (overwrite cache values). */ recalculateAllRowsHeight() { if (isVisible(this.hot.view.wt.wtTable.TABLE)) { this.clearCache(); this.calculateAllRowsHeight(); } } /** * Get value which tells how much rows will be calculated synchronously. Rest rows will be calculated asynchronously. * * @returns {Number} */ getSyncCalculationLimit() { let limit = AutoRowSize.SYNC_CALCULATION_LIMIT; let rowsLimit = this.hot.countRows() - 1; if (isObject(this.hot.getSettings().autoRowSize)) { limit = this.hot.getSettings().autoRowSize.syncLimit; if (isPercentValue(limit)) { limit = valueAccordingPercent(rowsLimit, limit); } else { // Force to Number limit = limit >> 0; } } return Math.min(limit, rowsLimit); } /** * Get calculated row height. * * @param {Number} row Row index. * @param {Number} [defaultHeight] Default row height. It will be pick up if no calculated height found. * @returns {Number} */ getRowHeight(row, defaultHeight = void 0) { let height = defaultHeight; if (this.heights[row] !== void 0 && this.heights[row] > (defaultHeight || 0)) { height = this.heights[row]; } return height; } /** * Get the calculated column header height. * * @returns {Number|undefined} */ getColumnHeaderHeight() { return this.heights[-1]; } /** * Get first visible row. * * @returns {Number} Returns row index or -1 if table is not rendered. */ getFirstVisibleRow() { const wot = this.hot.view.wt; if (wot.wtViewport.rowsVisibleCalculator) { return wot.wtTable.getFirstVisibleRow(); } if (wot.wtViewport.rowsRenderCalculator) { return wot.wtTable.getFirstRenderedRow(); } return -1; } /** * Get last visible row. * * @returns {Number} Returns row index or -1 if table is not rendered. */ getLastVisibleRow() { const wot = this.hot.view.wt; if (wot.wtViewport.rowsVisibleCalculator) { return wot.wtTable.getLastVisibleRow(); } if (wot.wtViewport.rowsRenderCalculator) { return wot.wtTable.getLastRenderedRow(); } return -1; } /** * Clear cached heights. */ clearCache() { this.heights.length = 0; this.heights[-1] = void 0; } /** * Clear cache by range. * * @param {Object|Number} range Row range object. */ clearCacheByRange(range) { if (typeof range === 'number') { range = {from: range, to: range}; } rangeEach(Math.min(range.from, range.to), Math.max(range.from, range.to), (row) => this.heights[row] = void 0); } /** * @returns {Boolean} */ isNeedRecalculate() { return arrayFilter(this.heights, (item) => (item === void 0)).length ? true : false; } /** * On before render listener. * * @private */ onBeforeRender() { let force = this.hot.renderCall; this.calculateRowsHeight({from: this.getFirstVisibleRow(), to: this.getLastVisibleRow()}, void 0, force); let fixedRowsBottom = this.hot.getSettings().fixedRowsBottom; // Calculate rows height synchronously for bottom overlay if (fixedRowsBottom) { let totalRows = this.hot.countRows() - 1; this.calculateRowsHeight({from: totalRows - fixedRowsBottom, to: totalRows}); } if (this.isNeedRecalculate() && !this.inProgress) { this.calculateAllRowsHeight(); } } /** * On before row move listener. * * @private * @param {Number} from Row index where was grabbed. * @param {Number} to Destination row index. */ onBeforeRowMove(from, to) { this.clearCacheByRange({from, to}); this.calculateAllRowsHeight(); } /** * On before row resize listener. * * @private * @param {Number} row * @param {Number} size * @param {Boolean} isDblClick * @returns {Number} */ onBeforeRowResize(row, size, isDblClick) { if (isDblClick) { this.calculateRowsHeight(row, void 0, true); size = this.getRowHeight(row); } return size; } /** * On after load data listener. * * @private */ onAfterLoadData() { if (this.hot.view) { this.recalculateAllRowsHeight(); } else { // first load - initialization setTimeout(() => { if (this.hot) { this.recalculateAllRowsHeight(); } }, 0); } } /** * On before change listener. * * @private * @param {Array} changes */ onBeforeChange(changes) { let range = null; if (changes.length === 1) { range = changes[0][0]; } else if (changes.length > 1) { range = { from: changes[0][0], to: changes[changes.length - 1][0], }; } if (range !== null) { this.clearCacheByRange(range); } } /** * Destroy plugin instance. */ destroy() { this.ghostTable.clean(); super.destroy(); } } export {AutoRowSize}; registerPlugin('autoRowSize', AutoRowSize);
exports.commands = { //commands for score and such resetleaderboard: function(arg, by, room) { if (!Bot.hasRank(by, '#~')) return false; Economy.clear(room, by); Bot.say(by, room, 'The leaderboard has been reset.'); }, registerroom: function(arg, by, room) { if (room.charAt(0) === ',' || !Bot.rankFrom(by, '~')) return false; if (Economy.addRoom(room)) { return Bot.say(by, room, 'An individual leaderboard has been enabled for this room.'); } else { return Bot.say(by, room, 'An individual leaderboard already exists for this room.'); } }, deregisterroom: function(arg, by, room) { if (room.charAt(0) === ',' || !Bot.rankFrom(by, '~')) return false; if (Economy.deleteRoom(room)) { return Bot.say(by, room, 'The individual leaderboard has been deleted for this room.'); } else { return Bot.say(by, room, 'An individual leaderboard does not exist for this room.'); } }, takepoints: 'givepoints', givepoints: function(arg, by, room, cmd) { if (!Bot.canUse('givepoints', room, by) || !arg) return false; if (!Economy.isRegistered(room) && !Bot.rankFrom(by, '@')) return false; arg = arg.split(','); var target = toId(arg[0]); var amount = toId(arg[1]).replace(/[^0-9]/g, ''); if (!amount) return; if (cmd === 'takepoints') amount = amount * -1; Economy.give(target, amount * 1, room); if (amount < 0) { return Bot.say(by, room, target + ' has lost ' + amount * -1 + ' ' + Economy.currency(room)); } return Bot.say(by, room, target + ' has been given ' + amount + ' ' + Economy.currency(room)); }, points: 'atm', score: 'atm', wallet: 'atm', atm: function(arg, by, room) { if (!Bot.hasRank(by, '+%@#&~')) { var targetRoom = ',' + by; } else { targetRoom = room; } if (arg) { var user = arg.split(',')[0]; if (arg.split(',')[1]) { room = toId(arg.split(',')[1]); } } var target = user || by; return Bot.say(by, targetRoom, '(' + (Economy.isRegistered(room) ? room : 'global') + ') ' + target + ' has ' + Economy.getPoints(target, room) + ' ' + Economy.currency(room)); }, top: function(arg, by, room) { if (!Bot.hasRank(by, '+%@#&~')) { var targetRoom = ',' + by; } else { targetRoom = room; } if (arg) { room = toId(arg); } Bot.say(by, targetRoom, Economy.getTop(room)); }, leaderboard: function(arg, by, room) { if (!Bot.hasRank(by, '+%@#&~')) { var targetRoom = ',' + by; } else { targetRoom = room; } if (arg) { room = toId(arg); } var text = Economy.getHastebinLeaderboard(room); Tools.uploadToHastebin(text, function(link) { return Bot.say(by, targetRoom, link); }.bind(this)); }, config: 'cp', cp: function(arg, by, room) { if (!Bot.hasRank(by, '#~') || !arg) return false; if (!Economy.isRegistered(room) && !Bot.rankFrom(by, '~')) return false; arg = arg.split(','); if (arg.length !== 2) return false; var param = toId(arg[0]); var value = arg[1].trim(); if (!param || !value) return false; if (Economy.isRegistered(room)) { var economyCP = Economy.economy.rooms[room].cp; } else { economyCP = Economy.economy.global.cp; } switch (param) { case 'currency': case 'name': case 'points': economyCP.currency = value; Bot.say(by, room, '"Points" renamed to ' + value); break; case 'factor': case 'payout': value = toId(value); if (/[^0-9]/i.test(value)) { return Bot.say(by, room, 'Invalid value.'); } economyCP.factor = value * 1; Bot.say(by, room, 'Payout factor for winning games is: ' + value); break; } Economy.write(); }, lbhelp: 'leaderboardhelp', leaderboardhelp: function(arg, by, room) { if (!Bot.hasRank(by, '@#&~')) room = ',' + by; Bot.say(by, room, 'http://pastebin.com/am4FgVCH'); } }; /**************************** * For C9 Users * *****************************/ // Yes, sadly it can't be done in one huge chunk w/o undoing it / looking ugly :( /* globals toId */ /* globals Bot */ /* globals Tools */ /* globals Economy */
module.exports = auth; auth.doAuth = doAuth; auth.desc = "Performs an auth call against an Auth Policy"; auth.usage = "\nfhc auth <policy-id> <client-token> <device> <params>" +"\n where <policy-id> is an Auth Policy Id" +"\n where <client-token> is typically an App Id" +"\n where <device> is an identifier for the device" +"\n where <params> are the auth parameters specific to the auth policy"; var log = require("../../utils/log"); var fhc = require("../../fhc"); var fhreq = require("../../utils/request"); var common = require("../../common"); var util = require('util'); var async = require('async'); var path = require('path'); var ini = require('../../utils/ini'); var Table = require('cli-table'); // Main auth entry point function auth (argv, cb) { var args = argv._; if (args.length !== 4){ return cb("Invalid arguments:" + auth.usage); } return doAuth(args[0], args[1], args[2], args[3], cb); } // do our auth function doAuth(policyId, clientToken, device, params, cb) { if (typeof params === 'string') { params = JSON.parse(params); } var cmd = JSON.stringify(params); cmd = '"' + cmd.replace(/"/g,'\\"') + '"'; log.silly("fhc auth " + policyId + " " + clientToken + " " + device + " " + cmd, "auth:"); common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/authpolicy/auth", {policyId: policyId, clientToken: clientToken, device: device, params: params}, "Error in auth call: ", function(err, auth){ if(err) return cb(err); return cb(undefined, auth); }); } // bash completion auth.completion = function (opts, cb) { var argv = opts.conf.argv.remain; if (argv[1] !== "auth") argv.unshift("auth"); /* if (argv.length === 2) { var cmds = ["list", "read", "create", "update", "delete"]; if (opts.partialWord !== "l") cmds.push("list"); return cb(undefined, cmds); } var action = argv[2]; switch (action) { case "update": case "read": case "delete": // get auth list break; case "list": return cb(null, []); default: return cb(null, []); } */ };
var express = require('express'); var helper = require('../helpers'); var datafile = 'server/data/activities.json'; var router = express.Router(); /* GET all activities */ /* http://localhost:3000/api/activities */ router.route('/') .get(function(req, res) { var data = helper.readData(datafile); var classroomDataFile = 'server/data/classrooms.json'; var classroomData = helper.readData(classroomDataFile); // attach classrooms to the activities data.forEach(function(activity, index, array) { activity.classroom = helper.getItemsById(classroomData, activity.classroom_id)[0]; }); res.send(data); }); /* GET, PUT and DELETE individual classrooms */ router.route('/:id') .get(function(req, res) { var data = helper.readData(datafile); var matchingActivities = data.filter(function(item) { return item.activity_id == req.params.id; }); if(matchingActivities.length === 0) { res.sendStatus(404); } else { res.send(matchingActivities[0]); } }); module.exports = router;
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.provide("website"); $.extend(frappe, { _assets_loaded: [], require: function(url) { if(frappe._assets_loaded.indexOf(url)!==-1) return; $.ajax({ url: url, async: false, dataType: "text", success: function(data) { if(url.split(".").splice(-1) == "js") { var el = document.createElement('script'); } else { var el = document.createElement('style'); } el.appendChild(document.createTextNode(data)); document.getElementsByTagName('head')[0].appendChild(el); frappe._assets_loaded.push(url); } }); }, hide_message: function(text) { $('.message-overlay').remove(); }, call: function(opts) { // opts = {"method": "PYTHON MODULE STRING", "args": {}, "callback": function(r) {}} frappe.prepare_call(opts); return $.ajax({ type: opts.type || "POST", url: "/", data: opts.args, dataType: "json", statusCode: { 404: function(xhr) { frappe.msgprint(__("Not found")); }, 403: function(xhr) { frappe.msgprint(__("Not permitted")); }, 200: function(data, xhr) { if(opts.callback) opts.callback(data); } } }).always(function(data) { // executed before statusCode functions if(data.responseText) { data = JSON.parse(data.responseText); } frappe.process_response(opts, data); }); }, prepare_call: function(opts) { if(opts.btn) { $(opts.btn).prop("disabled", true); } if(opts.msg) { $(opts.msg).toggle(false); } if(!opts.args) opts.args = {}; // get or post? if(!opts.args._type) { opts.args._type = opts.type || "GET"; } // method if(opts.method) { opts.args.cmd = opts.method; } // stringify $.each(opts.args, function(key, val) { if(typeof val != "string") { opts.args[key] = JSON.stringify(val); } }); if(!opts.no_spinner) { //NProgress.start(); } }, process_response: function(opts, data) { //if(!opts.no_spinner) NProgress.done(); if(opts.btn) { $(opts.btn).prop("disabled", false); } if (data._server_messages) { var server_messages = (JSON.parse(data._server_messages || '[]')).join("<br>"); if(opts.error_msg) { $(opts.error_msg).html(server_messages).toggle(true); } else { frappe.msgprint(server_messages); } } if(data.exc) { if(opts.btn) { $(opts.btn).addClass("btn-danger"); setTimeout(function() { $(opts.btn).removeClass("btn-danger"); }, 1000); } try { var err = JSON.parse(data.exc); if($.isArray(err)) { err = err.join("\n"); } console.error ? console.error(err) : console.log(err); } catch(e) { console.log(data.exc); } } else{ if(opts.btn) { $(opts.btn).addClass("btn-success"); setTimeout(function() { $(opts.btn).removeClass("btn-success"); }, 1000); } } if(opts.msg && data.message) { $(opts.msg).html(data.message).toggle(true); } }, show_message: function(text, icon) { if(!icon) icon="icon-refresh icon-spin"; frappe.hide_message(); $('<div class="message-overlay"></div>') .html('<div class="content"><i class="'+icon+' text-muted"></i><br>' +text+'</div>').appendTo(document.body); }, hide_message: function(text) { $('.message-overlay').remove(); }, get_sid: function() { var sid = getCookie("sid"); return sid && sid!=="Guest"; }, get_modal: function(title, body_html) { var modal = $('<div class="modal" style="overflow: auto;" tabindex="-1">\ <div class="modal-dialog">\ <div class="modal-content">\ <div class="modal-header">\ <a type="button" class="close"\ data-dismiss="modal" aria-hidden="true">&times;</a>\ <h4 class="modal-title">'+title+'</h4>\ </div>\ <div class="modal-body ui-front">'+body_html+'\ </div>\ </div>\ </div>\ </div>').appendTo(document.body); return modal; }, msgprint: function(html, title) { if(html.substr(0,1)==="[") html = JSON.parse(html); if($.isArray(html)) { html = html.join("<hr>") } return frappe.get_modal(title || "Message", html).modal("show"); }, send_message: function(opts, btn) { return frappe.call({ type: "POST", method: "frappe.templates.pages.contact.send_message", btn: btn, args: opts, callback: opts.callback }); }, has_permission: function(doctype, docname, perm_type, callback) { return frappe.call({ method: "frappe.client.has_permission", no_spinner: true, args: {doctype: doctype, docname: docname, perm_type: perm_type}, callback: function(r) { if(!r.exc && r.message.has_permission) { if(callback) { return callback(r); } } } }); }, render_user: function() { var sid = frappe.get_cookie("sid"); if(sid && sid!=="Guest") { $(".btn-login-area").toggle(false); $(".logged-in").toggle(true); $(".full-name").html(frappe.get_cookie("full_name")); $(".user-picture").attr("src", frappe.get_cookie("user_image")); } }, setup_push_state: function() { if(frappe.supports_pjax()) { // hack for chrome's onload popstate call window.initial_href = window.location.href $(document).on("click", "#wrap a", frappe.handle_click); $(window).on("popstate", function(event) { // don't run this on hash change if (location.hash && (!window.previous_href || window.previous_href.replace(location.hash, '') === location.href.replace(location.hash, ''))) return; // hack for chrome's onload popstate call if(window.initial_href==location.href && window.previous_href==undefined) { window.history.replaceState({"reload": true}, window.document.title, location.href); return; } window.previous_href = location.href; var state = event.originalEvent.state; if(!state) { window.location.reload(); return; } frappe.render_json(state); }); } }, handle_click: function(event) { // taken from jquery pjax var link = event.currentTarget if (link.tagName.toUpperCase() !== 'A') throw "using pjax requires an anchor element"; // Middle click, cmd click, and ctrl click should open // links in a new tab as normal. if ( event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey ) return; if (link.getAttribute("target")) return; // Ignore cross origin links if ( location.protocol !== link.protocol || location.hostname !== link.hostname ) return; // Ignore anchors on the same page if (link.hash && link.href.replace(link.hash, '') === location.href.replace(location.hash, '')) return; // Ignore empty anchor "foo.html#" if (link.href === location.href + '#') return; // our custom logic if (link.href.indexOf("cmd=")!==-1 || link.hasAttribute("no-pjax")) return; // has an extension, but is not htm/html var last_part = (link.href.split("/").slice(-1)[0] || ""); if (last_part.indexOf(".")!==-1 && (last_part.indexOf(".htm")===-1)) return; event.preventDefault() frappe.load_via_ajax(link.href); }, load_via_ajax: function(href) { // console.log("calling ajax"); window.previous_href = href; history.pushState(null, null, href); var _render = function(data) { try { history.replaceState(data, data.title, href); } catch(e) { // data too big (?) history.replaceState(null, data.title, href); } scroll(0,0); frappe.render_json(data); }; $.ajax({ url: href, cache: false, statusCode: { 200: _render, 404: function(xhr) { _render(xhr.responseJSON); } } }).fail(function(xhr, status, error) { window.location.reload(); }); }, render_json: function(data) { if (data.reload) { window.location.reload(); return; } $('[data-html-block]').each(function(i, section) { var $section = $(section); var stype = $section.attr("data-html-block"); // handle meta separately if (stype==="meta_block") return; var block_data = data[stype] || ""; // NOTE: use frappe.ready instead of $.ready for reliable execution if(stype==="script") { $section.remove(); $("<script data-html-block='script'></script>") .html(block_data) .appendTo("body"); } else if(stype==="script_lib") { // render once if(!$("[data-block-html='script_lib'][data-path='"+data.path+"']").length) { $("<script data-block-html='script_lib' data-path='"+data.path+"'></script>") .html(data.script_lib) .appendTo("body"); } } else { $section.html(block_data); } }); if(data.title) $("title").html(data.title); // change meta tags $('[data-html-block="meta_block"]').remove(); if(data.meta_block) { $("head").append(data.meta_block); } // change id of current page $(".page-container").attr("id", "page-" + data.path); // clear page-header-right $(".page-header-right").html(""); window.ga && ga('send', 'pageview', location.pathname); $(document).trigger("page-change"); }, supports_pjax: function() { return (window.history && window.history.pushState && window.history.replaceState && // pushState isn't reliable on iOS until 5. !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/)) }, get_pathname: function() { return location.pathname; }, page_ready_events: {}, ready: function(fn) { frappe.page_ready_events[frappe.get_pathname()] = fn; }, trigger_ready: function() { var ready = frappe.page_ready_events[frappe.get_pathname()]; ready && ready(); }, highlight_code_blocks: function() { if(hljs) { $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); } }, bind_filters: function() { // set in select $(".filter").each(function() { var key = $(this).attr("data-key"); var val = get_url_arg(key).replace(/\+/g, " "); if(val) $(this).val(val); }); // search url var search = function() { var args = {}; $(".filter").each(function() { var val = $(this).val(); if(val) args[$(this).attr("data-key")] = val; }); window.location.href = location.pathname + "?" + $.param(args); } $(".filter").on("change", function() { search(); }); }, make_navbar_active: function() { var pathname = window.location.pathname; $(".navbar a.active").removeClass("active"); $(".navbar a").each(function() { var href = $(this).attr("href"); if(href===pathname) { $(this).addClass("active"); return false; } }) }, toggle_template_blocks: function() { // this assumes frappe base template $(".page-header").toggleClass("hidden", !!!$("[data-html-block='header']").text().trim()); $(".page-footer").toggleClass("hidden", !!!$(".page-footer").text().trim()); // hide breadcrumbs if no breadcrumb content or if it is same as the header $("[data-html-block='breadcrumbs'] .breadcrumb").toggleClass("hidden", !$("[data-html-block='breadcrumbs']").text().trim() || $("[data-html-block='breadcrumbs']").text().trim()==$("[data-html-block='header']").text().trim()); // to show full content width, when no sidebar content var sidebar_has_content = !!$("[data-html-block='sidebar']").html().trim(); $(".page-sidebar, .toggle-sidebar").toggleClass("hidden", !sidebar_has_content); $(".page-sidebar").toggleClass("col-sm-push-9", sidebar_has_content); $(".page-content").toggleClass("col-sm-12", !sidebar_has_content); $(".page-content").toggleClass("col-sm-9 col-sm-pull-3", sidebar_has_content); // if everything in the sub-header is hidden, hide the sub-header // var hide_sub_header = $(".page-sub-header .row").children().length === $(".page-sub-header .row").find(".hidden").length; // $(".page-sub-header").toggleClass("hidden", hide_sub_header); // collapse sidebar in mobile view on page change if(!$(".page-sidebar").hasClass("hidden-xs")) { $(".toggle-sidebar").trigger("click"); } // TODO add private pages to sidebar // if(website.private_pages && $(".page-sidebar").length) { // $(website.private_pages).prependTo(".page-sidebar"); // } } }); // Utility functions function valid_email(id) { return (id.toLowerCase().search("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")==-1) ? 0 : 1; } var validate_email = valid_email; function get_url_arg(name) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if(results == null) return ""; else return decodeURIComponent(results[1]); } function make_query_string(obj) { var query_params = []; $.each(obj, function(k, v) { query_params.push(encodeURIComponent(k) + "=" + encodeURIComponent(v)); }); return "?" + query_params.join("&"); } function repl(s, dict) { if(s==null)return ''; for(key in dict) { s = s.split("%("+key+")s").join(dict[key]); } return s; } function replace_all(s, t1, t2) { return s.split(t1).join(t2); } function getCookie(name) { return getCookies()[name]; } frappe.get_cookie = getCookie; function getCookies() { var c = document.cookie, v = 0, cookies = {}; if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) { c = RegExp.$1; v = 1; } if (v === 0) { c.split(/[,;]/).map(function(cookie) { var parts = cookie.split(/=/, 2), name = decodeURIComponent(parts[0].trimLeft()), value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null; if(value && value.charAt(0)==='"') { value = value.substr(1, value.length-2); } cookies[name] = value; }); } else { c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) { var name = $0, value = $1.charAt(0) === '"' ? $1.substr(1, -1).replace(/\\(.)/g, "$1") : $1; cookies[name] = value; }); } return cookies; } if (typeof String.prototype.trimLeft !== "function") { String.prototype.trimLeft = function() { return this.replace(/^\s+/, ""); }; } if (typeof String.prototype.trimRight !== "function") { String.prototype.trimRight = function() { return this.replace(/\s+$/, ""); }; } if (typeof Array.prototype.map !== "function") { Array.prototype.map = function(callback, thisArg) { for (var i=0, n=this.length, a=[]; i<n; i++) { if (i in this) a[i] = callback.call(thisArg, this[i]); } return a; }; } function remove_script_and_style(txt) { return (!txt || (txt.indexOf("<script>")===-1 && txt.indexOf("<style>")===-1)) ? txt : $("<div></div>").html(txt).find("script,noscript,style,title,meta").remove().end().html(); } function is_html(txt) { if(txt.indexOf("<br>")==-1 && txt.indexOf("<p")==-1 && txt.indexOf("<img")==-1 && txt.indexOf("<div")==-1) { return false; } return true; } function ask_to_login() { if(!window.full_name) { if(localStorage) { localStorage.setItem("last_visited", window.location.href.replace(window.location.origin, "")); } window.location.href = "login"; } } // check if logged in? $(document).ready(function() { window.full_name = getCookie("full_name"); window.logged_in = getCookie("sid") && getCookie("sid")!=="Guest"; $("#website-login").toggleClass("hide", logged_in ? true : false); $("#website-post-login").toggleClass("hide", logged_in ? false : true); $(".toggle-sidebar").on("click", function() { $(".page-sidebar").toggleClass("hidden-xs"); $(".toggle-sidebar i").toggleClass("icon-rotate-180"); }); // switch to app link if(getCookie("system_user")==="yes") { $("#website-post-login .dropdown-menu").append('<li class="divider"></li>\ <li><a href="/desk" no-pjax><i class="icon-fixed-width icon-th-large"></i> Switch To Desk</a></li>'); } frappe.render_user(); frappe.setup_push_state() $(document).trigger("page-change"); }); $(document).on("page-change", function() { $(document).trigger("apply_permissions"); frappe.datetime.refresh_when(); frappe.toggle_template_blocks(); frappe.trigger_ready(); frappe.bind_filters(); frappe.highlight_code_blocks(); frappe.make_navbar_active(); });
// video plugin definition var vp; // Step 1: initialize plugins $(document).bind("deviceready", function() { vp = window.plugins.videoPlayer; }); // Step 2: prepare callback function for videoplugin var videoplayerCallBack = function(param) { // callback function should be: pluginname + CallBack if (param == 'finish') { $('#status').html("finish playing"); navigator.notification.alert("finish"); } }; // initialize jo jo.load(); App = { load:function() { var screen, stack, card; // create our UI screen = new joScreen( stack = new joStack().push( card = new joCard([ new joTitle("Video"), new joCaption("Video List"), new joDivider(), new joButton("Video 1").selectEvent.subscribe(function() { //navigator.notification.alert("finish"); vp.play('movie.mp4', 'YES'); }), new joButton("Video 2").selectEvent.subscribe(function() { vp.play('http://easyhtml5video.com/images/happyfit2.mp4', 'NO'); }) ]) ) ); } };
version https://git-lfs.github.com/spec/v1 oid sha256:cb46cc721cda5b746592c3cddcb48728604803d44389a8a2bc535fa3669d16a2 size 450
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.image.MagnifierLite"]){ dojo._hasResource["dojox.image.MagnifierLite"]=true; dojo.provide("dojox.image.MagnifierLite"); dojo.experimental("dojox.image.MagnifierLite"); dojo.require("dijit._Widget"); dojo.declare("dojox.image.MagnifierLite",dijit._Widget,{glassSize:125,scale:6,postCreate:function(){ this.inherited(arguments); this._adjustScale(); this._createGlass(); this.connect(this.domNode,"onmouseenter","_showGlass"); this.connect(this.glassNode,"onmousemove","_placeGlass"); this.connect(this.img,"onmouseout","_hideGlass"); this.connect(window,"onresize","_adjustScale"); },_createGlass:function(){ var _1=this.glassNode=dojo.create("div",{style:{height:this.glassSize+"px",width:this.glassSize+"px"},className:"glassNode"},dojo.body()); this.surfaceNode=_1.appendChild(dojo.create("div")); this.img=dojo.place(dojo.clone(this.domNode),_1); dojo.style(this.img,{position:"relative",top:0,left:0,width:this._zoomSize.w+"px",height:this._zoomSize.h+"px"}); },_adjustScale:function(){ this.offset=dojo.coords(this.domNode,true); this._imageSize={w:this.offset.w,h:this.offset.h}; this._zoomSize={w:this._imageSize.w*this.scale,h:this._imageSize.h*this.scale}; },_showGlass:function(e){ this._placeGlass(e); dojo.style(this.glassNode,{visibility:"visible",display:""}); },_hideGlass:function(e){ dojo.style(this.glassNode,{visibility:"hidden",display:"none"}); },_placeGlass:function(e){ this._setImage(e); var _2=Math.floor(this.glassSize/2); dojo.style(this.glassNode,{top:Math.floor(e.pageY-_2)+"px",left:Math.floor(e.pageX-_2)+"px"}); },_setImage:function(e){ var _3=(e.pageX-this.offset.l)/this.offset.w,_4=(e.pageY-this.offset.t)/this.offset.h,x=(this._zoomSize.w*_3*-1)+(this.glassSize*_3),y=(this._zoomSize.h*_4*-1)+(this.glassSize*_4); dojo.style(this.img,{top:y+"px",left:x+"px"}); },destroy:function(_5){ dojo.destroy(this.glassNode); this.inherited(arguments); }}); }
'use strict'; require('mocha'); require('should'); var assert = require('assert'); var generate = require('..'); var app; describe('app', function() { beforeEach(function() { app = generate(); app.create('docs'); }); describe('add doc', function() { it('should add docs to `app.views.docs`:', function() { app.doc('a.hbs', {path: 'a.hbs', content: 'a'}); app.doc('b.hbs', {path: 'b.hbs', content: 'b'}); app.doc('c.hbs', {path: 'c.hbs', content: 'c'}); assert(Object.keys(app.views.docs).length === 3); }); }); });
d3.sankey = function() { var sankey = {}, nodeWidth = 24, nodePadding = 8, size = [1, 1], nodes = [], links = [], sinksRight = true; sankey.nodeWidth = function(_) { if (!arguments.length) return nodeWidth; nodeWidth = +_; return sankey; }; sankey.nodePadding = function(_) { if (!arguments.length) return nodePadding; nodePadding = +_; return sankey; }; sankey.nodes = function(_) { if (!arguments.length) return nodes; nodes = _; return sankey; }; sankey.links = function(_) { if (!arguments.length) return links; links = _; return sankey; }; sankey.size = function(_) { if (!arguments.length) return size; size = _; return sankey; }; sankey.sinksRight = function (_) { if (!arguments.length) return sinksRight; sinksRight = _; return sankey; }; sankey.layout = function(iterations) { computeNodeLinks(); computeNodeValues(); computeNodeBreadths(); computeNodeDepths(iterations); return sankey; }; sankey.relayout = function() { computeLinkDepths(); return sankey; }; // SVG path data generator, to be used as "d" attribute on "path" element selection. sankey.link = function() { var curvature = .5; function link(d) { var xs = d.source.x + d.source.dx, xt = d.target.x, xi = d3.interpolateNumber(xs, xt), xsc = xi(curvature), xtc = xi(1 - curvature), ys = d.source.y + d.sy + d.dy / 2, yt = d.target.y + d.ty + d.dy / 2; if (!d.cycleBreaker) { return "M" + xs + "," + ys + "C" + xsc + "," + ys + " " + xtc + "," + yt + " " + xt + "," + yt; } else { var xdelta = (1.5 * d.dy + 0.05 * Math.abs(xs - xt)); xsc = xs + xdelta; xtc = xt - xdelta; var xm = xi(0.5); var ym = d3.interpolateNumber(ys, yt)(0.5); var ydelta = (2 * d.dy + 0.1 * Math.abs(xs - xt) + 0.1 * Math.abs(ys - yt)) * (ym < (size[1] / 2) ? -1 : 1); return "M" + xs + "," + ys + "C" + xsc + "," + ys + " " + xsc + "," + (ys + ydelta) + " " + xm + "," + (ym + ydelta) + "S" + xtc + "," + yt + " " + xt + "," + yt; } } link.curvature = function(_) { if (!arguments.length) return curvature; curvature = +_; return link; }; return link; }; // Populate the sourceLinks and targetLinks for each node. // Also, if the source and target are not objects, assume they are indices. function computeNodeLinks() { nodes.forEach(function(node) { // Links that have this node as source. node.sourceLinks = []; // Links that have this node as target. node.targetLinks = []; }); links.forEach(function(link) { var source = link.source, target = link.target; if (typeof source === "number") source = link.source = nodes[link.source]; if (typeof target === "number") target = link.target = nodes[link.target]; source.sourceLinks.push(link); target.targetLinks.push(link); }); } // Compute the value (size) of each node by summing the associated links. function computeNodeValues() { nodes.forEach(function(node) { node.value = Math.max( d3.sum(node.sourceLinks, value), d3.sum(node.targetLinks, value) ); }); } // Iteratively assign the breadth (x-position) for each node. // Nodes are assigned the maximum breadth of incoming neighbors plus one; // nodes with no incoming links are assigned breadth zero, while // nodes with no outgoing links are assigned the maximum breadth. function computeNodeBreadths() { var remainingNodes = nodes, nextNodes, x = 0; // Work from left to right. // Keep updating the breath (x-position) of nodes that are target of recently updated nodes. while (remainingNodes.length && x < nodes.length) { nextNodes = []; remainingNodes.forEach(function(node) { node.x = x; node.dx = nodeWidth; node.sourceLinks.forEach(function(link) { if (nextNodes.indexOf(link.target) < 0 && !link.cycleBreaker) { nextNodes.push(link.target); } }); }); if (nextNodes.length == remainingNodes.length) { // There must be a cycle here. Let's search for a link that breaks it. findAndMarkCycleBreaker(nextNodes); // Start over. // TODO: make this optional? return computeNodeBreadths(); } else { remainingNodes = nextNodes; ++x; } } // Optionally move pure sinks always to the right, and scale node breadths if (sinksRight) { moveSinksRight(x); scaleNodeBreadths((size[0] - nodeWidth) / (x - 1)); } else { scaleNodeBreadths((size[0] - nodeWidth) / x); } } // Find a link that breaks a cycle in the graph (if any). function findAndMarkCycleBreaker(nodes) { // Go through all nodes from the given subset and traverse links searching for cycles. var link; for (var n=nodes.length - 1; n >= 0; n--) { link = depthFirstCycleSearch(nodes[n], []); if (link) { return link; } } // Depth-first search to find a link that is part of a cycle. function depthFirstCycleSearch(cursorNode, path) { var target, link; for (var n = cursorNode.sourceLinks.length - 1; n >= 0; n--) { link = cursorNode.sourceLinks[n]; if (link.cycleBreaker) { // Skip already known cycle breakers. continue; } // Check if target of link makes a cycle in current path. target = link.target; for (var l = 0; l < path.length; l++) { if (path[l].source == target) { // We found a cycle. Search for weakest link in cycle var weakest = link; for (; l < path.length; l++) { if (path[l].value < weakest.value) { weakest = path[l]; } } // Mark weakest link as (known) cycle breaker and abort search. weakest.cycleBreaker = true; return weakest; } } // Recurse deeper. path.push(link); link = depthFirstCycleSearch(target, path); path.pop(); // Stop further search if we found a cycle breaker. if (link) { return link; } } } } function moveSourcesRight() { nodes.forEach(function(node) { if (!node.targetLinks.length) { node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1; } }); } function moveSinksRight(x) { nodes.forEach(function(node) { if (!node.sourceLinks.length) { node.x = x - 1; } else { //move node to second from right var nodes_to_right = 0; node.sourceLinks.forEach(function(n) { nodes_to_right = Math.max(nodes_to_right,n.target.sourceLinks.length) //console.log(node.name,n) }) //console.log(node.name,nodes_to_right) if (nodes_to_right==0)node.x = x - 2; } }); } function scaleNodeBreadths(kx) { nodes.forEach(function(node) { node.x *= kx; }); } // Compute the depth (y-position) for each node. function computeNodeDepths(iterations) { // Group nodes by breath. var nodesByBreadth = d3.nest() .key(function(d) { return d.x; }) .sortKeys(d3.ascending) .entries(nodes) .map(function(d) { return d.values; }); // initializeNodeDepth(); resolveCollisions(); computeLinkDepths(); for (var alpha = 1; iterations > 0; --iterations) { relaxRightToLeft(alpha *= .99); resolveCollisions(); computeLinkDepths(); relaxLeftToRight(alpha); resolveCollisions(); computeLinkDepths(); } function initializeNodeDepth() { // Calculate vertical scaling factor. var ky = d3.min(nodesByBreadth, function(nodes) { return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value); }); nodesByBreadth.forEach(function(nodes) { nodes.forEach(function(node, i) { node.y = i; node.dy = node.value * ky; }); }); links.forEach(function(link) { link.dy = link.value * ky; }); } function relaxLeftToRight(alpha) { nodesByBreadth.forEach(function(nodes, breadth) { nodes.forEach(function(node) { if (node.targetLinks.length) { // Value-weighted average of the y-position of source node centers linked to this node. var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value); node.y += (y - center(node)) * alpha; } }); }); function weightedSource(link) { return (link.source.y + link.sy + link.dy / 2) * link.value; } } function relaxRightToLeft(alpha) { nodesByBreadth.slice().reverse().forEach(function(nodes) { nodes.forEach(function(node) { if (node.sourceLinks.length) { // Value-weighted average of the y-positions of target nodes linked to this node. var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value); node.y += (y - center(node)) * alpha; } }); }); function weightedTarget(link) { return (link.target.y + link.ty + link.dy / 2) * link.value; } } function resolveCollisions() { nodesByBreadth.forEach(function(nodes) { var node, dy, y0 = 0, n = nodes.length, i; // Push any overlapping nodes down. nodes.sort(ascendingDepth); for (i = 0; i < n; ++i) { node = nodes[i]; dy = y0 - node.y; if (dy > 0) node.y += dy; y0 = node.y + node.dy + nodePadding; } // If the bottommost node goes outside the bounds, push it back up. dy = y0 - nodePadding - size[1]; if (dy > 0) { y0 = node.y -= dy; // Push any overlapping nodes back up. for (i = n - 2; i >= 0; --i) { node = nodes[i]; dy = node.y + node.dy + nodePadding - y0; if (dy > 0) node.y -= dy; y0 = node.y; } } }); } function ascendingDepth(a, b) { return a.y - b.y; } } // Compute y-offset of the source endpoint (sy) and target endpoints (ty) of links, // relative to the source/target node's y-position. function computeLinkDepths() { nodes.forEach(function(node) { node.sourceLinks.sort(ascendingTargetDepth); node.targetLinks.sort(ascendingSourceDepth); }); nodes.forEach(function(node) { var sy = 0, ty = 0; node.sourceLinks.forEach(function(link) { link.sy = sy; sy += link.dy; }); node.targetLinks.forEach(function(link) { link.ty = ty; ty += link.dy; }); }); function ascendingSourceDepth(a, b) { return a.source.y - b.source.y; } function ascendingTargetDepth(a, b) { return a.target.y - b.target.y; } } // Y-position of the middle of a node. function center(node) { return node.y + node.dy / 2; } // Value property accessor. function value(x) { return x.value; } return sankey; };
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; const common = require('../common'); const assert = require('assert'); const http = require('http'); const expected = 10000; let responses = 0; let requests = 0; let connection; const server = http.Server(function(req, res) { requests++; assert.strictEqual(req.connection, connection); res.writeHead(200); res.end('hello world\n'); }); server.once('connection', function(c) { connection = c; }); server.listen(common.PORT, function connect() { const request = http.get({ port: common.PORT, path: '/', headers: { 'Connection': 'Keep-alive' } }, function(res) { res.on('end', function() { if (++responses < expected) { connect(); } else { server.close(); } }); res.resume(); }).on('error', function(e) { console.log(e.message); process.exit(1); }); request.agent.maxSockets = 1; }); process.on('exit', function() { assert.strictEqual(expected, responses); assert.strictEqual(expected, requests); });
/** * Created by intelligrape on 9/7/14. */ // users.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UsersSchema = new Schema({ id: String, name: String, team: String, info: String }); module.exports = mongoose.model('Users', UsersSchema);
/* * The MIT License (MIT) * * Copyright (c) 2014 Apigee Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; var _ = require('lodash-compat'); var assert = require('assert'); var cp = require('child_process'); var path = require('path'); var swagger = require('../'); var errorHandler = module.exports.errorHandler = function () { return function (err, req, res, next) { if (err) { if (res.statusCode < 400) { res.statusCode = 500; } // Useful for debugging // console.log(err); // console.log(err.stack); // if (err.results) { // console.log(JSON.stringify(err.results, null, 2)); // } res.end(err.message); return next(); } else { return next(); } }; }; module.exports.createServer = function (initArgs, options, callback) { var app = require('connect')(); var serverInit = function (middleware) { var handler = options.handler || function (req, res) { res.end('OK'); }; function register (middleware) { if (_.isUndefined(options.mountPoint)) { app.use(middleware); } else { app.use(options.mountPoint, middleware); } } register(middleware.swaggerMetadata()); // Conditionally enable security (To avoid having to rewrite all Swagger documents or all tests) if (Object.keys(options.swaggerSecurityOptions || {}).length > 0) { register(middleware.swaggerSecurity(options.swaggerSecurityOptions)); } register(middleware.swaggerValidator(options.swaggerValidatorOptions)); register(middleware.swaggerRouter(options.swaggerRouterOptions)); register(middleware.swaggerUi(options.swaggerUiOptions)); register(handler); // Error handler middleware to pass errors downstream as JSON app.use(errorHandler()); callback(app); }; initArgs.push(serverInit); swagger.initializeMiddleware.apply(undefined, initArgs); }; var prepareText = module.exports.prepareText = function (text) { return text.replace(/&nbsp;/g, ' ').replace(/\n/g, ''); }; module.exports.expectContent = function (content, done) { return function (err, res) { if (err) { throw err; } if (_.isArray(content) || _.isPlainObject(content)) { assert.deepEqual(JSON.parse(prepareText(res.text)), content); } else { assert.equal(prepareText(res.text), content); } if (_.isFunction(done)) { done(); } }; }; module.exports.executeCLI = function (args, done) { // Add Node args args.unshift('node', path.resolve(path.join(__dirname, '..', 'bin', 'swagger-tools'))); cp.exec(args.join(' '), function (err, stdout, stderr) { done(stderr, stdout); }); };
/* */ "format register"; "use strict"; var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; var Behavior = require("aurelia-templating").Behavior; function addStyleString(str) { var node = document.createElement("style"); node.innerHTML = str; node.type = "text/css"; document.head.appendChild(node); } addStyleString(".aurelia-hide { display:none; }"); var Show = (function () { function Show(element) { this.element = element; } _prototypeProperties(Show, { metadata: { value: function metadata() { return Behavior.attachedBehavior("show").withProperty("value", "valueChanged", "show"); }, writable: true, enumerable: true, configurable: true }, inject: { value: function inject() { return [Element]; }, writable: true, enumerable: true, configurable: true } }, { valueChanged: { value: function valueChanged(newValue) { if (newValue) { this.element.classList.remove("aurelia-hide"); } else { this.element.classList.add("aurelia-hide"); } }, writable: true, enumerable: true, configurable: true } }); return Show; })(); exports.Show = Show;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { CONST } from 'angular2/src/facade/lang'; /** * * * @exportedAs angular2/di */ export let OpaqueToken = class { constructor(desc) { this._desc = 'Token(' + desc + ')'; } toString() { return this._desc; } }; OpaqueToken = __decorate([ CONST(), __metadata('design:paramtypes', [String]) ], OpaqueToken); //# sourceMappingURL=opaque_token.js.map
// @thisWillBeFlowInTest const {foo} = require('./empty');
/* 1. Write a script that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console. */ taskName = "1. Multiplied by 20"; function Main(bufferElement) { var numbers = new Array(20); for (var i = 0; i < numbers.length; i++) { numbers[i] = i * 5; } WriteLine(numbers.join(', ')); }
if (typeof module === "object" && typeof require === "function") { var sinon = require("sinon"); var buster = require("buster-core"); buster.extend(buster, { assertions: require("buster-assertions"), dotsReporter: require("../../../../lib/buster-test/reporters/dots") }); buster.util = require("buster-util"); } var assert = buster.assertions.assert; var refute = buster.assertions.refute; buster.util.testCase("DotsReporterEventMappingTest", sinon.testCase({ setUp: function () { this.stub(buster.dotsReporter, "reset"); this.stub(buster.dotsReporter, "printDetails"); this.stub(buster.dotsReporter, "startContext"); this.stub(buster.dotsReporter, "endContext"); this.stub(buster.dotsReporter, "unsupportedContext"); this.stub(buster.dotsReporter, "testSuccess"); this.stub(buster.dotsReporter, "testFailure"); this.stub(buster.dotsReporter, "testError"); this.stub(buster.dotsReporter, "testAsync"); this.stub(buster.dotsReporter, "testTimeout"); this.stub(buster.dotsReporter, "testDeferred"); this.stub(buster.dotsReporter, "log"); this.stub(buster.dotsReporter, "uncaughtException"); this.runner = buster.create(buster.eventEmitter); this.runner.console = buster.create(buster.eventEmitter); this.reporter = buster.dotsReporter.create().listen(this.runner); }, "should map suite:start to reset": function () { this.runner.emit("suite:start"); // reset is also called by the create method assert(this.reporter.reset.calledTwice); }, "should map suite:end to printDetails": function () { this.runner.emit("suite:end", {}); assert(this.reporter.printDetails.calledOnce); }, "should map context:start to startContext": function () { this.runner.emit("context:start"); assert(this.reporter.startContext.calledOnce); }, "should map context:end to endContext": function () { this.runner.emit("context:end"); assert(this.reporter.endContext.calledOnce); }, "should map context:unsupported to unsupportedContext": function () { this.runner.emit("context:unsupported"); assert(this.reporter.unsupportedContext.calledOnce); }, "should map test:success to testSuccess": function () { this.runner.emit("test:success"); assert(this.reporter.testSuccess.calledOnce); }, "should map test:error to testError": function () { this.runner.emit("test:error"); assert(this.reporter.testError.calledOnce); }, "should map test:fail to testFailure": function () { this.runner.emit("test:failure"); assert(this.reporter.testFailure.calledOnce); }, "should map test:async to testAsync": function () { this.runner.emit("test:async"); assert(this.reporter.testAsync.calledOnce); }, "should map test:timeout to testTimeout": function () { this.runner.emit("test:timeout"); assert(this.reporter.testTimeout.calledOnce); }, "should map logger log to log": function () { this.runner.console.emit("log"); assert(this.reporter.log.calledOnce); }, "should map test:deferred to testDeferred": function () { this.runner.emit("test:deferred"); assert(this.reporter.testDeferred.calledOnce); }, "should map uncaughtException to uncaughtException": function () { this.runner.emit("uncaughtException"); assert(this.reporter.uncaughtException.calledOnce); } }, "should")); function runnerSetUp() { this.io = { content: "", puts: function (str) { this.print(str + "\n"); }, print: function (str) { this.content += str; }, toString: function () { return this.content; } }; this.runner = buster.create(buster.eventEmitter); } function reporterSetUp() { runnerSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, logPassedMessages: true }).listen(this.runner); } buster.util.testCase("DotsReporterTestsRunningTest", { setUp: reporterSetUp, "should print dot when test passes": function () { this.reporter.testSuccess({ name: "Stuff" }); assert.equals(this.io.toString(), "."); }, "should not print dot when test passes if not printing progress": function () { this.reporter.displayProgress = false; this.reporter.testSuccess({ name: "Stuff" }); assert.equals(this.io.toString(), ""); }, "should print capital E when test errors": function () { this.reporter.testError({ name: "Stuff" }); assert.equals(this.io.toString(), "E"); }, "should print capital F when test fails": function () { this.reporter.testFailure({ name: "Stuff" }); assert.equals(this.io.toString(), "F"); }, "should print capital T when test times out": function () { this.runner.emit("test:timeout", { name: "Stuff" }); assert.equals(this.io.toString(), "T"); }, "should print capital A when test is asynchronous": function () { this.reporter.testAsync({ name: "Stuff" }); assert.equals(this.io.toString(), "A"); }, "should replace async marker when test completes": function () { this.reporter.testAsync({ name: "Stuff #1" }); this.reporter.testSuccess({ name: "Stuff #1" }); this.reporter.testAsync({ name: "Stuff #2" }); this.reporter.testFailure({ name: "Stuff #2" }); this.reporter.testAsync({ name: "Stuff #3" }); this.reporter.testError({ name: "Stuff #3" }); assert.equals(this.io.toString(), "A\033[1D.A\033[1DFA\033[1DE"); }, "should print context name when starting top-level context": function () { this.reporter.startContext({ name: "Stuff" }); assert.equals(this.io.toString(), "Stuff: "); }, "should not print context name when starting inner context": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.startContext({ name: "Inner" }); assert.equals(this.io.toString(), "Stuff: "); }, "should print line break when ending top-level context": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.endContext({ name: "Stuff" }); assert.match(this.io.toString(), "Stuff: \n"); }, "should not print line break when ending inner context": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.startContext({ name: "Inner" }); this.reporter.endContext({ name: "Inner" }); this.reporter.endContext({ name: "Stuff" }); assert.match(this.io.toString(), "Stuff: \n"); }, "should print all top-level context names": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.startContext({ name: "Second" }); this.reporter.endContext({ name: "Second" }); assert.match(this.io.toString(), "Stuff: \nSecond: \n"); } }); buster.util.testCase("DotsReporterMessagesTest", { setUp: function () { reporterSetUp.call(this); sinon.stub(this.reporter, "printStats"); }, "should print messages for passed test": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testSetUp({ name: "some test" }); this.reporter.log({ level: "log", message: "Is message" }); this.reporter.success({ name: "some test" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "Passed: Stuff some test"); assert.match(this.io.toString(), "[LOG] Is message"); }, "should not re-print messages for failed test": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testSetUp({ name: "some test" }); this.reporter.log({ level: "log", message: "Is message" }); this.reporter.testFailure({ name: "some test" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); refute.match(this.io.toString(), "Passed: Stuff some test"); }, "prints messages not belonging to a specific test": function () { this.reporter.log({ level: "log", message: "Is message" }); this.reporter.startContext({ name: "Stuff" }); this.reporter.testFailure({ name: "some test" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); refute.match(this.io.toString(), "undefined"); assert.match(this.io.toString(), "Global message log:"); assert.match(this.io.toString(), "[LOG] Is message"); }, "should print list of deferred tests": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testDeferred({ name: "some test" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "Deferred: Stuff some test"); }, "should print deferred test comment": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testDeferred({ name: "some test", comment: "Later" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "Deferred: Stuff some test\nLater"); }, "should not print messages for passed test if not configured to": function () { var reporter = buster.dotsReporter.create({ io: this.io, logPassedMessages: false }).listen(this.runner); reporter.startContext({ name: "Stuff" }); reporter.testSetUp({ name: "some test" }); reporter.log({ level: "log", message: "Is message" }); reporter.success({ name: "some test" }); reporter.endContext({ name: "Stuff" }); reporter.printDetails(); refute.match(this.io.toString(), "Passed: Stuff some test"); refute.match(this.io.toString(), "[LOG] Is message"); }, "should print global messages when configured not to log passed": function () { var reporter = buster.dotsReporter.create({ io: this.io, logPassedMessages: false }).listen(this.runner); reporter.log({ level: "log", message: "Is message" }); reporter.startContext({ name: "Stuff" }); reporter.testFailure({ name: "some test" }); reporter.endContext({ name: "Stuff" }); reporter.printDetails(); assert.match(this.io.toString(), "Global message log:"); assert.match(this.io.toString(), "[LOG] Is message"); } }); buster.util.testCase("DotsReporterStatsTest", { setUp: reporterSetUp, "should not print unsupported context during run": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.unsupportedContext({ context: { name: "Second" }, unsupported: ["localStorage"] }); refute.match(this.io.toString(), "localStorage"); }, "should print warning when skipping unsupported context": function () { this.reporter.unsupportedContext({ context: { name: "Stuff" }, unsupported: ["localStorage"] }); this.reporter.printDetails(); assert.match(this.io.toString(), "Skipping Stuff, unsupported requirement: localStorage\n"); }, "should print warning when skipping nested unsupported context": function () { this.reporter.startContext({ name: "Test" }); this.reporter.unsupportedContext({ context: { name: "Stuff" }, unsupported: ["localStorage"] }); this.reporter.printDetails(); assert.match(this.io.toString(), "Skipping Test Stuff, unsupported requirement: localStorage\n"); }, "should print all unsupported features": function () { this.reporter.unsupportedContext({ context: { name: "Stuff" }, unsupported: ["localStorage", "document"] }); this.reporter.printDetails(); assert.match(this.io.toString(), "Skipping Stuff, unsupported requirements:\n localStorage\n document\n"); }, "should print for one test case with one test": function () { this.reporter.printStats({ contexts: 1, tests: 1, assertions: 1, failures: 0, errors: 0 }); var expected = "1 test case, 1 test, 1 assertion, 0 failures, 0 errors, 0 timeouts\n"; assert.match(this.io.toString(), expected); }, "should print for two test cases": function () { this.reporter.printStats({ contexts: 2, tests: 2, assertions: 2, failures: 0, errors: 0 }); var expected = "2 test cases, 2 tests, 2 assertions, 0 failures, 0 errors, 0 timeouts\n"; assert.match(this.io.toString(), expected); }, "should print for errors and failures": function () { this.reporter.printStats({ contexts: 2, tests: 4, assertions: 5, failures: 1, errors: 1 }); var expected = "2 test cases, 4 tests, 5 assertions, 1 failure, 1 error, 0 timeouts\n"; assert.match(this.io.toString(), expected); }, "should report 0 assertions when assertions property is missing from test success": function () { this.reporter.printStats({ contexts: 1, tests: 1 }); var expected = "1 test case, 1 test, 0 assertions, 0 failures, 0 errors, 0 timeouts\n"; assert.match(this.io.toString(), expected); }, "should report timeouts": function () { this.reporter.printStats({ contexts: 1, tests: 1, timeouts: 1 }); var expected = "1 test case, 1 test, 0 assertions, 0 failures, 0 errors, 1 timeout\n"; assert.match(this.io.toString(), expected); }, "should report deferred tests": function () { this.reporter.printStats({ contexts: 1, tests: 1, deferred: 2 }); var expected = "1 test case, 1 test, 0 assertions, 0 failures, 0 errors, 0 timeouts, 2 deferred\n"; assert.match(this.io.toString(), expected); }, "should print warning when no tests": function () { this.reporter.printStats({ contexts: 0, tests: 0, assertions: 0 }); assert.match(this.io.toString(), "No tests"); }, "should print warning when no assertions": function () { this.reporter.printStats({ contexts: 1, tests: 1, assertions: 0 }); assert.match(this.io.toString(), "WARNING: No assertions"); }, "should not print warning for no assertions when no tests": function () { this.reporter.printStats({ contexts: 1, tests: 0, assertions: 0 }); refute.match(this.io.toString(), "WARNING: No assertions"); }, "should include time taken": function () { this.runner.emit("suite:start"); this.reporter.printStats({ contexts: 1, tests: 5, assertions: 10 }); assert.match(this.io.toString(), "Finished in"); } }); buster.util.testCase("DotsReporterFailureTest", { setUp: reporterSetUp, "should print full test name": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testFailure({ name: "should do stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printFailures(); assert.match(this.io.toString(), "Failure: Stuff should do stuff"); }, "should print error message": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testFailure({ name: "should do stuff", error: { message: "Expected a to be equal to b" } }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printFailures(); assert.match(this.io.toString(), " Expected a to be equal to b"); }, "should print log messages": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testSetUp({ name: "should do stuff" }); this.reporter.log({ level: "log", message: "Hey" }); this.reporter.testFailure({ name: "should do stuff", error: { message: "Expected a to be equal to b" } }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printFailures(); assert.match(this.io.toString(), "[LOG] Hey"); }, "should print stack trace": function () { var error = new Error("Expected a to be equal to b"); error.name = "AssertionError"; try { throw error; } catch (e) { error = e; } this.reporter.startContext({ name: "Stuff" }); this.reporter.testFailure({ name: "should do stuff", error: { message: "Expected a to be equal to b", stack: error.stack } }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printFailures(); assert.match(this.io.toString(), "\n at Object"); } }); buster.util.testCase("DotsReporterErrorTest", { setUp: reporterSetUp, "should print full test name": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testError({ name: "should do stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printErrors(); assert.match(this.io.toString(), "Error: Stuff should do stuff"); }, "should print error message": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testError({ name: "should do stuff", error: { message: "a is not defined", name: "ReferenceError" } }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printErrors(); assert.match(this.io.toString(), " ReferenceError: a is not defined"); }, "should print log messages": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testSetUp({ name: "should do stuff" }); this.reporter.log({ level: "log", message: "Hey" }); this.reporter.testError({ name: "should do stuff", error: { message: "Expected a to be equal to b" } }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printErrors(); assert.match(this.io.toString(), "[LOG] Hey"); }, "should print stack trace": function () { var error = new Error("Expected a to be equal to b"); error.name = "AssertionError"; try { throw error; } catch (e) { error = e; } this.reporter.startContext({ name: "Stuff" }); this.reporter.testError({ name: "should do stuff", error: { message: "a is not defined", name: "ReferenceError", stack: error.stack } }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printErrors(); assert.match(this.io.toString(), "\n at Object"); } }); buster.util.testCase("DotsReporterUncaughtExceptionTest", { setUp: reporterSetUp, "should print label": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.uncaughtException({ name: "should do stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printUncaughtExceptions(); assert.match(this.io.toString(), "Uncaught exception!"); }, "should print error message": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.uncaughtException({ message: "Expected a to be equal to b" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printUncaughtExceptions(); assert.match(this.io.toString(), " Expected a to be equal to b"); }, "should print stack trace": function () { var error = new Error("Expected a to be equal to b"); error.name = "AssertionError"; try { throw error; } catch (e) { error = e; } this.reporter.startContext({ name: "Stuff" }); this.reporter.uncaughtException({ message: "Expected a to be equal to b", stack: error.stack }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printUncaughtExceptions(); assert.match(this.io.toString(), "\n at Object"); } }); buster.util.testCase("DotsReporterColorOutputTest", { setUp: function () { runnerSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, color: true }).listen(this.runner); }, "should print green dot when test passes": function () { this.runner.emit("test:success", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[32m.\033[0m"); }, "should print green dot when test passes": function () { this.runner.emit("test:success", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[32m.\033[0m"); }, "should print yellow capital E when test errors": function () { this.runner.emit("test:error", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[33mE\033[0m"); }, "should print red capital F when test fails": function () { this.runner.emit("test:failure", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[31mF\033[0m"); }, "should print red capital T when test times out": function () { this.runner.emit("test:timeout", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[31mT\033[0m"); }, "should print purple capital A when test is asynchronous": function () { this.reporter.testAsync({ name: "Stuff" }); assert.equals(this.io.toString(), "\033[35mA\033[0m"); }, "should print deferred test in cyan": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testDeferred({ name: "some test" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "\033[36mDeferred: Stuff some test\033[0m"); }, "should print deferred test comment in light grey": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testDeferred({ name: "some test", comment: "Later" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "\033[38;5;8mLater\033[0m"); }, "should print unsupported test in yellow": function () { this.reporter.unsupportedContext({ context: { name: "Stuff" }, unsupported: ["localStorage"] }); this.reporter.printDetails(); assert.match(this.io.toString(), "\033[33mSkipping Stuff, unsupported requirement: localStorage\n\033[0m"); } }); buster.util.testCase("DotsReporterColorizedMessagesTest", { setUp: function () { reporterSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, color: true, logPassedMessages: true }).listen(this.runner); sinon.stub(this.reporter, "printStats"); }, "should print passed in green": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testSetUp({ name: "some test" }); this.reporter.log({ level: "log", message: "Is message" }); this.reporter.success({ name: "some test" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "\033[32mPassed: Stuff some test\033[0m"); } }); buster.util.testCase("DotsReporterColorizedStatsTest", { setUp: function () { runnerSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, color: true }).listen(this.runner); }, "should print in green when OK": function () { this.reporter.printStats({ contexts: 1, tests: 1, assertions: 1, failures: 0, errors: 0, timeouts: 0 }); var expected = "\033[32m1 test case, 1 test, 1 assertion, 0 failures, 0 errors, 0 timeouts\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in red when errors and failures": function () { this.reporter.printStats({ contexts: 1, tests: 2, assertions: 2, failures: 1, errors: 1 }); var expected = "\033[31m1 test case, 2 tests, 2 assertions, 1 failure, 1 error, 0 timeouts\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in red when no assertions": function () { this.reporter.printStats({ contexts: 1, tests: 1, assertions: 0 }); var expected = "\033[31m1 test case, 1 test, 0 assertions, 0 failures, 0 errors, 0 timeouts\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in red when no tests": function () { this.reporter.printStats({ contexts: 0, tests: 0 }); var expected = "\033[31mNo tests\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in red when timeouts": function () { this.reporter.printStats({ contexts: 1, tests: 2, errors: 0, failures: 0, timeouts: 1, assertions: 2 }); var expected = "\033[31m1 test case, 2 tests, 2 assertions, 0 failures, 0 errors, 1 timeout\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print no test warning in red": function () { this.reporter.printStats({ contexts: 0, tests: 0, assertions: 0 }); assert.match(this.io.toString(), "\033[31mNo tests\033[0m"); }, "should print no assertion warning in red": function () { this.reporter.printStats({ contexts: 1, tests: 1, assertions: 0 }); assert.match(this.io.toString(), "\033[31mWARNING: No assertions\033[0m"); } }); buster.util.testCase("DotsReporterColorizedExceptionTest", { setUp: function () { runnerSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, color: true }).listen(this.runner); }, "should print full test name with red label when failure": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testFailure({ name: "should do stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printFailures(); assert.match(this.io.toString(), "\033[31mFailure\033[0m: Stuff should do stuff"); }, "should print full test name with yellow label when error": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testError({ name: "should do stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printErrors(); assert.match(this.io.toString(), "\033[33mError\033[0m: Stuff should do stuff"); } }); buster.util.testCase("DotsReporterBrightColorOutputTest", { setUp: function () { runnerSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, color: true, bright: true }).listen(this.runner); }, "should print bright green dot when test passes": function () { this.runner.emit("test:success", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[1m\033[32m.\033[0m"); }, "should print bright yellow capital E when test errors": function () { this.runner.emit("test:error", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[1m\033[33mE\033[0m"); }, "should print bright red capital F when test fails": function () { this.runner.emit("test:failure", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[1m\033[31mF\033[0m"); }, "should print bright red capital T when test times out": function () { this.runner.emit("test:timeout", { name: "Stuff" }); assert.equals(this.io.toString(), "\033[1m\033[31mT\033[0m"); }, "should print bright purple capital A when test is asynchronous": function () { this.reporter.testAsync({ name: "Stuff" }); assert.equals(this.io.toString(), "\033[1m\033[35mA\033[0m"); }, "should print deferred test in bright cyan": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testDeferred({ name: "some test" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "\033[1m\033[36mDeferred: Stuff some test\033[0m"); }, "should print deferred test comment in bright grey": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testDeferred({ name: "some test", comment: "Later" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printDetails(); assert.match(this.io.toString(), "\033[1m\033[38;5;8mLater\033[0m"); }, "should print unsupported test in bright yellow": function () { this.reporter.unsupportedContext({ context: { name: "Stuff" }, unsupported: ["localStorage"] }); this.reporter.printDetails(); assert.match(this.io.toString(), "\033[1m\033[33mSkipping Stuff, unsupported requirement: localStorage\n\033[0m"); } }); buster.util.testCase("DotsReporterBrightlyColorizedStatsTest", { setUp: function () { runnerSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, color: true, bright: true }).listen(this.runner); }, "should print in bright green when OK": function () { this.reporter.printStats({ contexts: 1, tests: 1, failures: 0, errors: 0, assertions: 1, timeouts: 0 }); var expected = "\033[1m\033[32m1 test case, 1 test, 1 assertion, 0 failures, 0 errors, 0 timeouts\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in bright red when errors and failures": function () { this.reporter.printStats({ contexts: 1, tests: 2, failures: 1, errors: 1 }); var expected = "\033[1m\033[31m1 test case, 2 tests, 0 assertions, 1 failure, 1 error, 0 timeouts\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in bright red when no assertions": function () { this.reporter.printStats({ contexts: 1, tests: 1, assertions: 0 }); var expected = "\033[1m\033[31m1 test case, 1 test, 0 assertions, 0 failures, 0 errors, 0 timeouts\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in bright red when no tests": function () { this.reporter.printStats({ contexts: 0, tests: 0 }); var expected = "\033[1m\033[31mNo tests\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print in bright red when timeouts": function () { this.reporter.printStats({ contexts: 1, tests: 1, timeouts: 1 }); var expected = "\033[1m\033[31m1 test case, 1 test, 0 assertions, 0 failures, 0 errors, 1 timeout\033[0m\n"; assert.match(this.io.toString(), expected); }, "should print no test warning in bright red": function () { this.reporter.printStats({ tests: 0 }); assert.match(this.io.toString(), "\033[1m\033[31mNo tests\033[0m"); }, "should print no assertion warning in bright red": function () { this.reporter.printStats({ tests: 1, assertions: 0 }); assert.match(this.io.toString(), "\033[1m\033[31mWARNING: No assertions\033[0m"); } }); buster.util.testCase("DotsReporterBrightlyColorizedExceptionTest", { setUp: function () { runnerSetUp.call(this); this.reporter = buster.dotsReporter.create({ io: this.io, color: true, bright: true }).listen(this.runner); }, "should print full test name with red label when failure": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testFailure({ name: "should do stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printFailures(); assert.match(this.io.toString(), "\033[1m\033[31mFailure\033[0m: Stuff should do stuff"); }, "should print full test name with yellow label when error": function () { this.reporter.startContext({ name: "Stuff" }); this.reporter.testError({ name: "should do stuff" }); this.reporter.endContext({ name: "Stuff" }); this.reporter.printErrors(); assert.match(this.io.toString(), "\033[1m\033[33mError\033[0m: Stuff should do stuff"); } });
;(function(){ // CommonJS require() function require(p){ var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path){ var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn){ require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p.charAt(0)) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.register("browser/debug.js", function(module, exports, require){ module.exports = function(type){ return function(){ } }; }); // module: browser/debug.js require.register("browser/diff.js", function(module, exports, require){ /* See LICENSE file for terms of use */ /* * Text diff implementation. * * This library supports the following APIS: * JsDiff.diffChars: Character by character diff * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace * JsDiff.diffLines: Line based diff * * JsDiff.diffCss: Diff targeted at CSS content * * These methods are based on the implementation proposed in * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ var JsDiff = (function() { /*jshint maxparams: 5*/ function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&amp;'); n = n.replace(/</g, '&lt;'); n = n.replace(/>/g, '&gt;'); n = n.replace(/"/g, '&quot;'); return n; } var Diff = function(ignoreWhitespace) { this.ignoreWhitespace = ignoreWhitespace; }; Diff.prototype = { diff: function(oldString, newString) { // Handle the identity case (this is due to unrolling editLength == 0 if (newString === oldString) { return [{ value: newString }]; } if (!newString) { return [{ value: oldString, removed: true }]; } if (!oldString) { return [{ value: newString, added: true }]; } newString = this.tokenize(newString); oldString = this.tokenize(oldString); var newLen = newString.length, oldLen = oldString.length; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { return bestPath[0].components; } for (var editLength = 1; editLength <= maxEditLength; editLength++) { for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { var basePath; var addPath = bestPath[diagonalPath-1], removePath = bestPath[diagonalPath+1]; oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath-1] = undefined; } var canAdd = addPath && addPath.newPos+1 < newLen; var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; if (!canAdd && !canRemove) { bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { basePath = clonePath(removePath); this.pushComponent(basePath.components, oldString[oldPos], undefined, true); } else { basePath = clonePath(addPath); basePath.newPos++; this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); } var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { return basePath.components; } else { bestPath[diagonalPath] = basePath; } } } }, pushComponent: function(components, value, added, removed) { var last = components[components.length-1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length-1] = {value: this.join(last.value, value), added: added, removed: removed }; } else { components.push({value: value, added: added, removed: removed }); } }, extractCommon: function(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath; while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { newPos++; oldPos++; this.pushComponent(basePath.components, newString[newPos], undefined, undefined); } basePath.newPos = newPos; return oldPos; }, equals: function(left, right) { var reWhitespace = /\S/; if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { return true; } else { return left === right; } }, join: function(left, right) { return left + right; }, tokenize: function(value) { return value; } }; var CharDiff = new Diff(); var WordDiff = new Diff(true); var WordWithSpaceDiff = new Diff(); WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { return removeEmpty(value.split(/(\s+|\b)/)); }; var CssDiff = new Diff(true); CssDiff.tokenize = function(value) { return removeEmpty(value.split(/([{}:;,]|\s+)/)); }; var LineDiff = new Diff(); LineDiff.tokenize = function(value) { var retLines = [], lines = value.split(/^/m); for(var i = 0; i < lines.length; i++) { var line = lines[i], lastLine = lines[i - 1]; // Merge lines that may contain windows new lines if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { retLines[retLines.length - 1] += '\n'; } else if (line) { retLines.push(line); } } return retLines; }; return { Diff: Diff, diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { var ret = []; ret.push('Index: ' + fileName); ret.push('==================================================================='); ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); var diff = LineDiff.diff(oldStr, newStr); if (!diff[diff.length-1].value) { diff.pop(); // Remove trailing newline add } diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function(entry) { return ' ' + entry; }); } function eofNL(curRange, i, current) { var last = diff[diff.length-2], isLast = i === diff.length-2, isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); // Figure out if this is the last line for the given file and missing NL if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { curRange.push('\\ No newline at end of file'); } } var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (var i = 0; i < diff.length; i++) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { if (!oldRangeStart) { var prev = diff[i-1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = contextLines(prev.lines.slice(-4)); oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); eofNL(curRange, i, current); if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= 8 && i < diff.length-2) { // Overlapping curRange.push.apply(curRange, contextLines(lines)); } else { // end the range and output var contextSize = Math.min(lines.length, 4); ret.push( '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + ' @@'); ret.push.apply(ret, curRange); ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); if (lines.length <= 4) { eofNL(ret, i, current); } oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } } return ret.join('\n') + '\n'; }, applyPatch: function(oldStr, uniDiff) { var diffstr = uniDiff.split('\n'); var diff = []; var remEOFNL = false, addEOFNL = false; for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { if(diffstr[i][0] === '@') { var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); diff.unshift({ start:meh[3], oldlength:meh[2], oldlines:[], newlength:meh[4], newlines:[] }); } else if(diffstr[i][0] === '+') { diff[0].newlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === '-') { diff[0].oldlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === ' ') { diff[0].newlines.push(diffstr[i].substr(1)); diff[0].oldlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === '\\') { if (diffstr[i-1][0] === '+') { remEOFNL = true; } else if(diffstr[i-1][0] === '-') { addEOFNL = true; } } } var str = oldStr.split('\n'); for (var i = diff.length - 1; i >= 0; i--) { var d = diff[i]; for (var j = 0; j < d.oldlength; j++) { if(str[d.start-1+j] !== d.oldlines[j]) { return false; } } Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); } if (remEOFNL) { while (!str[str.length-1]) { str.pop(); } } else if (addEOFNL) { str.push(''); } return str.join('\n'); }, convertChangesToXML: function(changes){ var ret = []; for ( var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push('<ins>'); } else if (change.removed) { ret.push('<del>'); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push('</ins>'); } else if (change.removed) { ret.push('</del>'); } } return ret.join(''); }, // See: http://code.google.com/p/google-diff-match-patch/wiki/API convertChangesToDMP: function(changes){ var ret = [], change; for ( var i = 0; i < changes.length; i++) { change = changes[i]; ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); } return ret; } }; })(); if (typeof module !== 'undefined') { module.exports = JsDiff; } }); // module: browser/diff.js require.register("browser/escape-string-regexp.js", function(module, exports, require){ 'use strict'; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; module.exports = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; }); // module: browser/escape-string-regexp.js require.register("browser/events.js", function(module, exports, require){ /** * Module exports. */ exports.EventEmitter = EventEmitter; /** * Check if `obj` is an array. */ function isArray(obj) { return '[object Array]' == {}.toString.call(obj); } /** * Event emitter constructor. * * @api public */ function EventEmitter(){}; /** * Adds a listener. * * @api public */ EventEmitter.prototype.on = function (name, fn) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = fn; } else if (isArray(this.$events[name])) { this.$events[name].push(fn); } else { this.$events[name] = [this.$events[name], fn]; } return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; /** * Adds a volatile listener. * * @api public */ EventEmitter.prototype.once = function (name, fn) { var self = this; function on () { self.removeListener(name, on); fn.apply(this, arguments); }; on.listener = fn; this.on(name, on); return this; }; /** * Removes a listener. * * @api public */ EventEmitter.prototype.removeListener = function (name, fn) { if (this.$events && this.$events[name]) { var list = this.$events[name]; if (isArray(list)) { var pos = -1; for (var i = 0, l = list.length; i < l; i++) { if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { pos = i; break; } } if (pos < 0) { return this; } list.splice(pos, 1); if (!list.length) { delete this.$events[name]; } } else if (list === fn || (list.listener && list.listener === fn)) { delete this.$events[name]; } } return this; }; /** * Removes all listeners for an event. * * @api public */ EventEmitter.prototype.removeAllListeners = function (name) { if (name === undefined) { this.$events = {}; return this; } if (this.$events && this.$events[name]) { this.$events[name] = null; } return this; }; /** * Gets all listeners for a certain event. * * @api public */ EventEmitter.prototype.listeners = function (name) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = []; } if (!isArray(this.$events[name])) { this.$events[name] = [this.$events[name]]; } return this.$events[name]; }; /** * Emits an event. * * @api public */ EventEmitter.prototype.emit = function (name) { if (!this.$events) { return false; } var handler = this.$events[name]; if (!handler) { return false; } var args = [].slice.call(arguments, 1); if ('function' == typeof handler) { handler.apply(this, args); } else if (isArray(handler)) { var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(this, args); } } else { return false; } return true; }; }); // module: browser/events.js require.register("browser/fs.js", function(module, exports, require){ }); // module: browser/fs.js require.register("browser/glob.js", function(module, exports, require){ }); // module: browser/glob.js require.register("browser/path.js", function(module, exports, require){ }); // module: browser/path.js require.register("browser/progress.js", function(module, exports, require){ /** * Expose `Progress`. */ module.exports = Progress; /** * Initialize a new `Progress` indicator. */ function Progress() { this.percent = 0; this.size(0); this.fontSize(11); this.font('helvetica, arial, sans-serif'); } /** * Set progress size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.size = function(n){ this._size = n; return this; }; /** * Set text to `str`. * * @param {String} str * @return {Progress} for chaining * @api public */ Progress.prototype.text = function(str){ this._text = str; return this; }; /** * Set font size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.fontSize = function(n){ this._fontSize = n; return this; }; /** * Set font `family`. * * @param {String} family * @return {Progress} for chaining */ Progress.prototype.font = function(family){ this._font = family; return this; }; /** * Update percentage to `n`. * * @param {Number} n * @return {Progress} for chaining */ Progress.prototype.update = function(n){ this.percent = n; return this; }; /** * Draw on `ctx`. * * @param {CanvasRenderingContext2d} ctx * @return {Progress} for chaining */ Progress.prototype.draw = function(ctx){ try { var percent = Math.min(this.percent, 100) , size = this._size , half = size / 2 , x = half , y = half , rad = half - 1 , fontSize = this._fontSize; ctx.font = fontSize + 'px ' + this._font; var angle = Math.PI * 2 * (percent / 100); ctx.clearRect(0, 0, size, size); // outer circle ctx.strokeStyle = '#9f9f9f'; ctx.beginPath(); ctx.arc(x, y, rad, 0, angle, false); ctx.stroke(); // inner circle ctx.strokeStyle = '#eee'; ctx.beginPath(); ctx.arc(x, y, rad - 1, 0, angle, true); ctx.stroke(); // text var text = this._text || (percent | 0) + '%' , w = ctx.measureText(text).width; ctx.fillText( text , x - w / 2 + 1 , y + fontSize / 2 - 1); } catch (ex) {} //don't fail if we can't render progress return this; }; }); // module: browser/progress.js require.register("browser/tty.js", function(module, exports, require){ exports.isatty = function(){ return true; }; exports.getWindowSize = function(){ if ('innerHeight' in global) { return [global.innerHeight, global.innerWidth]; } else { // In a Web Worker, the DOM Window is not available. return [640, 480]; } }; }); // module: browser/tty.js require.register("context.js", function(module, exports, require){ /** * Expose `Context`. */ module.exports = Context; /** * Initialize a new `Context`. * * @api private */ function Context(){} /** * Set or get the context `Runnable` to `runnable`. * * @param {Runnable} runnable * @return {Context} * @api private */ Context.prototype.runnable = function(runnable){ if (0 == arguments.length) return this._runnable; this.test = this._runnable = runnable; return this; }; /** * Set test timeout `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.timeout = function(ms){ if (arguments.length === 0) return this.runnable().timeout(); this.runnable().timeout(ms); return this; }; /** * Set test timeout `enabled`. * * @param {Boolean} enabled * @return {Context} self * @api private */ Context.prototype.enableTimeouts = function (enabled) { this.runnable().enableTimeouts(enabled); return this; }; /** * Set test slowness threshold `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.slow = function(ms){ this.runnable().slow(ms); return this; }; /** * Inspect the context void of `._runnable`. * * @return {String} * @api private */ Context.prototype.inspect = function(){ return JSON.stringify(this, function(key, val){ if ('_runnable' == key) return; if ('test' == key) return; return val; }, 2); }; }); // module: context.js require.register("hook.js", function(module, exports, require){ /** * Module dependencies. */ var Runnable = require('./runnable'); /** * Expose `Hook`. */ module.exports = Hook; /** * Initialize a new `Hook` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Hook(title, fn) { Runnable.call(this, title, fn); this.type = 'hook'; } /** * Inherit from `Runnable.prototype`. */ function F(){}; F.prototype = Runnable.prototype; Hook.prototype = new F; Hook.prototype.constructor = Hook; /** * Get or set the test `err`. * * @param {Error} err * @return {Error} * @api public */ Hook.prototype.error = function(err){ if (0 == arguments.length) { var err = this._error; this._error = null; return err; } this._error = err; }; }); // module: hook.js require.register("interfaces/bdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test') , utils = require('../utils') , escapeRe = require('browser/escape-string-regexp'); /** * BDD-style interface: * * describe('Array', function(){ * describe('#indexOf()', function(){ * it('should return -1 when not present', function(){ * * }); * * it('should return the index when present', function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ context.before = function(name, fn){ suites[0].beforeAll(name, fn); }; /** * Execute after running tests. */ context.after = function(name, fn){ suites[0].afterAll(name, fn); }; /** * Execute before each test case. */ context.beforeEach = function(name, fn){ suites[0].beforeEach(name, fn); }; /** * Execute after each test case. */ context.afterEach = function(name, fn){ suites[0].afterEach(name, fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.describe = context.context = function(title, fn){ var suite = Suite.create(suites[0], title); suite.file = file; suites.unshift(suite); fn.call(suite); suites.shift(); return suite; }; /** * Pending describe. */ context.xdescribe = context.xcontext = context.describe.skip = function(title, fn){ var suite = Suite.create(suites[0], title); suite.pending = true; suites.unshift(suite); fn.call(suite); suites.shift(); }; /** * Exclusive suite. */ context.describe.only = function(title, fn){ var suite = context.describe(title, fn); mocha.grep(suite.fullTitle()); return suite; }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.it = context.specify = function(title, fn){ var suite = suites[0]; if (suite.pending) fn = null; var test = new Test(title, fn); test.file = file; suite.addTest(test); return test; }; /** * Exclusive test-case. */ context.it.only = function(title, fn){ var test = context.it(title, fn); var reString = '^' + escapeRe(test.fullTitle()) + '$'; mocha.grep(new RegExp(reString)); return test; }; /** * Pending test case. */ context.xit = context.xspecify = context.it.skip = function(title){ context.it(title); }; }); }; }); // module: interfaces/bdd.js require.register("interfaces/exports.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * TDD-style interface: * * exports.Array = { * '#indexOf()': { * 'should return -1 when the value is not present': function(){ * * }, * * 'should return the correct index when the value is present': function(){ * * } * } * }; * */ module.exports = function(suite){ var suites = [suite]; suite.on('require', visit); function visit(obj, file) { var suite; for (var key in obj) { if ('function' == typeof obj[key]) { var fn = obj[key]; switch (key) { case 'before': suites[0].beforeAll(fn); break; case 'after': suites[0].afterAll(fn); break; case 'beforeEach': suites[0].beforeEach(fn); break; case 'afterEach': suites[0].afterEach(fn); break; default: var test = new Test(key, fn); test.file = file; suites[0].addTest(test); } } else { suite = Suite.create(suites[0], key); suites.unshift(suite); visit(obj[key]); suites.shift(); } } } }; }); // module: interfaces/exports.js require.register("interfaces/index.js", function(module, exports, require){ exports.bdd = require('./bdd'); exports.tdd = require('./tdd'); exports.qunit = require('./qunit'); exports.exports = require('./exports'); }); // module: interfaces/index.js require.register("interfaces/qunit.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test') , escapeRe = require('browser/escape-string-regexp') , utils = require('../utils'); /** * QUnit-style interface: * * suite('Array'); * * test('#length', function(){ * var arr = [1,2,3]; * ok(arr.length == 3); * }); * * test('#indexOf()', function(){ * var arr = [1,2,3]; * ok(arr.indexOf(1) == 0); * ok(arr.indexOf(2) == 1); * ok(arr.indexOf(3) == 2); * }); * * suite('String'); * * test('#length', function(){ * ok('foo'.length == 3); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ context.before = function(name, fn){ suites[0].beforeAll(name, fn); }; /** * Execute after running tests. */ context.after = function(name, fn){ suites[0].afterAll(name, fn); }; /** * Execute before each test case. */ context.beforeEach = function(name, fn){ suites[0].beforeEach(name, fn); }; /** * Execute after each test case. */ context.afterEach = function(name, fn){ suites[0].afterEach(name, fn); }; /** * Describe a "suite" with the given `title`. */ context.suite = function(title){ if (suites.length > 1) suites.shift(); var suite = Suite.create(suites[0], title); suite.file = file; suites.unshift(suite); return suite; }; /** * Exclusive test-case. */ context.suite.only = function(title, fn){ var suite = context.suite(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ var test = new Test(title, fn); test.file = file; suites[0].addTest(test); return test; }; /** * Exclusive test-case. */ context.test.only = function(title, fn){ var test = context.test(title, fn); var reString = '^' + escapeRe(test.fullTitle()) + '$'; mocha.grep(new RegExp(reString)); }; /** * Pending test case. */ context.test.skip = function(title){ context.test(title); }; }); }; }); // module: interfaces/qunit.js require.register("interfaces/tdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test') , escapeRe = require('browser/escape-string-regexp') , utils = require('../utils'); /** * TDD-style interface: * * suite('Array', function(){ * suite('#indexOf()', function(){ * suiteSetup(function(){ * * }); * * test('should return -1 when not present', function(){ * * }); * * test('should return the index when present', function(){ * * }); * * suiteTeardown(function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before each test case. */ context.setup = function(name, fn){ suites[0].beforeEach(name, fn); }; /** * Execute after each test case. */ context.teardown = function(name, fn){ suites[0].afterEach(name, fn); }; /** * Execute before the suite. */ context.suiteSetup = function(name, fn){ suites[0].beforeAll(name, fn); }; /** * Execute after the suite. */ context.suiteTeardown = function(name, fn){ suites[0].afterAll(name, fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.suite = function(title, fn){ var suite = Suite.create(suites[0], title); suite.file = file; suites.unshift(suite); fn.call(suite); suites.shift(); return suite; }; /** * Pending suite. */ context.suite.skip = function(title, fn) { var suite = Suite.create(suites[0], title); suite.pending = true; suites.unshift(suite); fn.call(suite); suites.shift(); }; /** * Exclusive test-case. */ context.suite.only = function(title, fn){ var suite = context.suite(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ var suite = suites[0]; if (suite.pending) fn = null; var test = new Test(title, fn); test.file = file; suite.addTest(test); return test; }; /** * Exclusive test-case. */ context.test.only = function(title, fn){ var test = context.test(title, fn); var reString = '^' + escapeRe(test.fullTitle()) + '$'; mocha.grep(new RegExp(reString)); }; /** * Pending test case. */ context.test.skip = function(title){ context.test(title); }; }); }; }); // module: interfaces/tdd.js require.register("mocha.js", function(module, exports, require){ /*! * mocha * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var path = require('browser/path') , escapeRe = require('browser/escape-string-regexp') , utils = require('./utils'); /** * Expose `Mocha`. */ exports = module.exports = Mocha; /** * To require local UIs and reporters when running in node. */ if (typeof process !== 'undefined' && typeof process.cwd === 'function') { var join = path.join , cwd = process.cwd(); module.paths.push(cwd, join(cwd, 'node_modules')); } /** * Expose internals. */ exports.utils = utils; exports.interfaces = require('./interfaces'); exports.reporters = require('./reporters'); exports.Runnable = require('./runnable'); exports.Context = require('./context'); exports.Runner = require('./runner'); exports.Suite = require('./suite'); exports.Hook = require('./hook'); exports.Test = require('./test'); /** * Return image `name` path. * * @param {String} name * @return {String} * @api private */ function image(name) { return __dirname + '/../images/' + name + '.png'; } /** * Setup mocha with `options`. * * Options: * * - `ui` name "bdd", "tdd", "exports" etc * - `reporter` reporter instance, defaults to `mocha.reporters.spec` * - `globals` array of accepted globals * - `timeout` timeout in milliseconds * - `bail` bail on the first test failure * - `slow` milliseconds to wait before considering a test slow * - `ignoreLeaks` ignore global leaks * - `grep` string or regexp to filter tests with * * @param {Object} options * @api public */ function Mocha(options) { options = options || {}; this.files = []; this.options = options; this.grep(options.grep); this.suite = new exports.Suite('', new exports.Context); this.ui(options.ui); this.bail(options.bail); this.reporter(options.reporter); if (null != options.timeout) this.timeout(options.timeout); this.useColors(options.useColors) if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); if (options.slow) this.slow(options.slow); this.suite.on('pre-require', function (context) { exports.afterEach = context.afterEach || context.teardown; exports.after = context.after || context.suiteTeardown; exports.beforeEach = context.beforeEach || context.setup; exports.before = context.before || context.suiteSetup; exports.describe = context.describe || context.suite; exports.it = context.it || context.test; exports.setup = context.setup || context.beforeEach; exports.suiteSetup = context.suiteSetup || context.before; exports.suiteTeardown = context.suiteTeardown || context.after; exports.suite = context.suite || context.describe; exports.teardown = context.teardown || context.afterEach; exports.test = context.test || context.it; }); } /** * Enable or disable bailing on the first failure. * * @param {Boolean} [bail] * @api public */ Mocha.prototype.bail = function(bail){ if (0 == arguments.length) bail = true; this.suite.bail(bail); return this; }; /** * Add test `file`. * * @param {String} file * @api public */ Mocha.prototype.addFile = function(file){ this.files.push(file); return this; }; /** * Set reporter to `reporter`, defaults to "spec". * * @param {String|Function} reporter name or constructor * @api public */ Mocha.prototype.reporter = function(reporter){ if ('function' == typeof reporter) { this._reporter = reporter; } else { reporter = reporter || 'spec'; var _reporter; try { _reporter = require('./reporters/' + reporter); } catch (err) {}; if (!_reporter) try { _reporter = require(reporter); } catch (err) {}; if (!_reporter && reporter === 'teamcity') console.warn('The Teamcity reporter was moved to a package named ' + 'mocha-teamcity-reporter ' + '(https://npmjs.org/package/mocha-teamcity-reporter).'); if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); this._reporter = _reporter; } return this; }; /** * Set test UI `name`, defaults to "bdd". * * @param {String} bdd * @api public */ Mocha.prototype.ui = function(name){ name = name || 'bdd'; this._ui = exports.interfaces[name]; if (!this._ui) try { this._ui = require(name); } catch (err) {}; if (!this._ui) throw new Error('invalid interface "' + name + '"'); this._ui = this._ui(this.suite); return this; }; /** * Load registered files. * * @api private */ Mocha.prototype.loadFiles = function(fn){ var self = this; var suite = this.suite; var pending = this.files.length; this.files.forEach(function(file){ file = path.resolve(file); suite.emit('pre-require', global, file, self); suite.emit('require', require(file), file, self); suite.emit('post-require', global, file, self); --pending || (fn && fn()); }); }; /** * Enable growl support. * * @api private */ Mocha.prototype._growl = function(runner, reporter) { var notify = require('growl'); runner.on('end', function(){ var stats = reporter.stats; if (stats.failures) { var msg = stats.failures + ' of ' + runner.total + ' tests failed'; notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); } else { notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { name: 'mocha' , title: 'Passed' , image: image('ok') }); } }); }; /** * Add regexp to grep, if `re` is a string it is escaped. * * @param {RegExp|String} re * @return {Mocha} * @api public */ Mocha.prototype.grep = function(re){ this.options.grep = 'string' == typeof re ? new RegExp(escapeRe(re)) : re; return this; }; /** * Invert `.grep()` matches. * * @return {Mocha} * @api public */ Mocha.prototype.invert = function(){ this.options.invert = true; return this; }; /** * Ignore global leaks. * * @param {Boolean} ignore * @return {Mocha} * @api public */ Mocha.prototype.ignoreLeaks = function(ignore){ this.options.ignoreLeaks = !!ignore; return this; }; /** * Enable global leak checking. * * @return {Mocha} * @api public */ Mocha.prototype.checkLeaks = function(){ this.options.ignoreLeaks = false; return this; }; /** * Enable growl support. * * @return {Mocha} * @api public */ Mocha.prototype.growl = function(){ this.options.growl = true; return this; }; /** * Ignore `globals` array or string. * * @param {Array|String} globals * @return {Mocha} * @api public */ Mocha.prototype.globals = function(globals){ this.options.globals = (this.options.globals || []).concat(globals); return this; }; /** * Emit color output. * * @param {Boolean} colors * @return {Mocha} * @api public */ Mocha.prototype.useColors = function(colors){ this.options.useColors = arguments.length && colors != undefined ? colors : true; return this; }; /** * Use inline diffs rather than +/-. * * @param {Boolean} inlineDiffs * @return {Mocha} * @api public */ Mocha.prototype.useInlineDiffs = function(inlineDiffs) { this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined ? inlineDiffs : false; return this; }; /** * Set the timeout in milliseconds. * * @param {Number} timeout * @return {Mocha} * @api public */ Mocha.prototype.timeout = function(timeout){ this.suite.timeout(timeout); return this; }; /** * Set slowness threshold in milliseconds. * * @param {Number} slow * @return {Mocha} * @api public */ Mocha.prototype.slow = function(slow){ this.suite.slow(slow); return this; }; /** * Enable timeouts. * * @param {Boolean} enabled * @return {Mocha} * @api public */ Mocha.prototype.enableTimeouts = function(enabled) { this.suite.enableTimeouts(arguments.length && enabled !== undefined ? enabled : true); return this }; /** * Makes all tests async (accepting a callback) * * @return {Mocha} * @api public */ Mocha.prototype.asyncOnly = function(){ this.options.asyncOnly = true; return this; }; /** * Disable syntax highlighting (in browser). * @returns {Mocha} * @api public */ Mocha.prototype.noHighlighting = function() { this.options.noHighlighting = true; return this; }; /** * Run tests and invoke `fn()` when complete. * * @param {Function} fn * @return {Runner} * @api public */ Mocha.prototype.run = function(fn){ if (this.files.length) this.loadFiles(); var suite = this.suite; var options = this.options; options.files = this.files; var runner = new exports.Runner(suite); var reporter = new this._reporter(runner, options); runner.ignoreLeaks = false !== options.ignoreLeaks; runner.asyncOnly = options.asyncOnly; if (options.grep) runner.grep(options.grep, options.invert); if (options.globals) runner.globals(options.globals); if (options.growl) this._growl(runner, reporter); exports.reporters.Base.useColors = options.useColors; exports.reporters.Base.inlineDiffs = options.useInlineDiffs; return runner.run(fn); }; }); // module: mocha.js require.register("ms.js", function(module, exports, require){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @return {String|Number} * @api public */ module.exports = function(val, options){ options = options || {}; if ('string' == typeof val) return parse(val); return options['long'] ? longFormat(val) : shortFormat(val); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'h': return n * h; case 'minutes': case 'minute': case 'm': return n * m; case 'seconds': case 'second': case 's': return n * s; case 'ms': return n; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function shortFormat(ms) { if (ms >= d) return Math.round(ms / d) + 'd'; if (ms >= h) return Math.round(ms / h) + 'h'; if (ms >= m) return Math.round(ms / m) + 'm'; if (ms >= s) return Math.round(ms / s) + 's'; return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function longFormat(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) return; if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; return Math.ceil(ms / n) + ' ' + name + 's'; } }); // module: ms.js require.register("reporters/base.js", function(module, exports, require){ /** * Module dependencies. */ var tty = require('browser/tty') , diff = require('browser/diff') , ms = require('../ms') , utils = require('../utils'); /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Check if both stdio streams are associated with a tty. */ var isatty = tty.isatty(1) && tty.isatty(2); /** * Expose `Base`. */ exports = module.exports = Base; /** * Enable coloring by default. */ exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined); /** * Inline diffs instead of +/- */ exports.inlineDiffs = false; /** * Default color map. */ exports.colors = { 'pass': 90 , 'fail': 31 , 'bright pass': 92 , 'bright fail': 91 , 'bright yellow': 93 , 'pending': 36 , 'suite': 0 , 'error title': 0 , 'error message': 31 , 'error stack': 90 , 'checkmark': 32 , 'fast': 90 , 'medium': 33 , 'slow': 31 , 'green': 32 , 'light': 90 , 'diff gutter': 90 , 'diff added': 42 , 'diff removed': 41 }; /** * Default symbol map. */ exports.symbols = { ok: '✓', err: '✖', dot: '․' }; // With node.js on Windows: use symbols available in terminal default fonts if ('win32' == process.platform) { exports.symbols.ok = '\u221A'; exports.symbols.err = '\u00D7'; exports.symbols.dot = '.'; } /** * Color `str` with the given `type`, * allowing colors to be disabled, * as well as user-defined color * schemes. * * @param {String} type * @param {String} str * @return {String} * @api private */ var color = exports.color = function(type, str) { if (!exports.useColors) return str; return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; }; /** * Expose term window size, with some * defaults for when stderr is not a tty. */ exports.window = { width: isatty ? process.stdout.getWindowSize ? process.stdout.getWindowSize(1)[0] : tty.getWindowSize()[1] : 75 }; /** * Expose some basic cursor interactions * that are common among reporters. */ exports.cursor = { hide: function(){ isatty && process.stdout.write('\u001b[?25l'); }, show: function(){ isatty && process.stdout.write('\u001b[?25h'); }, deleteLine: function(){ isatty && process.stdout.write('\u001b[2K'); }, beginningOfLine: function(){ isatty && process.stdout.write('\u001b[0G'); }, CR: function(){ if (isatty) { exports.cursor.deleteLine(); exports.cursor.beginningOfLine(); } else { process.stdout.write('\r'); } } }; /** * Outut the given `failures` as a list. * * @param {Array} failures * @api public */ exports.list = function(failures){ console.error(); failures.forEach(function(test, i){ // format var fmt = color('error title', ' %s) %s:\n') + color('error message', ' %s') + color('error stack', '\n%s\n'); // msg var err = test.err , message = err.message || '' , stack = err.stack || message , index = stack.indexOf(message) + message.length , msg = stack.slice(0, index) , actual = err.actual , expected = err.expected , escape = true; // uncaught if (err.uncaught) { msg = 'Uncaught ' + msg; } // explicitly show diff if (err.showDiff && sameType(actual, expected)) { escape = false; err.actual = actual = utils.stringify(actual); err.expected = expected = utils.stringify(expected); } // actual / expected diff if (err.showDiff && 'string' == typeof actual && 'string' == typeof expected) { fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); var match = message.match(/^([^:]+): expected/); msg = '\n ' + color('error message', match ? match[1] : msg); if (exports.inlineDiffs) { msg += inlineDiff(err, escape); } else { msg += unifiedDiff(err, escape); } } // indent stack trace without msg stack = stack.slice(index ? index + 1 : index) .replace(/^/gm, ' '); console.error(fmt, (i + 1), test.fullTitle(), msg, stack); }); }; /** * Initialize a new `Base` reporter. * * All other reporters generally * inherit from this reporter, providing * stats such as test duration, number * of tests passed / failed etc. * * @param {Runner} runner * @api public */ function Base(runner) { var self = this , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } , failures = this.failures = []; if (!runner) return; this.runner = runner; runner.stats = stats; runner.on('start', function(){ stats.start = new Date; }); runner.on('suite', function(suite){ stats.suites = stats.suites || 0; suite.root || stats.suites++; }); runner.on('test end', function(test){ stats.tests = stats.tests || 0; stats.tests++; }); runner.on('pass', function(test){ stats.passes = stats.passes || 0; var medium = test.slow() / 2; test.speed = test.duration > test.slow() ? 'slow' : test.duration > medium ? 'medium' : 'fast'; stats.passes++; }); runner.on('fail', function(test, err){ stats.failures = stats.failures || 0; stats.failures++; test.err = err; failures.push(test); }); runner.on('end', function(){ stats.end = new Date; stats.duration = new Date - stats.start; }); runner.on('pending', function(){ stats.pending++; }); } /** * Output common epilogue used by many of * the bundled reporters. * * @api public */ Base.prototype.epilogue = function(){ var stats = this.stats; var tests; var fmt; console.log(); // passes fmt = color('bright pass', ' ') + color('green', ' %d passing') + color('light', ' (%s)'); console.log(fmt, stats.passes || 0, ms(stats.duration)); // pending if (stats.pending) { fmt = color('pending', ' ') + color('pending', ' %d pending'); console.log(fmt, stats.pending); } // failures if (stats.failures) { fmt = color('fail', ' %d failing'); console.error(fmt, stats.failures); Base.list(this.failures); console.error(); } console.log(); }; /** * Pad the given `str` to `len`. * * @param {String} str * @param {String} len * @return {String} * @api private */ function pad(str, len) { str = String(str); return Array(len - str.length + 1).join(' ') + str; } /** * Returns an inline diff between 2 strings with coloured ANSI output * * @param {Error} Error with actual/expected * @return {String} Diff * @api private */ function inlineDiff(err, escape) { var msg = errorDiff(err, 'WordsWithSpace', escape); // linenos var lines = msg.split('\n'); if (lines.length > 4) { var width = String(lines.length).length; msg = lines.map(function(str, i){ return pad(++i, width) + ' |' + ' ' + str; }).join('\n'); } // legend msg = '\n' + color('diff removed', 'actual') + ' ' + color('diff added', 'expected') + '\n\n' + msg + '\n'; // indent msg = msg.replace(/^/gm, ' '); return msg; } /** * Returns a unified diff between 2 strings * * @param {Error} Error with actual/expected * @return {String} Diff * @api private */ function unifiedDiff(err, escape) { var indent = ' '; function cleanUp(line) { if (escape) { line = escapeInvisibles(line); } if (line[0] === '+') return indent + colorLines('diff added', line); if (line[0] === '-') return indent + colorLines('diff removed', line); if (line.match(/\@\@/)) return null; if (line.match(/\\ No newline/)) return null; else return indent + line; } function notBlank(line) { return line != null; } msg = diff.createPatch('string', err.actual, err.expected); var lines = msg.split('\n').splice(4); return '\n ' + colorLines('diff added', '+ expected') + ' ' + colorLines('diff removed', '- actual') + '\n\n' + lines.map(cleanUp).filter(notBlank).join('\n'); } /** * Return a character diff for `err`. * * @param {Error} err * @return {String} * @api private */ function errorDiff(err, type, escape) { var actual = escape ? escapeInvisibles(err.actual) : err.actual; var expected = escape ? escapeInvisibles(err.expected) : err.expected; return diff['diff' + type](actual, expected).map(function(str){ if (str.added) return colorLines('diff added', str.value); if (str.removed) return colorLines('diff removed', str.value); return str.value; }).join(''); } /** * Returns a string with all invisible characters in plain text * * @param {String} line * @return {String} * @api private */ function escapeInvisibles(line) { return line.replace(/\t/g, '<tab>') .replace(/\r/g, '<CR>') .replace(/\n/g, '<LF>\n'); } /** * Color lines for `str`, using the color `name`. * * @param {String} name * @param {String} str * @return {String} * @api private */ function colorLines(name, str) { return str.split('\n').map(function(str){ return color(name, str); }).join('\n'); } /** * Check that a / b have the same type. * * @param {Object} a * @param {Object} b * @return {Boolean} * @api private */ function sameType(a, b) { a = Object.prototype.toString.call(a); b = Object.prototype.toString.call(b); return a == b; } }); // module: reporters/base.js require.register("reporters/doc.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = Doc; /** * Initialize a new `Doc` reporter. * * @param {Runner} runner * @api public */ function Doc(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , indents = 2; function indent() { return Array(indents).join(' '); } runner.on('suite', function(suite){ if (suite.root) return; ++indents; console.log('%s<section class="suite">', indent()); ++indents; console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title)); console.log('%s<dl>', indent()); }); runner.on('suite end', function(suite){ if (suite.root) return; console.log('%s</dl>', indent()); --indents; console.log('%s</section>', indent()); --indents; }); runner.on('pass', function(test){ console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.fn.toString())); console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code); }); runner.on('fail', function(test, err){ console.log('%s <dt class="error">%s</dt>', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.fn.toString())); console.log('%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code); console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err)); }); } }); // module: reporters/doc.js require.register("reporters/dot.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `Dot`. */ exports = module.exports = Dot; /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ function Dot(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , n = -1; runner.on('start', function(){ process.stdout.write('\n '); }); runner.on('pending', function(test){ if (++n % width == 0) process.stdout.write('\n '); process.stdout.write(color('pending', Base.symbols.dot)); }); runner.on('pass', function(test){ if (++n % width == 0) process.stdout.write('\n '); if ('slow' == test.speed) { process.stdout.write(color('bright yellow', Base.symbols.dot)); } else { process.stdout.write(color(test.speed, Base.symbols.dot)); } }); runner.on('fail', function(test, err){ if (++n % width == 0) process.stdout.write('\n '); process.stdout.write(color('fail', Base.symbols.dot)); }); runner.on('end', function(){ console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Dot.prototype = new F; Dot.prototype.constructor = Dot; }); // module: reporters/dot.js require.register("reporters/html-cov.js", function(module, exports, require){ /** * Module dependencies. */ var JSONCov = require('./json-cov') , fs = require('browser/fs'); /** * Expose `HTMLCov`. */ exports = module.exports = HTMLCov; /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner * @api public */ function HTMLCov(runner) { var jade = require('jade') , file = __dirname + '/templates/coverage.jade' , str = fs.readFileSync(file, 'utf8') , fn = jade.compile(str, { filename: file }) , self = this; JSONCov.call(this, runner, false); runner.on('end', function(){ process.stdout.write(fn({ cov: self.cov , coverageClass: coverageClass })); }); } /** * Return coverage class for `n`. * * @return {String} * @api private */ function coverageClass(n) { if (n >= 75) return 'high'; if (n >= 50) return 'medium'; if (n >= 25) return 'low'; return 'terrible'; } }); // module: reporters/html-cov.js require.register("reporters/html.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils') , Progress = require('../browser/progress') , escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `HTML`. */ exports = module.exports = HTML; /** * Stats template. */ var statsTemplate = '<ul id="mocha-stats">' + '<li class="progress"><canvas width="40" height="40"></canvas></li>' + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>' + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>' + '<li class="duration">duration: <em>0</em>s</li>' + '</ul>'; /** * Initialize a new `HTML` reporter. * * @param {Runner} runner * @api public */ function HTML(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , stat = fragment(statsTemplate) , items = stat.getElementsByTagName('li') , passes = items[1].getElementsByTagName('em')[0] , passesLink = items[1].getElementsByTagName('a')[0] , failures = items[2].getElementsByTagName('em')[0] , failuresLink = items[2].getElementsByTagName('a')[0] , duration = items[3].getElementsByTagName('em')[0] , canvas = stat.getElementsByTagName('canvas')[0] , report = fragment('<ul id="mocha-report"></ul>') , stack = [report] , progress , ctx , root = document.getElementById('mocha'); if (canvas.getContext) { var ratio = window.devicePixelRatio || 1; canvas.style.width = canvas.width; canvas.style.height = canvas.height; canvas.width *= ratio; canvas.height *= ratio; ctx = canvas.getContext('2d'); ctx.scale(ratio, ratio); progress = new Progress; } if (!root) return error('#mocha div missing, add it to your document'); // pass toggle on(passesLink, 'click', function(){ unhide(); var name = /pass/.test(report.className) ? '' : ' pass'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) hideSuitesWithout('test pass'); }); // failure toggle on(failuresLink, 'click', function(){ unhide(); var name = /fail/.test(report.className) ? '' : ' fail'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) hideSuitesWithout('test fail'); }); root.appendChild(stat); root.appendChild(report); if (progress) progress.size(40); runner.on('suite', function(suite){ if (suite.root) return; // suite var url = self.suiteURL(suite); var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title)); // container stack[0].appendChild(el); stack.unshift(document.createElement('ul')); el.appendChild(stack[0]); }); runner.on('suite end', function(suite){ if (suite.root) return; stack.shift(); }); runner.on('fail', function(test, err){ if ('hook' == test.type) runner.emit('test end', test); }); runner.on('test end', function(test){ // TODO: add to stats var percent = stats.tests / this.total * 100 | 0; if (progress) progress.update(percent).draw(ctx); // update stats var ms = new Date - stats.start; text(passes, stats.passes); text(failures, stats.failures); text(duration, (ms / 1000).toFixed(2)); // test if ('passed' == test.state) { var url = self.testURL(test); var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%s" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url); } else if (test.pending) { var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title); } else { var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle())); var str = test.err.stack || test.err.toString(); // FF / Opera do not add the message if (!~str.indexOf(test.err.message)) { str = test.err.message + '\n' + str; } // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we // check for the result of the stringifying. if ('[object Error]' == str) str = test.err.message; // Safari doesn't give you a stack. Let's at least provide a source line. if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; } el.appendChild(fragment('<pre class="error">%e</pre>', str)); } // toggle code // TODO: defer if (!test.pending) { var h2 = el.getElementsByTagName('h2')[0]; on(h2, 'click', function(){ pre.style.display = 'none' == pre.style.display ? 'block' : 'none'; }); var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString())); el.appendChild(pre); pre.style.display = 'none'; } // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. if (stack[0]) stack[0].appendChild(el); }); } /** * Provide suite URL * * @param {Object} [suite] */ HTML.prototype.suiteURL = function(suite){ return '?grep=' + encodeURIComponent(suite.fullTitle()); }; /** * Provide test URL * * @param {Object} [test] */ HTML.prototype.testURL = function(test){ return '?grep=' + encodeURIComponent(test.fullTitle()); }; /** * Display error `msg`. */ function error(msg) { document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg)); } /** * Return a DOM fragment from `html`. */ function fragment(html) { var args = arguments , div = document.createElement('div') , i = 1; div.innerHTML = html.replace(/%([se])/g, function(_, type){ switch (type) { case 's': return String(args[i++]); case 'e': return escape(args[i++]); } }); return div.firstChild; } /** * Check for suites that do not have elements * with `classname`, and hide them. */ function hideSuitesWithout(classname) { var suites = document.getElementsByClassName('suite'); for (var i = 0; i < suites.length; i++) { var els = suites[i].getElementsByClassName(classname); if (0 == els.length) suites[i].className += ' hidden'; } } /** * Unhide .hidden suites. */ function unhide() { var els = document.getElementsByClassName('suite hidden'); for (var i = 0; i < els.length; ++i) { els[i].className = els[i].className.replace('suite hidden', 'suite'); } } /** * Set `el` text to `str`. */ function text(el, str) { if (el.textContent) { el.textContent = str; } else { el.innerText = str; } } /** * Listen on `event` with callback `fn`. */ function on(el, event, fn) { if (el.addEventListener) { el.addEventListener(event, fn, false); } else { el.attachEvent('on' + event, fn); } } }); // module: reporters/html.js require.register("reporters/index.js", function(module, exports, require){ exports.Base = require('./base'); exports.Dot = require('./dot'); exports.Doc = require('./doc'); exports.TAP = require('./tap'); exports.JSON = require('./json'); exports.HTML = require('./html'); exports.List = require('./list'); exports.Min = require('./min'); exports.Spec = require('./spec'); exports.Nyan = require('./nyan'); exports.XUnit = require('./xunit'); exports.Markdown = require('./markdown'); exports.Progress = require('./progress'); exports.Landing = require('./landing'); exports.JSONCov = require('./json-cov'); exports.HTMLCov = require('./html-cov'); exports.JSONStream = require('./json-stream'); }); // module: reporters/index.js require.register("reporters/json-cov.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `JSONCov`. */ exports = module.exports = JSONCov; /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner * @param {Boolean} output * @api public */ function JSONCov(runner, output) { var self = this , output = 1 == arguments.length ? true : output; Base.call(this, runner); var tests = [] , failures = [] , passes = []; runner.on('test end', function(test){ tests.push(test); }); runner.on('pass', function(test){ passes.push(test); }); runner.on('fail', function(test){ failures.push(test); }); runner.on('end', function(){ var cov = global._$jscoverage || {}; var result = self.cov = map(cov); result.stats = self.stats; result.tests = tests.map(clean); result.failures = failures.map(clean); result.passes = passes.map(clean); if (!output) return; process.stdout.write(JSON.stringify(result, null, 2 )); }); } /** * Map jscoverage data to a JSON structure * suitable for reporting. * * @param {Object} cov * @return {Object} * @api private */ function map(cov) { var ret = { instrumentation: 'node-jscoverage' , sloc: 0 , hits: 0 , misses: 0 , coverage: 0 , files: [] }; for (var filename in cov) { var data = coverage(filename, cov[filename]); ret.files.push(data); ret.hits += data.hits; ret.misses += data.misses; ret.sloc += data.sloc; } ret.files.sort(function(a, b) { return a.filename.localeCompare(b.filename); }); if (ret.sloc > 0) { ret.coverage = (ret.hits / ret.sloc) * 100; } return ret; } /** * Map jscoverage data for a single source file * to a JSON structure suitable for reporting. * * @param {String} filename name of the source file * @param {Object} data jscoverage coverage data * @return {Object} * @api private */ function coverage(filename, data) { var ret = { filename: filename, coverage: 0, hits: 0, misses: 0, sloc: 0, source: {} }; data.source.forEach(function(line, num){ num++; if (data[num] === 0) { ret.misses++; ret.sloc++; } else if (data[num] !== undefined) { ret.hits++; ret.sloc++; } ret.source[num] = { source: line , coverage: data[num] === undefined ? '' : data[num] }; }); ret.coverage = ret.hits / ret.sloc * 100; return ret; } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json-cov.js require.register("reporters/json-stream.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `List`. */ exports = module.exports = List; /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ function List(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total; runner.on('start', function(){ console.log(JSON.stringify(['start', { total: total }])); }); runner.on('pass', function(test){ console.log(JSON.stringify(['pass', clean(test)])); }); runner.on('fail', function(test, err){ console.log(JSON.stringify(['fail', clean(test)])); }); runner.on('end', function(){ process.stdout.write(JSON.stringify(['end', self.stats])); }); } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json-stream.js require.register("reporters/json.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `JSON`. */ exports = module.exports = JSONReporter; /** * Initialize a new `JSON` reporter. * * @param {Runner} runner * @api public */ function JSONReporter(runner) { var self = this; Base.call(this, runner); var tests = [] , pending = [] , failures = [] , passes = []; runner.on('test end', function(test){ tests.push(test); }); runner.on('pass', function(test){ passes.push(test); }); runner.on('fail', function(test){ failures.push(test); }); runner.on('pending', function(test){ pending.push(test); }); runner.on('end', function(){ var obj = { stats: self.stats, tests: tests.map(clean), pending: pending.map(clean), failures: failures.map(clean), passes: passes.map(clean) }; runner.testResults = obj; process.stdout.write(JSON.stringify(obj, null, 2)); }); } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, err: errorJSON(test.err || {}) } } /** * Transform `error` into a JSON object. * @param {Error} err * @return {Object} */ function errorJSON(err) { var res = {}; Object.getOwnPropertyNames(err).forEach(function(key) { res[key] = err[key]; }, err); return res; } }); // module: reporters/json.js require.register("reporters/landing.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Landing`. */ exports = module.exports = Landing; /** * Airplane color. */ Base.colors.plane = 0; /** * Airplane crash color. */ Base.colors['plane crash'] = 31; /** * Runway color. */ Base.colors.runway = 90; /** * Initialize a new `Landing` reporter. * * @param {Runner} runner * @api public */ function Landing(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , total = runner.total , stream = process.stdout , plane = color('plane', '✈') , crashed = -1 , n = 0; function runway() { var buf = Array(width).join('-'); return ' ' + color('runway', buf); } runner.on('start', function(){ stream.write('\n '); cursor.hide(); }); runner.on('test end', function(test){ // check if the plane crashed var col = -1 == crashed ? width * ++n / total | 0 : crashed; // show the crash if ('failed' == test.state) { plane = color('plane crash', '✈'); crashed = col; } // render landing strip stream.write('\u001b[4F\n\n'); stream.write(runway()); stream.write('\n '); stream.write(color('runway', Array(col).join('⋅'))); stream.write(plane) stream.write(color('runway', Array(width - col).join('⋅') + '\n')); stream.write(runway()); stream.write('\u001b[0m'); }); runner.on('end', function(){ cursor.show(); console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Landing.prototype = new F; Landing.prototype.constructor = Landing; }); // module: reporters/landing.js require.register("reporters/list.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `List`. */ exports = module.exports = List; /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ function List(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 0; runner.on('start', function(){ console.log(); }); runner.on('test', function(test){ process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); runner.on('pending', function(test){ var fmt = color('checkmark', ' -') + color('pending', ' %s'); console.log(fmt, test.fullTitle()); }); runner.on('pass', function(test){ var fmt = color('checkmark', ' '+Base.symbols.dot) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); runner.on('fail', function(test, err){ cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); runner.on('end', self.epilogue.bind(self)); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; List.prototype = new F; List.prototype.constructor = List; }); // module: reporters/list.js require.register("reporters/markdown.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Markdown`. */ exports = module.exports = Markdown; /** * Initialize a new `Markdown` reporter. * * @param {Runner} runner * @api public */ function Markdown(runner) { Base.call(this, runner); var self = this , stats = this.stats , level = 0 , buf = ''; function title(str) { return Array(level).join('#') + ' ' + str; } function indent() { return Array(level).join(' '); } function mapTOC(suite, obj) { var ret = obj; obj = obj[suite.title] = obj[suite.title] || { suite: suite }; suite.suites.forEach(function(suite){ mapTOC(suite, obj); }); return ret; } function stringifyTOC(obj, level) { ++level; var buf = ''; var link; for (var key in obj) { if ('suite' == key) continue; if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; if (key) buf += Array(level).join(' ') + link; buf += stringifyTOC(obj[key], level); } --level; return buf; } function generateTOC(suite) { var obj = mapTOC(suite, {}); return stringifyTOC(obj, 0); } generateTOC(runner.suite); runner.on('suite', function(suite){ ++level; var slug = utils.slug(suite.fullTitle()); buf += '<a name="' + slug + '"></a>' + '\n'; buf += title(suite.title) + '\n'; }); runner.on('suite end', function(suite){ --level; }); runner.on('pass', function(test){ var code = utils.clean(test.fn.toString()); buf += test.title + '.\n'; buf += '\n```js\n'; buf += code + '\n'; buf += '```\n\n'; }); runner.on('end', function(){ process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); }); } }); // module: reporters/markdown.js require.register("reporters/min.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `Min`. */ exports = module.exports = Min; /** * Initialize a new `Min` minimal test reporter (best used with --watch). * * @param {Runner} runner * @api public */ function Min(runner) { Base.call(this, runner); runner.on('start', function(){ // clear screen process.stdout.write('\u001b[2J'); // set cursor position process.stdout.write('\u001b[1;3H'); }); runner.on('end', this.epilogue.bind(this)); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Min.prototype = new F; Min.prototype.constructor = Min; }); // module: reporters/min.js require.register("reporters/nyan.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `Dot`. */ exports = module.exports = NyanCat; /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ function NyanCat(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , rainbowColors = this.rainbowColors = self.generateColors() , colorIndex = this.colorIndex = 0 , numerOfLines = this.numberOfLines = 4 , trajectories = this.trajectories = [[], [], [], []] , nyanCatWidth = this.nyanCatWidth = 11 , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) , scoreboardWidth = this.scoreboardWidth = 5 , tick = this.tick = 0 , n = 0; runner.on('start', function(){ Base.cursor.hide(); self.draw(); }); runner.on('pending', function(test){ self.draw(); }); runner.on('pass', function(test){ self.draw(); }); runner.on('fail', function(test, err){ self.draw(); }); runner.on('end', function(){ Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) write('\n'); self.epilogue(); }); } /** * Draw the nyan cat * * @api private */ NyanCat.prototype.draw = function(){ this.appendRainbow(); this.drawScoreboard(); this.drawRainbow(); this.drawNyanCat(); this.tick = !this.tick; }; /** * Draw the "scoreboard" showing the number * of passes, failures and pending tests. * * @api private */ NyanCat.prototype.drawScoreboard = function(){ var stats = this.stats; var colors = Base.colors; function draw(color, n) { write(' '); write('\u001b[' + color + 'm' + n + '\u001b[0m'); write('\n'); } draw(colors.green, stats.passes); draw(colors.fail, stats.failures); draw(colors.pending, stats.pending); write('\n'); this.cursorUp(this.numberOfLines); }; /** * Append the rainbow. * * @api private */ NyanCat.prototype.appendRainbow = function(){ var segment = this.tick ? '_' : '-'; var rainbowified = this.rainbowify(segment); for (var index = 0; index < this.numberOfLines; index++) { var trajectory = this.trajectories[index]; if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); trajectory.push(rainbowified); } }; /** * Draw the rainbow. * * @api private */ NyanCat.prototype.drawRainbow = function(){ var self = this; this.trajectories.forEach(function(line, index) { write('\u001b[' + self.scoreboardWidth + 'C'); write(line.join('')); write('\n'); }); this.cursorUp(this.numberOfLines); }; /** * Draw the nyan cat * * @api private */ NyanCat.prototype.drawNyanCat = function() { var self = this; var startWidth = this.scoreboardWidth + this.trajectories[0].length; var color = '\u001b[' + startWidth + 'C'; var padding = ''; write(color); write('_,------,'); write('\n'); write(color); padding = self.tick ? ' ' : ' '; write('_|' + padding + '/\\_/\\ '); write('\n'); write(color); padding = self.tick ? '_' : '__'; var tail = self.tick ? '~' : '^'; var face; write(tail + '|' + padding + this.face() + ' '); write('\n'); write(color); padding = self.tick ? ' ' : ' '; write(padding + '"" "" '); write('\n'); this.cursorUp(this.numberOfLines); }; /** * Draw nyan cat face. * * @return {String} * @api private */ NyanCat.prototype.face = function() { var stats = this.stats; if (stats.failures) { return '( x .x)'; } else if (stats.pending) { return '( o .o)'; } else if(stats.passes) { return '( ^ .^)'; } else { return '( - .-)'; } }; /** * Move cursor up `n`. * * @param {Number} n * @api private */ NyanCat.prototype.cursorUp = function(n) { write('\u001b[' + n + 'A'); }; /** * Move cursor down `n`. * * @param {Number} n * @api private */ NyanCat.prototype.cursorDown = function(n) { write('\u001b[' + n + 'B'); }; /** * Generate rainbow colors. * * @return {Array} * @api private */ NyanCat.prototype.generateColors = function(){ var colors = []; for (var i = 0; i < (6 * 7); i++) { var pi3 = Math.floor(Math.PI / 3); var n = (i * (1.0 / 6)); var r = Math.floor(3 * Math.sin(n) + 3); var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); colors.push(36 * r + 6 * g + b + 16); } return colors; }; /** * Apply rainbow to the given `str`. * * @param {String} str * @return {String} * @api private */ NyanCat.prototype.rainbowify = function(str){ var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; this.colorIndex += 1; return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; }; /** * Stdout helper. */ function write(string) { process.stdout.write(string); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; NyanCat.prototype = new F; NyanCat.prototype.constructor = NyanCat; }); // module: reporters/nyan.js require.register("reporters/progress.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Progress`. */ exports = module.exports = Progress; /** * General progress bar color. */ Base.colors.progress = 90; /** * Initialize a new `Progress` bar test reporter. * * @param {Runner} runner * @param {Object} options * @api public */ function Progress(runner, options) { Base.call(this, runner); var self = this , options = options || {} , stats = this.stats , width = Base.window.width * .50 | 0 , total = runner.total , complete = 0 , max = Math.max , lastN = -1; // default chars options.open = options.open || '['; options.complete = options.complete || '▬'; options.incomplete = options.incomplete || Base.symbols.dot; options.close = options.close || ']'; options.verbose = false; // tests started runner.on('start', function(){ console.log(); cursor.hide(); }); // tests complete runner.on('test end', function(){ complete++; var incomplete = total - complete , percent = complete / total , n = width * percent | 0 , i = width - n; if (lastN === n && !options.verbose) { // Don't re-render the line if it hasn't changed return; } lastN = n; cursor.CR(); process.stdout.write('\u001b[J'); process.stdout.write(color('progress', ' ' + options.open)); process.stdout.write(Array(n).join(options.complete)); process.stdout.write(Array(i).join(options.incomplete)); process.stdout.write(color('progress', options.close)); if (options.verbose) { process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); } }); // tests are complete, output some stats // and the failures if any runner.on('end', function(){ cursor.show(); console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Progress.prototype = new F; Progress.prototype.constructor = Progress; }); // module: reporters/progress.js require.register("reporters/spec.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Spec`. */ exports = module.exports = Spec; /** * Initialize a new `Spec` test reporter. * * @param {Runner} runner * @api public */ function Spec(runner) { Base.call(this, runner); var self = this , stats = this.stats , indents = 0 , n = 0; function indent() { return Array(indents).join(' ') } runner.on('start', function(){ console.log(); }); runner.on('suite', function(suite){ ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); runner.on('suite end', function(suite){ --indents; if (1 == indents) console.log(); }); runner.on('pending', function(test){ var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); runner.on('pass', function(test){ if ('fast' == test.speed) { var fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s '); cursor.CR(); console.log(fmt, test.title); } else { var fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s ') + color(test.speed, '(%dms)'); cursor.CR(); console.log(fmt, test.title, test.duration); } }); runner.on('fail', function(test, err){ cursor.CR(); console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); runner.on('end', self.epilogue.bind(self)); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; Spec.prototype = new F; Spec.prototype.constructor = Spec; }); // module: reporters/spec.js require.register("reporters/tap.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `TAP`. */ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 1 , passes = 0 , failures = 0; runner.on('start', function(){ var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pending', function(test){ console.log('ok %d %s # SKIP -', n, title(test)); }); runner.on('pass', function(test){ passes++; console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ failures++; console.log('not ok %d %s', n, title(test)); if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); }); runner.on('end', function(){ console.log('# tests ' + (passes + failures)); console.log('# pass ' + passes); console.log('# fail ' + failures); }); } /** * Return a TAP-safe title of `test` * * @param {Object} test * @return {String} * @api private */ function title(test) { return test.fullTitle().replace(/#/g, ''); } }); // module: reporters/tap.js require.register("reporters/xunit.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils') , escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `XUnit`. */ exports = module.exports = XUnit; /** * Initialize a new `XUnit` reporter. * * @param {Runner} runner * @api public */ function XUnit(runner) { Base.call(this, runner); var stats = this.stats , tests = [] , self = this; runner.on('pending', function(test){ tests.push(test); }); runner.on('pass', function(test){ tests.push(test); }); runner.on('fail', function(test){ tests.push(test); }); runner.on('end', function(){ console.log(tag('testsuite', { name: 'Mocha Tests' , tests: stats.tests , failures: stats.failures , errors: stats.failures , skipped: stats.tests - stats.failures - stats.passes , timestamp: (new Date).toUTCString() , time: (stats.duration / 1000) || 0 }, false)); tests.forEach(test); console.log('</testsuite>'); }); } /** * Inherit from `Base.prototype`. */ function F(){}; F.prototype = Base.prototype; XUnit.prototype = new F; XUnit.prototype.constructor = XUnit; /** * Output tag for the given `test.` */ function test(test) { var attrs = { classname: test.parent.fullTitle() , name: test.title , time: (test.duration / 1000) || 0 }; if ('failed' == test.state) { var err = test.err; console.log(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); } else if (test.pending) { console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); } else { console.log(tag('testcase', attrs, true) ); } } /** * HTML tag helper. */ function tag(name, attrs, close, content) { var end = close ? '/>' : '>' , pairs = [] , tag; for (var key in attrs) { pairs.push(key + '="' + escape(attrs[key]) + '"'); } tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; if (content) tag += content + '</' + name + end; return tag; } /** * Return cdata escaped CDATA `str`. */ function cdata(str) { return '<![CDATA[' + escape(str) + ']]>'; } }); // module: reporters/xunit.js require.register("runnable.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:runnable') , milliseconds = require('./ms'); /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Object#toString(). */ var toString = Object.prototype.toString; /** * Expose `Runnable`. */ module.exports = Runnable; /** * Initialize a new `Runnable` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Runnable(title, fn) { this.title = title; this.fn = fn; this.async = fn && fn.length; this.sync = ! this.async; this._timeout = 2000; this._slow = 75; this._enableTimeouts = true; this.timedOut = false; } /** * Inherit from `EventEmitter.prototype`. */ function F(){}; F.prototype = EventEmitter.prototype; Runnable.prototype = new F; Runnable.prototype.constructor = Runnable; /** * Set & get timeout `ms`. * * @param {Number|String} ms * @return {Runnable|Number} ms or self * @api private */ Runnable.prototype.timeout = function(ms){ if (0 == arguments.length) return this._timeout; if (ms === 0) this._enableTimeouts = false; if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._timeout = ms; if (this.timer) this.resetTimeout(); return this; }; /** * Set & get slow `ms`. * * @param {Number|String} ms * @return {Runnable|Number} ms or self * @api private */ Runnable.prototype.slow = function(ms){ if (0 === arguments.length) return this._slow; if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._slow = ms; return this; }; /** * Set and & get timeout `enabled`. * * @param {Boolean} enabled * @return {Runnable|Boolean} enabled or self * @api private */ Runnable.prototype.enableTimeouts = function(enabled){ if (arguments.length === 0) return this._enableTimeouts; debug('enableTimeouts %s', enabled); this._enableTimeouts = enabled; return this; }; /** * Return the full title generated by recursively * concatenating the parent's full title. * * @return {String} * @api public */ Runnable.prototype.fullTitle = function(){ return this.parent.fullTitle() + ' ' + this.title; }; /** * Clear the timeout. * * @api private */ Runnable.prototype.clearTimeout = function(){ clearTimeout(this.timer); }; /** * Inspect the runnable void of private properties. * * @return {String} * @api private */ Runnable.prototype.inspect = function(){ return JSON.stringify(this, function(key, val){ if ('_' == key[0]) return; if ('parent' == key) return '#<Suite>'; if ('ctx' == key) return '#<Context>'; return val; }, 2); }; /** * Reset the timeout. * * @api private */ Runnable.prototype.resetTimeout = function(){ var self = this; var ms = this.timeout() || 1e9; if (!this._enableTimeouts) return; this.clearTimeout(); this.timer = setTimeout(function(){ if (!self._enableTimeouts) return; self.callback(new Error('timeout of ' + ms + 'ms exceeded')); self.timedOut = true; }, ms); }; /** * Whitelist these globals for this test run * * @api private */ Runnable.prototype.globals = function(arr){ var self = this; this._allowedGlobals = arr; }; /** * Run the test and invoke `fn(err)`. * * @param {Function} fn * @api private */ Runnable.prototype.run = function(fn){ var self = this , start = new Date , ctx = this.ctx , finished , emitted; // Some times the ctx exists but it is not runnable if (ctx && ctx.runnable) ctx.runnable(this); // called multiple times function multiple(err) { if (emitted) return; emitted = true; self.emit('error', err || new Error('done() called multiple times')); } // finished function done(err) { var ms = self.timeout(); if (self.timedOut) return; if (finished) return multiple(err); self.clearTimeout(); self.duration = new Date - start; finished = true; if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded'); fn(err); } // for .resetTimeout() this.callback = done; // explicit async with `done` argument if (this.async) { this.resetTimeout(); try { this.fn.call(ctx, function(err){ if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); if (null != err) { if (Object.prototype.toString.call(err) === '[object Object]') { return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); } else { return done(new Error('done() invoked with non-Error: ' + err)); } } done(); }); } catch (err) { done(err); } return; } if (this.asyncOnly) { return done(new Error('--async-only option in use without declaring `done()`')); } // sync or promise-returning try { if (this.pending) { done(); } else { callFn(this.fn); } } catch (err) { done(err); } function callFn(fn) { var result = fn.call(ctx); if (result && typeof result.then === 'function') { self.resetTimeout(); result .then(function() { done() }, function(reason) { done(reason || new Error('Promise rejected with no or falsy reason')) }); } else { done(); } } }; }); // module: runnable.js require.register("runner.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:runner') , Test = require('./test') , utils = require('./utils') , filter = utils.filter , keys = utils.keys; /** * Non-enumerable globals. */ var globals = [ 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'XMLHttpRequest', 'Date' ]; /** * Expose `Runner`. */ module.exports = Runner; /** * Initialize a `Runner` for the given `suite`. * * Events: * * - `start` execution started * - `end` execution complete * - `suite` (suite) test suite execution started * - `suite end` (suite) all tests (and sub-suites) have finished * - `test` (test) test execution started * - `test end` (test) test completed * - `hook` (hook) hook execution started * - `hook end` (hook) hook complete * - `pass` (test) test passed * - `fail` (test, err) test failed * - `pending` (test) test pending * * @api public */ function Runner(suite) { var self = this; this._globals = []; this._abort = false; this.suite = suite; this.total = suite.total(); this.failures = 0; this.on('test end', function(test){ self.checkGlobals(test); }); this.on('hook end', function(hook){ self.checkGlobals(hook); }); this.grep(/.*/); this.globals(this.globalProps().concat(extraGlobals())); } /** * Wrapper for setImmediate, process.nextTick, or browser polyfill. * * @param {Function} fn * @api private */ Runner.immediately = global.setImmediate || process.nextTick; /** * Inherit from `EventEmitter.prototype`. */ function F(){}; F.prototype = EventEmitter.prototype; Runner.prototype = new F; Runner.prototype.constructor = Runner; /** * Run tests with full titles matching `re`. Updates runner.total * with number of tests matched. * * @param {RegExp} re * @param {Boolean} invert * @return {Runner} for chaining * @api public */ Runner.prototype.grep = function(re, invert){ debug('grep %s', re); this._grep = re; this._invert = invert; this.total = this.grepTotal(this.suite); return this; }; /** * Returns the number of tests matching the grep search for the * given suite. * * @param {Suite} suite * @return {Number} * @api public */ Runner.prototype.grepTotal = function(suite) { var self = this; var total = 0; suite.eachTest(function(test){ var match = self._grep.test(test.fullTitle()); if (self._invert) match = !match; if (match) total++; }); return total; }; /** * Return a list of global properties. * * @return {Array} * @api private */ Runner.prototype.globalProps = function() { var props = utils.keys(global); // non-enumerables for (var i = 0; i < globals.length; ++i) { if (~utils.indexOf(props, globals[i])) continue; props.push(globals[i]); } return props; }; /** * Allow the given `arr` of globals. * * @param {Array} arr * @return {Runner} for chaining * @api public */ Runner.prototype.globals = function(arr){ if (0 == arguments.length) return this._globals; debug('globals %j', arr); this._globals = this._globals.concat(arr); return this; }; /** * Check for global variable leaks. * * @api private */ Runner.prototype.checkGlobals = function(test){ if (this.ignoreLeaks) return; var ok = this._globals; var globals = this.globalProps(); var leaks; if (test) { ok = ok.concat(test._allowedGlobals || []); } if(this.prevGlobalsLength == globals.length) return; this.prevGlobalsLength = globals.length; leaks = filterLeaks(ok, globals); this._globals = this._globals.concat(leaks); if (leaks.length > 1) { this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); } else if (leaks.length) { this.fail(test, new Error('global leak detected: ' + leaks[0])); } }; /** * Fail the given `test`. * * @param {Test} test * @param {Error} err * @api private */ Runner.prototype.fail = function(test, err){ ++this.failures; test.state = 'failed'; if ('string' == typeof err) { err = new Error('the string "' + err + '" was thrown, throw an Error :)'); } this.emit('fail', test, err); }; /** * Fail the given `hook` with `err`. * * Hook failures work in the following pattern: * - If bail, then exit * - Failed `before` hook skips all tests in a suite and subsuites, * but jumps to corresponding `after` hook * - Failed `before each` hook skips remaining tests in a * suite and jumps to corresponding `after each` hook, * which is run only once * - Failed `after` hook does not alter * execution order * - Failed `after each` hook skips remaining tests in a * suite and subsuites, but executes other `after each` * hooks * * @param {Hook} hook * @param {Error} err * @api private */ Runner.prototype.failHook = function(hook, err){ this.fail(hook, err); if (this.suite.bail()) {
const express = require('express'); const path = require('path'); const config = require('../../../config'); const constants = require('../../../lib/constants'); const themeUtils = require('../../../services/themes'); function isBlackListedFileType(file) { const blackListedFileTypes = ['.hbs', '.md', '.json']; const ext = path.extname(file); return blackListedFileTypes.includes(ext); } function isWhiteListedFile(file) { const whiteListedFiles = ['manifest.json']; const base = path.basename(file); return whiteListedFiles.includes(base); } function forwardToExpressStatic(req, res, next) { if (!themeUtils.getActive()) { return next(); } const configMaxAge = config.get('caching:theme:maxAge'); express.static(themeUtils.getActive().path, {maxAge: (configMaxAge || configMaxAge === 0) ? configMaxAge : constants.ONE_YEAR_MS} )(req, res, next); } function staticTheme() { return function blackListStatic(req, res, next) { if (!isWhiteListedFile(req.path) && isBlackListedFileType(req.path)) { return next(); } return forwardToExpressStatic(req, res, next); }; } module.exports = staticTheme;
import React, { Component } from 'react' import Router from 'next/router' import { TabBar, Icon } from 'antd-mobile' export default class MenuBar extends Component { render () { const { pathname, children } = this.props return ( <TabBar> {tabBarData.map(({ title, icon, selectedIcon, link, dot, component: Component }) => ( <TabBar.Item key={link} title={title} icon={<Icon type={icon} />} selectedIcon={<Icon type={selectedIcon} />} selected={pathname === link} onPress={() => Router.push(link)} > {children} </TabBar.Item> ))} </TabBar> ) } } const tabBarData = [ { title: 'Home', icon: 'koubei-o', selectedIcon: 'koubei', link: '/home' }, { title: 'Icon', icon: 'check-circle-o', selectedIcon: 'check-circle', link: '/icon' }, { title: 'Trick', icon: 'cross-circle-o', selectedIcon: 'cross-circle', link: '/trick' } ]
'use strict'; var is = require('../is'); var Style = require('../style'); var corefn = ({ style: function( newStyle ){ if( newStyle ){ var s = this.setStyle( newStyle ); s.update(); } return this._private.style; }, setStyle: function( style ){ var _p = this._private; if( is.stylesheet(style) ){ _p.style = style.generateStyle(this); } else if( is.array(style) ) { _p.style = Style.fromJson(this, style); } else if( is.string(style) ){ _p.style = Style.fromString(this, style); } else { _p.style = Style( this ); } return _p.style; } }); module.exports = corefn;
export function Corge ( x ) { this.value = x; }
var searchData= [ ['grab_5fangle',['grab_angle',['../a00029.html#a0681b9e1a1802a371c77ee589f29a2c8',1,'LEAP_HAND']]], ['grab_5fstrength',['grab_strength',['../a00029.html#ae269e3744fbc60922a6530d9c2563b17',1,'LEAP_HAND']]] ];
import renderOpenApi from './openapi'; export default renderOpenApi;
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'specialchar', 'gl', { options: 'Opcións de caracteres especiais', title: 'Seleccione un carácter especial', toolbar: 'Inserir un carácter especial' });
// Generated by CoffeeScript 1.3.3 (function() { exports.Mask = require('./lib/mask'); exports.RelPathSpec = require('./lib/relpathspec'); exports.RelPathList = require('./lib/relpathlist'); exports.TreeStream = require('./lib/treestream'); exports.find = require('./lib/find'); }).call(this);
/* cssx/shim/inlineBlock (c) copyright 2010, unscriptable.com author: john LICENSE: see the LICENSE.txt file. If file is missing, this file is subject to the AFL 3.0 license at the following url: http://www.opensource.org/licenses/afl-3.0.php. This cssx plugin fixes lack of inline-block support in IE6 and IE7 */ define(function () { var inlineBlockRx = /inline-block/; return { display: function (prop, value, selectors) { if (inlineBlockRx.test(value)) { return 'display:inline;zoom:1;'; } } }; });
// Last time updated at Nov 18, 2014, 08:32:23 // Latest file can be found here: https://cdn.webrtc-experiment.com/ConcatenateBlobs.js // Muaz Khan - www.MuazKhan.com // MIT License - www.WebRTC-Experiment.com/licence // Source Code - https://github.com/muaz-khan/ConcatenateBlobs // Demo - https://www.WebRTC-Experiment.com/ConcatenateBlobs/ // ___________________ // ConcatenateBlobs.js // Simply pass array of blobs. // This javascript library will concatenate all blobs in single "Blob" object. (function() { window.ConcatenateBlobs = function(blobs, type, callback) { var buffers = []; var index = 0; function readAsArrayBuffer() { if (!blobs[index]) { return concatenateBuffers(); } var reader = new FileReader(); reader.onload = function(event) { buffers.push(event.target.result); index++; readAsArrayBuffer(); }; reader.readAsArrayBuffer(blobs[index]); } readAsArrayBuffer(); function concatenateBuffers() { var byteLength = 0; buffers.forEach(function(buffer) { byteLength += buffer.byteLength; }); var tmp = new Uint16Array(byteLength); var lastOffset = 0; buffers.forEach(function(buffer) { // BYTES_PER_ELEMENT == 2 for Uint16Array var reusableByteLength = buffer.byteLength; if (reusableByteLength % 2 != 0) { buffer = buffer.slice(0, reusableByteLength - 1) } tmp.set(new Uint16Array(buffer), lastOffset); lastOffset += reusableByteLength; }); var blob = new Blob([tmp.buffer], { type: type }); callback(blob); } }; })();
var React = require('react'); var joinClasses = require('./utils/joinClasses'); var classSet = require('./utils/classSet'); var cloneWithProps = require('./utils/cloneWithProps'); var BootstrapMixin = require('./BootstrapMixin'); var ValidComponentChildren = require('./utils/ValidComponentChildren'); var PanelGroup = React.createClass({displayName: "PanelGroup", mixins: [BootstrapMixin], propTypes: { collapsable: React.PropTypes.bool, activeKey: React.PropTypes.any, defaultActiveKey: React.PropTypes.any, onSelect: React.PropTypes.func }, getDefaultProps: function () { return { bsClass: 'panel-group' }; }, getInitialState: function () { var defaultActiveKey = this.props.defaultActiveKey; return { activeKey: defaultActiveKey }; }, render: function () { var classes = this.getBsClassSet(); return ( React.createElement("div", React.__spread({}, this.props, {className: joinClasses(this.props.className, classSet(classes)), onSelect: null}), ValidComponentChildren.map(this.props.children, this.renderPanel) ) ); }, renderPanel: function (child, index) { var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey; var props = { bsStyle: child.props.bsStyle || this.props.bsStyle, key: child.key ? child.key : index, ref: child.ref }; if (this.props.accordion) { props.collapsable = true; props.expanded = (child.props.eventKey === activeKey); props.onSelect = this.handleSelect; } return cloneWithProps( child, props ); }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onSelect` handler. return !this._isChanging; }, handleSelect: function (key) { if (this.props.onSelect) { this._isChanging = true; this.props.onSelect(key); this._isChanging = false; } if (this.state.activeKey === key) { key = null; } this.setState({ activeKey: key }); } }); module.exports = PanelGroup;
import { PromiseWrapper } from 'angular2/src/facade/async'; export class Rectangle { constructor(left, top, width, height) { this.left = left; this.right = left + width; this.top = top; this.bottom = top + height; this.height = height; this.width = width; } } export class Ruler { constructor(domAdapter) { this.domAdapter = domAdapter; } measure(el) { var clntRect = this.domAdapter.getBoundingClientRect(el.nativeElement); // even if getBoundingClientRect is synchronous we use async API in preparation for further // changes return PromiseWrapper.resolve(new Rectangle(clntRect.left, clntRect.top, clntRect.width, clntRect.height)); } } //# sourceMappingURL=ruler.js.map
var FILE_ENCODING = 'utf-8', SRC_DIR = 'dev/src', DIST_DIR = 'dist', DIST_NAME = 'crossroads.js', DIST_MIN_NAME = 'crossroads.min.js', DIST_PATH = DIST_DIR +'/'+ DIST_NAME, DIST_MIN_PATH = DIST_DIR +'/'+ DIST_MIN_NAME; var _fs = require('fs'), _path = require('path'), _pkg = JSON.parse(readFile('package.json')), _now = new Date(), _replacements = { NAME : _pkg.name, AUTHOR : _pkg.author.name, VERSION_NUMBER : _pkg.version, HOMEPAGE : _pkg.homepage, LICENSE : _pkg.license, BUILD_DATE : _now.getUTCFullYear() +'/'+ pad(_now.getUTCMonth() + 1) +'/'+ pad(_now.getUTCDate()) +' '+ pad(_now.getUTCHours()) +':'+ pad(_now.getUTCMinutes()) }; function purgeDeploy(){ [DIST_PATH, DIST_MIN_PATH].forEach(function(filePath){ if( _fs.existsSync(filePath) ){ _fs.unlinkSync(filePath); } }); console.log(' purged deploy.'); } function build(){ var wrapper = readFile(SRC_DIR + '/wrapper.js'), deploy = tmpl(wrapper, { LICENSE : readFile(SRC_DIR + '/license.txt'), INTRO_JS : readFile(SRC_DIR + '/intro.js'), CROSSROADS_JS : readFile(SRC_DIR + '/crossroads.js'), ROUTE_JS : readFile(SRC_DIR + '/route.js'), LEXER_JS : readFile(SRC_DIR + '/pattern_lexer.js') }, /\/\/::(\w+)::\/\//g); _fs.writeFileSync(DIST_PATH, tmpl(deploy, _replacements), FILE_ENCODING); console.log(' '+ DIST_PATH +' built.'); } function readFile(filePath) { return _fs.readFileSync(filePath, FILE_ENCODING); } function tmpl(template, data, regexp){ function replaceFn(match, prop){ return (prop in data)? data[prop] : ''; } return template.replace(regexp || /::(\w+)::/g, replaceFn); } function uglify(srcPath) { var uglyfyJS = require('uglify-js'), jsp = uglyfyJS.parser, pro = uglyfyJS.uglify, ast = jsp.parse( _fs.readFileSync(srcPath, FILE_ENCODING) ); ast = pro.ast_mangle(ast); ast = pro.ast_squeeze(ast); return pro.gen_code(ast); } function minify(){ var license = tmpl( readFile(SRC_DIR +'/license.txt'), _replacements ); // we add a leading/trailing ";" to avoid concat issues (#73) _fs.writeFileSync(DIST_MIN_PATH, license +';'+ uglify(DIST_PATH) +';', FILE_ENCODING); console.log(' '+ DIST_MIN_PATH +' built.'); } function pad(val){ val = String(val); if (val.length < 2) { return '0'+ val; } else { return val; } } // --- run --- purgeDeploy(); build(); minify();
/*! * # Semantic UI 2.6.3 - Tab * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { 'use strict'; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.tab = function(parameters) { var // use window context if none specified $allModules = $.isFunction(this) ? $(window) : $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), initializedHistory = false, returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.tab.settings, parameters) : $.extend({}, $.fn.tab.settings), className = settings.className, metadata = settings.metadata, selector = settings.selector, error = settings.error, eventNamespace = '.' + settings.namespace, moduleNamespace = 'module-' + settings.namespace, $module = $(this), $context, $tabs, cache = {}, firstLoad = true, recursionDepth = 0, element = this, instance = $module.data(moduleNamespace), activeTabPath, parameterArray, module, historyEvent ; module = { initialize: function() { module.debug('Initializing tab menu item', $module); module.fix.callbacks(); module.determineTabs(); module.debug('Determining tabs', settings.context, $tabs); // set up automatic routing if(settings.auto) { module.set.auto(); } module.bind.events(); if(settings.history && !initializedHistory) { module.initializeHistory(); initializedHistory = true; } module.instantiate(); }, instantiate: function () { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.debug('Destroying tabs', $module); $module .removeData(moduleNamespace) .off(eventNamespace) ; }, bind: { events: function() { // if using $.tab don't add events if( !$.isWindow( element ) ) { module.debug('Attaching tab activation events to element', $module); $module .on('click' + eventNamespace, module.event.click) ; } } }, determineTabs: function() { var $reference ; // determine tab context if(settings.context === 'parent') { if($module.closest(selector.ui).length > 0) { $reference = $module.closest(selector.ui); module.verbose('Using closest UI element as parent', $reference); } else { $reference = $module; } $context = $reference.parent(); module.verbose('Determined parent element for creating context', $context); } else if(settings.context) { $context = $(settings.context); module.verbose('Using selector for tab context', settings.context, $context); } else { $context = $('body'); } // find tabs if(settings.childrenOnly) { $tabs = $context.children(selector.tabs); module.debug('Searching tab context children for tabs', $context, $tabs); } else { $tabs = $context.find(selector.tabs); module.debug('Searching tab context for tabs', $context, $tabs); } }, fix: { callbacks: function() { if( $.isPlainObject(parameters) && (parameters.onTabLoad || parameters.onTabInit) ) { if(parameters.onTabLoad) { parameters.onLoad = parameters.onTabLoad; delete parameters.onTabLoad; module.error(error.legacyLoad, parameters.onLoad); } if(parameters.onTabInit) { parameters.onFirstLoad = parameters.onTabInit; delete parameters.onTabInit; module.error(error.legacyInit, parameters.onFirstLoad); } settings = $.extend(true, {}, $.fn.tab.settings, parameters); } } }, initializeHistory: function() { module.debug('Initializing page state'); if( $.address === undefined ) { module.error(error.state); return false; } else { if(settings.historyType == 'state') { module.debug('Using HTML5 to manage state'); if(settings.path !== false) { $.address .history(true) .state(settings.path) ; } else { module.error(error.path); return false; } } $.address .bind('change', module.event.history.change) ; } }, event: { click: function(event) { var tabPath = $(this).data(metadata.tab) ; if(tabPath !== undefined) { if(settings.history) { module.verbose('Updating page state', event); $.address.value(tabPath); } else { module.verbose('Changing tab', event); module.changeTab(tabPath); } event.preventDefault(); } else { module.debug('No tab specified'); } }, history: { change: function(event) { var tabPath = event.pathNames.join('/') || module.get.initialPath(), pageTitle = settings.templates.determineTitle(tabPath) || false ; module.performance.display(); module.debug('History change event', tabPath, event); historyEvent = event; if(tabPath !== undefined) { module.changeTab(tabPath); } if(pageTitle) { $.address.title(pageTitle); } } } }, refresh: function() { if(activeTabPath) { module.debug('Refreshing tab', activeTabPath); module.changeTab(activeTabPath); } }, cache: { read: function(cacheKey) { return (cacheKey !== undefined) ? cache[cacheKey] : false ; }, add: function(cacheKey, content) { cacheKey = cacheKey || activeTabPath; module.debug('Adding cached content for', cacheKey); cache[cacheKey] = content; }, remove: function(cacheKey) { cacheKey = cacheKey || activeTabPath; module.debug('Removing cached content for', cacheKey); delete cache[cacheKey]; } }, set: { auto: function() { var url = (typeof settings.path == 'string') ? settings.path.replace(/\/$/, '') + '/{$tab}' : '/{$tab}' ; module.verbose('Setting up automatic tab retrieval from server', url); if($.isPlainObject(settings.apiSettings)) { settings.apiSettings.url = url; } else { settings.apiSettings = { url: url }; } }, loading: function(tabPath) { var $tab = module.get.tabElement(tabPath), isLoading = $tab.hasClass(className.loading) ; if(!isLoading) { module.verbose('Setting loading state for', $tab); $tab .addClass(className.loading) .siblings($tabs) .removeClass(className.active + ' ' + className.loading) ; if($tab.length > 0) { settings.onRequest.call($tab[0], tabPath); } } }, state: function(state) { $.address.value(state); } }, changeTab: function(tabPath) { var pushStateAvailable = (window.history && window.history.pushState), shouldIgnoreLoad = (pushStateAvailable && settings.ignoreFirstLoad && firstLoad), remoteContent = (settings.auto || $.isPlainObject(settings.apiSettings) ), // only add default path if not remote content pathArray = (remoteContent && !shouldIgnoreLoad) ? module.utilities.pathToArray(tabPath) : module.get.defaultPathArray(tabPath) ; tabPath = module.utilities.arrayToPath(pathArray); $.each(pathArray, function(index, tab) { var currentPathArray = pathArray.slice(0, index + 1), currentPath = module.utilities.arrayToPath(currentPathArray), isTab = module.is.tab(currentPath), isLastIndex = (index + 1 == pathArray.length), $tab = module.get.tabElement(currentPath), $anchor, nextPathArray, nextPath, isLastTab ; module.verbose('Looking for tab', tab); if(isTab) { module.verbose('Tab was found', tab); // scope up activeTabPath = currentPath; parameterArray = module.utilities.filterArray(pathArray, currentPathArray); if(isLastIndex) { isLastTab = true; } else { nextPathArray = pathArray.slice(0, index + 2); nextPath = module.utilities.arrayToPath(nextPathArray); isLastTab = ( !module.is.tab(nextPath) ); if(isLastTab) { module.verbose('Tab parameters found', nextPathArray); } } if(isLastTab && remoteContent) { if(!shouldIgnoreLoad) { module.activate.navigation(currentPath); module.fetch.content(currentPath, tabPath); } else { module.debug('Ignoring remote content on first tab load', currentPath); firstLoad = false; module.cache.add(tabPath, $tab.html()); module.activate.all(currentPath); settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent); settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent); } return false; } else { module.debug('Opened local tab', currentPath); module.activate.all(currentPath); if( !module.cache.read(currentPath) ) { module.cache.add(currentPath, true); module.debug('First time tab loaded calling tab init'); settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent); } settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent); } } else if(tabPath.search('/') == -1 && tabPath !== '') { // look for in page anchor $anchor = $('#' + tabPath + ', a[name="' + tabPath + '"]'); currentPath = $anchor.closest('[data-tab]').data(metadata.tab); $tab = module.get.tabElement(currentPath); // if anchor exists use parent tab if($anchor && $anchor.length > 0 && currentPath) { module.debug('Anchor link used, opening parent tab', $tab, $anchor); if( !$tab.hasClass(className.active) ) { setTimeout(function() { module.scrollTo($anchor); }, 0); } module.activate.all(currentPath); if( !module.cache.read(currentPath) ) { module.cache.add(currentPath, true); module.debug('First time tab loaded calling tab init'); settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent); } settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent); return false; } } else { module.error(error.missingTab, $module, $context, currentPath); return false; } }); }, scrollTo: function($element) { var scrollOffset = ($element && $element.length > 0) ? $element.offset().top : false ; if(scrollOffset !== false) { module.debug('Forcing scroll to an in-page link in a hidden tab', scrollOffset, $element); $(document).scrollTop(scrollOffset); } }, update: { content: function(tabPath, html, evaluateScripts) { var $tab = module.get.tabElement(tabPath), tab = $tab[0] ; evaluateScripts = (evaluateScripts !== undefined) ? evaluateScripts : settings.evaluateScripts ; if(typeof settings.cacheType == 'string' && settings.cacheType.toLowerCase() == 'dom' && typeof html !== 'string') { $tab .empty() .append($(html).clone(true)) ; } else { if(evaluateScripts) { module.debug('Updating HTML and evaluating inline scripts', tabPath, html); $tab.html(html); } else { module.debug('Updating HTML', tabPath, html); tab.innerHTML = html; } } } }, fetch: { content: function(tabPath, fullTabPath) { var $tab = module.get.tabElement(tabPath), apiSettings = { dataType : 'html', encodeParameters : false, on : 'now', cache : settings.alwaysRefresh, headers : { 'X-Remote': true }, onSuccess : function(response) { if(settings.cacheType == 'response') { module.cache.add(fullTabPath, response); } module.update.content(tabPath, response); if(tabPath == activeTabPath) { module.debug('Content loaded', tabPath); module.activate.tab(tabPath); } else { module.debug('Content loaded in background', tabPath); } settings.onFirstLoad.call($tab[0], tabPath, parameterArray, historyEvent); settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent); if(settings.loadOnce) { module.cache.add(fullTabPath, true); } else if(typeof settings.cacheType == 'string' && settings.cacheType.toLowerCase() == 'dom' && $tab.children().length > 0) { setTimeout(function() { var $clone = $tab.children().clone(true) ; $clone = $clone.not('script'); module.cache.add(fullTabPath, $clone); }, 0); } else { module.cache.add(fullTabPath, $tab.html()); } }, urlData: { tab: fullTabPath } }, request = $tab.api('get request') || false, existingRequest = ( request && request.state() === 'pending' ), requestSettings, cachedContent ; fullTabPath = fullTabPath || tabPath; cachedContent = module.cache.read(fullTabPath); if(settings.cache && cachedContent) { module.activate.tab(tabPath); module.debug('Adding cached content', fullTabPath); if(!settings.loadOnce) { if(settings.evaluateScripts == 'once') { module.update.content(tabPath, cachedContent, false); } else { module.update.content(tabPath, cachedContent); } } settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent); } else if(existingRequest) { module.set.loading(tabPath); module.debug('Content is already loading', fullTabPath); } else if($.api !== undefined) { requestSettings = $.extend(true, {}, settings.apiSettings, apiSettings); module.debug('Retrieving remote content', fullTabPath, requestSettings); module.set.loading(tabPath); $tab.api(requestSettings); } else { module.error(error.api); } } }, activate: { all: function(tabPath) { module.activate.tab(tabPath); module.activate.navigation(tabPath); }, tab: function(tabPath) { var $tab = module.get.tabElement(tabPath), $deactiveTabs = (settings.deactivate == 'siblings') ? $tab.siblings($tabs) : $tabs.not($tab), isActive = $tab.hasClass(className.active) ; module.verbose('Showing tab content for', $tab); if(!isActive) { $tab .addClass(className.active) ; $deactiveTabs .removeClass(className.active + ' ' + className.loading) ; if($tab.length > 0) { settings.onVisible.call($tab[0], tabPath); } } }, navigation: function(tabPath) { var $navigation = module.get.navElement(tabPath), $deactiveNavigation = (settings.deactivate == 'siblings') ? $navigation.siblings($allModules) : $allModules.not($navigation), isActive = $navigation.hasClass(className.active) ; module.verbose('Activating tab navigation for', $navigation, tabPath); if(!isActive) { $navigation .addClass(className.active) ; $deactiveNavigation .removeClass(className.active + ' ' + className.loading) ; } } }, deactivate: { all: function() { module.deactivate.navigation(); module.deactivate.tabs(); }, navigation: function() { $allModules .removeClass(className.active) ; }, tabs: function() { $tabs .removeClass(className.active + ' ' + className.loading) ; } }, is: { tab: function(tabName) { return (tabName !== undefined) ? ( module.get.tabElement(tabName).length > 0 ) : false ; } }, get: { initialPath: function() { return $allModules.eq(0).data(metadata.tab) || $tabs.eq(0).data(metadata.tab); }, path: function() { return $.address.value(); }, // adds default tabs to tab path defaultPathArray: function(tabPath) { return module.utilities.pathToArray( module.get.defaultPath(tabPath) ); }, defaultPath: function(tabPath) { var $defaultNav = $allModules.filter('[data-' + metadata.tab + '^="' + tabPath + '/"]').eq(0), defaultTab = $defaultNav.data(metadata.tab) || false ; if( defaultTab ) { module.debug('Found default tab', defaultTab); if(recursionDepth < settings.maxDepth) { recursionDepth++; return module.get.defaultPath(defaultTab); } module.error(error.recursion); } else { module.debug('No default tabs found for', tabPath, $tabs); } recursionDepth = 0; return tabPath; }, navElement: function(tabPath) { tabPath = tabPath || activeTabPath; return $allModules.filter('[data-' + metadata.tab + '="' + tabPath + '"]'); }, tabElement: function(tabPath) { var $fullPathTab, $simplePathTab, tabPathArray, lastTab ; tabPath = tabPath || activeTabPath; tabPathArray = module.utilities.pathToArray(tabPath); lastTab = module.utilities.last(tabPathArray); $fullPathTab = $tabs.filter('[data-' + metadata.tab + '="' + tabPath + '"]'); $simplePathTab = $tabs.filter('[data-' + metadata.tab + '="' + lastTab + '"]'); return ($fullPathTab.length > 0) ? $fullPathTab : $simplePathTab ; }, tab: function() { return activeTabPath; } }, utilities: { filterArray: function(keepArray, removeArray) { return $.grep(keepArray, function(keepValue) { return ( $.inArray(keepValue, removeArray) == -1); }); }, last: function(array) { return $.isArray(array) ? array[ array.length - 1] : false ; }, pathToArray: function(pathName) { if(pathName === undefined) { pathName = activeTabPath; } return typeof pathName == 'string' ? pathName.split('/') : [pathName] ; }, arrayToPath: function(pathArray) { return $.isArray(pathArray) ? pathArray.join('/') : false ; } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { if($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; // shortcut for tabbed content with no defined navigation $.tab = function() { $(window).tab.apply(this, arguments); }; $.fn.tab.settings = { name : 'Tab', namespace : 'tab', silent : false, debug : false, verbose : false, performance : true, auto : false, // uses pjax style endpoints fetching content from same url with remote-content headers history : false, // use browser history historyType : 'hash', // #/ or html5 state path : false, // base path of url context : false, // specify a context that tabs must appear inside childrenOnly : false, // use only tabs that are children of context maxDepth : 25, // max depth a tab can be nested deactivate : 'siblings', // whether tabs should deactivate sibling menu elements or all elements initialized together alwaysRefresh : false, // load tab content new every tab click cache : true, // cache the content requests to pull locally loadOnce : false, // Whether tab data should only be loaded once when using remote content cacheType : 'response', // Whether to cache exact response, or to html cache contents after scripts execute ignoreFirstLoad : false, // don't load remote content on first load apiSettings : false, // settings for api call evaluateScripts : 'once', // whether inline scripts should be parsed (true/false/once). Once will not re-evaluate on cached content onFirstLoad : function(tabPath, parameterArray, historyEvent) {}, // called first time loaded onLoad : function(tabPath, parameterArray, historyEvent) {}, // called on every load onVisible : function(tabPath, parameterArray, historyEvent) {}, // called every time tab visible onRequest : function(tabPath, parameterArray, historyEvent) {}, // called ever time a tab beings loading remote content templates : { determineTitle: function(tabArray) {} // returns page title for path }, error: { api : 'You attempted to load content without API module', method : 'The method you called is not defined', missingTab : 'Activated tab cannot be found. Tabs are case-sensitive.', noContent : 'The tab you specified is missing a content url.', path : 'History enabled, but no path was specified', recursion : 'Max recursive depth reached', legacyInit : 'onTabInit has been renamed to onFirstLoad in 2.0, please adjust your code.', legacyLoad : 'onTabLoad has been renamed to onLoad in 2.0. Please adjust your code', state : 'History requires Asual\'s Address library <https://github.com/asual/jquery-address>' }, metadata : { tab : 'tab', loaded : 'loaded', promise: 'promise' }, className : { loading : 'loading', active : 'active' }, selector : { tabs : '.ui.tab', ui : '.ui' } }; })( jQuery, window, document );
define(function (require) { var d3 = require("d3"); return function rect() { // Private variables var x = function (d) { return d.x; }; var y = function (d) { return d.y; }; var width = 10; var height = 10; var cssClass = "rect"; var fillStyle = "blue"; var lineWidth = 3; var strokeStyle = "black"; var globalAlpha = 1; function element(selection) { selection.each(function (data, index) { var canvas = d3.select(this); var context = canvas.node().getContext("2d"); // var container = canvas.append("custom"); canvas.node().addEventListener("click", function (event) { console.log(event); }); // Clear Canvas context.fillStyle = "#fff"; context.rect(0, 0, canvas.attr("width"), canvas.attr("height")); context.fill(); data.forEach(function (d, i) { d.fillStyle = (typeof fillStyle === "function") ? fillStyle.call(data, d, i) : fillStyle; d.strokeStyle = (typeof strokeStyle === "function") ? strokeStyle.call(data, d, i) : strokeStyle; d.globalAlpha = (typeof globalAlpha === "function") ? globalAlpha.call(data, d, i) : globalAlpha; d.lineWidth = (typeof lineWidth === "function") ? lineWidth.call(data, d, i) : lineWidth; d.width = (typeof width === "function") ? width.call(data, d, i) : width; d.height = (typeof height === "function") ? height.call(data, d, i) : height; context.beginPath(); context.fillStyle = d.fillStyle; context.strokeStyle = d.strokeStyle; context.lineWidth = d.lineWidth; context.globalAlpha = d.globalAlpha; context.rect(x.call(data, d, i), y.call(data, d, i), d.width, d.height); context.fill(); context.closePath(); }); // var rects = container.selectAll("custom.rect") // .data(data); // // Exit // rects.exit().remove(); // // Enter // rects.enter().append("custom"); // // Update // rects // .attr("class", cssClass) // .attr("x", x) // .attr("y", y) // .attr("width", width) // .attr("height", height) // .attr("fillStyle", fillStyle) // .attr("lineWidth", lineWidth) // .attr("globalAlpha", globalAlpha) // .attr("strokeStyle", strokeStyle); // // Clear Canvas // context.fillStyle = "#fff"; // context.rect(0, 0, canvas.attr("width"), canvas.attr("height")); // context.fill(); // var elements = container.selectAll("custom.rect"); // elements.each(function (d, i) { // var node = d3.select(this); // context.beginPath(); // context.fillStyle = node.attr("fillstyle"); // context.globalAlpha = node.attr("globalAlpha"); // context.rect(node.attr("x"), node.attr("y"), node.attr("width"), node.attr("height")); // context.fill(); // context.closePath(); // }); }); } // Public API element.class = function (_) { if (!arguments.length) { return cssClass; } cssClass = _; return element; }; element.x = function (_) { if (!arguments.length) { return x; } x = _; return element; }; element.y = function (_) { if (!arguments.length) { return y; } y = _; return element; }; element.width = function (_) { if (!arguments.length) { return width; } width = _; return element; }; element.height = function (_) { if (!arguments.length) { return height; } height = _; return element; }; element.fillStyle = function (_) { if (!arguments.length) { return fillStyle; } fillStyle = _; return element; }; element.opacity = function (_) { if (!arguments.length) { return globalAlpha; } globalAlpha = _; return element; }; element.lineWidth = function (_) { if (!arguments.length) { return lineWidth; } lineWidth = _; return element; }; element.strokeStyle = function (_) { if (!arguments.length) { return strokeStyle; } strokeStyle = _; return element; }; return element; }; });
// Vex Flow // Mohit Muthanna <mohit@muthanna.com> // // Copyright Mohit Cheppudira 2010 /** @constructor */ Vex.Flow.Stave = function(x, y, width, options) { if (arguments.length > 0) this.init(x, y, width, options); } Vex.Flow.Stave.prototype.init = function(x, y, width, options) { this.x = x; this.y = y; this.width = width; this.glyph_start_x = x + 5; this.start_x = this.glyph_start_x + 5; this.context = null; this.glyphs = []; this.options = { vertical_bar_width: 10, // Width around vertical bar end-marker glyph_spacing_px: 10, num_lines: 5, spacing_between_lines_px: 10, // in pixels space_above_staff_ln: 4, // in staff lines space_below_staff_ln: 4, // in staff lines top_text_position: 1 // in staff lines }; this.height = (this.options.num_lines + this.options.space_above_staff_ln) * this.options.spacing_between_lines_px; Vex.Merge(this.options, options); } Vex.Flow.Stave.prototype.setNoteStartX = function(x) { this.start_x = x; return this; } Vex.Flow.Stave.prototype.getNoteStartX = function() { return this.start_x; } Vex.Flow.Stave.prototype.getTieStartX = function() { return this.start_x; } Vex.Flow.Stave.prototype.getTieEndX = function() { return this.x + this.width; } Vex.Flow.Stave.prototype.setContext = function(context) { this.context = context; return this; } Vex.Flow.Stave.prototype.setY = function(y) { this.y = y; return this; } Vex.Flow.Stave.prototype.setWidth = function(width) { this.width = width; return this; } Vex.Flow.Stave.prototype.getHeight = function(width) { return this.height; } Vex.Flow.Stave.prototype.getBottomY = function() { var options = this.options; var spacing = options.spacing_between_lines_px; var score_bottom = this.getYForLine(options.num_lines) + (options.space_below_staff_ln * spacing); return score_bottom; } Vex.Flow.Stave.prototype.getYForLine = function(line) { var options = this.options; var spacing = options.spacing_between_lines_px; var headroom = options.space_above_staff_ln; var y = this.y + ((line * spacing) + (headroom * spacing)); return y; } Vex.Flow.Stave.prototype.getYForTopText = function(line) { var l = line || 0; return this.getYForLine(-l - this.options.top_text_position); } Vex.Flow.Stave.prototype.getYForNote = function(line) { var options = this.options; var spacing = options.spacing_between_lines_px; var headroom = options.space_above_staff_ln; var y = this.y + (headroom * spacing) + (5 * spacing) - (line * spacing); return y; } Vex.Flow.Stave.prototype.getYForGlyphs = function() { return this.getYForLine(3); } Vex.Flow.Stave.prototype.addGlyph= function(glyph) { glyph.setStave(this); this.glyphs.push(glyph); this.start_x += glyph.getMetrics().width; return this; } Vex.Flow.Stave.prototype.addModifier = function(modifier) { modifier.addToStave(this, (this.glyphs.length == 0)); return this; } Vex.Flow.Stave.prototype.addKeySignature = function(keySpec) { this.addModifier(new Vex.Flow.KeySignature(keySpec)); return this; } Vex.Flow.Stave.prototype.addClef = function(clef) { this.addModifier(new Vex.Flow.Clef(clef)); return this; } Vex.Flow.Stave.prototype.addTimeSignature = function(timeSpec) { this.addModifier(new Vex.Flow.TimeSignature(timeSpec)); return this; } Vex.Flow.Stave.prototype.addTrebleGlyph = function() { this.addGlyph(new Vex.Flow.Glyph("v83", 40)); return this; } /** * All drawing functions below need the context to be set. */ Vex.Flow.Stave.prototype.draw = function(context) { if (!this.context) throw new Vex.RERR("NoCanvasContext", "Can't draw stave without canvas context."); var num_lines = this.options.num_lines; var width = this.width; var x = this.x; this.drawVerticalBar(0); for (var line=0; line < num_lines; line++) { var y = this.getYForLine(line); this.context.fillRect(x, y, width, 1); } x = this.glyph_start_x; for (var i = 0; i < this.glyphs.length; ++i) { var glyph = this.glyphs[i]; if (!glyph.getContext()) glyph.setContext(this.context); glyph.renderToStave(x); x += glyph.getMetrics().width; } this.drawVerticalBar(this.width); return this; } Vex.Flow.Stave.prototype.drawVerticalBar = function(x) { this.drawVerticalBarFixed(this.x + x); } Vex.Flow.Stave.prototype.drawVerticalBarFixed = function(x) { if (!this.context) throw new Vex.RERR("NoCanvasContext", "Can't draw stave without canvas context."); var top_line = this.getYForLine(0); var bottom_line = this.getYForLine(this.options.num_lines - 1); this.context.fillRect(x, top_line, 1, bottom_line - top_line + 1); }
'use strict'; /*! * Simplified lodash.get to work around the annoying null quirk. See: * https://github.com/lodash/lodash/issues/3659 */ module.exports = function get(obj, path, def) { const parts = path.split('.'); let rest = path; let cur = obj; for (const part of parts) { if (cur == null) { return def; } // `lib/cast.js` depends on being able to get dotted paths in updates, // like `{ $set: { 'a.b': 42 } }` if (cur[rest] != null) { return cur[rest]; } cur = getProperty(cur, part); rest = rest.substr(part.length + 1); } return cur == null ? def : cur; }; function getProperty(obj, prop) { if (obj == null) { return obj; } if (obj instanceof Map) { return obj.get(prop); } return obj[prop]; }
var searchData= [ ['m',['m',['../structedda_1_1dist_1_1GMMTuple.html#a51f92001831208525f57b22006b874e8',1,'edda::dist::GMMTuple']]], ['m_5fbinwidth',['m_binWidth',['../classedda_1_1dist_1_1Histogram.html#a78e968cd9358d661ba8b06ce44f5c987',1,'edda::dist::Histogram']]], ['m_5fcdf',['m_cdf',['../classedda_1_1dist_1_1Histogram.html#a8bb932b42a80e859598e131d67e8e686',1,'edda::dist::Histogram']]], ['m_5fmaxvalue',['m_maxValue',['../classedda_1_1dist_1_1Histogram.html#ac9205c786a9a3063b4556d8a559802d5',1,'edda::dist::Histogram']]], ['m_5fminvalue',['m_minValue',['../classedda_1_1dist_1_1Histogram.html#ad567bb59006090492cdbb34c3a5e5d38',1,'edda::dist::Histogram']]], ['m_5fnbins',['m_nBins',['../classedda_1_1dist_1_1Histogram.html#a646ad7e9990bd5a75f420c2c073f506a',1,'edda::dist::Histogram']]], ['m_5fndimension',['m_nDimension',['../classedda_1_1CartesianGrid.html#ab87b87344ff04b342fba7a09bfd36259',1,'edda::CartesianGrid']]], ['m_5fvmaxbound',['m_vMaxBound',['../classedda_1_1CartesianGrid.html#a096d323e8074766915b96d4d5ba545c3',1,'edda::CartesianGrid']]], ['m_5fvmaxrealbound',['m_vMaxRealBound',['../classedda_1_1CartesianGrid.html#a363b39d07aa945fd4b0ea38ed36831e3',1,'edda::CartesianGrid']]], ['m_5fvminbound',['m_vMinBound',['../classedda_1_1CartesianGrid.html#a6b76c040a7f84ec3ccf4bc29de8672fc',1,'edda::CartesianGrid']]], ['m_5fvminrealbound',['m_vMinRealBound',['../classedda_1_1CartesianGrid.html#a5eda0e56f6f7d3b802ece2d418e2e9f4',1,'edda::CartesianGrid']]], ['maskpoints',['MaskPoints',['../classeddaRandomProbeFilter.html#aaa3705c5768ecba66c0ab92b081bc7c5',1,'eddaRandomProbeFilter']]], ['max_5fsteps',['max_steps',['../classedda_1_1StreamTracer.html#abb1e966b1b8d8674a082f9f23e9948f5',1,'edda::StreamTracer']]], ['mean',['mean',['../structedda_1_1dist_1_1Gaussian.html#abded38b8a7bfc642a7d3fe7690b58a7c',1,'edda::dist::Gaussian::mean()'],['../structedda_1_1dist_1_1JointHistogram.html#a8aa0e9ab4fc3c3067f4e2466e12344c1',1,'edda::dist::JointHistogram::mean()']]], ['models',['models',['../classedda_1_1dist_1_1GaussianMixture.html#a58cc2e067440f90ca4386511f7b1832d',1,'edda::dist::GaussianMixture']]] ];
/** * This code is mostly from the old Etherpad. Please help us to comment this code. * This helps other people to understand this code better and helps them to improve it. * TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED */ /** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var padutils = require('/pad_utils').padutils; var paddocbar = require('/pad_docbar').paddocbar; var padmodals = (function() { /*var clearFeedbackEmail = function() {}; function clearFeedback() { clearFeedbackEmail(); $("#feedbackbox-message").val(''); } var sendingFeedback = false; function setSendingFeedback(v) { v = !! v; if (sendingFeedback != v) { sendingFeedback = v; if (v) { $("#feedbackbox-send").css('opacity', 0.75); } else { $("#feedbackbox-send").css('opacity', 1); } } }*/ var sendingInvite = false; function setSendingInvite(v) { v = !! v; if (sendingInvite != v) { sendingInvite = v; if (v) { $(".sharebox-send").css('opacity', 0.75); } else { $("#sharebox-send").css('opacity', 1); } } } var clearShareBoxTo = function() {}; function clearShareBox() { clearShareBoxTo(); } var pad = undefined; var self = { init: function(_pad) { pad = _pad; self.initFeedback(); self.initShareBox(); }, initFeedback: function() { /*var emailField = $("#feedbackbox-email"); clearFeedbackEmail = padutils.makeFieldLabeledWhenEmpty(emailField, '(your email address)').clear; clearFeedback();*/ $("#feedbackbox-hide").click(function() { self.hideModal(); }); /*$("#feedbackbox-send").click(function() { self.sendFeedbackEmail(); });*/ $("#feedbackbutton").click(function() { self.showFeedback(); }); }, initShareBox: function() { $("#sharebutton").click(function() { self.showShareBox(); }); $("#sharebox-hide").click(function() { self.hideModal(); }); $("#sharebox-send").click(function() { self.sendInvite(); }); $("#sharebox-url").click(function() { $("#sharebox-url").focus().select(); }); clearShareBoxTo = padutils.makeFieldLabeledWhenEmpty($("#sharebox-to"), "(email addresses)").clear; clearShareBox(); $("#sharebox-subject").val(self.getDefaultShareBoxSubjectForName(pad.getUserName())); $("#sharebox-message").val(self.getDefaultShareBoxMessageForName(pad.getUserName())); $("#sharebox-stripe .setsecurity").click(function() { self.hideModal(); paddocbar.setShownPanel('security'); }); }, getDefaultShareBoxMessageForName: function(name) { return (name || "Somebody") + " has shared an EtherPad document with you." + "\n\n" + "View it here:\n\n" + padutils.escapeHtml($(".sharebox-url").val() + "\n"); }, getDefaultShareBoxSubjectForName: function(name) { return (name || "Somebody") + " invited you to an EtherPad document"; }, relayoutWithBottom: function(px) { $("#modaloverlay").height(px); $("#sharebox").css('left', Math.floor(($(window).width() - $("#sharebox").outerWidth()) / 2)); $("#feedbackbox").css('left', Math.floor(($(window).width() - $("#feedbackbox").outerWidth()) / 2)); }, showFeedback: function() { self.showModal("#feedbackbox"); }, showShareBox: function() { // when showing the dialog, if it still says "Somebody" invited you // then we fill in the updated username if there is one; // otherwise, we don't touch it, perhaps the user is happy with it var msgbox = $("#sharebox-message"); if (msgbox.val() == self.getDefaultShareBoxMessageForName(null)) { msgbox.val(self.getDefaultShareBoxMessageForName(pad.getUserName())); } var subjBox = $("#sharebox-subject"); if (subjBox.val() == self.getDefaultShareBoxSubjectForName(null)) { subjBox.val(self.getDefaultShareBoxSubjectForName(pad.getUserName())); } if (pad.isPadPublic()) { $("#sharebox-stripe").get(0).className = 'sharebox-stripe-public'; } else { $("#sharebox-stripe").get(0).className = 'sharebox-stripe-private'; } self.showModal("#sharebox", 500); $("#sharebox-url").focus().select(); }, showModal: function(modalId, duration) { $(".modaldialog").hide(); $(modalId).show().css( { 'opacity': 0 }).animate( { 'opacity': 1 }, duration); $("#modaloverlay").show().css( { 'opacity': 0 }).animate( { 'opacity': 1 }, duration); }, hideModal: function(duration) { padutils.cancelActions('hide-feedbackbox'); padutils.cancelActions('hide-sharebox'); $("#sharebox-response").hide(); $(".modaldialog").animate( { 'opacity': 0 }, duration, function() { $("#modaloverlay").hide(); }); $("#modaloverlay").animate( { 'opacity': 0 }, duration, function() { $("#modaloverlay").hide(); }); }, hideFeedbackLaterIfNoOtherInteraction: function() { return padutils.getCancellableAction('hide-feedbackbox', function() { self.hideModal(); }); }, hideShareboxLaterIfNoOtherInteraction: function() { return padutils.getCancellableAction('hide-sharebox', function() { self.hideModal(); }); }, /* sendFeedbackEmail: function() { if (sendingFeedback) { return; } var message = $("#feedbackbox-message").val(); if (! message) { return; } var email = ($("#feedbackbox-email").hasClass('editempty') ? '' : $("#feedbackbox-email").val()); var padId = pad.getPadId(); var username = pad.getUserName(); setSendingFeedback(true); $("#feedbackbox-response").html("Sending...").get(0).className = ''; $("#feedbackbox-response").show(); $.ajax({ type: 'post', url: '/ep/pad/feedback', data: { feedback: message, padId: padId, username: username, email: email }, success: success, error: error }); var hideCall = self.hideFeedbackLaterIfNoOtherInteraction(); function success(msg) { setSendingFeedback(false); clearFeedback(); $("#feedbackbox-response").html("Thanks for your feedback").get(0).className = 'goodresponse'; $("#feedbackbox-response").show(); window.setTimeout(function() { $("#feedbackbox-response").fadeOut('slow', function() { hideCall(); }); }, 1500); } function error(e) { setSendingFeedback(false); $("#feedbackbox-response").html("Could not send feedback. Please email us at feedback"+"@"+"etherpad.com instead.").get(0).className = 'badresponse'; $("#feedbackbox-response").show(); } },*/ sendInvite: function() { if (sendingInvite) { return; } if (!pad.isFullyConnected()) { displayErrorMessage("Error: Connection to the server is down or flaky."); return; } var message = $("#sharebox-message").val(); if (!message) { displayErrorMessage("Please enter a message body before sending."); return; } var emails = ($("#sharebox-to").hasClass('editempty') ? '' : $("#sharebox-to").val()) || ''; // find runs of characters that aren't obviously non-email punctuation var emailArray = emails.match(/[^\s,:;<>\"\'\/\(\)\[\]{}]+/g) || []; if (emailArray.length == 0) { displayErrorMessage('Please enter at least one "To:" address.'); $("#sharebox-to").focus().select(); return; } for (var i = 0; i < emailArray.length; i++) { var addr = emailArray[i]; if (!addr.match(/^[\w\.\_\+\-]+\@[\w\_\-]+\.[\w\_\-\.]+$/)) { displayErrorMessage('"' + padutils.escapeHtml(addr) + '" does not appear to be a valid email address.'); return; } } var subject = $("#sharebox-subject").val(); if (!subject) { subject = self.getDefaultShareBoxSubjectForName(pad.getUserName()); $("#sharebox-subject").val(subject); // force the default subject } var padId = pad.getPadId(); var username = pad.getUserName(); setSendingInvite(true); $("#sharebox-response").html("Sending...").get(0).className = ''; $("#sharebox-response").show(); $.ajax( { type: 'post', url: '/ep/pad/emailinvite', data: { message: message, toEmails: emailArray.join(','), subject: subject, username: username, padId: padId }, success: success, error: error }); var hideCall = self.hideShareboxLaterIfNoOtherInteraction(); function success(msg) { setSendingInvite(false); $("#sharebox-response").html("Email invitation sent!").get(0).className = 'goodresponse'; $("#sharebox-response").show(); window.setTimeout(function() { $("#sharebox-response").fadeOut('slow', function() { hideCall(); }); }, 1500); } function error(e) { setSendingFeedback(false); $("#sharebox-response").html("An error occurred; no email was sent.").get(0).className = 'badresponse'; $("#sharebox-response").show(); } function displayErrorMessage(msgHtml) { $("#sharebox-response").html(msgHtml).get(0).className = 'badresponse'; $("#sharebox-response").show(); } } }; return self; }()); exports.padmodals = padmodals;
'use strict'; /** * @ngdoc function * @name ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log){ return function(exception, cause) { $log.error.apply($log, arguments); }; }]; }
/* eslint-disable */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['../core'], factory); } else if (typeof exports === 'object') { // Node.js module.exports = factory(require('../core')); } else { // Browser root.Blockly.Msg = factory(root.Blockly); } }(this, function(Blockly) { var Blockly = {};Blockly.Msg={};// This file was automatically generated. Do not modify. 'use strict'; Blockly.Msg["ADD_COMMENT"] = "Dodaj Komentarz"; Blockly.Msg["CANNOT_DELETE_VARIABLE_PROCEDURE"] = "Nie można usunąć zmiennej '%1', ponieważ jest częścią definicji funkcji '%2'"; Blockly.Msg["CHANGE_VALUE_TITLE"] = "Zmień wartość:"; Blockly.Msg["CLEAN_UP"] = "Uporządkuj Bloki"; Blockly.Msg["COLLAPSED_WARNINGS_WARNING"] = "Collapsed blocks contain warnings."; // untranslated Blockly.Msg["COLLAPSE_ALL"] = "Zwiń Bloki"; Blockly.Msg["COLLAPSE_BLOCK"] = "Zwiń Klocek"; Blockly.Msg["COLOUR_BLEND_COLOUR1"] = "kolor 1"; Blockly.Msg["COLOUR_BLEND_COLOUR2"] = "kolor 2"; Blockly.Msg["COLOUR_BLEND_HELPURL"] = "http://meyerweb.com/eric/tools/color-blend/"; Blockly.Msg["COLOUR_BLEND_RATIO"] = "proporcja"; Blockly.Msg["COLOUR_BLEND_TITLE"] = "wymieszaj"; Blockly.Msg["COLOUR_BLEND_TOOLTIP"] = "Miesza dwa kolory w danej proporcji (0.0 - 1.0)."; Blockly.Msg["COLOUR_PICKER_HELPURL"] = "https://en.wikipedia.org/wiki/Color"; Blockly.Msg["COLOUR_PICKER_TOOLTIP"] = "Wybierz kolor z palety."; Blockly.Msg["COLOUR_RANDOM_HELPURL"] = "http://randomcolour.com"; // untranslated Blockly.Msg["COLOUR_RANDOM_TITLE"] = "losowy kolor"; Blockly.Msg["COLOUR_RANDOM_TOOLTIP"] = "Wybierz kolor w sposób losowy."; Blockly.Msg["COLOUR_RGB_BLUE"] = "niebieski"; Blockly.Msg["COLOUR_RGB_GREEN"] = "zielony"; Blockly.Msg["COLOUR_RGB_HELPURL"] = "http://www.december.com/html/spec/colorper.html"; Blockly.Msg["COLOUR_RGB_RED"] = "czerwony"; Blockly.Msg["COLOUR_RGB_TITLE"] = "kolor z"; Blockly.Msg["COLOUR_RGB_TOOLTIP"] = "Utwórz kolor składający sie z podanej ilości czerwieni, zieleni i błękitu. Zakres wartości: 0 do 100."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK"] = "przerwij pętlę"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE"] = "przejdź do kolejnej iteracji pętli"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK"] = "Przerwij działanie pętli."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE"] = "Pomiń resztę pętli i kontynuuj w kolejnej iteracji."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_WARNING"] = "Uwaga: Ten klocek może być użyty tylko wewnątrz pętli."; Blockly.Msg["CONTROLS_FOREACH_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated Blockly.Msg["CONTROLS_FOREACH_TITLE"] = "dla każdego elementu %1 listy %2"; Blockly.Msg["CONTROLS_FOREACH_TOOLTIP"] = "Przypisz zmiennej '%1' kolejno wartość każdego elementu listy, a następnie wykonaj kilka instrukcji."; Blockly.Msg["CONTROLS_FOR_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated Blockly.Msg["CONTROLS_FOR_TITLE"] = "licz z %1 od %2 do %3 co %4 (wartość kroku)"; Blockly.Msg["CONTROLS_FOR_TOOLTIP"] = "Zmiennej '%1' przypisuje wartości z podanego zakresu z podanym interwałem i wykonuje zadane bloki."; Blockly.Msg["CONTROLS_IF_ELSEIF_TOOLTIP"] = "Dodaj warunek do klocka „jeśli”."; Blockly.Msg["CONTROLS_IF_ELSE_TOOLTIP"] = "Dodaj ostatni zawsze prawdziwy warunek do klocka „jeśli”."; Blockly.Msg["CONTROLS_IF_HELPURL"] = "https://github.com/google/blockly/wiki/IfElse"; // untranslated Blockly.Msg["CONTROLS_IF_IF_TOOLTIP"] = "Dodaj, usuń lub zmień kolejność czynności, żeby zmodyfikować ten klocek „jeśli”."; Blockly.Msg["CONTROLS_IF_MSG_ELSE"] = "w przeciwnym razie"; Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"] = "w przeciwnym razie, jeśli"; Blockly.Msg["CONTROLS_IF_MSG_IF"] = "jeśli"; Blockly.Msg["CONTROLS_IF_TOOLTIP_1"] = "Jeśli warunek jest spełniony, wykonaj zadane czynności."; Blockly.Msg["CONTROLS_IF_TOOLTIP_2"] = "Jeśli warunek jest spełniony, wykonaj pierwszy blok instrukcji. W przeciwnym razie, wykonaj drugi blok instrukcji."; Blockly.Msg["CONTROLS_IF_TOOLTIP_3"] = "Jeśli pierwszy warunek jest spełniony, wykonaj pierwszy blok instrukcji. W przeciwnym razie, jeśli drugi warunek jest spełniony, wykonaj drugi blok instrukcji."; Blockly.Msg["CONTROLS_IF_TOOLTIP_4"] = "Jeśli pierwszy warunek jest spełniony, wykonaj pierwszy blok czynności. W przeciwnym razie jeśli drugi warunek jest spełniony, wykonaj drugi blok czynności. Jeżeli żaden z warunków nie zostanie spełniony, wykonaj ostatni blok czynności."; Blockly.Msg["CONTROLS_REPEAT_HELPURL"] = "https://en.wikipedia.org/wiki/For_loop"; Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"] = "wykonaj"; Blockly.Msg["CONTROLS_REPEAT_TITLE"] = "powtórz %1 razy"; Blockly.Msg["CONTROLS_REPEAT_TOOLTIP"] = "Wykonaj niektóre instrukcje kilka razy."; Blockly.Msg["CONTROLS_WHILEUNTIL_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_UNTIL"] = "powtarzaj aż do"; Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_WHILE"] = "powtarzaj dopóki"; Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL"] = "Dopóki wyrażenie jest nieprawdziwe, wykonaj zadane czynności."; Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_WHILE"] = "Dopóki wyrażenie jest prawdziwe, wykonaj zadane czynności."; Blockly.Msg["DELETE_ALL_BLOCKS"] = "Usunąć wszystkie klocki z %1?"; Blockly.Msg["DELETE_BLOCK"] = "Usuń Klocek"; Blockly.Msg["DELETE_VARIABLE"] = "Usuń zmienną '%1'"; Blockly.Msg["DELETE_VARIABLE_CONFIRMATION"] = "Usunąć %1 wystąpień zmiennej '%2'?"; Blockly.Msg["DELETE_X_BLOCKS"] = "Usuń %1 Bloki(ów)"; Blockly.Msg["DISABLE_BLOCK"] = "Wyłącz Klocek"; Blockly.Msg["DUPLICATE_BLOCK"] = "Powiel"; Blockly.Msg["DUPLICATE_COMMENT"] = "Zduplikowany komentarz"; Blockly.Msg["ENABLE_BLOCK"] = "Włącz Blok"; Blockly.Msg["EXPAND_ALL"] = "Rozwiń Bloki"; Blockly.Msg["EXPAND_BLOCK"] = "Rozwiń Klocek"; Blockly.Msg["EXTERNAL_INPUTS"] = "Zewnętrzne Wejścia"; Blockly.Msg["HELP"] = "Pomoc"; Blockly.Msg["INLINE_INPUTS"] = "Wbudowane Wejścia"; Blockly.Msg["IOS_CANCEL"] = "Anuluj"; Blockly.Msg["IOS_ERROR"] = "Błąd"; Blockly.Msg["IOS_OK"] = "OK"; Blockly.Msg["IOS_PROCEDURES_ADD_INPUT"] = "+ Dodaj Wejście"; Blockly.Msg["IOS_PROCEDURES_ALLOW_STATEMENTS"] = "Zezwalaj na czynności."; Blockly.Msg["IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR"] = "Ta funkcja ma zduplikowane wejścia."; Blockly.Msg["IOS_PROCEDURES_INPUTS"] = "WEJŚCIA"; Blockly.Msg["IOS_VARIABLES_ADD_BUTTON"] = "Dodaj"; Blockly.Msg["IOS_VARIABLES_ADD_VARIABLE"] = "+ Dodaj Zmienną"; Blockly.Msg["IOS_VARIABLES_DELETE_BUTTON"] = "Usuń"; Blockly.Msg["IOS_VARIABLES_EMPTY_NAME_ERROR"] = "Nie możesz utworzyć funkcji bez nazwy."; Blockly.Msg["IOS_VARIABLES_RENAME_BUTTON"] = "Zmień nazwę"; Blockly.Msg["IOS_VARIABLES_VARIABLE_NAME"] = "Nazwa zmiennej"; Blockly.Msg["LISTS_CREATE_EMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; Blockly.Msg["LISTS_CREATE_EMPTY_TITLE"] = "utwórz pustą listę"; Blockly.Msg["LISTS_CREATE_EMPTY_TOOLTIP"] = "Zwraca listę o długości 0, nie zawierającą danych"; Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TITLE_ADD"] = "lista"; Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TOOLTIP"] = "Dodaj, usuń lub zmień kolejność sekcji aby przekonfigurować blok tej listy."; Blockly.Msg["LISTS_CREATE_WITH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_INPUT_WITH"] = "utwórz listę z"; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TOOLTIP"] = "Dodaj element do listy."; Blockly.Msg["LISTS_CREATE_WITH_TOOLTIP"] = "Utwórz listę z dowolną ilością elementów."; Blockly.Msg["LISTS_GET_INDEX_FIRST"] = "pierwszy"; Blockly.Msg["LISTS_GET_INDEX_FROM_END"] = "# od końca"; Blockly.Msg["LISTS_GET_INDEX_FROM_START"] = "#"; Blockly.Msg["LISTS_GET_INDEX_GET"] = "pobierz"; Blockly.Msg["LISTS_GET_INDEX_GET_REMOVE"] = "zabierz"; Blockly.Msg["LISTS_GET_INDEX_LAST"] = "ostatni"; Blockly.Msg["LISTS_GET_INDEX_RANDOM"] = "losowy"; Blockly.Msg["LISTS_GET_INDEX_REMOVE"] = "usuń"; Blockly.Msg["LISTS_GET_INDEX_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FIRST"] = "Zwraca pierwszy element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FROM"] = "Zwraca element z konkretnej pozycji na liście."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_LAST"] = "Zwraca ostatni element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_RANDOM"] = "Zwraca losowy element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST"] = "Usuwa i zwraca pierwszy element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM"] = "Usuwa i zwraca element z określonej pozycji na liście."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST"] = "Usuwa i zwraca ostatni element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM"] = "Usuwa i zwraca losowy element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST"] = "Usuwa pierwszy element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM"] = "Usuwa element z określonej pozycji na liście."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST"] = "Usuwa ostatni element z listy."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM"] = "Usuwa losowy element z listy."; Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_END"] = "do # od końca"; Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_START"] = "do #"; Blockly.Msg["LISTS_GET_SUBLIST_END_LAST"] = "do ostatniego"; Blockly.Msg["LISTS_GET_SUBLIST_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FIRST"] = "utwórz listę podrzędną od pierwszego"; Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_END"] = "utwórz listę podrzędną z # od końca"; Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_START"] = "utwórz listę podrzędną z #"; Blockly.Msg["LISTS_GET_SUBLIST_TAIL"] = ""; Blockly.Msg["LISTS_GET_SUBLIST_TOOLTIP"] = "Tworzy kopię żądanej części listy."; Blockly.Msg["LISTS_INDEX_FROM_END_TOOLTIP"] = "%1 to ostatni element."; Blockly.Msg["LISTS_INDEX_FROM_START_TOOLTIP"] = "%1 to pierwszy element."; Blockly.Msg["LISTS_INDEX_OF_FIRST"] = "znajdź pierwsze wystąpienie elementu"; Blockly.Msg["LISTS_INDEX_OF_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated Blockly.Msg["LISTS_INDEX_OF_LAST"] = "znajdź ostatanie wystąpienie elementu"; Blockly.Msg["LISTS_INDEX_OF_TOOLTIP"] = "Zwraca indeks pierwszego/ostatniego wystąpienia elementu z listy. Zwraca %1, jeśli nie zostanie znaleziony."; Blockly.Msg["LISTS_INLIST"] = "na liście"; Blockly.Msg["LISTS_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated Blockly.Msg["LISTS_ISEMPTY_TITLE"] = "%1 jest pusta"; Blockly.Msg["LISTS_ISEMPTY_TOOLTIP"] = "Zwraca \"prawda\" jeśli lista jest pusta."; Blockly.Msg["LISTS_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated Blockly.Msg["LISTS_LENGTH_TITLE"] = "długość %1"; Blockly.Msg["LISTS_LENGTH_TOOLTIP"] = "Zwraca długość listy."; Blockly.Msg["LISTS_REPEAT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_REPEAT_TITLE"] = "utwórz listę powtarzając %1 %2 razy."; Blockly.Msg["LISTS_REPEAT_TOOLTIP"] = "Tworzy listę zawierającą podaną wartość powtórzoną żądaną ilość razy."; Blockly.Msg["LISTS_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated Blockly.Msg["LISTS_REVERSE_MESSAGE0"] = "odwróć %1"; Blockly.Msg["LISTS_REVERSE_TOOLTIP"] = "Odwraca kolejność danych w kopii listy."; Blockly.Msg["LISTS_SET_INDEX_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated Blockly.Msg["LISTS_SET_INDEX_INPUT_TO"] = "jako"; Blockly.Msg["LISTS_SET_INDEX_INSERT"] = "wstaw w"; Blockly.Msg["LISTS_SET_INDEX_SET"] = "ustaw"; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST"] = "Wstawia element na początku listy."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FROM"] = "Wstawia element na żądanej pozycji listy."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_LAST"] = "Dodaj element na koniec listy."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM"] = "Wstawia element w losowym miejscu na liście."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FIRST"] = "Ustawia pierwszy element na liście."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FROM"] = "Ustawia element w określonym miejscu na liście."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_LAST"] = "Ustawia ostatni element na liście."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_RANDOM"] = "Ustawia losowy element na liście."; Blockly.Msg["LISTS_SORT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; Blockly.Msg["LISTS_SORT_ORDER_ASCENDING"] = "rosnąco"; Blockly.Msg["LISTS_SORT_ORDER_DESCENDING"] = "malejąco"; Blockly.Msg["LISTS_SORT_TITLE"] = "sortuj %1 %2 %3"; Blockly.Msg["LISTS_SORT_TOOLTIP"] = "Sortuj kopię listy."; Blockly.Msg["LISTS_SORT_TYPE_IGNORECASE"] = "alfabetycznie, ignoruj wielkość liter"; Blockly.Msg["LISTS_SORT_TYPE_NUMERIC"] = "numerycznie"; Blockly.Msg["LISTS_SORT_TYPE_TEXT"] = "alfabetycznie"; Blockly.Msg["LISTS_SPLIT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated Blockly.Msg["LISTS_SPLIT_LIST_FROM_TEXT"] = "utwórz listę z tekstu"; Blockly.Msg["LISTS_SPLIT_TEXT_FROM_LIST"] = "utwórz tekst z listy"; Blockly.Msg["LISTS_SPLIT_TOOLTIP_JOIN"] = "Łączy listę tekstów w jeden tekst, rozdzielany separatorem."; Blockly.Msg["LISTS_SPLIT_TOOLTIP_SPLIT"] = "Rozdziela tekst zgodnie z separatorem tworząc listę z powstałych elementów."; Blockly.Msg["LISTS_SPLIT_WITH_DELIMITER"] = "z separatorem"; Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "fałsz"; Blockly.Msg["LOGIC_BOOLEAN_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "Zwraca 'prawda' lub 'fałsz'."; Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "prawda"; Blockly.Msg["LOGIC_COMPARE_HELPURL"] = "https://pl.wikipedia.org/wiki/Nierówność"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_EQ"] = "Zwraca \"prawda\", jeśli wejścia są identyczne."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GT"] = "Zwraca \"prawda\" jeśli pierwsze wejście jest większe od drugiego."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GTE"] = "Zwraca \"prawda\", jeśli pierwsze wejście jest większe lub równe drugiemu."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LT"] = "Zwraca \"prawda\" jeśli pierwsze wejście jest mniejsze od drugiego."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LTE"] = "Zwraca \"prawda\", jeśli pierwsze wejście jest mniejsze lub równe drugiemu."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_NEQ"] = "Zwraca \"prawda\", jeśli wejścia nie są identyczne."; Blockly.Msg["LOGIC_NEGATE_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated Blockly.Msg["LOGIC_NEGATE_TITLE"] = "nie %1"; Blockly.Msg["LOGIC_NEGATE_TOOLTIP"] = "Zwraca \"prawda\", jeśli wejściu jest \"fałsz\". Zwraca \"fałsz\", jeśli na wejściu jest \"prawda\"."; Blockly.Msg["LOGIC_NULL"] = "nic"; Blockly.Msg["LOGIC_NULL_HELPURL"] = "https://en.wikipedia.org/wiki/Nullable_type"; Blockly.Msg["LOGIC_NULL_TOOLTIP"] = "Zwraca nic."; Blockly.Msg["LOGIC_OPERATION_AND"] = "i"; Blockly.Msg["LOGIC_OPERATION_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated Blockly.Msg["LOGIC_OPERATION_OR"] = "lub"; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_AND"] = "Zwraca \"prawda\" jeśli na obydwóch wejściach jest \"prawda\"."; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_OR"] = "Zwraca \"prawda\" jeśli co najmniej na jednyk wejściu jest \"prawda\"."; Blockly.Msg["LOGIC_TERNARY_CONDITION"] = "test"; Blockly.Msg["LOGIC_TERNARY_HELPURL"] = "https://en.wikipedia.org/wiki/%3F:"; Blockly.Msg["LOGIC_TERNARY_IF_FALSE"] = "jeśli fałsz"; Blockly.Msg["LOGIC_TERNARY_IF_TRUE"] = "jeśli prawda"; Blockly.Msg["LOGIC_TERNARY_TOOLTIP"] = "Sprawdź warunek w „test”. Jeśli warunek jest prawdziwy, to zwróci „jeśli prawda”; jeśli nie jest prawdziwy to zwróci „jeśli fałsz”."; Blockly.Msg["MATH_ADDITION_SYMBOL"] = "+"; Blockly.Msg["MATH_ARITHMETIC_HELPURL"] = "https://pl.wikipedia.org/wiki/Arytmetyka"; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_ADD"] = "Zwróć sumę dwóch liczb."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_DIVIDE"] = "Zwróć iloraz dwóch liczb."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MINUS"] = "Zwróć różnicę dwóch liczb."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MULTIPLY"] = "Zwróć iloczyn dwóch liczb."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_POWER"] = "Zwróć pierwszą liczbę podniesioną do potęgi o wykładniku drugiej liczby."; Blockly.Msg["MATH_ATAN2_HELPURL"] = "https://en.wikipedia.org/wiki/Atan2"; // untranslated Blockly.Msg["MATH_ATAN2_TITLE"] = "atan2 of X:%1 Y:%2"; // untranslated Blockly.Msg["MATH_ATAN2_TOOLTIP"] = "Return the arctangent of point (X, Y) in degrees from -180 to 180."; // untranslated Blockly.Msg["MATH_CHANGE_HELPURL"] = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; Blockly.Msg["MATH_CHANGE_TITLE"] = "zmień %1 o %2"; Blockly.Msg["MATH_CHANGE_TOOLTIP"] = "Dodaj liczbę do zmiennej '%1'."; Blockly.Msg["MATH_CONSTANT_HELPURL"] = "https://pl.wikipedia.org/wiki/Stała_(matematyka)"; Blockly.Msg["MATH_CONSTANT_TOOLTIP"] = "Zwróć jedną wspólną stałą: π (3.141), e (2.718...), φ (1.618...), sqrt(2) (1.414...), sqrt(½) (0.707...) lub ∞ (nieskończoność)."; Blockly.Msg["MATH_CONSTRAIN_HELPURL"] = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated Blockly.Msg["MATH_CONSTRAIN_TITLE"] = "ogranicz %1 z dołu %2 z góry %3"; Blockly.Msg["MATH_CONSTRAIN_TOOLTIP"] = "Ogranicz liczbę, aby była w określonych granicach (włącznie)."; Blockly.Msg["MATH_DIVISION_SYMBOL"] = "/"; Blockly.Msg["MATH_IS_DIVISIBLE_BY"] = "jest podzielna przez"; Blockly.Msg["MATH_IS_EVEN"] = "jest parzysta"; Blockly.Msg["MATH_IS_NEGATIVE"] = "jest ujemna"; Blockly.Msg["MATH_IS_ODD"] = "jest nieparzysta"; Blockly.Msg["MATH_IS_POSITIVE"] = "jest dodatnia"; Blockly.Msg["MATH_IS_PRIME"] = "jest liczbą pierwszą"; Blockly.Msg["MATH_IS_TOOLTIP"] = "Sprawdź, czy liczba jest parzysta, nieparzysta, pierwsza, całkowita, dodatnia, ujemna, lub czy jest podzielna przez podaną liczbę. Zwraca wartość \"prawda\" lub \"fałsz\"."; Blockly.Msg["MATH_IS_WHOLE"] = "jest liczbą całkowitą"; Blockly.Msg["MATH_MODULO_HELPURL"] = "https://pl.wikipedia.org/wiki/Modulo"; Blockly.Msg["MATH_MODULO_TITLE"] = "reszta z dzielenia %1 przez %2"; Blockly.Msg["MATH_MODULO_TOOLTIP"] = "Zwróć resztę z dzielenia dwóch liczb przez siebie."; Blockly.Msg["MATH_MULTIPLICATION_SYMBOL"] = "×"; Blockly.Msg["MATH_NUMBER_HELPURL"] = "https://en.wikipedia.org/wiki/Number"; Blockly.Msg["MATH_NUMBER_TOOLTIP"] = "Liczba."; Blockly.Msg["MATH_ONLIST_HELPURL"] = ""; Blockly.Msg["MATH_ONLIST_OPERATOR_AVERAGE"] = "średnia elementów listy"; Blockly.Msg["MATH_ONLIST_OPERATOR_MAX"] = "maksymalna wartość z listy"; Blockly.Msg["MATH_ONLIST_OPERATOR_MEDIAN"] = "mediana listy"; Blockly.Msg["MATH_ONLIST_OPERATOR_MIN"] = "minimalna wartość z listy"; Blockly.Msg["MATH_ONLIST_OPERATOR_MODE"] = "dominanty listy"; Blockly.Msg["MATH_ONLIST_OPERATOR_RANDOM"] = "losowy element z listy"; Blockly.Msg["MATH_ONLIST_OPERATOR_STD_DEV"] = "odchylenie standardowe listy"; Blockly.Msg["MATH_ONLIST_OPERATOR_SUM"] = "suma elementów listy"; Blockly.Msg["MATH_ONLIST_TOOLTIP_AVERAGE"] = "Zwróć średnią (średnią arytmetyczną) wartości liczbowych z listy."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MAX"] = "Zwróć największą liczbę w liście."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MEDIAN"] = "Zwróć medianę listy."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MIN"] = "Zwróć najmniejszą liczbę w liście."; Blockly.Msg["MATH_ONLIST_TOOLTIP_MODE"] = "Zwróć listę najczęściej występujących elementów w liście."; Blockly.Msg["MATH_ONLIST_TOOLTIP_RANDOM"] = "Zwróć losowy element z listy."; Blockly.Msg["MATH_ONLIST_TOOLTIP_STD_DEV"] = "Zwróć odchylenie standardowe listy."; Blockly.Msg["MATH_ONLIST_TOOLTIP_SUM"] = "Zwróć sumę wszystkich liczb z listy."; Blockly.Msg["MATH_POWER_SYMBOL"] = "^"; Blockly.Msg["MATH_RANDOM_FLOAT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg["MATH_RANDOM_FLOAT_TITLE_RANDOM"] = "losowy ułamek"; Blockly.Msg["MATH_RANDOM_FLOAT_TOOLTIP"] = "Zwróć losowy ułamek między 0.0 (włącznie), a 1.0 (wyłącznie)."; Blockly.Msg["MATH_RANDOM_INT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg["MATH_RANDOM_INT_TITLE"] = "losowa liczba całkowita od %1 do %2"; Blockly.Msg["MATH_RANDOM_INT_TOOLTIP"] = "Zwróć losową liczbę całkowitą w ramach dwóch wyznaczonych granic, włącznie."; Blockly.Msg["MATH_ROUND_HELPURL"] = "https://pl.wikipedia.org/wiki/Zaokrąglanie"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUND"] = "zaokrąglij"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDDOWN"] = "zaokrąglij w dół"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDUP"] = "zaokrąglij w górę"; Blockly.Msg["MATH_ROUND_TOOLTIP"] = "Zaokrąglij w górę lub w dół."; Blockly.Msg["MATH_SINGLE_HELPURL"] = "https://pl.wikipedia.org/wiki/Pierwiastek_kwadratowy"; Blockly.Msg["MATH_SINGLE_OP_ABSOLUTE"] = "wartość bezwzględna"; Blockly.Msg["MATH_SINGLE_OP_ROOT"] = "pierwiastek kwadratowy"; Blockly.Msg["MATH_SINGLE_TOOLTIP_ABS"] = "Zwróć wartość bezwzględną danej liczby."; Blockly.Msg["MATH_SINGLE_TOOLTIP_EXP"] = "Zwróć e do potęgi danej liczby."; Blockly.Msg["MATH_SINGLE_TOOLTIP_LN"] = "Zwróć logarytm naturalny danej liczby."; Blockly.Msg["MATH_SINGLE_TOOLTIP_LOG10"] = "Zwraca logarytm dziesiętny danej liczby."; Blockly.Msg["MATH_SINGLE_TOOLTIP_NEG"] = "Zwróć negację danej liczby."; Blockly.Msg["MATH_SINGLE_TOOLTIP_POW10"] = "Zwróć 10 do potęgi danej liczby."; Blockly.Msg["MATH_SINGLE_TOOLTIP_ROOT"] = "Zwróć pierwiastek kwadratowy danej liczby."; Blockly.Msg["MATH_SUBTRACTION_SYMBOL"] = "-"; Blockly.Msg["MATH_TRIG_ACOS"] = "arccos"; Blockly.Msg["MATH_TRIG_ASIN"] = "arcsin"; Blockly.Msg["MATH_TRIG_ATAN"] = "arctg"; Blockly.Msg["MATH_TRIG_COS"] = "cos"; Blockly.Msg["MATH_TRIG_HELPURL"] = "https://pl.wikipedia.org/wiki/Funkcje_trygonometryczne"; Blockly.Msg["MATH_TRIG_SIN"] = "sin"; Blockly.Msg["MATH_TRIG_TAN"] = "tg"; Blockly.Msg["MATH_TRIG_TOOLTIP_ACOS"] = "Zwróć arcus cosinus danej liczby."; Blockly.Msg["MATH_TRIG_TOOLTIP_ASIN"] = "Zwróć arcus sinus danej liczby."; Blockly.Msg["MATH_TRIG_TOOLTIP_ATAN"] = "Zwróć arcus tangens danej liczby."; Blockly.Msg["MATH_TRIG_TOOLTIP_COS"] = "Zwróć wartość cosinusa o stopniu (nie w radianach)."; Blockly.Msg["MATH_TRIG_TOOLTIP_SIN"] = "Zwróć wartość sinusa o stopniu (nie w radianach)."; Blockly.Msg["MATH_TRIG_TOOLTIP_TAN"] = "Zwróć tangens o stopniu (nie w radianach)."; Blockly.Msg["NEW_COLOUR_VARIABLE"] = "Utwórz zmienną colour"; Blockly.Msg["NEW_NUMBER_VARIABLE"] = "Utwórz zmienną typu number"; Blockly.Msg["NEW_STRING_VARIABLE"] = "Utwórz zmienną typu string"; Blockly.Msg["NEW_VARIABLE"] = "Utwórz zmienną..."; Blockly.Msg["NEW_VARIABLE_TITLE"] = "Nowa nazwa zmiennej:"; Blockly.Msg["NEW_VARIABLE_TYPE_TITLE"] = "Nowy typ zmiennej:"; Blockly.Msg["ORDINAL_NUMBER_SUFFIX"] = ""; Blockly.Msg["PROCEDURES_ALLOW_STATEMENTS"] = "zezwól na czynności"; Blockly.Msg["PROCEDURES_BEFORE_PARAMS"] = "z:"; Blockly.Msg["PROCEDURES_CALLNORETURN_HELPURL"] = "https://pl.wikipedia.org/wiki/Podprogram"; Blockly.Msg["PROCEDURES_CALLNORETURN_TOOLTIP"] = "Uruchom zdefiniowaną przez użytkownika funkcję '%1'."; Blockly.Msg["PROCEDURES_CALLRETURN_HELPURL"] = "https://pl.wikipedia.org/wiki/Podprogram"; Blockly.Msg["PROCEDURES_CALLRETURN_TOOLTIP"] = "Uruchom zdefiniowaną przez użytkownika funkcję '%1' i użyj jej wyjścia."; Blockly.Msg["PROCEDURES_CALL_BEFORE_PARAMS"] = "z:"; Blockly.Msg["PROCEDURES_CREATE_DO"] = "Utwórz '%1'"; Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"] = "Opisz tę funkcję..."; Blockly.Msg["PROCEDURES_DEFNORETURN_DO"] = ""; Blockly.Msg["PROCEDURES_DEFNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"] = "zrób coś"; Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"] = "do"; Blockly.Msg["PROCEDURES_DEFNORETURN_TOOLTIP"] = "Tworzy funkcję nie posiadającą wyjścia."; Blockly.Msg["PROCEDURES_DEFRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg["PROCEDURES_DEFRETURN_RETURN"] = "zwróć"; Blockly.Msg["PROCEDURES_DEFRETURN_TOOLTIP"] = "Tworzy funkcję posiadającą wyjście."; Blockly.Msg["PROCEDURES_DEF_DUPLICATE_WARNING"] = "Uwaga: Ta funkcja ma powtórzone parametry."; Blockly.Msg["PROCEDURES_HIGHLIGHT_DEF"] = "Podświetl definicję funkcji"; Blockly.Msg["PROCEDURES_IFRETURN_HELPURL"] = "http://c2.com/cgi/wiki?GuardClause"; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_TOOLTIP"] = "Jeśli warunek jest spełniony zwróć drugą wartość."; Blockly.Msg["PROCEDURES_IFRETURN_WARNING"] = "Uwaga: Ten klocek może być używany tylko w definicji funkcji."; Blockly.Msg["PROCEDURES_MUTATORARG_TITLE"] = "nazwa wejścia:"; Blockly.Msg["PROCEDURES_MUTATORARG_TOOLTIP"] = "Dodaj wejście do funkcji."; Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TITLE"] = "wejścia"; Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TOOLTIP"] = "Dodaj, usuń lub zmień kolejność wejść tej funkcji."; Blockly.Msg["REDO"] = "Ponów"; Blockly.Msg["REMOVE_COMMENT"] = "Usuń komentarz"; Blockly.Msg["RENAME_VARIABLE"] = "Zmień nazwę zmiennej..."; Blockly.Msg["RENAME_VARIABLE_TITLE"] = "Zmień nazwy wszystkich '%1' zmiennych na:"; Blockly.Msg["TEXT_APPEND_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_APPEND_TITLE"] = "dodaj tekst %2 do %1"; Blockly.Msg["TEXT_APPEND_TOOLTIP"] = "Dołącz tekst do zmiennej '%1'."; Blockly.Msg["TEXT_CHANGECASE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_LOWERCASE"] = "na małe litery"; Blockly.Msg["TEXT_CHANGECASE_OPERATOR_TITLECASE"] = "na Pierwsza Duża"; Blockly.Msg["TEXT_CHANGECASE_OPERATOR_UPPERCASE"] = "na WIELKIE LITERY"; Blockly.Msg["TEXT_CHANGECASE_TOOLTIP"] = "Zwraca kopię tekstu z odwruconą wielkością liter."; Blockly.Msg["TEXT_CHARAT_FIRST"] = "pobierz pierwszą literę"; Blockly.Msg["TEXT_CHARAT_FROM_END"] = "pobierz literę # od końca"; Blockly.Msg["TEXT_CHARAT_FROM_START"] = "pobierz literę #"; Blockly.Msg["TEXT_CHARAT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated Blockly.Msg["TEXT_CHARAT_LAST"] = "pobierz ostatnią literę"; Blockly.Msg["TEXT_CHARAT_RANDOM"] = "pobierz losową literę"; Blockly.Msg["TEXT_CHARAT_TAIL"] = ""; Blockly.Msg["TEXT_CHARAT_TITLE"] = "w tekście %1 %2"; Blockly.Msg["TEXT_CHARAT_TOOLTIP"] = "Zwraca literę z określonej pozycji."; Blockly.Msg["TEXT_COUNT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#counting-substrings"; Blockly.Msg["TEXT_COUNT_MESSAGE0"] = "policz %1 w %2"; Blockly.Msg["TEXT_COUNT_TOOLTIP"] = "Liczy ile razy dany tekst występuje w innym tekście."; Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TOOLTIP"] = "Dodaj element do tekstu."; Blockly.Msg["TEXT_CREATE_JOIN_TITLE_JOIN"] = "połącz"; Blockly.Msg["TEXT_CREATE_JOIN_TOOLTIP"] = "Dodaj, usuń lub zmień kolejność sekcji, aby zmodyfikować klocek tekstowy."; Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_END"] = "do # litery od końca"; Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_START"] = "do # litery"; Blockly.Msg["TEXT_GET_SUBSTRING_END_LAST"] = "do ostatniej litery"; Blockly.Msg["TEXT_GET_SUBSTRING_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_INPUT_IN_TEXT"] = "w tekście"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FIRST"] = "pobierz podciąg od pierwszej litery"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_END"] = "pobierz podciąg od # litery od końca"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_START"] = "pobierz podciąg od # litery"; Blockly.Msg["TEXT_GET_SUBSTRING_TAIL"] = ""; Blockly.Msg["TEXT_GET_SUBSTRING_TOOLTIP"] = "Zwraca określoną część tekstu."; Blockly.Msg["TEXT_INDEXOF_HELPURL"] = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated Blockly.Msg["TEXT_INDEXOF_OPERATOR_FIRST"] = "znajdź pierwsze wystąpienie tekstu"; Blockly.Msg["TEXT_INDEXOF_OPERATOR_LAST"] = "znajdź ostatnie wystąpienie tekstu"; Blockly.Msg["TEXT_INDEXOF_TITLE"] = "w tekście %1 %2 %3"; Blockly.Msg["TEXT_INDEXOF_TOOLTIP"] = "Zwraca indeks pierwszego/ostatniego wystąpienia pierwszego tekstu w drugim tekście. Zwraca wartość %1, jeśli tekst nie został znaleziony."; Blockly.Msg["TEXT_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated Blockly.Msg["TEXT_ISEMPTY_TITLE"] = "%1 jest pusty"; Blockly.Msg["TEXT_ISEMPTY_TOOLTIP"] = "Zwraca prawda (true), jeśli podany tekst jest pusty."; Blockly.Msg["TEXT_JOIN_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated Blockly.Msg["TEXT_JOIN_TITLE_CREATEWITH"] = "utwórz tekst z"; Blockly.Msg["TEXT_JOIN_TOOLTIP"] = "Tworzy fragment tekstu, łącząc ze sobą dowolną liczbę tekstów."; Blockly.Msg["TEXT_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_LENGTH_TITLE"] = "długość %1"; Blockly.Msg["TEXT_LENGTH_TOOLTIP"] = "Zwraca liczbę liter (łącznie ze spacjami) w podanym tekście."; Blockly.Msg["TEXT_PRINT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated Blockly.Msg["TEXT_PRINT_TITLE"] = "wydrukuj %1"; Blockly.Msg["TEXT_PRINT_TOOLTIP"] = "Wyświetl określony tekst, liczbę lub inną wartość."; Blockly.Msg["TEXT_PROMPT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated Blockly.Msg["TEXT_PROMPT_TOOLTIP_NUMBER"] = "Zapytaj użytkownika o liczbę."; Blockly.Msg["TEXT_PROMPT_TOOLTIP_TEXT"] = "Zapytaj użytkownika o jakiś tekst."; Blockly.Msg["TEXT_PROMPT_TYPE_NUMBER"] = "poproś o liczbę z tą wiadomością"; Blockly.Msg["TEXT_PROMPT_TYPE_TEXT"] = "poproś o tekst z tą wiadomością"; Blockly.Msg["TEXT_REPLACE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated Blockly.Msg["TEXT_REPLACE_MESSAGE0"] = "zamień %1 na %2 w %3"; Blockly.Msg["TEXT_REPLACE_TOOLTIP"] = "Zastąp wszystkie wystąpienia danego tekstu innym."; Blockly.Msg["TEXT_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#reversing-text"; Blockly.Msg["TEXT_REVERSE_MESSAGE0"] = "odwróć %1"; Blockly.Msg["TEXT_REVERSE_TOOLTIP"] = "Odwraca kolejność znaków w tekście."; Blockly.Msg["TEXT_TEXT_HELPURL"] = "https://pl.wikipedia.org/wiki/Tekstowy_typ_danych"; Blockly.Msg["TEXT_TEXT_TOOLTIP"] = "Litera, wyraz lub linia tekstu."; Blockly.Msg["TEXT_TRIM_HELPURL"] = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_BOTH"] = "usuń spacje po obu stronach"; Blockly.Msg["TEXT_TRIM_OPERATOR_LEFT"] = "usuń spacje z lewej strony"; Blockly.Msg["TEXT_TRIM_OPERATOR_RIGHT"] = "usuń spacje z prawej strony"; Blockly.Msg["TEXT_TRIM_TOOLTIP"] = "Zwraca kopię tekstu z usuniętymi spacjami z jednego lub z obu końców tekstu."; Blockly.Msg["TODAY"] = "Dzisiaj"; Blockly.Msg["UNDO"] = "Cofnij"; Blockly.Msg["UNNAMED_KEY"] = "bez nazwy"; Blockly.Msg["VARIABLES_DEFAULT_NAME"] = "element"; Blockly.Msg["VARIABLES_GET_CREATE_SET"] = "Utwórz klocek 'ustaw %1'"; Blockly.Msg["VARIABLES_GET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated Blockly.Msg["VARIABLES_GET_TOOLTIP"] = "Zwraca wartość tej zmiennej."; Blockly.Msg["VARIABLES_SET"] = "przypisz %1 wartość %2"; Blockly.Msg["VARIABLES_SET_CREATE_GET"] = "Utwórz klocek 'pobierz %1'"; Blockly.Msg["VARIABLES_SET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated Blockly.Msg["VARIABLES_SET_TOOLTIP"] = "Wartości zmiennej i wejście będą identyczne."; Blockly.Msg["VARIABLE_ALREADY_EXISTS"] = "Zmienna o nazwie '%1' już istnieje."; Blockly.Msg["VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE"] = "Zmienna o nazwie '%1' już istnieje i jest typu '%2'."; Blockly.Msg["WORKSPACE_COMMENT_DEFAULT_TEXT"] = "Powiedz coś..."; Blockly.Msg["CONTROLS_FOREACH_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_FOR_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_IF_ELSEIF_TITLE_ELSEIF"] = Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"]; Blockly.Msg["CONTROLS_IF_ELSE_TITLE_ELSE"] = Blockly.Msg["CONTROLS_IF_MSG_ELSE"]; Blockly.Msg["CONTROLS_IF_IF_TITLE_IF"] = Blockly.Msg["CONTROLS_IF_MSG_IF"]; Blockly.Msg["CONTROLS_IF_MSG_THEN"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_WHILEUNTIL_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TITLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["LISTS_GET_INDEX_HELPURL"] = Blockly.Msg["LISTS_INDEX_OF_HELPURL"]; Blockly.Msg["LISTS_GET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_GET_SUBLIST_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_INDEX_OF_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_SET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["MATH_CHANGE_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["PROCEDURES_DEFRETURN_COMMENT"] = Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"]; Blockly.Msg["PROCEDURES_DEFRETURN_DO"] = Blockly.Msg["PROCEDURES_DEFNORETURN_DO"]; Blockly.Msg["PROCEDURES_DEFRETURN_PROCEDURE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"]; Blockly.Msg["PROCEDURES_DEFRETURN_TITLE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"]; Blockly.Msg["TEXT_APPEND_VARIABLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["MATH_HUE"] = "230"; Blockly.Msg["LOOPS_HUE"] = "120"; Blockly.Msg["LISTS_HUE"] = "260"; Blockly.Msg["LOGIC_HUE"] = "210"; Blockly.Msg["VARIABLES_HUE"] = "330"; Blockly.Msg["TEXTS_HUE"] = "160"; Blockly.Msg["PROCEDURES_HUE"] = "290"; Blockly.Msg["COLOUR_HUE"] = "20"; Blockly.Msg["VARIABLES_DYNAMIC_HUE"] = "310"; return Blockly.Msg; }));
// This file was automatically generated. Do not modify. 'use strict'; goog.provide('Blockly.Msg.az'); goog.require('Blockly.Msg'); Blockly.Msg.ADD_COMMENT = "Şərh əlavə et"; Blockly.Msg.CHANGE_VALUE_TITLE = "Qiyməti dəyiş:"; Blockly.Msg.CLEAN_UP = "Blokları təmizlə"; Blockly.Msg.COLLAPSE_ALL = "Blokları yığ"; Blockly.Msg.COLLAPSE_BLOCK = "Bloku yığ"; Blockly.Msg.COLOUR_BLEND_COLOUR1 = "rəng 1"; Blockly.Msg.COLOUR_BLEND_COLOUR2 = "rəng 2"; Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; Blockly.Msg.COLOUR_BLEND_RATIO = "nisbət"; Blockly.Msg.COLOUR_BLEND_TITLE = "qarışdır"; Blockly.Msg.COLOUR_BLEND_TOOLTIP = "İki rəngi verilmiş nisbətdə (0,0 - 1,0) qarışdırır."; Blockly.Msg.COLOUR_PICKER_HELPURL = "https://az.wikipedia.org/wiki/Rəng"; Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Palitradan bir rəng seçin."; Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated Blockly.Msg.COLOUR_RANDOM_TITLE = "təsadüfi rəng"; Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Təsadüfi bir rəng seçin."; Blockly.Msg.COLOUR_RGB_BLUE = "mavi"; Blockly.Msg.COLOUR_RGB_GREEN = "yaşıl"; Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; Blockly.Msg.COLOUR_RGB_RED = "qırmızı"; Blockly.Msg.COLOUR_RGB_TITLE = "rənglə"; Blockly.Msg.COLOUR_RGB_TOOLTIP = "Qırmızı, yaşıl və mavinin göstərilən miqdarı ilə bir rəng düzəlt. Bütün qiymətlər 0 ilə 100 arasında olmalıdır."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "dövrdən çıx"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "dövrün növbəti addımından davam et"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Cari dövrdən çıx."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Bu dövrün qalanını ötür və növbəti addımla davam et."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Xəbərdarlıq: Bu blok ancaq dövr daxilində istifadə oluna bilər."; Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated Blockly.Msg.CONTROLS_FOREACH_TITLE = "hər element üçün %1 siyahıda %2"; Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Siyahıdakı hər element üçün \"%1\" dəyişənini elementə mənimsət və bundan sonra bəzi əmrləri yerinə yetir."; Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated Blockly.Msg.CONTROLS_FOR_TITLE = "say: %1 %2 ilə başlayıb, %3 qiymətinə kimi %4 qədər dəyiş"; Blockly.Msg.CONTROLS_FOR_TOOLTIP = "\"%1\" dəyişəni başlanğıc ədəddən son ədədə qədər göstərilən aralıqla qiymətlər aldıqca göstərilən blokları yerinə yetir."; Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "\"Əgər\" blokuna bir şərt əlavə et."; Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "\"Əgər\" blokuna qalan bütün halları əhatə edəb son bir şərt əlavə et."; Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Bu \"əgər\" blokunu dəyişdirmək üçün bölümlərin yenisini əlavə et, sil və ya yerini dəyiş."; Blockly.Msg.CONTROLS_IF_MSG_ELSE = "əks halda"; Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "əks halda əgər"; Blockly.Msg.CONTROLS_IF_MSG_IF = "əgər"; Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Əgər qiymət doğrudursa, onda bəzi əmrləri yerinə yetir."; Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Əgər qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda isə ikinci əmrlər blokunu yerinə yetir."; Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir."; Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir. Əgər qiymətlərdən heç biri doğru deyilsə, onda axırıncı əmrlər blokunu yerinə yetir."; Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://az.wikipedia.org/wiki/For_loop"; Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "icra et"; Blockly.Msg.CONTROLS_REPEAT_TITLE = "%1 dəfə təkrar et"; Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Bəzi əmrləri bir neçə dəfə yerinə yetir."; Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "təkrar et, ta ki"; Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "təkrar et, hələ ki"; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Hələ ki, qiymət \"yalan\"dır, bəzi əmrləri yerinə yetir."; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Hələ ki, qiymət \"doğru\"dur, bəzi əmrləri yerinə yetir."; Blockly.Msg.DELETE_ALL_BLOCKS = "Bütün %1 blok silinsin?"; Blockly.Msg.DELETE_BLOCK = "Bloku sil"; Blockly.Msg.DELETE_VARIABLE = "Delete the '%1' variable"; // untranslated Blockly.Msg.DELETE_VARIABLE_CONFIRMATION = "Delete %1 uses of the '%2' variable?"; // untranslated Blockly.Msg.DELETE_X_BLOCKS = "%1 bloku sil"; Blockly.Msg.DISABLE_BLOCK = "Bloku söndür"; Blockly.Msg.DUPLICATE_BLOCK = "Dublikat"; Blockly.Msg.ENABLE_BLOCK = "Bloku aktivləşdir"; Blockly.Msg.EXPAND_ALL = "Blokları aç"; Blockly.Msg.EXPAND_BLOCK = "Bloku aç"; Blockly.Msg.EXTERNAL_INPUTS = "Xarici girişlər"; Blockly.Msg.HELP = "Kömək"; Blockly.Msg.INLINE_INPUTS = "Sətiriçi girişlər"; Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "boş siyahı düzəlt"; Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Heç bir verilən qeyd olunmamış, uzunluğu 0 olan bir siyahı verir"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "siyahı"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Bu siyahı blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin."; Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "bunlardan siyahı düzəlt"; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Siyahıya element əlavə edin."; Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "İstənilən ölçülü siyahı yaradın."; Blockly.Msg.LISTS_GET_INDEX_FIRST = "birinci"; Blockly.Msg.LISTS_GET_INDEX_FROM_END = "axırdan # nömrəli"; Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; Blockly.Msg.LISTS_GET_INDEX_GET = "götür"; Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "götür və sil"; Blockly.Msg.LISTS_GET_INDEX_LAST = "axırıncı"; Blockly.Msg.LISTS_GET_INDEX_RANDOM = "təsadüfi"; Blockly.Msg.LISTS_GET_INDEX_REMOVE = "yığışdır"; Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Siyahının ilk elementini qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM = "Siyahıdan təyin olunmuş indeksli elementi qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Siyahının son elementini qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Siyahıdan hər hansı təsadüfi elementi qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Siyahıdan ilk elementi silir və qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM = "Siyahıdan təyin olunmuş indeksli elementi silir və qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Siyahıdan son elementi silir və qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Siyahıdan təsadufi elementi silir və qaytarır."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Siyahıdan ilk elementi silir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM = "Siyahıdan təyin olunmuş indeksli elementi silir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Siyahıdan son elementi silir."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Siyahıdan təsadüfi bir elementi silir."; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "sondan # nömrəliyə"; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "# nömrəliyə"; Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "Sonuncuya"; Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "Birincidən alt-siyahını alın"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "# sonuncudan alt-siyahını alın"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "# - dən alt-siyahını alın"; Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Siyahının təyin olunmuş hissəsinin surətini yaradın."; Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP = "%1 son elementdir."; Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP = "%1 ilk elementdir."; Blockly.Msg.LISTS_INDEX_OF_FIRST = "Element ilə ilk rastlaşma indeksini müəyyən edin"; Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated Blockly.Msg.LISTS_INDEX_OF_LAST = "Element ilə son rastlaşma indeksini müəyyən edin"; Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Siyahıda element ilə ilk/son rastlaşma indeksini qaytarır. Əgər tekst siyahıda tapılmazsa, %1 qaytarılır."; Blockly.Msg.LISTS_INLIST = "siyahıda"; Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 boşdur"; Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "Siyahı boşdursa \"doğru\" cavabını qaytarır."; Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated Blockly.Msg.LISTS_LENGTH_TITLE = "%1 siyahısının uzunluğu"; Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Siyahının uzunluğunu verir."; Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg.LISTS_REPEAT_TITLE = "%1 elementinin %2 dəfə təkrarlandığı siyahı düzəlt"; Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Təyin olunmuş elementin/qiymətin təyin olunmuş sayda təkrarlandığı siyahını yaradır."; Blockly.Msg.LISTS_REVERSE_HELPURL = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated Blockly.Msg.LISTS_REVERSE_MESSAGE0 = "reverse %1"; // untranslated Blockly.Msg.LISTS_REVERSE_TOOLTIP = "Reverse a copy of a list."; // untranslated Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "Kimi"; Blockly.Msg.LISTS_SET_INDEX_INSERT = "daxil et"; Blockly.Msg.LISTS_SET_INDEX_SET = "təyin et"; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Elementi siyahının əvvəlinə daxil edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM = "Elementi siyahıda göstərilən yerə daxil edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Elementi siyahının sonuna artırır."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Elementi siyahıda təsadüfi seçilmiş bir yerə atır."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Siyahıda birinci elementi təyin edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM = "Siyahının göstərilən yerdəki elementini təyin edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Siyahının sonuncu elementini təyin edir."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Siyahının təsadüfi seçilmiş bir elementini təyin edir."; Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; // untranslated Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "ascending"; // untranslated Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "descending"; // untranslated Blockly.Msg.LISTS_SORT_TITLE = "sort %1 %2 %3"; // untranslated Blockly.Msg.LISTS_SORT_TOOLTIP = "Sort a copy of a list."; // untranslated Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "alphabetic, ignore case"; // untranslated Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "numeric"; // untranslated Blockly.Msg.LISTS_SORT_TYPE_TEXT = "alphabetic"; // untranslated Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "make list from text"; // untranslated Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "make text from list"; // untranslated Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Join a list of texts into one text, separated by a delimiter."; // untranslated Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Split text into a list of texts, breaking at each delimiter."; // untranslated Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "with delimiter"; // untranslated Blockly.Msg.LOGIC_BOOLEAN_FALSE = "səhf"; Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "\"doğru\" və ya \"səhf\" cavanını qaytarır."; Blockly.Msg.LOGIC_BOOLEAN_TRUE = "doğru"; Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://az.wikipedia.org/wiki/bərabərsizlik_(riyazi)"; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Girişlər bir birinə bərabərdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Birinci giriş ikincidən böyükdürsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Birinci giriş ikincidən böyük və ya bərarbərdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Birinci giriş ikincidən kiçikdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Birinci giriş ikincidən kiçik və ya bərarbərdirsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Girişlər bərabər deyillərsə \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated Blockly.Msg.LOGIC_NEGATE_TITLE = "%1 deyil"; Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Giriş \"yalan\"-dursa \"doğru\" cavabını qaytarır. Giriş \"doğru\"-dursa \"səhf\" cavabını qaytarır."; Blockly.Msg.LOGIC_NULL = "boş"; Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated Blockly.Msg.LOGIC_NULL_TOOLTIP = "Boş cavab qaytarır."; Blockly.Msg.LOGIC_OPERATION_AND = "və"; Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated Blockly.Msg.LOGIC_OPERATION_OR = "və ya"; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Hər iki giriş \"doğru\"-dursa \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Girişlərdən heç olmasa biri \"doğru\"-dursa \"doğru\" cavabını qaytarır."; Blockly.Msg.LOGIC_TERNARY_CONDITION = "test"; Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "əgər səhfdirsə"; Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "əgər doğrudursa"; Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "'Yoxla' əmrindəki şərtə nəzər yetirin. Əgər şərt \"doğru\"-dursa \"əgər doğru\", əks halda isə \"əgər yalan\" cavabını qaytarır."; Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://az.wikipedia.org/wiki/Hesab"; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "İki ədədin cəmini qaytarır."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "İki ədədin nisbətini qaytarır."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "İki ədədin fərqini qaytarır."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "İki ədədin hasilini verir."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Birinci ədədin ikinci ədəd dərəcəsindən qüvvətini qaytarır."; Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; // untranslated Blockly.Msg.MATH_CHANGE_TITLE = "dəyiş: %1 buna: %2"; Blockly.Msg.MATH_CHANGE_TOOLTIP = "'%1' dəyişəninin üzərinə bir ədəd artır."; Blockly.Msg.MATH_CONSTANT_HELPURL = "https://az.wikipedia.org/wiki/Riyazi_sabitlər"; Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Ümumi sabitlərdən birini qaytarır π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), və ya ∞ (sonsuzluq)."; Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated Blockly.Msg.MATH_CONSTRAIN_TITLE = "%1 üçün ən aşağı %2, ən yuxarı %3 olmağı tələb et"; Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Bir ədədin verilmiş iki ədəd arasında olmasını tələb edir (sərhədlər də daxil olmaqla)."; Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; Blockly.Msg.MATH_IS_DIVISIBLE_BY = "bölünür"; Blockly.Msg.MATH_IS_EVEN = "cütdür"; Blockly.Msg.MATH_IS_NEGATIVE = "mənfidir"; Blockly.Msg.MATH_IS_ODD = "təkdir"; Blockly.Msg.MATH_IS_POSITIVE = "müsətdir"; Blockly.Msg.MATH_IS_PRIME = "sadədir"; Blockly.Msg.MATH_IS_TOOLTIP = "Bir ədədin cüt, tək, sadə, tam, müsbət, mənfi olmasını və ya müəyyən bir ədədə bölünməsini yoxlayır. \"Doğru\" və ya \"yalan\" qiymətini qaytarır."; Blockly.Msg.MATH_IS_WHOLE = "tamdır"; Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; // untranslated Blockly.Msg.MATH_MODULO_TITLE = "%1 ÷ %2 bölməsinin qalığı"; Blockly.Msg.MATH_MODULO_TOOLTIP = "İki ədədin nisbətindən alınan qalığı qaytarır."; Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; Blockly.Msg.MATH_NUMBER_HELPURL = "https://az.wikipedia.org/wiki/Ədəd"; Blockly.Msg.MATH_NUMBER_TOOLTIP = "Ədəd."; Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "siyahının ədədi ortası"; Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "siyahının maksimumu"; Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "siyahının medianı"; Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "siyahının minimumu"; Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "Siyahı modları( Ən çox rastlaşılan elementləri)"; Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "siyahıdan təsadüfi seçilmiş bir element"; Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "Siyahının standart deviasiyası"; Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "Siyahının cəmi"; Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Siyahıdaki ədədlərin ədədi ortasını qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Siyahıdaki ən böyük elementi qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Siyahının median elementini qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Siyahıdaki ən kiçik ədədi qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Siyahıdaki ən çox rastlanan element(lər)dən ibarət siyahı qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Siyahıdan təsadüfi bir element qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Siyahının standart deviasiyasını qaytarır."; Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Siyahıdakı bütün ədədlərin cəmini qaytarır."; Blockly.Msg.MATH_POWER_SYMBOL = "^"; Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "təsadüfi kəsr"; Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "0.0 (daxil olmaqla) və 1.0 (daxil olmamaqla) ədədlərinin arasından təsadüfi bir kəsr ədəd qaytarır."; Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated Blockly.Msg.MATH_RANDOM_INT_TITLE = "%1 ilə %2 arasından təsadüfi tam ədəd"; Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Verilmiş iki ədəd arasından (ədədrlər də daxil olmaqla) təsadüfi bir tam ədəd qaytarır."; Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; // untranslated Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "yuvarlaqlaşdır"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "aşağı yuvarlaqlaşdır"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "yuxarı yuvarlaqlaşdır"; Blockly.Msg.MATH_ROUND_TOOLTIP = "Ədədi aşağı və ya yuxari yuvarlaqşdır."; Blockly.Msg.MATH_SINGLE_HELPURL = "https://az.wikipedia.org/wiki/Kvadrat_kökləri"; Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "modul"; Blockly.Msg.MATH_SINGLE_OP_ROOT = "kvadrat kök"; Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Ədədin modulunu qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "e sabitinin verilmiş ədədə qüvvətini qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Ədədin natural loqarifmini tapır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Ədədin 10-cu dərəcədən loqarifmini tapır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Ədədin əksini qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "10-un verilmiş ədədə qüvvətini qaytarır."; Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Ədədin kvadrat kökünü qaytarır."; Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; Blockly.Msg.MATH_TRIG_ACOS = "arccos"; Blockly.Msg.MATH_TRIG_ASIN = "arcsin"; Blockly.Msg.MATH_TRIG_ATAN = "arctan"; Blockly.Msg.MATH_TRIG_COS = "cos"; Blockly.Msg.MATH_TRIG_HELPURL = "https://az.wikipedia.org/wiki/Triqonometrik_funksiyalar"; Blockly.Msg.MATH_TRIG_SIN = "sin"; Blockly.Msg.MATH_TRIG_TAN = "tg"; Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Ədədin arccosinusunu qaytarır."; Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Ədədin arcsinusunu qaytarır."; Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Ədədin arctanqensini qaytarır."; Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Dərəcənin kosinusunu qaytarır (radianın yox)."; Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Dərəcənin sinusunu qaytar (radianın yox)."; Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Dərəcənin tangensini qaytar (radianın yox)."; Blockly.Msg.NEW_VARIABLE = "Yeni dəyişən..."; Blockly.Msg.NEW_VARIABLE_TITLE = "Yeni dəyişənin adı:"; Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "allow statements"; // untranslated Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "ilə:"; Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır."; Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır və nəticəni istifadə et."; Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "ilə:"; Blockly.Msg.PROCEDURES_CREATE_DO = "'%1' yarat"; Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Describe this function..."; // untranslated Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "hansısa əməliyyat"; Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "icra et:"; Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Nəticəsi olmayan funksiya yaradır."; Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "qaytar"; Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Nəticəsi olan funksiya yaradır."; Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Xəbərdarlıq: Bu funksiyanın təkrar olunmuş parametrləri var."; Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Funksiyanın təyinatını vurğula"; Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause"; // untranslated Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Əgər bir dəyər \"doğru\"-dursa onda ikinci dəyəri qaytar."; Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Xəbərdarlıq: Bu blok ancaq bir funksiyanın təyinatı daxilində işlədilə bilər."; Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "Giriş adı:"; Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Add an input to the function."; // untranslated Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "girişlər"; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Add, remove, or reorder inputs to this function."; // untranslated Blockly.Msg.REDO = "Redo"; // untranslated Blockly.Msg.REMOVE_COMMENT = "Şərhi sil"; Blockly.Msg.RENAME_VARIABLE = "Dəyişənin adını dəyiş..."; Blockly.Msg.RENAME_VARIABLE_TITLE = "Bütün '%1' dəyişənlərinin adını buna dəyiş:"; Blockly.Msg.TEXT_APPEND_APPENDTEXT = "bu mətni əlavə et:"; Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg.TEXT_APPEND_TO = "bu mətnin sonuna:"; Blockly.Msg.TEXT_APPEND_TOOLTIP = "'%1' dəyişəninin sonuna nəsə əlavə et."; Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "kiçik hərflərlə"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "Baş Hərflərlə"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "BÖYÜK HƏRFLƏRLƏ"; Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Mətndə hərflərin böyük-kiçikliyini dəyiş."; Blockly.Msg.TEXT_CHARAT_FIRST = "birinci hərfi götür"; Blockly.Msg.TEXT_CHARAT_FROM_END = "axırdan bu nömrəli hərfi götür"; Blockly.Msg.TEXT_CHARAT_FROM_START = "bu nömrəli hərfi götür"; Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "növbəti mətndə"; Blockly.Msg.TEXT_CHARAT_LAST = "axırıncı hərfi götür"; Blockly.Msg.TEXT_CHARAT_RANDOM = "təsadüfi hərf götür"; Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Göstərilən mövqedəki hərfi qaytarır."; Blockly.Msg.TEXT_COUNT_HELPURL = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated Blockly.Msg.TEXT_COUNT_MESSAGE0 = "count %1 in %2"; // untranslated Blockly.Msg.TEXT_COUNT_TOOLTIP = "Count how many times some text occurs within some other text."; // untranslated Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Mətnə bir element əlavə et."; Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "birləşdir"; Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Bu mətn blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin."; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "axırdan bu nömrəli hərfə qədər"; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "bu nömrəli hərfə qədər"; Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "son hərfə qədər"; Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "mətndə"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "Mətnin surətini ilk hərfdən"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "Mətnin surətini sondan bu nömrəli # hərfdən"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "Mətnin surətini bu nömrəli hərfdən"; Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Mətnin təyin olunmuş hissəsini qaytarır."; Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "mətndə"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "Bu mətn ilə ilk rastlaşmanı tap:"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "Bu mətn ilə son rastlaşmanı tap:"; Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Birinci mətnin ikinci mətndə ilk/son rastlaşma indeksini qaytarır. Əgər rastlaşma baş verməzsə, %1 qaytarır."; Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 boşdur"; Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Verilmiş mətn boşdursa, doğru qiymətini qaytarır."; Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "Verilmişlərlə mətn yarat"; Blockly.Msg.TEXT_JOIN_TOOLTIP = "İxtiyari sayda elementlərinin birləşməsi ilə mətn parçası yarat."; Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg.TEXT_LENGTH_TITLE = "%1 - ın uzunluğu"; Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Verilmiş mətndəki hərflərin(sözlər arası boşluqlar sayılmaqla) sayını qaytarır."; Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated Blockly.Msg.TEXT_PRINT_TITLE = "%1 - i çap elə"; Blockly.Msg.TEXT_PRINT_TOOLTIP = "Təyin olunmuş mətn, ədəd və ya hər hansı bir başqa elementi çap elə."; Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğu/tələb göndərin."; Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğu/tələb göndərin."; Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğunu/tələbi ismarıc kimi göndərin"; Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğunu/tələbi ismarıc ilə göndərin"; Blockly.Msg.TEXT_REPLACE_HELPURL = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated Blockly.Msg.TEXT_REPLACE_MESSAGE0 = "replace %1 with %2 in %3"; // untranslated Blockly.Msg.TEXT_REPLACE_TOOLTIP = "Replace all occurances of some text within some other text."; // untranslated Blockly.Msg.TEXT_REVERSE_HELPURL = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated Blockly.Msg.TEXT_REVERSE_MESSAGE0 = "reverse %1"; // untranslated Blockly.Msg.TEXT_REVERSE_TOOLTIP = "Reverses the order of the characters in the text."; // untranslated Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; // untranslated Blockly.Msg.TEXT_TEXT_TOOLTIP = "Mətndəki hərf, söz və ya sətir."; Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "Boşluqları hər iki tərəfdən pozun"; Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "Boşluqlari yalnız sol tərəfdən pozun"; Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "Boşluqları yalnız sağ tərəfdən pozun"; Blockly.Msg.TEXT_TRIM_TOOLTIP = "Mətnin hər iki və ya yalnız bir tərəfdən olan boşluqları pozulmuş surətini qaytarın."; Blockly.Msg.TODAY = "Bugün"; Blockly.Msg.UNDO = "Undo"; // untranslated Blockly.Msg.VARIABLES_DEFAULT_NAME = "element"; Blockly.Msg.VARIABLES_GET_CREATE_SET = "'%1 - i təyin et' - i yarat"; Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated Blockly.Msg.VARIABLES_GET_TOOLTIP = "Bu dəyişənin qiymətini qaytarır."; Blockly.Msg.VARIABLES_SET = "%1 - i bu qiymət ilə təyin et: %2"; Blockly.Msg.VARIABLES_SET_CREATE_GET = "'%1 - i götür' - ü yarat"; Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated Blockly.Msg.VARIABLES_SET_TOOLTIP = "Bu dəyişəni daxil edilmiş qiymətə bərabər edir."; Blockly.Msg.VARIABLE_ALREADY_EXISTS = "A variable named '%1' already exists."; // untranslated Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE; Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF; Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE; Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO; Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF; Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL; Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT; Blockly.Msg.MATH_HUE = "230"; Blockly.Msg.LOOPS_HUE = "120"; Blockly.Msg.LISTS_HUE = "260"; Blockly.Msg.LOGIC_HUE = "210"; Blockly.Msg.VARIABLES_HUE = "330"; Blockly.Msg.TEXTS_HUE = "160"; Blockly.Msg.PROCEDURES_HUE = "290"; Blockly.Msg.COLOUR_HUE = "20";
Clazz.declarePackage ("JV"); Clazz.load (["JU.A4", "$.M3", "$.M4", "$.P3", "$.P3i", "$.V3", "J.c.STER", "JU.Point3fi"], "JV.TransformManager", ["java.lang.Boolean", "$.Float", "java.util.Hashtable", "JU.P4", "$.Quat", "$.SB", "J.api.Interface", "JU.Escape", "$.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.vwr = null; this.movetoThread = null; this.vibrationThread = null; this.spinThread = null; this.perspectiveModel = 11; this.cameraScaleFactor = 0; this.referencePlaneOffset = 0; this.aperatureAngle = 0; this.cameraDistanceFromCenter = 0; this.modelCenterOffset = 0; this.modelRadius = 0; this.modelRadiusPixels = 0; this.navigationCenter = null; this.navigationOffset = null; this.navigationShiftXY = null; this.navigationDepthPercent = 0; this.matrixTemp = null; this.vectorTemp = null; this.haveNotifiedNaN = false; this.spinX = 0; this.spinY = 30; this.spinZ = 0; this.spinFps = 30; this.navX = 0; this.navY = 0; this.navZ = 0; this.navFps = NaN; this.isSpinInternal = false; this.isSpinFixed = false; this.isSpinSelected = false; this.doTransform4D = false; this.fixedRotationOffset = null; this.fixedRotationCenter = null; this.perspectiveOffset = null; this.perspectiveShiftXY = null; this.rotationCenterDefault = null; this.rotationRadiusDefault = 0; this.fixedRotationAxis = null; this.internalRotationAxis = null; this.internalTranslation = null; this.internalRotationCenter = null; this.internalRotationAngle = 0; this.matrixRotate = null; this.matrixTemp3 = null; this.matrixTemp4 = null; this.axisangleT = null; this.vectorT = null; this.vectorT2 = null; this.pointT2 = null; this.rotationAxis = null; this.rotationRate = 0; this.fixedTranslation = null; this.camera = null; this.cameraSetting = null; this.xTranslationFraction = 0.5; this.yTranslationFraction = 0.5; this.prevZoomSetting = 0; this.previousX = 0; this.previousY = 0; this.zoomEnabled = true; this.zmPct = 100; this.zmPctSet = 100; this.zoomRatio = 0; this.slabEnabled = false; this.zShadeEnabled = false; this.internalSlab = false; this.slabPercentSetting = 0; this.depthPercentSetting = 0; this.slabValue = 0; this.depthValue = 0; this.zSlabPercentSetting = 50; this.zDepthPercentSetting = 0; this.zSlabPoint = null; this.zSlabValue = 0; this.zDepthValue = 0; this.slabRange = 0; this.slabPlane = null; this.depthPlane = null; this.perspectiveDepth = true; this.scale3D = false; this.cameraDepth = 3; this.cameraDepthSetting = 3; this.visualRangeAngstroms = 0; this.cameraDistance = 1000; this.width = 0; this.height = 0; this.screenPixelCount = 0; this.scalePixelsPerAngstrom = 0; this.scaleDefaultPixelsPerAngstrom = 0; this.scale3DAngstromsPerInch = 0; this.antialias = false; this.useZoomLarge = false; this.zoomHeight = false; this.screenWidth = 0; this.screenHeight = 0; this.matrixTransform = null; this.matrixTransformInv = null; this.fScrPt = null; this.iScrPt = null; this.ptVibTemp = null; this.navigating = false; this.mode = 0; this.defaultMode = 0; this.untransformedPoint = null; this.ptTest1 = null; this.ptTest2 = null; this.ptTest3 = null; this.aaTest1 = null; this.matrixTest = null; this.spinOn = false; this.navOn = false; this.spinIsGesture = false; this.vibrationOn = false; this.vibrationPeriod = 0; this.vibrationPeriodMs = 0; this.vibrationScale = 0; this.vibrationT = null; this.stereoMode = null; this.stereoColors = null; this.stereoDoubleDTI = false; this.stereoDoubleFull = false; this.stereoDegrees = NaN; this.stereoRadians = 0; this.stereoFrame = false; this.matrixStereo = null; this.windowCentered = false; this.frameOffset = null; this.frameOffsets = null; this.bsFrameOffsets = null; this.bsSelectedAtoms = null; this.ptOffset = null; this.navMode = 1; this.zoomFactor = 3.4028235E38; this.navigationSlabOffset = 0; this.nav = null; Clazz.instantialize (this, arguments); }, JV, "TransformManager"); Clazz.prepareFields (c$, function () { this.navigationCenter = new JU.P3 (); this.navigationOffset = new JU.P3 (); this.navigationShiftXY = new JU.P3 (); this.matrixTemp = new JU.M4 (); this.vectorTemp = new JU.V3 (); this.fixedRotationOffset = new JU.P3 (); this.fixedRotationCenter = new JU.P3 (); this.perspectiveOffset = new JU.P3 (); this.perspectiveShiftXY = new JU.P3 (); this.rotationCenterDefault = new JU.P3 (); this.fixedRotationAxis = new JU.A4 (); this.internalRotationAxis = new JU.A4 (); this.internalRotationCenter = JU.P3.new3 (0, 0, 0); this.matrixRotate = new JU.M3 (); this.matrixTemp3 = new JU.M3 (); this.matrixTemp4 = new JU.M4 (); this.axisangleT = new JU.A4 (); this.vectorT = new JU.V3 (); this.vectorT2 = new JU.V3 (); this.pointT2 = new JU.P3 (); this.rotationAxis = new JU.V3 (); this.fixedTranslation = new JU.P3 (); this.camera = new JU.P3 (); this.cameraSetting = new JU.P3 (); this.matrixTransform = new JU.M4 (); this.matrixTransformInv = new JU.M4 (); this.fScrPt = new JU.P3 (); this.iScrPt = new JU.P3i (); this.ptVibTemp = new JU.Point3fi (); this.untransformedPoint = new JU.P3 (); this.ptTest1 = new JU.P3 (); this.ptTest2 = new JU.P3 (); this.ptTest3 = new JU.P3 (); this.aaTest1 = new JU.A4 (); this.matrixTest = new JU.M3 (); this.vibrationT = new JU.P3 (); this.stereoMode = J.c.STER.NONE; this.matrixStereo = new JU.M3 (); this.frameOffset = new JU.P3 (); this.ptOffset = new JU.P3 (); }); Clazz.makeConstructor (c$, function () { }); c$.getTransformManager = Clazz.defineMethod (c$, "getTransformManager", function (vwr, width, height, is4D) { var me = (is4D ? J.api.Interface.getInterface ("JV.TransformManager4D", vwr, "tm") : new JV.TransformManager ()); me.vwr = vwr; me.setScreenParameters (width, height, true, false, true, true); return me; }, "JV.Viewer,~N,~N,~B"); Clazz.defineMethod (c$, "setDefaultPerspective", function () { this.setCameraDepthPercent (3.0, true); this.setPerspectiveDepth (true); this.setStereoDegrees (-5); this.visualRangeAngstroms = 5.0; this.setSpinOff (); this.setVibrationPeriod (0); }); Clazz.defineMethod (c$, "homePosition", function (resetSpin) { if (resetSpin) this.setSpinOff (); this.setNavOn (false); this.navFps = 10; this.navX = this.navY = this.navZ = 0; this.rotationCenterDefault.setT (this.vwr.getBoundBoxCenter ()); this.setFixedRotationCenter (this.rotationCenterDefault); this.rotationRadiusDefault = this.setRotationRadius (0, true); this.windowCentered = true; this.setRotationCenterAndRadiusXYZ (null, true); this.resetRotation (); var m = this.vwr.ms.getInfoM ("defaultOrientationMatrix"); if (m != null) this.setRotation (m); this.setZoomEnabled (true); this.zoomToPercent (this.vwr.g.modelKitMode ? 50 : 100); this.zmPct = this.zmPctSet; this.slabReset (); this.resetFitToScreen (true); if (this.vwr.isJmolDataFrame ()) { this.fixedRotationCenter.set (0, 0, 0); } else { if (this.vwr.g.axesOrientationRasmol) this.matrixRotate.setAsXRotation (3.141592653589793); }this.vwr.stm.saveOrientation ("default", null); if (this.mode == 1) this.setNavigationMode (true); }, "~B"); Clazz.defineMethod (c$, "setRotation", function (m) { if (m.isRotation ()) this.matrixRotate.setM3 (m); else this.resetRotation (); }, "JU.M3"); Clazz.defineMethod (c$, "resetRotation", function () { this.matrixRotate.setScale (1); }); Clazz.defineMethod (c$, "clearThreads", function () { this.clearVibration (); this.clearSpin (); this.setNavOn (false); this.stopMotion (); }); Clazz.defineMethod (c$, "clear", function () { this.fixedRotationCenter.set (0, 0, 0); this.navigating = false; this.slabPlane = null; this.depthPlane = null; this.zSlabPoint = null; this.resetNavigationPoint (true); }); Clazz.defineMethod (c$, "setFixedRotationCenter", function (center) { if (center == null) return; this.fixedRotationCenter.setT (center); }, "JU.T3"); Clazz.defineMethod (c$, "setRotationPointXY", function (center) { var newCenterScreen = this.transformPt (center); this.fixedTranslation.set (newCenterScreen.x, newCenterScreen.y, 0); }, "JU.P3"); Clazz.defineMethod (c$, "spinXYBy", function (xDelta, yDelta, speed) { if (xDelta == 0 && yDelta == 0) { if (this.spinThread != null && this.spinIsGesture) this.clearSpin (); return; }this.clearSpin (); var pt1 = JU.P3.newP (this.fixedRotationCenter); var ptScreen = new JU.P3 (); this.transformPt3f (pt1, ptScreen); var pt2 = JU.P3.new3 (-yDelta, xDelta, 0); pt2.add (ptScreen); this.unTransformPoint (pt2, pt2); this.vwr.setInMotion (false); this.rotateAboutPointsInternal (null, pt2, pt1, 10 * speed, NaN, false, true, null, true, null, null, null, null); }, "~N,~N,~N"); Clazz.defineMethod (c$, "rotateXYBy", function (degX, degY, bsAtoms) { this.rotate3DBall (degX, degY, bsAtoms); }, "~N,~N,JU.BS"); Clazz.defineMethod (c$, "rotateZBy", function (zDelta, x, y) { if (x != 2147483647 && y != 2147483647) this.resetXYCenter (x, y); this.rotateZRadians ((zDelta / 57.29577951308232)); }, "~N,~N,~N"); Clazz.defineMethod (c$, "applyRotation", function (mNew, isInternal, bsAtoms, translation, translationOnly, m4) { if (bsAtoms == null) { this.matrixRotate.mul2 (mNew, this.matrixRotate); return; }this.vwr.moveAtoms (m4, mNew, this.matrixRotate, translation, this.internalRotationCenter, isInternal, bsAtoms, translationOnly); if (translation != null) { this.internalRotationCenter.add (translation); }}, "JU.M3,~B,JU.BS,JU.V3,~B,JU.M4"); Clazz.defineMethod (c$, "rotate3DBall", function (xDeg, yDeg, bsAtoms) { if (this.matrixTemp3.setAsBallRotation (0.017453292, -yDeg, -xDeg)) this.applyRotation (this.matrixTemp3, false, bsAtoms, null, false, null); }, "~N,~N,JU.BS"); Clazz.defineMethod (c$, "rotateXRadians", function (angleRadians, bsAtoms) { this.applyRotation (this.matrixTemp3.setAsXRotation (angleRadians), false, bsAtoms, null, false, null); }, "~N,JU.BS"); Clazz.defineMethod (c$, "rotateYRadians", function (angleRadians, bsAtoms) { this.applyRotation (this.matrixTemp3.setAsYRotation (angleRadians), false, bsAtoms, null, false, null); }, "~N,JU.BS"); Clazz.defineMethod (c$, "rotateZRadians", function (angleRadians) { this.applyRotation (this.matrixTemp3.setAsZRotation (angleRadians), false, null, null, false, null); }, "~N"); Clazz.defineMethod (c$, "rotateAxisAngle", function (rotAxis, radians) { this.axisangleT.setVA (rotAxis, radians); this.rotateAxisAngle2 (this.axisangleT, null); }, "JU.V3,~N"); Clazz.defineMethod (c$, "rotateAxisAngle2", function (axisAngle, bsAtoms) { this.applyRotation (this.matrixTemp3.setAA (axisAngle), false, bsAtoms, null, false, null); }, "JU.A4,JU.BS"); Clazz.defineMethod (c$, "rotateAxisAngleAtCenter", function (eval, rotCenter, rotAxis, degreesPerSecond, endDegrees, isSpin, bsAtoms) { if (rotCenter != null) this.moveRotationCenter (rotCenter, true); this.setSpinOff (); this.setNavOn (false); if (this.vwr.headless) { if (isSpin && endDegrees == 3.4028235E38) return false; isSpin = false; }if (Float.isNaN (degreesPerSecond) || degreesPerSecond == 0 || endDegrees == 0) return false; if (rotCenter != null) { this.setRotationPointXY (rotCenter); }this.setFixedRotationCenter (rotCenter); this.rotationAxis.setT (rotAxis); this.rotationRate = degreesPerSecond; if (isSpin) { this.fixedRotationAxis.setVA (rotAxis, degreesPerSecond * 0.017453292); this.isSpinInternal = false; this.isSpinFixed = true; this.isSpinSelected = (bsAtoms != null); this.setSpin (eval, true, endDegrees, null, null, bsAtoms, false); return (endDegrees != 3.4028235E38); }var radians = endDegrees * 0.017453292; this.fixedRotationAxis.setVA (rotAxis, endDegrees); this.rotateAxisAngleRadiansFixed (radians, bsAtoms); return true; }, "J.api.JmolScriptEvaluator,JU.P3,JU.V3,~N,~N,~B,JU.BS"); Clazz.defineMethod (c$, "rotateAxisAngleRadiansFixed", function (angleRadians, bsAtoms) { this.axisangleT.setAA (this.fixedRotationAxis); this.axisangleT.angle = angleRadians; this.rotateAxisAngle2 (this.axisangleT, bsAtoms); }, "~N,JU.BS"); Clazz.defineMethod (c$, "rotateAboutPointsInternal", function (eval, point1, point2, degreesPerSecond, endDegrees, isClockwise, isSpin, bsAtoms, isGesture, translation, finalPoints, dihedralList, m4) { this.setSpinOff (); this.setNavOn (false); if (dihedralList == null && (translation == null || translation.length () < 0.001) && (isSpin ? Float.isNaN (degreesPerSecond) || degreesPerSecond == 0 : endDegrees == 0)) return false; var axis = null; if (dihedralList == null) { axis = JU.V3.newVsub (point2, point1); if (isClockwise) axis.scale (-1.0); this.internalRotationCenter.setT (point1); this.rotationAxis.setT (axis); this.internalTranslation = (translation == null ? null : JU.V3.newV (translation)); }var isSelected = (bsAtoms != null); if (isSpin) { if (dihedralList == null) { if (endDegrees == 0) endDegrees = NaN; if (Float.isNaN (endDegrees)) { this.rotationRate = degreesPerSecond; } else { var nFrames = Clazz.doubleToInt (Math.abs (endDegrees) / Math.abs (degreesPerSecond) * this.spinFps + 0.5); this.rotationRate = degreesPerSecond = endDegrees / nFrames * this.spinFps; if (translation != null) this.internalTranslation.scale (1 / nFrames); }this.internalRotationAxis.setVA (axis, (Float.isNaN (this.rotationRate) ? 0 : this.rotationRate) * 0.017453292); this.isSpinInternal = true; this.isSpinFixed = false; this.isSpinSelected = isSelected; } else { endDegrees = degreesPerSecond; }this.setSpin (eval, true, endDegrees, finalPoints, dihedralList, bsAtoms, isGesture); return !Float.isNaN (endDegrees); }var radians = endDegrees * 0.017453292; this.internalRotationAxis.setVA (axis, radians); this.rotateAxisAngleRadiansInternal (radians, bsAtoms, m4); return false; }, "J.api.JmolScriptEvaluator,JU.T3,JU.T3,~N,~N,~B,~B,JU.BS,~B,JU.V3,JU.Lst,~A,JU.M4"); Clazz.defineMethod (c$, "rotateAxisAngleRadiansInternal", function (radians, bsAtoms, m4) { this.internalRotationAngle = radians; this.vectorT.set (this.internalRotationAxis.x, this.internalRotationAxis.y, this.internalRotationAxis.z); this.matrixRotate.rotate2 (this.vectorT, this.vectorT2); this.axisangleT.setVA (this.vectorT2, radians); this.applyRotation (this.matrixTemp3.setAA (this.axisangleT), true, bsAtoms, this.internalTranslation, radians > 1e6, m4); if (bsAtoms == null) this.getNewFixedRotationCenter (); }, "~N,JU.BS,JU.M4"); Clazz.defineMethod (c$, "getNewFixedRotationCenter", function () { this.axisangleT.setAA (this.internalRotationAxis); this.axisangleT.angle = -this.internalRotationAngle; this.matrixTemp4.setToAA (this.axisangleT); this.vectorT.setT (this.internalRotationCenter); this.pointT2.sub2 (this.fixedRotationCenter, this.vectorT); var pt = this.matrixTemp4.rotTrans2 (this.pointT2, new JU.P3 ()); pt.add (this.vectorT); this.setRotationCenterAndRadiusXYZ (pt, false); }); Clazz.defineMethod (c$, "setTranslationFractions", function () { this.xTranslationFraction = this.fixedTranslation.x / this.width; this.yTranslationFraction = this.fixedTranslation.y / this.height; }); Clazz.defineMethod (c$, "centerAt", function (x, y, pt) { if (pt == null) { this.translateXYBy (x, y); return; }if (this.windowCentered) this.vwr.setBooleanProperty ("windowCentered", false); this.fixedTranslation.x = x; this.fixedTranslation.y = y; this.setFixedRotationCenter (pt); }, "~N,~N,JU.P3"); Clazz.defineMethod (c$, "percentToPixels", function (xyz, percent) { switch (xyz) { case 'x': return Clazz.doubleToInt (Math.floor (percent / 100 * this.width)); case 'y': return Clazz.doubleToInt (Math.floor (percent / 100 * this.height)); case 'z': return Clazz.doubleToInt (Math.floor (percent / 100 * this.screenPixelCount)); } return 0; }, "~S,~N"); Clazz.defineMethod (c$, "angstromsToPixels", function (distance) { return Clazz.doubleToInt (Math.floor (this.scalePixelsPerAngstrom * distance)); }, "~N"); Clazz.defineMethod (c$, "translateXYBy", function (xDelta, yDelta) { this.fixedTranslation.x += xDelta; this.fixedTranslation.y += yDelta; this.setTranslationFractions (); }, "~N,~N"); Clazz.defineMethod (c$, "setCamera", function (x, y) { this.cameraSetting.set (x, y, (x == 0 && y == 0 ? 0 : 1)); }, "~N,~N"); Clazz.defineMethod (c$, "translateToPercent", function (type, percent) { switch (type) { case 'x': this.xTranslationFraction = 0.5 + percent / 100; this.fixedTranslation.x = this.width * this.xTranslationFraction; return; case 'y': this.yTranslationFraction = 0.5 + percent / 100; this.fixedTranslation.y = this.height * this.yTranslationFraction; return; case 'z': if (this.mode == 1) this.setNavigationDepthPercent (percent); return; } }, "~S,~N"); Clazz.defineMethod (c$, "getTranslationXPercent", function () { return (this.width == 0 ? 0 : (this.fixedTranslation.x - this.width / 2) * 100 / this.width); }); Clazz.defineMethod (c$, "getTranslationYPercent", function () { return (this.height == 0 ? 0 : (this.fixedTranslation.y - this.height / 2) * 100 / this.height); }); Clazz.defineMethod (c$, "getTranslationScript", function () { var info = ""; var f = this.getTranslationXPercent (); if (f != 0.0) info += "translate x " + f + ";"; f = this.getTranslationYPercent (); if (f != 0.0) info += "translate y " + f + ";"; return info; }); Clazz.defineMethod (c$, "getOrientationText", function (type) { switch (type) { case 4129: return this.getMoveToText (1, false); case 1073742132: return this.getRotationQ ().toString (); case 1073742178: var sb = new JU.SB (); JV.TransformManager.truncate2 (sb, this.getTranslationXPercent ()); JV.TransformManager.truncate2 (sb, this.getTranslationYPercent ()); return sb.toString (); default: return this.getMoveToText (1, true) + "\n#OR\n" + this.getRotateZyzText (true); } }, "~N"); Clazz.defineMethod (c$, "getRotationQ", function () { return JU.Quat.newM (this.matrixRotate); }); Clazz.defineMethod (c$, "getOrientationInfo", function () { var info = new java.util.Hashtable (); info.put ("moveTo", this.getMoveToText (1, false)); info.put ("center", "center " + this.getCenterText ()); info.put ("centerPt", this.fixedRotationCenter); var aa = new JU.A4 (); aa.setM (this.matrixRotate); info.put ("axisAngle", aa); info.put ("quaternion", this.getRotationQ ().toPoint4f ()); info.put ("rotationMatrix", this.matrixRotate); info.put ("rotateZYZ", this.getRotateZyzText (false)); info.put ("rotateXYZ", this.getRotateXyzText ()); info.put ("transXPercent", Float.$valueOf (this.getTranslationXPercent ())); info.put ("transYPercent", Float.$valueOf (this.getTranslationYPercent ())); info.put ("zoom", Float.$valueOf (this.zmPct)); info.put ("modelRadius", Float.$valueOf (this.modelRadius)); if (this.mode == 1) { info.put ("navigationCenter", "navigate center " + JU.Escape.eP (this.navigationCenter)); info.put ("navigationOffsetXPercent", Float.$valueOf (this.getNavigationOffsetPercent ('X'))); info.put ("navigationOffsetYPercent", Float.$valueOf (this.getNavigationOffsetPercent ('Y'))); info.put ("navigationDepthPercent", Float.$valueOf (this.navigationDepthPercent)); }return info; }); Clazz.defineMethod (c$, "getRotation", function (m) { m.setM3 (this.matrixRotate); }, "JU.M3"); Clazz.defineMethod (c$, "setZoomHeight", function (zoomHeight, zoomLarge) { this.zoomHeight = zoomHeight; this.scaleFitToScreen (false, zoomLarge, false, true); }, "~B,~B"); Clazz.defineMethod (c$, "zoomBy", function (pixels) { if (pixels > 20) pixels = 20; else if (pixels < -20) pixels = -20; var deltaPercent = pixels * this.zmPctSet / 50; if (deltaPercent == 0) deltaPercent = (pixels > 0 ? 1 : (deltaPercent < 0 ? -1 : 0)); this.zoomRatio = (deltaPercent + this.zmPctSet) / this.zmPctSet; this.zmPctSet += deltaPercent; }, "~N"); Clazz.defineMethod (c$, "zoomByFactor", function (factor, x, y) { if (factor <= 0 || !this.zoomEnabled) return; if (this.mode != 1) { this.zoomRatio = factor; this.zmPctSet *= factor; this.resetXYCenter (x, y); } else if (this.getNav ()) { this.nav.zoomByFactor (factor, x, y); }}, "~N,~N,~N"); Clazz.defineMethod (c$, "zoomToPercent", function (percentZoom) { this.zmPctSet = percentZoom; this.zoomRatio = 0; }, "~N"); Clazz.defineMethod (c$, "translateZBy", function (pixels) { if (pixels >= this.screenPixelCount) return; var sppa = this.scalePixelsPerAngstrom / (1 - pixels * 1.0 / this.screenPixelCount); if (sppa >= this.screenPixelCount) return; var newZoomPercent = sppa / this.scaleDefaultPixelsPerAngstrom * 100; this.zoomRatio = newZoomPercent / this.zmPctSet; this.zmPctSet = newZoomPercent; }, "~N"); Clazz.defineMethod (c$, "resetXYCenter", function (x, y) { if (x == 2147483647 || y == 2147483647) return; if (this.windowCentered) this.vwr.setBooleanProperty ("windowCentered", false); var pt = new JU.P3 (); this.transformPt3f (this.fixedRotationCenter, pt); pt.set (x, y, pt.z); this.unTransformPoint (pt, pt); this.fixedTranslation.set (x, y, 0); this.setFixedRotationCenter (pt); }, "~N,~N"); Clazz.defineMethod (c$, "zoomByPercent", function (percentZoom) { var deltaPercent = percentZoom * this.zmPctSet / 100; if (deltaPercent == 0) deltaPercent = (percentZoom < 0) ? -1 : 1; this.zoomRatio = (deltaPercent + this.zmPctSet) / this.zmPctSet; this.zmPctSet += deltaPercent; }, "~N"); Clazz.defineMethod (c$, "setScaleAngstromsPerInch", function (angstromsPerInch) { this.scale3D = (angstromsPerInch > 0); if (this.scale3D) this.scale3DAngstromsPerInch = angstromsPerInch; this.perspectiveDepth = !this.scale3D; }, "~N"); Clazz.defineMethod (c$, "setSlabRange", function (value) { this.slabRange = value; }, "~N"); Clazz.defineMethod (c$, "setSlabEnabled", function (slabEnabled) { this.slabEnabled = slabEnabled; this.vwr.g.setB ("slabEnabled", slabEnabled); }, "~B"); Clazz.defineMethod (c$, "setZShadeEnabled", function (zShadeEnabled) { this.zShadeEnabled = zShadeEnabled; this.vwr.g.setB ("zShade", zShadeEnabled); }, "~B"); Clazz.defineMethod (c$, "setZoomEnabled", function (zoomEnabled) { this.zoomEnabled = zoomEnabled; this.vwr.g.setB ("zoomEnabled", zoomEnabled); }, "~B"); Clazz.defineMethod (c$, "slabReset", function () { this.slabToPercent (100); this.depthToPercent (0); this.depthPlane = null; this.slabPlane = null; this.setSlabEnabled (false); this.setZShadeEnabled (false); this.slabDepthChanged (); }); Clazz.defineMethod (c$, "getSlabPercentSetting", function () { return this.slabPercentSetting; }); Clazz.defineMethod (c$, "slabDepthChanged", function () { this.vwr.g.setI ("slab", this.slabPercentSetting); this.vwr.g.setI ("depth", this.depthPercentSetting); this.finalizeTransformParameters (); }); Clazz.defineMethod (c$, "slabByPercentagePoints", function (percentage) { this.slabPlane = null; if (percentage < 0 ? this.slabPercentSetting <= Math.max (0, this.depthPercentSetting) : this.slabPercentSetting >= 100) return; this.slabPercentSetting += percentage; this.slabDepthChanged (); if (this.depthPercentSetting >= this.slabPercentSetting) this.depthPercentSetting = this.slabPercentSetting - 1; }, "~N"); Clazz.defineMethod (c$, "depthByPercentagePoints", function (percentage) { this.depthPlane = null; if (percentage < 0 ? this.depthPercentSetting <= 0 : this.depthPercentSetting >= Math.min (100, this.slabPercentSetting)) return; this.depthPercentSetting += percentage; if (this.slabPercentSetting <= this.depthPercentSetting) this.slabPercentSetting = this.depthPercentSetting + 1; this.slabDepthChanged (); }, "~N"); Clazz.defineMethod (c$, "slabDepthByPercentagePoints", function (percentage) { this.slabPlane = null; this.depthPlane = null; if (percentage < 0 ? this.slabPercentSetting <= Math.max (0, this.depthPercentSetting) : this.depthPercentSetting >= Math.min (100, this.slabPercentSetting)) return; this.slabPercentSetting += percentage; this.depthPercentSetting += percentage; this.slabDepthChanged (); }, "~N"); Clazz.defineMethod (c$, "slabToPercent", function (percentSlab) { this.vwr.setFloatProperty ("slabRange", 0); this.slabPercentSetting = percentSlab; this.slabPlane = null; if (this.depthPercentSetting >= this.slabPercentSetting) this.depthPercentSetting = this.slabPercentSetting - 1; this.slabDepthChanged (); }, "~N"); Clazz.defineMethod (c$, "depthToPercent", function (percentDepth) { this.vwr.g.setI ("depth", percentDepth); this.depthPercentSetting = percentDepth; if (this.slabPercentSetting <= this.depthPercentSetting) this.slabPercentSetting = this.depthPercentSetting + 1; this.slabDepthChanged (); }, "~N"); Clazz.defineMethod (c$, "zSlabToPercent", function (percentSlab) { this.zSlabPercentSetting = percentSlab; if (this.zDepthPercentSetting > this.zSlabPercentSetting) this.zDepthPercentSetting = percentSlab; }, "~N"); Clazz.defineMethod (c$, "zDepthToPercent", function (percentDepth) { this.zDepthPercentSetting = percentDepth; if (this.zDepthPercentSetting > this.zSlabPercentSetting) this.zSlabPercentSetting = percentDepth; }, "~N"); Clazz.defineMethod (c$, "slabInternal", function (plane, isDepth) { if (isDepth) { this.depthPlane = plane; this.depthPercentSetting = 0; } else { this.slabPlane = plane; this.slabPercentSetting = 100; }this.slabDepthChanged (); }, "JU.P4,~B"); Clazz.defineMethod (c$, "setSlabDepthInternal", function (isDepth) { if (isDepth) this.depthPlane = null; else this.slabPlane = null; this.slabInternal (this.getSlabDepthPlane (isDepth), isDepth); }, "~B"); Clazz.defineMethod (c$, "getSlabDepthPlane", function (isDepth) { if (isDepth) { if (this.depthPlane != null) return this.depthPlane; } else { if (this.slabPlane != null) return this.slabPlane; }var m = this.matrixTransform; return JU.P4.new4 (-m.m20, -m.m21, -m.m22, -m.m23 + (isDepth ? this.depthValue : this.slabValue)); }, "~B"); Clazz.defineMethod (c$, "getCameraFactors", function () { this.aperatureAngle = (Math.atan2 (this.screenPixelCount / 2, this.referencePlaneOffset) * 2 * 180 / 3.141592653589793); this.cameraDistanceFromCenter = this.referencePlaneOffset / this.scalePixelsPerAngstrom; var ptRef = JU.P3.new3 (Clazz.doubleToInt (this.screenWidth / 2), Clazz.doubleToInt (this.screenHeight / 2), this.referencePlaneOffset); this.unTransformPoint (ptRef, ptRef); var ptCamera = JU.P3.new3 (Clazz.doubleToInt (this.screenWidth / 2), Clazz.doubleToInt (this.screenHeight / 2), 0); this.unTransformPoint (ptCamera, ptCamera); ptCamera.sub (this.fixedRotationCenter); var pt = JU.P3.new3 (Clazz.doubleToInt (this.screenWidth / 2), Clazz.doubleToInt (this.screenHeight / 2), this.cameraDistanceFromCenter * this.scalePixelsPerAngstrom); this.unTransformPoint (pt, pt); pt.sub (this.fixedRotationCenter); ptCamera.add (pt); return Clazz.newArray (-1, [ptRef, ptCamera, this.fixedRotationCenter, JU.P3.new3 (this.cameraDistanceFromCenter, this.aperatureAngle, this.scalePixelsPerAngstrom)]); }); Clazz.defineMethod (c$, "setPerspectiveDepth", function (perspectiveDepth) { if (this.perspectiveDepth == perspectiveDepth) return; this.perspectiveDepth = perspectiveDepth; this.vwr.g.setB ("perspectiveDepth", perspectiveDepth); this.resetFitToScreen (false); }, "~B"); Clazz.defineMethod (c$, "getPerspectiveDepth", function () { return this.perspectiveDepth; }); Clazz.defineMethod (c$, "setCameraDepthPercent", function (percent, resetSlab) { this.resetNavigationPoint (resetSlab); var screenMultiples = (percent < 0 ? -percent / 100 : percent); if (screenMultiples == 0) return; this.cameraDepthSetting = screenMultiples; this.vwr.g.setF ("cameraDepth", this.cameraDepthSetting); this.cameraDepth = NaN; }, "~N,~B"); Clazz.defineMethod (c$, "getCameraDepth", function () { return this.cameraDepthSetting; }); Clazz.defineMethod (c$, "setScreenParameters0", function (screenWidth, screenHeight, useZoomLarge, antialias, resetSlab, resetZoom) { if (screenWidth == 2147483647) return; this.screenWidth = screenWidth; this.screenHeight = screenHeight; this.useZoomLarge = useZoomLarge; this.antialias = antialias; this.width = (antialias ? screenWidth * 2 : screenWidth); this.height = (antialias ? screenHeight * 2 : screenHeight); this.scaleFitToScreen (false, useZoomLarge, resetSlab, resetZoom); }, "~N,~N,~B,~B,~B,~B"); Clazz.defineMethod (c$, "setAntialias", function (TF) { var isNew = (this.antialias != TF); this.antialias = TF; this.width = (this.antialias ? this.screenWidth * 2 : this.screenWidth); this.height = (this.antialias ? this.screenHeight * 2 : this.screenHeight); if (isNew) this.scaleFitToScreen (false, this.useZoomLarge, false, false); }, "~B"); Clazz.defineMethod (c$, "defaultScaleToScreen", function (radius) { return this.screenPixelCount / 2 / radius; }, "~N"); Clazz.defineMethod (c$, "resetFitToScreen", function (andCenter) { this.scaleFitToScreen (andCenter, this.vwr.g.zoomLarge, true, true); }, "~B"); Clazz.defineMethod (c$, "scaleFitToScreen", function (andCenter, zoomLarge, resetSlab, resetZoom) { if (this.width == 0 || this.height == 0) { this.screenPixelCount = 1; } else { this.fixedTranslation.set (this.width * (andCenter ? 0.5 : this.xTranslationFraction), this.height * (andCenter ? 0.5 : this.yTranslationFraction), 0); this.setTranslationFractions (); if (andCenter) this.camera.set (0, 0, 0); if (resetZoom) this.resetNavigationPoint (resetSlab); if (this.zoomHeight) zoomLarge = (this.height > this.width); this.screenPixelCount = (zoomLarge == (this.height > this.width) ? this.height : this.width); }if (this.screenPixelCount > 2) this.screenPixelCount -= 2; this.scaleDefaultPixelsPerAngstrom = this.defaultScaleToScreen (this.modelRadius); }, "~B,~B,~B,~B"); Clazz.defineMethod (c$, "scaleToScreen", function (z, milliAngstroms) { if (milliAngstroms == 0 || z < 2) return 0; var pixelSize = this.scaleToPerspective (z, milliAngstroms * this.scalePixelsPerAngstrom / 1000); return (pixelSize > 0 ? pixelSize : 1); }, "~N,~N"); Clazz.defineMethod (c$, "unscaleToScreen", function (z, screenDistance) { var d = screenDistance / this.scalePixelsPerAngstrom; return (this.perspectiveDepth ? d / this.getPerspectiveFactor (z) : d); }, "~N,~N"); Clazz.defineMethod (c$, "scaleToPerspective", function (z, sizeAngstroms) { return (this.perspectiveDepth ? sizeAngstroms * this.getPerspectiveFactor (z) : sizeAngstroms); }, "~N,~N"); Clazz.defineMethod (c$, "setNavigationMode", function (TF) { this.mode = (TF ? 1 : this.defaultMode); this.resetNavigationPoint (true); }, "~B"); Clazz.defineMethod (c$, "isNavigating", function () { return this.navigating || this.navOn; }); Clazz.defineMethod (c$, "finalizeTransformParameters", function () { this.haveNotifiedNaN = false; this.fixedRotationOffset.setT (this.fixedTranslation); this.camera.setT (this.cameraSetting); this.internalSlab = this.slabEnabled && (this.slabPlane != null || this.depthPlane != null); var newZoom = this.getZoomSetting (); if (this.zmPct != newZoom) { this.zmPct = newZoom; if (!this.vwr.g.fontCaching) this.vwr.gdata.clearFontCache (); }this.calcCameraFactors (); this.calcTransformMatrix (); if (this.mode == 1) this.calcNavigationPoint (); else this.calcSlabAndDepthValues (); }); Clazz.defineMethod (c$, "getZoomSetting", function () { if (this.zmPctSet < 5) this.zmPctSet = 5; if (this.zmPctSet > 200000) this.zmPctSet = 200000; return (this.zoomEnabled || this.mode == 1 ? this.zmPctSet : 100); }); Clazz.defineMethod (c$, "calcSlabAndDepthValues", function () { if (this.slabRange < 1) this.slabValue = this.zValueFromPercent (this.slabPercentSetting); else this.slabValue = Clazz.doubleToInt (Math.floor (this.modelCenterOffset * this.slabRange / (2 * this.modelRadius) * (this.zmPctSet / 100))); this.depthValue = this.zValueFromPercent (this.depthPercentSetting); if (this.zSlabPercentSetting == this.zDepthPercentSetting) { this.zSlabValue = this.slabValue; this.zDepthValue = this.depthValue; } else { this.zSlabValue = this.zValueFromPercent (this.zSlabPercentSetting); this.zDepthValue = this.zValueFromPercent (this.zDepthPercentSetting); }if (this.zSlabPoint != null) { try { this.transformPt3f (this.zSlabPoint, this.pointT2); this.zSlabValue = Clazz.floatToInt (this.pointT2.z); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } }this.vwr.g.setO ("_slabPlane", JU.Escape.eP4 (this.getSlabDepthPlane (false))); this.vwr.g.setO ("_depthPlane", JU.Escape.eP4 (this.getSlabDepthPlane (true))); if (this.slabEnabled) return; this.slabValue = 0; this.depthValue = 2147483647; }); Clazz.defineMethod (c$, "zValueFromPercent", function (zPercent) { return Clazz.doubleToInt (Math.floor ((1 - zPercent / 50) * this.modelRadiusPixels + this.modelCenterOffset)); }, "~N"); Clazz.defineMethod (c$, "calcTransformMatrix", function () { this.matrixTransform.setIdentity (); this.vectorTemp.sub2 (this.frameOffset, this.fixedRotationCenter); this.matrixTransform.setTranslation (this.vectorTemp); this.matrixTemp.setToM3 (this.stereoFrame ? this.matrixStereo : this.matrixRotate); this.matrixTransform.mul2 (this.matrixTemp, this.matrixTransform); this.matrixTemp.setIdentity (); this.matrixTemp.m00 = this.matrixTemp.m11 = this.matrixTemp.m22 = this.scalePixelsPerAngstrom; this.matrixTemp.m11 = this.matrixTemp.m22 = -this.scalePixelsPerAngstrom; this.matrixTransform.mul2 (this.matrixTemp, this.matrixTransform); this.matrixTransform.m23 += this.modelCenterOffset; try { this.matrixTransformInv.setM4 (this.matrixTransform).invert (); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { System.out.println ("ERROR INVERTING matrixTransform!"); } else { throw e; } } }); Clazz.defineMethod (c$, "rotatePoint", function (pt, ptRot) { this.matrixRotate.rotate2 (pt, ptRot); ptRot.y = -ptRot.y; }, "JU.T3,JU.T3"); Clazz.defineMethod (c$, "getScreenTemp", function (ptXYZ) { this.matrixTransform.rotTrans2 (ptXYZ, this.fScrPt); }, "JU.T3"); Clazz.defineMethod (c$, "transformPtScr", function (ptXYZ, pointScreen) { pointScreen.setT (this.transformPt (ptXYZ)); }, "JU.T3,JU.P3i"); Clazz.defineMethod (c$, "transformPtScrT3", function (ptXYZ, pointScreen) { this.transformPt (ptXYZ); pointScreen.setT (this.fScrPt); }, "JU.T3,JU.T3"); Clazz.defineMethod (c$, "transformPtNoClip", function (ptXYZ, pointScreen) { this.applyPerspective (ptXYZ, null); pointScreen.setT (this.fScrPt); }, "JU.T3,JU.T3"); Clazz.defineMethod (c$, "transformPt", function (ptXYZ) { return this.applyPerspective (ptXYZ, this.internalSlab ? ptXYZ : null); }, "JU.T3"); Clazz.defineMethod (c$, "transformPtVib", function (ptXYZ, v) { this.ptVibTemp.setT (ptXYZ); return this.applyPerspective (this.getVibrationPoint (v, this.ptVibTemp, NaN), ptXYZ); }, "JU.P3,JU.Vibration"); Clazz.defineMethod (c$, "getVibrationPoint", function (v, pt, scale) { return v.setCalcPoint (pt, this.vibrationT, (Float.isNaN (scale) ? this.vibrationScale : scale), this.vwr.g.modulationScale); }, "JU.Vibration,JU.T3,~N"); Clazz.defineMethod (c$, "transformPt3f", function (ptXYZ, screen) { this.applyPerspective (ptXYZ, ptXYZ); screen.setT (this.fScrPt); }, "JU.T3,JU.P3"); Clazz.defineMethod (c$, "transformPt2D", function (ptXyp) { if (ptXyp.z == -3.4028235E38) { this.iScrPt.x = Clazz.doubleToInt (Math.floor (ptXyp.x / 100 * this.screenWidth)); this.iScrPt.y = Clazz.doubleToInt (Math.floor ((1 - ptXyp.y / 100) * this.screenHeight)); } else { this.iScrPt.x = Clazz.floatToInt (ptXyp.x); this.iScrPt.y = (this.screenHeight - Clazz.floatToInt (ptXyp.y)); }if (this.antialias) { this.iScrPt.x <<= 1; this.iScrPt.y <<= 1; }this.matrixTransform.rotTrans2 (this.fixedRotationCenter, this.fScrPt); this.iScrPt.z = Clazz.floatToInt (this.fScrPt.z); return this.iScrPt; }, "JU.T3"); Clazz.defineMethod (c$, "applyPerspective", function (ptXYZ, ptRef) { this.getScreenTemp (ptXYZ); var z = this.fScrPt.z; if (Float.isNaN (z)) { if (!this.haveNotifiedNaN && JU.Logger.debugging) JU.Logger.debug ("NaN seen in TransformPoint"); this.haveNotifiedNaN = true; z = this.fScrPt.z = 1; } else if (z <= 0) { z = this.fScrPt.z = 1; }switch (this.mode) { case 1: this.fScrPt.x -= this.navigationShiftXY.x; this.fScrPt.y -= this.navigationShiftXY.y; break; case 2: this.fScrPt.x += this.perspectiveShiftXY.x; this.fScrPt.y += this.perspectiveShiftXY.y; break; } if (this.perspectiveDepth) { var factor = this.getPerspectiveFactor (z); this.fScrPt.x *= factor; this.fScrPt.y *= factor; }switch (this.mode) { case 1: this.fScrPt.x += this.navigationOffset.x; this.fScrPt.y += this.navigationOffset.y; break; case 2: this.fScrPt.x -= this.perspectiveShiftXY.x; this.fScrPt.y -= this.perspectiveShiftXY.y; case 0: this.fScrPt.x += this.fixedRotationOffset.x; this.fScrPt.y += this.fixedRotationOffset.y; break; } if (Float.isNaN (this.fScrPt.x) && !this.haveNotifiedNaN) { if (JU.Logger.debugging) JU.Logger.debug ("NaN found in transformPoint "); this.haveNotifiedNaN = true; }this.iScrPt.set (Clazz.floatToInt (this.fScrPt.x), Clazz.floatToInt (this.fScrPt.y), Clazz.floatToInt (this.fScrPt.z)); if (ptRef != null && (this.slabPlane != null && ptRef.x * this.slabPlane.x + ptRef.y * this.slabPlane.y + ptRef.z * this.slabPlane.z + this.slabPlane.w > 0 || this.depthPlane != null && ptRef.x * this.depthPlane.x + ptRef.y * this.depthPlane.y + ptRef.z * this.depthPlane.z + this.depthPlane.w < 0)) this.fScrPt.z = this.iScrPt.z = 1; return this.iScrPt; }, "JU.T3,JU.T3"); Clazz.defineMethod (c$, "move", function (eval, dRot, dZoom, dTrans, dSlab, floatSecondsTotal, fps) { this.movetoThread = J.api.Interface.getOption ("thread.MoveToThread", this.vwr, "tm"); this.movetoThread.setManager (this, this.vwr, Clazz.newArray (-1, [dRot, dTrans, Clazz.newFloatArray (-1, [dZoom, dSlab, floatSecondsTotal, fps])])); if (floatSecondsTotal > 0) this.movetoThread.setEval (eval); this.movetoThread.run (); }, "J.api.JmolScriptEvaluator,JU.V3,~N,JU.V3,~N,~N,~N"); Clazz.defineMethod (c$, "isInPosition", function (axis, degrees) { if (Float.isNaN (degrees)) return true; this.aaTest1.setVA (axis, (degrees / 57.29577951308232)); this.ptTest1.set (4.321, 1.23456, 3.14159); this.getRotation (this.matrixTest); this.matrixTest.rotate2 (this.ptTest1, this.ptTest2); this.matrixTest.setAA (this.aaTest1).rotate2 (this.ptTest1, this.ptTest3); return (this.ptTest3.distance (this.ptTest2) < 0.1); }, "JU.V3,~N"); Clazz.defineMethod (c$, "moveToPyMOL", function (eval, floatSecondsTotal, pymolView) { var m3 = JU.M3.newA9 (pymolView); m3.invert (); var cameraX = pymolView[9]; var cameraY = -pymolView[10]; var pymolDistanceToCenter = -pymolView[11]; var center = JU.P3.new3 (pymolView[12], pymolView[13], pymolView[14]); var pymolDistanceToSlab = pymolView[15]; var pymolDistanceToDepth = pymolView[16]; var fov = pymolView[17]; var isOrtho = (fov >= 0); this.setPerspectiveDepth (!isOrtho); var theta = Math.abs (fov) / 2; var tan = Math.tan (theta * 3.141592653589793 / 180); var rotationRadius = pymolDistanceToCenter * tan; var jmolCameraToCenter = 0.5 / tan; var cameraDepth = jmolCameraToCenter - 0.5; var f = 50 / rotationRadius; if (pymolDistanceToSlab > 0) { var slab = 50 + Clazz.floatToInt ((pymolDistanceToCenter - pymolDistanceToSlab) * f); var depth = 50 + Clazz.floatToInt ((pymolDistanceToCenter - pymolDistanceToDepth) * f); this.setSlabEnabled (true); this.slabToPercent (slab); this.depthToPercent (depth); if (pymolView.length == 21) { var depthCue = (pymolView[18] != 0); var fog = (pymolView[19] != 0); var fogStart = pymolView[20]; this.setZShadeEnabled (depthCue); if (depthCue) { if (fog) { this.vwr.setIntProperty ("zSlab", Clazz.floatToInt (Math.min (100, slab + fogStart * (depth - slab)))); } else { this.vwr.setIntProperty ("zSlab", Clazz.floatToInt ((slab + depth) / 2)); }this.vwr.setIntProperty ("zDepth", depth); }}}this.moveTo (eval, floatSecondsTotal, center, null, 0, m3, 100, NaN, NaN, rotationRadius, null, NaN, NaN, NaN, cameraDepth, cameraX, cameraY); return true; }, "J.api.JmolScriptEvaluator,~N,~A"); Clazz.defineMethod (c$, "moveTo", function (eval, floatSecondsTotal, center, rotAxis, degrees, matrixEnd, zoom, xTrans, yTrans, newRotationRadius, navCenter, xNav, yNav, navDepth, cameraDepth, cameraX, cameraY) { if (matrixEnd == null) { matrixEnd = new JU.M3 (); var axis = JU.V3.newV (rotAxis); if (Float.isNaN (degrees)) { matrixEnd.m00 = NaN; } else if (degrees < 0.01 && degrees > -0.01) { matrixEnd.setScale (1); } else { if (axis.x == 0 && axis.y == 0 && axis.z == 0) { return; }var aaMoveTo = new JU.A4 (); aaMoveTo.setVA (axis, (degrees / 57.29577951308232)); matrixEnd.setAA (aaMoveTo); }}if (cameraX == this.cameraSetting.x) cameraX = NaN; if (cameraY == this.cameraSetting.y) cameraY = NaN; if (cameraDepth == this.cameraDepth) cameraDepth = NaN; if (!Float.isNaN (cameraX)) xTrans = cameraX * 50 / newRotationRadius / this.width * this.screenPixelCount; if (!Float.isNaN (cameraY)) yTrans = cameraY * 50 / newRotationRadius / this.height * this.screenPixelCount; var pixelScale = (center == null ? this.scaleDefaultPixelsPerAngstrom : this.defaultScaleToScreen (newRotationRadius)); if (floatSecondsTotal <= 0) { this.setAll (center, matrixEnd, navCenter, zoom, xTrans, yTrans, newRotationRadius, pixelScale, navDepth, xNav, yNav, cameraDepth, cameraX, cameraY); this.vwr.moveUpdate (floatSecondsTotal); this.vwr.finalizeTransformParameters (); return; }try { if (this.movetoThread == null) this.movetoThread = J.api.Interface.getOption ("thread.MoveToThread", this.vwr, "tm"); var nSteps = this.movetoThread.setManager (this, this.vwr, Clazz.newArray (-1, [center, matrixEnd, navCenter, Clazz.newFloatArray (-1, [floatSecondsTotal, zoom, xTrans, yTrans, newRotationRadius, pixelScale, navDepth, xNav, yNav, cameraDepth, cameraX, cameraY])])); if (nSteps <= 0 || this.vwr.g.waitForMoveTo) { if (nSteps > 0) this.movetoThread.setEval (eval); this.movetoThread.run (); if (!this.vwr.isSingleThreaded) this.movetoThread = null; } else { this.movetoThread.start (); }} catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } }, "J.api.JmolScriptEvaluator,~N,JU.P3,JU.T3,~N,JU.M3,~N,~N,~N,~N,JU.P3,~N,~N,~N,~N,~N,~N"); Clazz.defineMethod (c$, "setAll", function (center, m, navCenter, zoom, xTrans, yTrans, rotationRadius, pixelScale, navDepth, xNav, yNav, cameraDepth, cameraX, cameraY) { if (!Float.isNaN (m.m00)) this.setRotation (m); if (center != null) this.moveRotationCenter (center, !this.windowCentered); if (navCenter != null && this.mode == 1) this.navigationCenter.setT (navCenter); if (!Float.isNaN (cameraDepth)) this.setCameraDepthPercent (cameraDepth, false); if (!Float.isNaN (cameraX) && !Float.isNaN (cameraY)) this.setCamera (cameraX, cameraY); if (!Float.isNaN (zoom)) this.zoomToPercent (zoom); if (!Float.isNaN (rotationRadius)) this.modelRadius = rotationRadius; if (!Float.isNaN (pixelScale)) this.scaleDefaultPixelsPerAngstrom = pixelScale; if (!Float.isNaN (xTrans) && !Float.isNaN (yTrans)) { this.translateToPercent ('x', xTrans); this.translateToPercent ('y', yTrans); }if (this.mode == 1) { if (!Float.isNaN (xNav) && !Float.isNaN (yNav)) this.navTranslatePercentOrTo (0, xNav, yNav); if (!Float.isNaN (navDepth)) this.setNavigationDepthPercent (navDepth); }}, "JU.P3,JU.M3,JU.P3,~N,~N,~N,~N,~N,~N,~N,~N,~N,~N,~N"); Clazz.defineMethod (c$, "stopMotion", function () { this.movetoThread = null; }); Clazz.defineMethod (c$, "getRotationText", function () { this.axisangleT.setM (this.matrixRotate); var degrees = (this.axisangleT.angle * 57.29577951308232); var sb = new JU.SB (); this.vectorT.set (this.axisangleT.x, this.axisangleT.y, this.axisangleT.z); if (degrees < 0.01) return "{0 0 1 0}"; this.vectorT.normalize (); this.vectorT.scale (1000); sb.append ("{"); JV.TransformManager.truncate0 (sb, this.vectorT.x); JV.TransformManager.truncate0 (sb, this.vectorT.y); JV.TransformManager.truncate0 (sb, this.vectorT.z); JV.TransformManager.truncate2 (sb, degrees); sb.append ("}"); return sb.toString (); }); Clazz.defineMethod (c$, "getMoveToText", function (timespan, addComments) { this.finalizeTransformParameters (); var sb = new JU.SB (); sb.append ("moveto "); if (addComments) sb.append ("/* time, axisAngle */ "); sb.appendF (timespan); sb.append (" ").append (this.getRotationText ()); if (addComments) sb.append (" /* zoom, translation */ "); JV.TransformManager.truncate2 (sb, this.zmPctSet); JV.TransformManager.truncate2 (sb, this.getTranslationXPercent ()); JV.TransformManager.truncate2 (sb, this.getTranslationYPercent ()); sb.append (" "); if (addComments) sb.append (" /* center, rotationRadius */ "); sb.append (this.getCenterText ()); sb.append (" ").appendF (this.modelRadius); sb.append (this.getNavigationText (addComments)); if (addComments) sb.append (" /* cameraDepth, cameraX, cameraY */ "); JV.TransformManager.truncate2 (sb, this.cameraDepth); JV.TransformManager.truncate2 (sb, this.cameraSetting.x); JV.TransformManager.truncate2 (sb, this.cameraSetting.y); sb.append (";"); return sb.toString (); }, "~N,~B"); Clazz.defineMethod (c$, "getCenterText", function () { return JU.Escape.eP (this.fixedRotationCenter); }); Clazz.defineMethod (c$, "getRotateXyzText", function () { var sb = new JU.SB (); var m20 = this.matrixRotate.m20; var rY = -(Math.asin (m20) * 57.29577951308232); var rX; var rZ; if (m20 > .999 || m20 < -0.999) { rX = -(Math.atan2 (this.matrixRotate.m12, this.matrixRotate.m11) * 57.29577951308232); rZ = 0; } else { rX = (Math.atan2 (this.matrixRotate.m21, this.matrixRotate.m22) * 57.29577951308232); rZ = (Math.atan2 (this.matrixRotate.m10, this.matrixRotate.m00) * 57.29577951308232); }sb.append ("reset"); sb.append (";center ").append (this.getCenterText ()); if (rX != 0) { sb.append ("; rotate x"); JV.TransformManager.truncate2 (sb, rX); }if (rY != 0) { sb.append ("; rotate y"); JV.TransformManager.truncate2 (sb, rY); }if (rZ != 0) { sb.append ("; rotate z"); JV.TransformManager.truncate2 (sb, rZ); }sb.append (";"); this.addZoomTranslationNavigationText (sb); return sb.toString (); }); Clazz.defineMethod (c$, "addZoomTranslationNavigationText", function (sb) { if (this.zmPct != 100) { sb.append (" zoom"); JV.TransformManager.truncate2 (sb, this.zmPct); sb.append (";"); }var tX = this.getTranslationXPercent (); if (tX != 0) { sb.append (" translate x"); JV.TransformManager.truncate2 (sb, tX); sb.append (";"); }var tY = this.getTranslationYPercent (); if (tY != 0) { sb.append (" translate y"); JV.TransformManager.truncate2 (sb, tY); sb.append (";"); }if (this.modelRadius != this.rotationRadiusDefault || this.modelRadius == 10) { sb.append (" set rotationRadius"); JV.TransformManager.truncate2 (sb, this.modelRadius); sb.append (";"); }if (this.mode == 1) { sb.append ("navigate 0 center ").append (JU.Escape.eP (this.navigationCenter)); sb.append (";navigate 0 translate"); JV.TransformManager.truncate2 (sb, this.getNavigationOffsetPercent ('X')); JV.TransformManager.truncate2 (sb, this.getNavigationOffsetPercent ('Y')); sb.append (";navigate 0 depth "); JV.TransformManager.truncate2 (sb, this.navigationDepthPercent); sb.append (";"); }}, "JU.SB"); Clazz.defineMethod (c$, "getRotateZyzText", function (iAddComment) { var sb = new JU.SB (); var m = this.vwr.ms.getInfoM ("defaultOrientationMatrix"); if (m == null) { m = this.matrixRotate; } else { m = JU.M3.newM3 (m); m.invert (); m.mul2 (this.matrixRotate, m); }var m22 = m.m22; var rY = (Math.acos (m22) * 57.29577951308232); var rZ1; var rZ2; if (m22 > .999 || m22 < -0.999) { rZ1 = (Math.atan2 (m.m10, m.m11) * 57.29577951308232); rZ2 = 0; } else { rZ1 = (Math.atan2 (m.m21, -m.m20) * 57.29577951308232); rZ2 = (Math.atan2 (m.m12, m.m02) * 57.29577951308232); }if (rZ1 != 0 && rY != 0 && rZ2 != 0 && iAddComment) sb.append ("#Follows Z-Y-Z convention for Euler angles\n"); sb.append ("reset"); sb.append (";center ").append (this.getCenterText ()); if (rZ1 != 0) { sb.append ("; rotate z"); JV.TransformManager.truncate2 (sb, rZ1); }if (rY != 0) { sb.append ("; rotate y"); JV.TransformManager.truncate2 (sb, rY); }if (rZ2 != 0) { sb.append ("; rotate z"); JV.TransformManager.truncate2 (sb, rZ2); }sb.append (";"); this.addZoomTranslationNavigationText (sb); return sb.toString (); }, "~B"); c$.truncate0 = Clazz.defineMethod (c$, "truncate0", function (sb, val) { sb.appendC (' '); sb.appendI (Math.round (val)); }, "JU.SB,~N"); c$.truncate2 = Clazz.defineMethod (c$, "truncate2", function (sb, val) { sb.appendC (' '); sb.appendF (Math.round (val * 100) / 100); }, "JU.SB,~N"); Clazz.defineMethod (c$, "setSpinXYZ", function (x, y, z) { if (!Float.isNaN (x)) this.spinX = x; if (!Float.isNaN (y)) this.spinY = y; if (!Float.isNaN (z)) this.spinZ = z; if (this.isSpinInternal || this.isSpinFixed) this.clearSpin (); }, "~N,~N,~N"); Clazz.defineMethod (c$, "setSpinFps", function (value) { if (value <= 0) value = 1; else if (value > 50) value = 50; this.spinFps = value; }, "~N"); Clazz.defineMethod (c$, "setNavXYZ", function (x, y, z) { if (!Float.isNaN (x)) this.navX = x; if (!Float.isNaN (y)) this.navY = y; if (!Float.isNaN (z)) this.navZ = z; }, "~N,~N,~N"); Clazz.defineMethod (c$, "clearSpin", function () { this.setSpinOff (); this.setNavOn (false); this.isSpinInternal = false; this.isSpinFixed = false; }); Clazz.defineMethod (c$, "setSpinOn", function () { this.setSpin (null, true, 3.4028235E38, null, null, null, false); }); Clazz.defineMethod (c$, "setSpinOff", function () { this.setSpin (null, false, 3.4028235E38, null, null, null, false); }); Clazz.defineMethod (c$, "setSpin", function (eval, spinOn, endDegrees, endPositions, dihedralList, bsAtoms, isGesture) { if (this.navOn && spinOn) this.setNavOn (false); if (this.spinOn == spinOn) return; this.spinOn = spinOn; this.vwr.g.setB ("_spinning", spinOn); if (spinOn) { if (this.spinThread == null) { this.spinThread = J.api.Interface.getOption ("thread.SpinThread", this.vwr, "tm"); this.spinThread.setManager (this, this.vwr, Clazz.newArray (-1, [Float.$valueOf (endDegrees), endPositions, dihedralList, bsAtoms, isGesture ? Boolean.TRUE : null])); this.spinIsGesture = isGesture; if ((Float.isNaN (endDegrees) || endDegrees == 3.4028235E38 || !this.vwr.g.waitForMoveTo)) { this.spinThread.start (); } else { this.spinThread.setEval (eval); this.spinThread.run (); }}} else if (this.spinThread != null) { this.spinThread.reset (); this.spinThread = null; }}, "J.api.JmolScriptEvaluator,~B,~N,JU.Lst,~A,JU.BS,~B"); Clazz.defineMethod (c$, "setNavOn", function (navOn) { if (Float.isNaN (this.navFps)) return; var wasOn = this.navOn; if (navOn && this.spinOn) this.setSpin (null, false, 0, null, null, null, false); this.navOn = navOn; this.vwr.g.setB ("_navigating", navOn); if (!navOn) this.navInterrupt (); if (navOn) { if (this.navX == 0 && this.navY == 0 && this.navZ == 0) this.navZ = 1; if (this.navFps == 0) this.navFps = 10; if (this.spinThread == null) { this.spinThread = J.api.Interface.getOption ("thread.SpinThread", this.vwr, "tm"); this.spinThread.setManager (this, this.vwr, null); this.spinThread.start (); }} else if (wasOn) { if (this.spinThread != null) { this.spinThread.interrupt (); this.spinThread = null; }}}, "~B"); Clazz.defineMethod (c$, "setVibrationScale", function (scale) { this.vibrationScale = scale; }, "~N"); Clazz.defineMethod (c$, "setVibrationPeriod", function (period) { if (Float.isNaN (period)) { period = this.vibrationPeriod; } else if (period == 0) { this.vibrationPeriod = 0; this.vibrationPeriodMs = 0; } else { this.vibrationPeriod = Math.abs (period); this.vibrationPeriodMs = Clazz.floatToInt (this.vibrationPeriod * 1000); if (period > 0) return; period = -period; }this.setVibrationOn (period > 0 && (this.vwr.ms.getLastVibrationVector (this.vwr.am.cmi, 0) >= 0)); }, "~N"); Clazz.defineMethod (c$, "setVibrationT", function (t) { this.vibrationT.x = t; if (this.vibrationScale == 0) this.vibrationScale = this.vwr.g.vibrationScale; }, "~N"); Clazz.defineMethod (c$, "isVibrationOn", function () { return this.vibrationOn; }); Clazz.defineMethod (c$, "setVibrationOn", function (vibrationOn) { if (!vibrationOn) { if (this.vibrationThread != null) { this.vibrationThread.interrupt (); this.vibrationThread = null; }this.vibrationOn = false; this.vibrationT.x = 0; return; }if (this.vwr.ms.mc < 1) { this.vibrationOn = false; this.vibrationT.x = 0; return; }if (this.vibrationThread == null) { this.vibrationThread = J.api.Interface.getOption ("thread.VibrationThread", this.vwr, "tm"); this.vibrationThread.setManager (this, this.vwr, null); this.vibrationThread.start (); }this.vibrationOn = true; }, "~B"); Clazz.defineMethod (c$, "clearVibration", function () { this.setVibrationOn (false); this.vibrationScale = 0; }); Clazz.defineMethod (c$, "setStereoMode2", function (twoColors) { this.stereoMode = J.c.STER.CUSTOM; this.stereoColors = twoColors; }, "~A"); Clazz.defineMethod (c$, "setStereoMode", function (stereoMode) { this.stereoColors = null; this.stereoMode = stereoMode; this.stereoDoubleDTI = (stereoMode === J.c.STER.DTI); this.stereoDoubleFull = (stereoMode === J.c.STER.DOUBLE); }, "J.c.STER"); Clazz.defineMethod (c$, "setStereoDegrees", function (stereoDegrees) { this.stereoDegrees = stereoDegrees; this.stereoRadians = stereoDegrees * 0.017453292; }, "~N"); Clazz.defineMethod (c$, "getStereoRotationMatrix", function (stereoFrame) { this.stereoFrame = stereoFrame; if (!stereoFrame) return this.matrixRotate; this.matrixTemp3.setAsYRotation (-this.stereoRadians); this.matrixStereo.mul2 (this.matrixTemp3, this.matrixRotate); return this.matrixStereo; }, "~B"); Clazz.defineMethod (c$, "isWindowCentered", function () { return this.windowCentered; }); Clazz.defineMethod (c$, "setWindowCentered", function (TF) { this.windowCentered = TF; this.resetNavigationPoint (true); }, "~B"); Clazz.defineMethod (c$, "setRotationRadius", function (angstroms, doAll) { angstroms = (this.modelRadius = (angstroms <= 0 ? this.vwr.ms.calcRotationRadius (this.vwr.am.cmi, this.fixedRotationCenter, true) : angstroms)); if (doAll) this.vwr.setRotationRadius (angstroms, false); return angstroms; }, "~N,~B"); Clazz.defineMethod (c$, "setRotationCenterAndRadiusXYZ", function (newCenterOfRotation, andRadius) { this.resetNavigationPoint (false); if (newCenterOfRotation == null) { this.setFixedRotationCenter (this.rotationCenterDefault); this.modelRadius = this.rotationRadiusDefault; return; }this.setFixedRotationCenter (newCenterOfRotation); if (andRadius && this.windowCentered) this.modelRadius = this.vwr.ms.calcRotationRadius (this.vwr.am.cmi, this.fixedRotationCenter, true); }, "JU.T3,~B"); Clazz.defineMethod (c$, "setNewRotationCenter", function (center, doScale) { if (center == null) center = this.rotationCenterDefault; if (this.windowCentered) { this.translateToPercent ('x', 0); this.translateToPercent ('y', 0); this.setRotationCenterAndRadiusXYZ (center, true); if (doScale) this.resetFitToScreen (true); } else { this.moveRotationCenter (center, true); }}, "JU.P3,~B"); Clazz.defineMethod (c$, "moveRotationCenter", function (center, toXY) { this.setRotationCenterAndRadiusXYZ (center, false); if (toXY) this.setRotationPointXY (this.fixedRotationCenter); }, "JU.P3,~B"); Clazz.defineMethod (c$, "setCenter", function () { this.setRotationCenterAndRadiusXYZ (this.fixedRotationCenter, true); }); Clazz.defineMethod (c$, "setCenterAt", function (relativeTo, pt) { var pt1 = JU.P3.newP (pt); switch (relativeTo) { case 96: pt1.add (this.vwr.ms.getAverageAtomPoint ()); break; case 1678381065: pt1.add (this.vwr.getBoundBoxCenter ()); break; case 1073741826: pt1.setT (this.rotationCenterDefault); break; } this.setRotationCenterAndRadiusXYZ (pt1, true); this.resetFitToScreen (true); }, "~N,JU.P3"); Clazz.defineMethod (c$, "setFrameOffset", function (modelIndex) { if (this.frameOffsets == null || modelIndex < 0 || modelIndex >= this.frameOffsets.length) this.frameOffset.set (0, 0, 0); else this.frameOffset.setT (this.frameOffsets[modelIndex]); }, "~N"); Clazz.defineMethod (c$, "setSelectedTranslation", function (bsAtoms, xyz, xy) { this.bsSelectedAtoms = bsAtoms; switch (xyz) { case 'X': case 'x': this.ptOffset.x += xy; break; case 'Y': case 'y': this.ptOffset.y += xy; break; case 'Z': case 'z': this.ptOffset.z += xy; break; } }, "JU.BS,~S,~N"); Clazz.defineMethod (c$, "setNavFps", function (navFps) { this.navFps = navFps; }, "~N"); Clazz.defineMethod (c$, "calcCameraFactors", function () { if (Float.isNaN (this.cameraDepth)) { this.cameraDepth = this.cameraDepthSetting; this.zoomFactor = 3.4028235E38; }this.cameraDistance = this.cameraDepth * this.screenPixelCount; this.referencePlaneOffset = this.cameraDistance + this.screenPixelCount / 2; this.scalePixelsPerAngstrom = (this.scale3D && !this.perspectiveDepth && this.mode != 1 ? 72 / this.scale3DAngstromsPerInch * (this.antialias ? 2 : 1) : this.screenPixelCount / this.visualRangeAngstroms); if (this.mode != 1) this.mode = (this.camera.z == 0 ? 0 : 2); this.perspectiveShiftXY.set (this.camera.z == 0 ? 0 : this.camera.x * this.scalePixelsPerAngstrom / this.screenWidth * 100, this.camera.z == 0 ? 0 : this.camera.y * this.scalePixelsPerAngstrom / this.screenHeight * 100, 0); this.modelRadiusPixels = this.modelRadius * this.scalePixelsPerAngstrom; var offset100 = (2 * this.modelRadius) / this.visualRangeAngstroms * this.referencePlaneOffset; if (this.mode == 1) { this.calcNavCameraFactors (offset100); return; }this.zoomFactor = 3.4028235E38; this.modelCenterOffset = this.referencePlaneOffset; if (!this.scale3D || this.perspectiveDepth) this.scalePixelsPerAngstrom *= (this.modelCenterOffset / offset100) * this.zmPct / 100; this.modelRadiusPixels = this.modelRadius * this.scalePixelsPerAngstrom; }); Clazz.defineMethod (c$, "calcNavCameraFactors", function (offset100) { if (this.zoomFactor == 3.4028235E38) { if (this.zmPct > 10000) this.zmPct = 10000; this.modelCenterOffset = offset100 * 100 / this.zmPct; } else if (this.prevZoomSetting != this.zmPctSet) { if (this.zoomRatio == 0) this.modelCenterOffset = offset100 * 100 / this.zmPctSet; else this.modelCenterOffset += (1 - this.zoomRatio) * this.referencePlaneOffset; this.navMode = -1; }this.prevZoomSetting = this.zmPctSet; this.zoomFactor = this.modelCenterOffset / this.referencePlaneOffset; this.zmPct = (this.zoomFactor == 0 ? 10000 : offset100 / this.modelCenterOffset * 100); }, "~N"); Clazz.defineMethod (c$, "getPerspectiveFactor", function (z) { return (z <= 0 ? this.referencePlaneOffset : this.referencePlaneOffset / z); }, "~N"); Clazz.defineMethod (c$, "unTransformPoint", function (screenPt, coordPt) { this.untransformedPoint.setT (screenPt); switch (this.mode) { case 1: this.untransformedPoint.x -= this.navigationOffset.x; this.untransformedPoint.y -= this.navigationOffset.y; break; case 2: this.fScrPt.x += this.perspectiveShiftXY.x; this.fScrPt.y += this.perspectiveShiftXY.y; case 0: this.untransformedPoint.x -= this.fixedRotationOffset.x; this.untransformedPoint.y -= this.fixedRotationOffset.y; } if (this.perspectiveDepth) { var factor = this.getPerspectiveFactor (this.untransformedPoint.z); this.untransformedPoint.x /= factor; this.untransformedPoint.y /= factor; }switch (this.mode) { case 1: this.untransformedPoint.x += this.navigationShiftXY.x; this.untransformedPoint.y += this.navigationShiftXY.y; break; case 2: this.untransformedPoint.x -= this.perspectiveShiftXY.x; this.untransformedPoint.y -= this.perspectiveShiftXY.y; break; } this.matrixTransformInv.rotTrans2 (this.untransformedPoint, coordPt); }, "JU.T3,JU.T3"); Clazz.defineMethod (c$, "resetNavigationPoint", function (doResetSlab) { if (this.zmPct < 5 && this.mode != 1) { this.perspectiveDepth = true; this.mode = 1; return; }if (this.mode == 1) { this.navMode = 1; this.slabPercentSetting = 0; this.perspectiveDepth = true; } else if (doResetSlab) { this.slabPercentSetting = 100; }this.vwr.setFloatProperty ("slabRange", 0); if (doResetSlab) { this.setSlabEnabled (this.mode == 1); }this.zoomFactor = 3.4028235E38; this.zmPctSet = this.zmPct; }, "~B"); Clazz.defineMethod (c$, "setNavigatePt", function (pt) { this.navigationCenter.setT (pt); this.navMode = 3; this.navigating = true; this.finalizeTransformParameters (); this.navigating = false; }, "JU.P3"); Clazz.defineMethod (c$, "setNavigationSlabOffsetPercent", function (percent) { this.vwr.g.setF ("navigationSlab", percent); this.calcCameraFactors (); this.navigationSlabOffset = percent / 50 * this.modelRadiusPixels; }, "~N"); Clazz.defineMethod (c$, "getNavigationOffset", function () { this.transformPt3f (this.navigationCenter, this.navigationOffset); return this.navigationOffset; }); Clazz.defineMethod (c$, "getNavPtHeight", function () { return this.height / 2; }); Clazz.defineMethod (c$, "getNavigationOffsetPercent", function (XorY) { this.getNavigationOffset (); if (this.width == 0 || this.height == 0) return 0; return (XorY == 'X' ? (this.navigationOffset.x - this.width / 2) * 100 / this.width : (this.navigationOffset.y - this.getNavPtHeight ()) * 100 / this.height); }, "~S"); Clazz.defineMethod (c$, "getNavigationText", function (addComments) { var s = (addComments ? " /* navigation center, translation, depth */ " : " "); if (this.mode != 1) return s + "{0 0 0} 0 0 0"; this.getNavigationOffset (); return s + JU.Escape.eP (this.navigationCenter) + " " + this.getNavigationOffsetPercent ('X') + " " + this.getNavigationOffsetPercent ('Y') + " " + this.navigationDepthPercent; }, "~B"); Clazz.defineMethod (c$, "setScreenParameters", function (screenWidth, screenHeight, useZoomLarge, antialias, resetSlab, resetZoom) { var pt = (this.mode == 1 ? JU.P3.newP (this.navigationCenter) : null); var ptoff = JU.P3.newP (this.navigationOffset); ptoff.x = ptoff.x / this.width; ptoff.y = ptoff.y / this.height; this.setScreenParameters0 (screenWidth, screenHeight, useZoomLarge, antialias, resetSlab, resetZoom); if (pt != null) { this.navigationCenter.setT (pt); this.navTranslatePercentOrTo (-1, ptoff.x * this.width, ptoff.y * this.height); this.setNavigatePt (pt); }}, "~N,~N,~B,~B,~B,~B"); Clazz.defineMethod (c$, "navInterrupt", function () { if (this.nav != null) this.nav.interrupt (); }); Clazz.defineMethod (c$, "getNav", function () { if (this.nav != null) return true; this.nav = J.api.Interface.getOption ("navigate.Navigator", this.vwr, "tm"); if (this.nav == null) return false; this.nav.set (this, this.vwr); return true; }); Clazz.defineMethod (c$, "navigateList", function (eval, list) { if (this.getNav ()) this.nav.navigateList (eval, list); }, "J.api.JmolScriptEvaluator,JU.Lst"); Clazz.defineMethod (c$, "navigateAxis", function (rotAxis, degrees) { if (this.getNav ()) this.nav.navigateAxis (rotAxis, degrees); }, "JU.V3,~N"); Clazz.defineMethod (c$, "setNavigationOffsetRelative", function () { if (this.getNav ()) this.nav.setNavigationOffsetRelative (); }); Clazz.defineMethod (c$, "navigateKey", function (keyCode, modifiers) { if (this.getNav ()) this.nav.navigateKey (keyCode, modifiers); }, "~N,~N"); Clazz.defineMethod (c$, "setNavigationDepthPercent", function (percent) { if (this.getNav ()) this.nav.setNavigationDepthPercent (percent); }, "~N"); Clazz.defineMethod (c$, "navTranslatePercentOrTo", function (seconds, x, y) { if (this.getNav ()) this.nav.navTranslatePercentOrTo (seconds, x, y); }, "~N,~N,~N"); Clazz.defineMethod (c$, "calcNavigationPoint", function () { if (this.getNav ()) this.nav.calcNavigationPoint (); }); Clazz.defineMethod (c$, "getNavigationState", function () { return (this.mode == 1 && this.getNav () ? this.nav.getNavigationState () : ""); }); Clazz.defineStatics (c$, "DEFAULT_SPIN_Y", 30, "DEFAULT_SPIN_FPS", 30, "DEFAULT_NAV_FPS", 10, "DEFAULT_VISUAL_RANGE", 5, "DEFAULT_STEREO_DEGREES", -5, "MODE_STANDARD", 0, "MODE_NAVIGATION", 1, "MODE_PERSPECTIVE_PYMOL", 2, "DEFAULT_PERSPECTIVE_MODEL", 11, "DEFAULT_PERSPECTIVE_DEPTH", true, "DEFAULT_CAMERA_DEPTH", 3.0, "degreesPerRadian", 57.29577951308232, "MAXIMUM_ZOOM_PERCENTAGE", 200000, "MAXIMUM_ZOOM_PERSPECTIVE_DEPTH", 10000, "NAV_MODE_IGNORE", -2, "NAV_MODE_ZOOMED", -1, "NAV_MODE_NONE", 0, "NAV_MODE_RESET", 1, "NAV_MODE_NEWXY", 2, "NAV_MODE_NEWXYZ", 3, "NAV_MODE_NEWZ", 4); });
/* */ "format global"; "deps angular"; /** * @license AngularJS v1.5.8 * (c) 2010-2016 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) {'use strict'; var forEach; var isArray; var isString; var jqLite; /** * @ngdoc module * @name ngMessages * @description * * The `ngMessages` module provides enhanced support for displaying messages within templates * (typically within forms or when rendering message objects that return key/value data). * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to * show and hide error messages specific to the state of an input field, the `ngMessages` and * `ngMessage` directives are designed to handle the complexity, inheritance and priority * sequencing based on the order of how the messages are defined in the template. * * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude` * `ngMessage` and `ngMessageExp` directives. * * # Usage * The `ngMessages` directive allows keys in a key/value collection to be associated with a child element * (or 'message') that will show or hide based on the truthiness of that key's value in the collection. A common use * case for `ngMessages` is to display error messages for inputs using the `$error` object exposed by the * {@link ngModel ngModel} directive. * * The child elements of the `ngMessages` directive are matched to the collection keys by a `ngMessage` or * `ngMessageExp` directive. The value of these attributes must match a key in the collection that is provided by * the `ngMessages` directive. * * Consider the following example, which illustrates a typical use case of `ngMessages`. Within the form `myForm` we * have a text input named `myField` which is bound to the scope variable `field` using the {@link ngModel ngModel} * directive. * * The `myField` field is a required input of type `email` with a maximum length of 15 characters. * * ```html * <form name="myForm"> * <label> * Enter text: * <input type="email" ng-model="field" name="myField" required maxlength="15" /> * </label> * <div ng-messages="myForm.myField.$error" role="alert"> * <div ng-message="required">Please enter a value for this field.</div> * <div ng-message="email">This field must be a valid email address.</div> * <div ng-message="maxlength">This field can be at most 15 characters long.</div> * </div> * </form> * ``` * * In order to show error messages corresponding to `myField` we first create an element with an `ngMessages` attribute * set to the `$error` object owned by the `myField` input in our `myForm` form. * * Within this element we then create separate elements for each of the possible errors that `myField` could have. * The `ngMessage` attribute is used to declare which element(s) will appear for which error - for example, * setting `ng-message="required"` specifies that this particular element should be displayed when there * is no value present for the required field `myField` (because the key `required` will be `true` in the object * `myForm.myField.$error`). * * ### Message order * * By default, `ngMessages` will only display one message for a particular key/value collection at any time. If more * than one message (or error) key is currently true, then which message is shown is determined by the order of messages * in the HTML template code (messages declared first are prioritised). This mechanism means the developer does not have * to prioritise messages using custom JavaScript code. * * Given the following error object for our example (which informs us that the field `myField` currently has both the * `required` and `email` errors): * * ```javascript * <!-- keep in mind that ngModel automatically sets these error flags --> * myField.$error = { required : true, email: true, maxlength: false }; * ``` * The `required` message will be displayed to the user since it appears before the `email` message in the DOM. * Once the user types a single character, the `required` message will disappear (since the field now has a value) * but the `email` message will be visible because it is still applicable. * * ### Displaying multiple messages at the same time * * While `ngMessages` will by default only display one error element at a time, the `ng-messages-multiple` attribute can * be applied to the `ngMessages` container element to cause it to display all applicable error messages at once: * * ```html * <!-- attribute-style usage --> * <div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div> * * <!-- element-style usage --> * <ng-messages for="myForm.myField.$error" multiple>...</ng-messages> * ``` * * ## Reusing and Overriding Messages * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline * template. This allows for generic collection of messages to be reused across multiple parts of an * application. * * ```html * <script type="text/ng-template" id="error-messages"> * <div ng-message="required">This field is required</div> * <div ng-message="minlength">This field is too short</div> * </script> * * <div ng-messages="myForm.myField.$error" role="alert"> * <div ng-messages-include="error-messages"></div> * </div> * ``` * * However, including generic messages may not be useful enough to match all input fields, therefore, * `ngMessages` provides the ability to override messages defined in the remote template by redefining * them within the directive container. * * ```html * <!-- a generic template of error messages known as "my-custom-messages" --> * <script type="text/ng-template" id="my-custom-messages"> * <div ng-message="required">This field is required</div> * <div ng-message="minlength">This field is too short</div> * </script> * * <form name="myForm"> * <label> * Email address * <input type="email" * id="email" * name="myEmail" * ng-model="email" * minlength="5" * required /> * </label> * <!-- any ng-message elements that appear BEFORE the ng-messages-include will * override the messages present in the ng-messages-include template --> * <div ng-messages="myForm.myEmail.$error" role="alert"> * <!-- this required message has overridden the template message --> * <div ng-message="required">You did not enter your email address</div> * * <!-- this is a brand new message and will appear last in the prioritization --> * <div ng-message="email">Your email address is invalid</div> * * <!-- and here are the generic error messages --> * <div ng-messages-include="my-custom-messages"></div> * </div> * </form> * ``` * * In the example HTML code above the message that is set on required will override the corresponding * required message defined within the remote template. Therefore, with particular input fields (such * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied * while more generic messages can be used to handle other, more general input errors. * * ## Dynamic Messaging * ngMessages also supports using expressions to dynamically change key values. Using arrays and * repeaters to list messages is also supported. This means that the code below will be able to * fully adapt itself and display the appropriate message when any of the expression data changes: * * ```html * <form name="myForm"> * <label> * Email address * <input type="email" * name="myEmail" * ng-model="email" * minlength="5" * required /> * </label> * <div ng-messages="myForm.myEmail.$error" role="alert"> * <div ng-message="required">You did not enter your email address</div> * <div ng-repeat="errorMessage in errorMessages"> * <!-- use ng-message-exp for a message whose key is given by an expression --> * <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div> * </div> * </div> * </form> * ``` * * The `errorMessage.type` expression can be a string value or it can be an array so * that multiple errors can be associated with a single error message: * * ```html * <label> * Email address * <input type="email" * ng-model="data.email" * name="myEmail" * ng-minlength="5" * ng-maxlength="100" * required /> * </label> * <div ng-messages="myForm.myEmail.$error" role="alert"> * <div ng-message-exp="'required'">You did not enter your email address</div> * <div ng-message-exp="['minlength', 'maxlength']"> * Your email must be between 5 and 100 characters long * </div> * </div> * ``` * * Feel free to use other structural directives such as ng-if and ng-switch to further control * what messages are active and when. Be careful, if you place ng-message on the same element * as these structural directives, Angular may not be able to determine if a message is active * or not. Therefore it is best to place the ng-message on a child element of the structural * directive. * * ```html * <div ng-messages="myForm.myEmail.$error" role="alert"> * <div ng-if="showRequiredError"> * <div ng-message="required">Please enter something</div> * </div> * </div> * ``` * * ## Animations * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from * the DOM by the `ngMessages` directive. * * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can * hook into the animations whenever these classes are added/removed. * * Let's say that our HTML code for our messages container looks like so: * * ```html * <div ng-messages="myMessages" class="my-messages" role="alert"> * <div ng-message="alert" class="some-message">...</div> * <div ng-message="fail" class="some-message">...</div> * </div> * ``` * * Then the CSS animation code for the message container looks like so: * * ```css * .my-messages { * transition:1s linear all; * } * .my-messages.ng-active { * // messages are visible * } * .my-messages.ng-inactive { * // messages are hidden * } * ``` * * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter * and leave animation is triggered for each particular element bound to the `ngMessage` directive. * * Therefore, the CSS code for the inner messages looks like so: * * ```css * .some-message { * transition:1s linear all; * } * * .some-message.ng-enter {} * .some-message.ng-enter.ng-enter-active {} * * .some-message.ng-leave {} * .some-message.ng-leave.ng-leave-active {} * ``` * * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate. */ angular.module('ngMessages', [], function initAngularHelpers() { // Access helpers from angular core. // Do it inside a `config` block to ensure `window.angular` is available. forEach = angular.forEach; isArray = angular.isArray; isString = angular.isString; jqLite = angular.element; }) /** * @ngdoc directive * @module ngMessages * @name ngMessages * @restrict AE * * @description * `ngMessages` is a directive that is designed to show and hide messages based on the state * of a key/value object that it listens on. The directive itself complements error message * reporting with the `ngModel` $error object (which stores a key/value state of validation errors). * * `ngMessages` manages the state of internal messages within its container element. The internal * messages use the `ngMessage` directive and will be inserted/removed from the page depending * on if they're present within the key/value object. By default, only one message will be displayed * at a time and this depends on the prioritization of the messages within the template. (This can * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.) * * A remote template can also be used to promote message reusability and messages can also be * overridden. * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression" role="alert"> * <ANY ng-message="stringValue">...</ANY> * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY> * <ANY ng-message-exp="expressionValue">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression" role="alert"> * <ng-message when="stringValue">...</ng-message> * <ng-message when="stringValue1, stringValue2, ...">...</ng-message> * <ng-message when-exp="expressionValue">...</ng-message> * </ng-messages> * ``` * * @param {string} ngMessages an angular expression evaluating to a key/value object * (this is typically the $error object on an ngModel instance). * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true * * @example * <example name="ngMessages-directive" module="ngMessagesExample" * deps="angular-messages.js" * animations="true" fixBase="true"> * <file name="index.html"> * <form name="myForm"> * <label> * Enter your name: * <input type="text" * name="myName" * ng-model="name" * ng-minlength="5" * ng-maxlength="20" * required /> * </label> * <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre> * * <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert"> * <div ng-message="required">You did not enter a field</div> * <div ng-message="minlength">Your field is too short</div> * <div ng-message="maxlength">Your field is too long</div> * </div> * </form> * </file> * <file name="script.js"> * angular.module('ngMessagesExample', ['ngMessages']); * </file> * </example> */ .directive('ngMessages', ['$animate', function($animate) { var ACTIVE_CLASS = 'ng-active'; var INACTIVE_CLASS = 'ng-inactive'; return { require: 'ngMessages', restrict: 'AE', controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var ctrl = this; var latestKey = 0; var nextAttachId = 0; this.getAttachId = function getAttachId() { return nextAttachId++; }; var messages = this.messages = {}; var renderLater, cachedCollection; this.render = function(collection) { collection = collection || {}; renderLater = false; cachedCollection = collection; // this is true if the attribute is empty or if the attribute value is truthy var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) || isAttrTruthy($scope, $attrs.multiple); var unmatchedMessages = []; var matchedKeys = {}; var messageItem = ctrl.head; var messageFound = false; var totalMessages = 0; // we use != instead of !== to allow for both undefined and null values while (messageItem != null) { totalMessages++; var messageCtrl = messageItem.message; var messageUsed = false; if (!messageFound) { forEach(collection, function(value, key) { if (!messageUsed && truthy(value) && messageCtrl.test(key)) { // this is to prevent the same error name from showing up twice if (matchedKeys[key]) return; matchedKeys[key] = true; messageUsed = true; messageCtrl.attach(); } }); } if (messageUsed) { // unless we want to display multiple messages then we should // set a flag here to avoid displaying the next message in the list messageFound = !multiple; } else { unmatchedMessages.push(messageCtrl); } messageItem = messageItem.next; } forEach(unmatchedMessages, function(messageCtrl) { messageCtrl.detach(); }); unmatchedMessages.length !== totalMessages ? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS) : $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS); }; $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render); // If the element is destroyed, proactively destroy all the currently visible messages $element.on('$destroy', function() { forEach(messages, function(item) { item.message.detach(); }); }); this.reRender = function() { if (!renderLater) { renderLater = true; $scope.$evalAsync(function() { if (renderLater) { cachedCollection && ctrl.render(cachedCollection); } }); } }; this.register = function(comment, messageCtrl) { var nextKey = latestKey.toString(); messages[nextKey] = { message: messageCtrl }; insertMessageNode($element[0], comment, nextKey); comment.$$ngMessageNode = nextKey; latestKey++; ctrl.reRender(); }; this.deregister = function(comment) { var key = comment.$$ngMessageNode; delete comment.$$ngMessageNode; removeMessageNode($element[0], comment, key); delete messages[key]; ctrl.reRender(); }; function findPreviousMessage(parent, comment) { var prevNode = comment; var parentLookup = []; while (prevNode && prevNode !== parent) { var prevKey = prevNode.$$ngMessageNode; if (prevKey && prevKey.length) { return messages[prevKey]; } // dive deeper into the DOM and examine its children for any ngMessage // comments that may be in an element that appears deeper in the list if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) === -1) { parentLookup.push(prevNode); prevNode = prevNode.childNodes[prevNode.childNodes.length - 1]; } else if (prevNode.previousSibling) { prevNode = prevNode.previousSibling; } else { prevNode = prevNode.parentNode; parentLookup.push(prevNode); } } } function insertMessageNode(parent, comment, key) { var messageNode = messages[key]; if (!ctrl.head) { ctrl.head = messageNode; } else { var match = findPreviousMessage(parent, comment); if (match) { messageNode.next = match.next; match.next = messageNode; } else { messageNode.next = ctrl.head; ctrl.head = messageNode; } } } function removeMessageNode(parent, comment, key) { var messageNode = messages[key]; var match = findPreviousMessage(parent, comment); if (match) { match.next = messageNode.next; } else { ctrl.head = messageNode.next; } } }] }; function isAttrTruthy(scope, attr) { return (isString(attr) && attr.length === 0) || //empty attribute truthy(scope.$eval(attr)); } function truthy(val) { return isString(val) ? val.length : !!val; } }]) /** * @ngdoc directive * @name ngMessagesInclude * @restrict AE * @scope * * @description * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template * code from a remote template and place the downloaded template code into the exact spot * that the ngMessagesInclude directive is placed within the ngMessages container. This allows * for a series of pre-defined messages to be reused and also allows for the developer to * determine what messages are overridden due to the placement of the ngMessagesInclude directive. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression" role="alert"> * <ANY ng-messages-include="remoteTplString">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression" role="alert"> * <ng-messages-include src="expressionValue1">...</ng-messages-include> * </ng-messages> * ``` * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @param {string} ngMessagesInclude|src a string value corresponding to the remote template. */ .directive('ngMessagesInclude', ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) { return { restrict: 'AE', require: '^^ngMessages', // we only require this for validation sake link: function($scope, element, attrs) { var src = attrs.ngMessagesInclude || attrs.src; $templateRequest(src).then(function(html) { if ($scope.$$destroyed) return; if (isString(html) && !html.trim()) { // Empty template - nothing to compile replaceElementWithMarker(element, src); } else { // Non-empty template - compile and link $compile(html)($scope, function(contents) { element.after(contents); replaceElementWithMarker(element, src); }); } }); } }; // Helpers function replaceElementWithMarker(element, src) { // A comment marker is placed for debugging purposes var comment = $compile.$$createComment ? $compile.$$createComment('ngMessagesInclude', src) : $document[0].createComment(' ngMessagesInclude: ' + src + ' '); var marker = jqLite(comment); element.after(marker); // Don't pollute the DOM anymore by keeping an empty directive element element.remove(); } }]) /** * @ngdoc directive * @name ngMessage * @restrict AE * @scope * * @description * `ngMessage` is a directive with the purpose to show and hide a particular message. * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element * must be situated since it determines which messages are visible based on the state * of the provided key/value map that `ngMessages` listens on. * * More information about using `ngMessage` can be found in the * {@link module:ngMessages `ngMessages` module documentation}. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression" role="alert"> * <ANY ng-message="stringValue">...</ANY> * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression" role="alert"> * <ng-message when="stringValue">...</ng-message> * <ng-message when="stringValue1, stringValue2, ...">...</ng-message> * </ng-messages> * ``` * * @param {expression} ngMessage|when a string value corresponding to the message key. */ .directive('ngMessage', ngMessageDirectiveFactory()) /** * @ngdoc directive * @name ngMessageExp * @restrict AE * @priority 1 * @scope * * @description * `ngMessageExp` is a directive with the purpose to show and hide a particular message. * For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element * must be situated since it determines which messages are visible based on the state * of the provided key/value map that `ngMessages` listens on. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression"> * <ANY ng-message-exp="expressionValue">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression"> * <ng-message when-exp="expressionValue">...</ng-message> * </ng-messages> * ``` * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key. */ .directive('ngMessageExp', ngMessageDirectiveFactory()); function ngMessageDirectiveFactory() { return ['$animate', function($animate) { return { restrict: 'AE', transclude: 'element', priority: 1, // must run before ngBind, otherwise the text is set on the comment terminal: true, require: '^^ngMessages', link: function(scope, element, attrs, ngMessagesCtrl, $transclude) { var commentNode = element[0]; var records; var staticExp = attrs.ngMessage || attrs.when; var dynamicExp = attrs.ngMessageExp || attrs.whenExp; var assignRecords = function(items) { records = items ? (isArray(items) ? items : items.split(/[\s,]+/)) : null; ngMessagesCtrl.reRender(); }; if (dynamicExp) { assignRecords(scope.$eval(dynamicExp)); scope.$watchCollection(dynamicExp, assignRecords); } else { assignRecords(staticExp); } var currentElement, messageCtrl; ngMessagesCtrl.register(commentNode, messageCtrl = { test: function(name) { return contains(records, name); }, attach: function() { if (!currentElement) { $transclude(function(elm, newScope) { $animate.enter(elm, null, element); currentElement = elm; // Each time we attach this node to a message we get a new id that we can match // when we are destroying the node later. var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId(); // in the event that the element or a parent element is destroyed // by another structural directive then it's time // to deregister the message from the controller currentElement.on('$destroy', function() { if (currentElement && currentElement.$$attachId === $$attachId) { ngMessagesCtrl.deregister(commentNode); messageCtrl.detach(); } newScope.$destroy(); }); }); } }, detach: function() { if (currentElement) { var elm = currentElement; currentElement = null; $animate.leave(elm); } } }); } }; }]; function contains(collection, key) { if (collection) { return isArray(collection) ? collection.indexOf(key) >= 0 : collection.hasOwnProperty(key); } } } })(window, window.angular);
'use strict'; var CleanCSS = require('clean-css'); var decode = require('he').decode; var HTMLParser = require('./htmlparser').HTMLParser; var RelateUrl = require('relateurl'); var TokenChain = require('./tokenchain'); var UglifyJS = require('uglify-js'); var utils = require('./utils'); function trimWhitespace(str) { if (typeof str !== 'string') { return str; } return str.replace(/^[ \n\r\t\f]+/, '').replace(/[ \n\r\t\f]+$/, ''); } function collapseWhitespaceAll(str) { // Non-breaking space is specifically handled inside the replacer function here: return str && str.replace(/[ \n\r\t\f\xA0]+/g, function(spaces) { return spaces === '\t' ? '\t' : spaces.replace(/(^|\xA0+)[^\xA0]+/g, '$1 '); }); } function collapseWhitespace(str, options, trimLeft, trimRight, collapseAll) { var lineBreakBefore = '', lineBreakAfter = ''; if (options.preserveLineBreaks) { str = str.replace(/^[ \n\r\t\f]*?[\n\r][ \n\r\t\f]*/, function() { lineBreakBefore = '\n'; return ''; }).replace(/[ \n\r\t\f]*?[\n\r][ \n\r\t\f]*$/, function() { lineBreakAfter = '\n'; return ''; }); } if (trimLeft) { // Non-breaking space is specifically handled inside the replacer function here: str = str.replace(/^[ \n\r\t\f\xA0]+/, function(spaces) { var conservative = !lineBreakBefore && options.conservativeCollapse; if (conservative && spaces === '\t') { return '\t'; } return spaces.replace(/^[^\xA0]+/, '').replace(/(\xA0+)[^\xA0]+/g, '$1 ') || (conservative ? ' ' : ''); }); } if (trimRight) { // Non-breaking space is specifically handled inside the replacer function here: str = str.replace(/[ \n\r\t\f\xA0]+$/, function(spaces) { var conservative = !lineBreakAfter && options.conservativeCollapse; if (conservative && spaces === '\t') { return '\t'; } return spaces.replace(/[^\xA0]+(\xA0+)/g, ' $1').replace(/[^\xA0]+$/, '') || (conservative ? ' ' : ''); }); } if (collapseAll) { // strip non space whitespace then compress spaces to one str = collapseWhitespaceAll(str); } return lineBreakBefore + str + lineBreakAfter; } var createMapFromString = utils.createMapFromString; // non-empty tags that will maintain whitespace around them var inlineTags = createMapFromString('a,abbr,acronym,b,bdi,bdo,big,button,cite,code,del,dfn,em,font,i,ins,kbd,label,mark,math,nobr,object,q,rt,rp,s,samp,select,small,span,strike,strong,sub,sup,svg,textarea,time,tt,u,var'); // non-empty tags that will maintain whitespace within them var inlineTextTags = createMapFromString('a,abbr,acronym,b,big,del,em,font,i,ins,kbd,mark,nobr,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var'); // self-closing tags that will maintain whitespace around them var selfClosingInlineTags = createMapFromString('comment,img,input,wbr'); function collapseWhitespaceSmart(str, prevTag, nextTag, options) { var trimLeft = prevTag && !selfClosingInlineTags(prevTag); if (trimLeft && !options.collapseInlineTagWhitespace) { trimLeft = prevTag.charAt(0) === '/' ? !inlineTags(prevTag.slice(1)) : !inlineTextTags(prevTag); } var trimRight = nextTag && !selfClosingInlineTags(nextTag); if (trimRight && !options.collapseInlineTagWhitespace) { trimRight = nextTag.charAt(0) === '/' ? !inlineTextTags(nextTag.slice(1)) : !inlineTags(nextTag); } return collapseWhitespace(str, options, trimLeft, trimRight, prevTag && nextTag); } function isConditionalComment(text) { return /^\[if\s[^\]]+]|\[endif]$/.test(text); } function isIgnoredComment(text, options) { for (var i = 0, len = options.ignoreCustomComments.length; i < len; i++) { if (options.ignoreCustomComments[i].test(text)) { return true; } } return false; } function isEventAttribute(attrName, options) { var patterns = options.customEventAttributes; if (patterns) { for (var i = patterns.length; i--;) { if (patterns[i].test(attrName)) { return true; } } return false; } return /^on[a-z]{3,}$/.test(attrName); } function canRemoveAttributeQuotes(value) { // http://mathiasbynens.be/notes/unquoted-attribute-values return /^[^ \t\n\f\r"'`=<>]+$/.test(value); } function attributesInclude(attributes, attribute) { for (var i = attributes.length; i--;) { if (attributes[i].name.toLowerCase() === attribute) { return true; } } return false; } function isAttributeRedundant(tag, attrName, attrValue, attrs) { attrValue = attrValue ? trimWhitespace(attrValue.toLowerCase()) : ''; return ( tag === 'script' && attrName === 'language' && attrValue === 'javascript' || tag === 'form' && attrName === 'method' && attrValue === 'get' || tag === 'input' && attrName === 'type' && attrValue === 'text' || tag === 'script' && attrName === 'charset' && !attributesInclude(attrs, 'src') || tag === 'a' && attrName === 'name' && attributesInclude(attrs, 'id') || tag === 'area' && attrName === 'shape' && attrValue === 'rect' ); } // https://mathiasbynens.be/demo/javascript-mime-type // https://developer.mozilla.org/en/docs/Web/HTML/Element/script#attr-type var executableScriptsMimetypes = utils.createMap([ 'text/javascript', 'text/ecmascript', 'text/jscript', 'application/javascript', 'application/x-javascript', 'application/ecmascript' ]); function isScriptTypeAttribute(attrValue) { attrValue = trimWhitespace(attrValue.split(/;/, 2)[0]).toLowerCase(); return attrValue === '' || executableScriptsMimetypes(attrValue); } function isExecutableScript(tag, attrs) { if (tag !== 'script') { return false; } for (var i = 0, len = attrs.length; i < len; i++) { var attrName = attrs[i].name.toLowerCase(); if (attrName === 'type') { return isScriptTypeAttribute(attrs[i].value); } } return true; } function isStyleLinkTypeAttribute(attrValue) { attrValue = trimWhitespace(attrValue).toLowerCase(); return attrValue === '' || attrValue === 'text/css'; } function isStyleSheet(tag, attrs) { if (tag !== 'style') { return false; } for (var i = 0, len = attrs.length; i < len; i++) { var attrName = attrs[i].name.toLowerCase(); if (attrName === 'type') { return isStyleLinkTypeAttribute(attrs[i].value); } } return true; } var isSimpleBoolean = createMapFromString('allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,truespeed,typemustmatch,visible'); var isBooleanValue = createMapFromString('true,false'); function isBooleanAttribute(attrName, attrValue) { return isSimpleBoolean(attrName) || attrName === 'draggable' && !isBooleanValue(attrValue); } function isUriTypeAttribute(attrName, tag) { return ( /^(?:a|area|link|base)$/.test(tag) && attrName === 'href' || tag === 'img' && /^(?:src|longdesc|usemap)$/.test(attrName) || tag === 'object' && /^(?:classid|codebase|data|usemap)$/.test(attrName) || tag === 'q' && attrName === 'cite' || tag === 'blockquote' && attrName === 'cite' || (tag === 'ins' || tag === 'del') && attrName === 'cite' || tag === 'form' && attrName === 'action' || tag === 'input' && (attrName === 'src' || attrName === 'usemap') || tag === 'head' && attrName === 'profile' || tag === 'script' && (attrName === 'src' || attrName === 'for') ); } function isNumberTypeAttribute(attrName, tag) { return ( /^(?:a|area|object|button)$/.test(tag) && attrName === 'tabindex' || tag === 'input' && (attrName === 'maxlength' || attrName === 'tabindex') || tag === 'select' && (attrName === 'size' || attrName === 'tabindex') || tag === 'textarea' && /^(?:rows|cols|tabindex)$/.test(attrName) || tag === 'colgroup' && attrName === 'span' || tag === 'col' && attrName === 'span' || (tag === 'th' || tag === 'td') && (attrName === 'rowspan' || attrName === 'colspan') ); } function isLinkType(tag, attrs, value) { if (tag !== 'link') { return false; } for (var i = 0, len = attrs.length; i < len; i++) { if (attrs[i].name === 'rel' && attrs[i].value === value) { return true; } } } function isMediaQuery(tag, attrs, attrName) { return attrName === 'media' && (isLinkType(tag, attrs, 'stylesheet') || isStyleSheet(tag, attrs)); } var srcsetTags = createMapFromString('img,source'); function isSrcset(attrName, tag) { return attrName === 'srcset' && srcsetTags(tag); } function cleanAttributeValue(tag, attrName, attrValue, options, attrs) { if (attrValue && isEventAttribute(attrName, options)) { attrValue = trimWhitespace(attrValue).replace(/^javascript:\s*/i, ''); return options.minifyJS(attrValue, true); } else if (attrName === 'class') { attrValue = trimWhitespace(attrValue); if (options.sortClassName) { attrValue = options.sortClassName(attrValue); } else { attrValue = collapseWhitespaceAll(attrValue); } return attrValue; } else if (isUriTypeAttribute(attrName, tag)) { attrValue = trimWhitespace(attrValue); return isLinkType(tag, attrs, 'canonical') ? attrValue : options.minifyURLs(attrValue); } else if (isNumberTypeAttribute(attrName, tag)) { return trimWhitespace(attrValue); } else if (attrName === 'style') { attrValue = trimWhitespace(attrValue); if (attrValue) { if (/;$/.test(attrValue) && !/&#?[0-9a-zA-Z]+;$/.test(attrValue)) { attrValue = attrValue.replace(/\s*;$/, ';'); } attrValue = unwrapInlineCSS(options.minifyCSS(wrapInlineCSS(attrValue))); } return attrValue; } else if (isSrcset(attrName, tag)) { // https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-srcset attrValue = trimWhitespace(attrValue).split(/\s+,\s*|\s*,\s+/).map(function(candidate) { var url = candidate; var descriptor = ''; var match = candidate.match(/\s+([1-9][0-9]*w|[0-9]+(?:\.[0-9]+)?x)$/); if (match) { url = url.slice(0, -match[0].length); var num = +match[1].slice(0, -1); var suffix = match[1].slice(-1); if (num !== 1 || suffix !== 'x') { descriptor = ' ' + num + suffix; } } return options.minifyURLs(url) + descriptor; }).join(', '); } else if (isMetaViewport(tag, attrs) && attrName === 'content') { attrValue = attrValue.replace(/\s+/g, '').replace(/[0-9]+\.[0-9]+/g, function(numString) { // "0.90000" -> "0.9" // "1.0" -> "1" // "1.0001" -> "1.0001" (unchanged) return (+numString).toString(); }); } else if (attrValue && options.customAttrCollapse && options.customAttrCollapse.test(attrName)) { attrValue = attrValue.replace(/\n+|\r+|\s{2,}/g, ''); } else if (tag === 'script' && attrName === 'type') { attrValue = trimWhitespace(attrValue.replace(/\s*;\s*/g, ';')); } else if (isMediaQuery(tag, attrs, attrName)) { attrValue = trimWhitespace(attrValue); return unwrapMediaQuery(options.minifyCSS(wrapMediaQuery(attrValue))); } return attrValue; } function isMetaViewport(tag, attrs) { if (tag !== 'meta') { return false; } for (var i = 0, len = attrs.length; i < len; i++) { if (attrs[i].name === 'name' && attrs[i].value === 'viewport') { return true; } } } // Wrap CSS declarations for CleanCSS > 3.x // See https://github.com/jakubpawlowicz/clean-css/issues/418 function wrapInlineCSS(text) { return '*{' + text + '}'; } function unwrapInlineCSS(text) { var matches = text.match(/^\*\{([\s\S]*)\}$/); return matches ? matches[1] : text; } function wrapMediaQuery(text) { return '@media ' + text + '{a{top:0}}'; } function unwrapMediaQuery(text) { var matches = text.match(/^@media ([\s\S]*?)\s*{[\s\S]*}$/); return matches ? matches[1] : text; } function cleanConditionalComment(comment, options) { return options.processConditionalComments ? comment.replace(/^(\[if\s[^\]]+]>)([\s\S]*?)(<!\[endif])$/, function(match, prefix, text, suffix) { return prefix + minify(text, options, true) + suffix; }) : comment; } function processScript(text, options, currentAttrs) { for (var i = 0, len = currentAttrs.length; i < len; i++) { if (currentAttrs[i].name.toLowerCase() === 'type' && options.processScripts.indexOf(currentAttrs[i].value) > -1) { return minify(text, options); } } return text; } // Tag omission rules from https://html.spec.whatwg.org/multipage/syntax.html#optional-tags // with the following deviations: // - retain <body> if followed by <noscript> // - </rb>, </rt>, </rtc>, </rp> & </tfoot> follow http://www.w3.org/TR/html5/syntax.html#optional-tags // - retain all tags which are adjacent to non-standard HTML tags var optionalStartTags = createMapFromString('html,head,body,colgroup,tbody'); var optionalEndTags = createMapFromString('html,head,body,li,dt,dd,p,rb,rt,rtc,rp,optgroup,option,colgroup,caption,thead,tbody,tfoot,tr,td,th'); var headerTags = createMapFromString('meta,link,script,style,template,noscript'); var descriptionTags = createMapFromString('dt,dd'); var pBlockTags = createMapFromString('address,article,aside,blockquote,details,div,dl,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,main,menu,nav,ol,p,pre,section,table,ul'); var pInlineTags = createMapFromString('a,audio,del,ins,map,noscript,video'); var rubyTags = createMapFromString('rb,rt,rtc,rp'); var rtcTag = createMapFromString('rb,rtc,rp'); var optionTag = createMapFromString('option,optgroup'); var tableContentTags = createMapFromString('tbody,tfoot'); var tableSectionTags = createMapFromString('thead,tbody,tfoot'); var cellTags = createMapFromString('td,th'); var topLevelTags = createMapFromString('html,head,body'); var compactTags = createMapFromString('html,body'); var looseTags = createMapFromString('head,colgroup,caption'); var trailingTags = createMapFromString('dt,thead'); var htmlTags = createMapFromString('a,abbr,acronym,address,applet,area,article,aside,audio,b,base,basefont,bdi,bdo,bgsound,big,blink,blockquote,body,br,button,canvas,caption,center,cite,code,col,colgroup,command,content,data,datalist,dd,del,details,dfn,dialog,dir,div,dl,dt,element,em,embed,fieldset,figcaption,figure,font,footer,form,frame,frameset,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,image,img,input,ins,isindex,kbd,keygen,label,legend,li,link,listing,main,map,mark,marquee,menu,menuitem,meta,meter,multicol,nav,nobr,noembed,noframes,noscript,object,ol,optgroup,option,output,p,param,picture,plaintext,pre,progress,q,rp,rt,rtc,ruby,s,samp,script,section,select,shadow,small,source,spacer,span,strike,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,tt,u,ul,var,video,wbr,xmp'); function canRemoveParentTag(optionalStartTag, tag) { switch (optionalStartTag) { case 'html': case 'head': return true; case 'body': return !headerTags(tag); case 'colgroup': return tag === 'col'; case 'tbody': return tag === 'tr'; } return false; } function isStartTagMandatory(optionalEndTag, tag) { switch (tag) { case 'colgroup': return optionalEndTag === 'colgroup'; case 'tbody': return tableSectionTags(optionalEndTag); } return false; } function canRemovePrecedingTag(optionalEndTag, tag) { switch (optionalEndTag) { case 'html': case 'head': case 'body': case 'colgroup': case 'caption': return true; case 'li': case 'optgroup': case 'tr': return tag === optionalEndTag; case 'dt': case 'dd': return descriptionTags(tag); case 'p': return pBlockTags(tag); case 'rb': case 'rt': case 'rp': return rubyTags(tag); case 'rtc': return rtcTag(tag); case 'option': return optionTag(tag); case 'thead': case 'tbody': return tableContentTags(tag); case 'tfoot': return tag === 'tbody'; case 'td': case 'th': return cellTags(tag); } return false; } var reEmptyAttribute = new RegExp( '^(?:class|id|style|title|lang|dir|on(?:focus|blur|change|click|dblclick|mouse(' + '?:down|up|over|move|out)|key(?:press|down|up)))$'); function canDeleteEmptyAttribute(tag, attrName, attrValue, options) { var isValueEmpty = !attrValue || /^\s*$/.test(attrValue); if (!isValueEmpty) { return false; } if (typeof options.removeEmptyAttributes === 'function') { return options.removeEmptyAttributes(attrName, tag); } return tag === 'input' && attrName === 'value' || reEmptyAttribute.test(attrName); } function hasAttrName(name, attrs) { for (var i = attrs.length - 1; i >= 0; i--) { if (attrs[i].name === name) { return true; } } return false; } function canRemoveElement(tag, attrs) { switch (tag) { case 'textarea': return false; case 'audio': case 'script': case 'video': if (hasAttrName('src', attrs)) { return false; } break; case 'iframe': if (hasAttrName('src', attrs) || hasAttrName('srcdoc', attrs)) { return false; } break; case 'object': if (hasAttrName('data', attrs)) { return false; } break; case 'applet': if (hasAttrName('code', attrs)) { return false; } break; } return true; } function canCollapseWhitespace(tag) { return !/^(?:script|style|pre|textarea)$/.test(tag); } function canTrimWhitespace(tag) { return !/^(?:pre|textarea)$/.test(tag); } function normalizeAttr(attr, attrs, tag, options) { var attrName = options.caseSensitive ? attr.name : attr.name.toLowerCase(), attrValue = attr.value; if (options.decodeEntities && attrValue) { attrValue = decode(attrValue, { isAttributeValue: true }); } if (options.removeRedundantAttributes && isAttributeRedundant(tag, attrName, attrValue, attrs) || options.removeScriptTypeAttributes && tag === 'script' && attrName === 'type' && isScriptTypeAttribute(attrValue) || options.removeStyleLinkTypeAttributes && (tag === 'style' || tag === 'link') && attrName === 'type' && isStyleLinkTypeAttribute(attrValue)) { return; } attrValue = cleanAttributeValue(tag, attrName, attrValue, options, attrs); if (options.removeEmptyAttributes && canDeleteEmptyAttribute(tag, attrName, attrValue, options)) { return; } if (options.decodeEntities && attrValue) { attrValue = attrValue.replace(/&(#?[0-9a-zA-Z]+;)/g, '&amp;$1'); } return { attr: attr, name: attrName, value: attrValue }; } function buildAttr(normalized, hasUnarySlash, options, isLast, uidAttr) { var attrName = normalized.name, attrValue = normalized.value, attr = normalized.attr, attrQuote = attr.quote, attrFragment, emittedAttrValue; if (typeof attrValue !== 'undefined' && (!options.removeAttributeQuotes || ~attrValue.indexOf(uidAttr) || !canRemoveAttributeQuotes(attrValue))) { if (!options.preventAttributesEscaping) { if (typeof options.quoteCharacter === 'undefined') { var apos = (attrValue.match(/'/g) || []).length; var quot = (attrValue.match(/"/g) || []).length; attrQuote = apos < quot ? '\'' : '"'; } else { attrQuote = options.quoteCharacter === '\'' ? '\'' : '"'; } if (attrQuote === '"') { attrValue = attrValue.replace(/"/g, '&#34;'); } else { attrValue = attrValue.replace(/'/g, '&#39;'); } } emittedAttrValue = attrQuote + attrValue + attrQuote; if (!isLast && !options.removeTagWhitespace) { emittedAttrValue += ' '; } } // make sure trailing slash is not interpreted as HTML self-closing tag else if (isLast && !hasUnarySlash && !/\/$/.test(attrValue)) { emittedAttrValue = attrValue; } else { emittedAttrValue = attrValue + ' '; } if (typeof attrValue === 'undefined' || options.collapseBooleanAttributes && isBooleanAttribute(attrName.toLowerCase(), attrValue.toLowerCase())) { attrFragment = attrName; if (!isLast) { attrFragment += ' '; } } else { attrFragment = attrName + attr.customAssign + emittedAttrValue; } return attr.customOpen + attrFragment + attr.customClose; } function identity(value) { return value; } function processOptions(options) { ['html5', 'includeAutoGeneratedTags'].forEach(function(key) { if (!(key in options)) { options[key] = true; } }); if (typeof options.log !== 'function') { options.log = identity; } if (!options.canCollapseWhitespace) { options.canCollapseWhitespace = canCollapseWhitespace; } if (!options.canTrimWhitespace) { options.canTrimWhitespace = canTrimWhitespace; } if (!('ignoreCustomComments' in options)) { options.ignoreCustomComments = [/^!/]; } if (!('ignoreCustomFragments' in options)) { options.ignoreCustomFragments = [ /<%[\s\S]*?%>/, /<\?[\s\S]*?\?>/ ]; } if (!options.minifyURLs) { options.minifyURLs = identity; } if (typeof options.minifyURLs !== 'function') { var minifyURLs = options.minifyURLs; if (typeof minifyURLs === 'string') { minifyURLs = { site: minifyURLs }; } else if (typeof minifyURLs !== 'object') { minifyURLs = {}; } options.minifyURLs = function(text) { try { return RelateUrl.relate(text, minifyURLs); } catch (err) { options.log(err); return text; } }; } if (!options.minifyJS) { options.minifyJS = identity; } if (typeof options.minifyJS !== 'function') { var minifyJS = options.minifyJS; if (typeof minifyJS !== 'object') { minifyJS = {}; } (minifyJS.parse || (minifyJS.parse = {})).bare_returns = false; options.minifyJS = function(text, inline) { var start = text.match(/^\s*<!--.*/); var code = start ? text.slice(start[0].length).replace(/\n\s*-->\s*$/, '') : text; minifyJS.parse.bare_returns = inline; var result = UglifyJS.minify(code, minifyJS); if (result.error) { options.log(result.error); return text; } return result.code.replace(/;$/, ''); }; } if (!options.minifyCSS) { options.minifyCSS = identity; } if (typeof options.minifyCSS !== 'function') { var minifyCSS = options.minifyCSS; if (typeof minifyCSS !== 'object') { minifyCSS = {}; } options.minifyCSS = function(text) { text = text.replace(/(url\s*\(\s*)("|'|)(.*?)\2(\s*\))/ig, function(match, prefix, quote, url, suffix) { return prefix + quote + options.minifyURLs(url) + quote + suffix; }); try { return new CleanCSS(minifyCSS).minify(text).styles; } catch (err) { options.log(err); return text; } }; } } function uniqueId(value) { var id; do { id = Math.random().toString(36).replace(/^0\.[0-9]*/, ''); } while (~value.indexOf(id)); return id; } var specialContentTags = createMapFromString('script,style'); function createSortFns(value, options, uidIgnore, uidAttr) { var attrChains = options.sortAttributes && Object.create(null); var classChain = options.sortClassName && new TokenChain(); function attrNames(attrs) { return attrs.map(function(attr) { return options.caseSensitive ? attr.name : attr.name.toLowerCase(); }); } function shouldSkipUID(token, uid) { return !uid || token.indexOf(uid) === -1; } function shouldSkipUIDs(token) { return shouldSkipUID(token, uidIgnore) && shouldSkipUID(token, uidAttr); } function scan(input) { var currentTag, currentType; new HTMLParser(input, { start: function(tag, attrs) { if (attrChains) { if (!attrChains[tag]) { attrChains[tag] = new TokenChain(); } attrChains[tag].add(attrNames(attrs).filter(shouldSkipUIDs)); } for (var i = 0, len = attrs.length; i < len; i++) { var attr = attrs[i]; if (classChain && (options.caseSensitive ? attr.name : attr.name.toLowerCase()) === 'class') { classChain.add(trimWhitespace(attr.value).split(/[ \t\n\f\r]+/).filter(shouldSkipUIDs)); } else if (options.processScripts && attr.name.toLowerCase() === 'type') { currentTag = tag; currentType = attr.value; } } }, end: function() { currentTag = ''; }, chars: function(text) { if (options.processScripts && specialContentTags(currentTag) && options.processScripts.indexOf(currentType) > -1) { scan(text); } } }); } var log = options.log; options.log = null; options.sortAttributes = false; options.sortClassName = false; scan(minify(value, options)); options.log = log; if (attrChains) { var attrSorters = Object.create(null); for (var tag in attrChains) { attrSorters[tag] = attrChains[tag].createSorter(); } options.sortAttributes = function(tag, attrs) { var sorter = attrSorters[tag]; if (sorter) { var attrMap = Object.create(null); var names = attrNames(attrs); names.forEach(function(name, index) { (attrMap[name] || (attrMap[name] = [])).push(attrs[index]); }); sorter.sort(names).forEach(function(name, index) { attrs[index] = attrMap[name].shift(); }); } }; } if (classChain) { var sorter = classChain.createSorter(); options.sortClassName = function(value) { return sorter.sort(value.split(/[ \n\f\r]+/)).join(' '); }; } } function minify(value, options, partialMarkup) { options = options || {}; var optionsStack = []; processOptions(options); if (options.collapseWhitespace) { value = collapseWhitespace(value, options, true, true); } var buffer = [], charsPrevTag, currentChars = '', hasChars, currentTag = '', currentAttrs = [], stackNoTrimWhitespace = [], stackNoCollapseWhitespace = [], optionalStartTag = '', optionalEndTag = '', t = Date.now(), ignoredMarkupChunks = [], ignoredCustomMarkupChunks = [], uidIgnore, uidAttr, uidPattern; // temporarily replace ignored chunks with comments, // so that we don't have to worry what's there. // for all we care there might be // completely-horribly-broken-alien-non-html-emoj-cthulhu-filled content value = value.replace(/<!-- htmlmin:ignore -->([\s\S]*?)<!-- htmlmin:ignore -->/g, function(match, group1) { if (!uidIgnore) { uidIgnore = uniqueId(value); var pattern = new RegExp('^' + uidIgnore + '([0-9]+)$'); if (options.ignoreCustomComments) { options.ignoreCustomComments.push(pattern); } else { options.ignoreCustomComments = [pattern]; } } var token = '<!--' + uidIgnore + ignoredMarkupChunks.length + '-->'; ignoredMarkupChunks.push(group1); return token; }); function escapeFragments(text) { return text.replace(uidPattern, function(match, prefix, index) { var chunks = ignoredCustomMarkupChunks[+index]; return chunks[1] + uidAttr + index + chunks[2]; }); } var customFragments = options.ignoreCustomFragments.map(function(re) { return re.source; }); if (customFragments.length) { var reCustomIgnore = new RegExp('\\s*(?:' + customFragments.join('|') + ')+\\s*', 'g'); // temporarily replace custom ignored fragments with unique attributes value = value.replace(reCustomIgnore, function(match) { if (!uidAttr) { uidAttr = uniqueId(value); uidPattern = new RegExp('(\\s*)' + uidAttr + '([0-9]+)(\\s*)', 'g'); var minifyCSS = options.minifyCSS; if (minifyCSS) { options.minifyCSS = function(text) { return minifyCSS(escapeFragments(text)); }; } var minifyJS = options.minifyJS; if (minifyJS) { options.minifyJS = function(text, inline) { return minifyJS(escapeFragments(text), inline); }; } } var token = uidAttr + ignoredCustomMarkupChunks.length; ignoredCustomMarkupChunks.push(/^(\s*)[\s\S]*?(\s*)$/.exec(match)); return '\t' + token + '\t'; }); } if (options.sortAttributes && typeof options.sortAttributes !== 'function' || options.sortClassName && typeof options.sortClassName !== 'function') { createSortFns(value, options, uidIgnore, uidAttr); } function _canCollapseWhitespace(tag, attrs) { return options.canCollapseWhitespace(tag, attrs, canCollapseWhitespace); } function _canTrimWhitespace(tag, attrs) { return options.canTrimWhitespace(tag, attrs, canTrimWhitespace); } function removeStartTag() { var index = buffer.length - 1; while (index > 0 && !/^<[^/!]/.test(buffer[index])) { index--; } buffer.length = Math.max(0, index); } function removeEndTag() { var index = buffer.length - 1; while (index > 0 && !/^<\//.test(buffer[index])) { index--; } buffer.length = Math.max(0, index); } // look for trailing whitespaces, bypass any inline tags function trimTrailingWhitespace(index, nextTag) { for (var endTag = null; index >= 0 && _canTrimWhitespace(endTag); index--) { var str = buffer[index]; var match = str.match(/^<\/([\w:-]+)>$/); if (match) { endTag = match[1]; } else if (/>$/.test(str) || (buffer[index] = collapseWhitespaceSmart(str, null, nextTag, options))) { break; } } } // look for trailing whitespaces from previously processed text // which may not be trimmed due to a following comment or an empty // element which has now been removed function squashTrailingWhitespace(nextTag) { var charsIndex = buffer.length - 1; if (buffer.length > 1) { var item = buffer[buffer.length - 1]; if (/^(?:<!|$)/.test(item) && item.indexOf(uidIgnore) === -1) { charsIndex--; } } trimTrailingWhitespace(charsIndex, nextTag); } new HTMLParser(value, { partialMarkup: partialMarkup, html5: options.html5, start: function(tag, attrs, unary, unarySlash, autoGenerated) { var lowerTag = tag.toLowerCase(); if (lowerTag === 'svg') { optionsStack.push(options); var nextOptions = {}; for (var key in options) { nextOptions[key] = options[key]; } nextOptions.keepClosingSlash = true; nextOptions.caseSensitive = true; options = nextOptions; } tag = options.caseSensitive ? tag : lowerTag; currentTag = tag; charsPrevTag = tag; if (!inlineTextTags(tag)) { currentChars = ''; } hasChars = false; currentAttrs = attrs; var optional = options.removeOptionalTags; if (optional) { var htmlTag = htmlTags(tag); // <html> may be omitted if first thing inside is not comment // <head> may be omitted if first thing inside is an element // <body> may be omitted if first thing inside is not space, comment, <meta>, <link>, <script>, <style> or <template> // <colgroup> may be omitted if first thing inside is <col> // <tbody> may be omitted if first thing inside is <tr> if (htmlTag && canRemoveParentTag(optionalStartTag, tag)) { removeStartTag(); } optionalStartTag = ''; // end-tag-followed-by-start-tag omission rules if (htmlTag && canRemovePrecedingTag(optionalEndTag, tag)) { removeEndTag(); // <colgroup> cannot be omitted if preceding </colgroup> is omitted // <tbody> cannot be omitted if preceding </tbody>, </thead> or </tfoot> is omitted optional = !isStartTagMandatory(optionalEndTag, tag); } optionalEndTag = ''; } // set whitespace flags for nested tags (eg. <code> within a <pre>) if (options.collapseWhitespace) { if (!stackNoTrimWhitespace.length) { squashTrailingWhitespace(tag); } if (!unary) { if (!_canTrimWhitespace(tag, attrs) || stackNoTrimWhitespace.length) { stackNoTrimWhitespace.push(tag); } if (!_canCollapseWhitespace(tag, attrs) || stackNoCollapseWhitespace.length) { stackNoCollapseWhitespace.push(tag); } } } var openTag = '<' + tag; var hasUnarySlash = unarySlash && options.keepClosingSlash; buffer.push(openTag); if (options.sortAttributes) { options.sortAttributes(tag, attrs); } var parts = []; for (var i = attrs.length, isLast = true; --i >= 0;) { var normalized = normalizeAttr(attrs[i], attrs, tag, options); if (normalized) { parts.unshift(buildAttr(normalized, hasUnarySlash, options, isLast, uidAttr)); isLast = false; } } if (parts.length > 0) { buffer.push(' '); buffer.push.apply(buffer, parts); } // start tag must never be omitted if it has any attributes else if (optional && optionalStartTags(tag)) { optionalStartTag = tag; } buffer.push(buffer.pop() + (hasUnarySlash ? '/' : '') + '>'); if (autoGenerated && !options.includeAutoGeneratedTags) { removeStartTag(); optionalStartTag = ''; } }, end: function(tag, attrs, autoGenerated) { var lowerTag = tag.toLowerCase(); if (lowerTag === 'svg') { options = optionsStack.pop(); } tag = options.caseSensitive ? tag : lowerTag; // check if current tag is in a whitespace stack if (options.collapseWhitespace) { if (stackNoTrimWhitespace.length) { if (tag === stackNoTrimWhitespace[stackNoTrimWhitespace.length - 1]) { stackNoTrimWhitespace.pop(); } } else { squashTrailingWhitespace('/' + tag); } if (stackNoCollapseWhitespace.length && tag === stackNoCollapseWhitespace[stackNoCollapseWhitespace.length - 1]) { stackNoCollapseWhitespace.pop(); } } var isElementEmpty = false; if (tag === currentTag) { currentTag = ''; isElementEmpty = !hasChars; } if (options.removeOptionalTags) { // <html>, <head> or <body> may be omitted if the element is empty if (isElementEmpty && topLevelTags(optionalStartTag)) { removeStartTag(); } optionalStartTag = ''; // </html> or </body> may be omitted if not followed by comment // </head> may be omitted if not followed by space or comment // </p> may be omitted if no more content in non-</a> parent // except for </dt> or </thead>, end tags may be omitted if no more content in parent element if (htmlTags(tag) && optionalEndTag && !trailingTags(optionalEndTag) && (optionalEndTag !== 'p' || !pInlineTags(tag))) { removeEndTag(); } optionalEndTag = optionalEndTags(tag) ? tag : ''; } if (options.removeEmptyElements && isElementEmpty && canRemoveElement(tag, attrs)) { // remove last "element" from buffer removeStartTag(); optionalStartTag = ''; optionalEndTag = ''; } else { if (autoGenerated && !options.includeAutoGeneratedTags) { optionalEndTag = ''; } else { buffer.push('</' + tag + '>'); } charsPrevTag = '/' + tag; if (!inlineTags(tag)) { currentChars = ''; } else if (isElementEmpty) { currentChars += '|'; } } }, chars: function(text, prevTag, nextTag) { prevTag = prevTag === '' ? 'comment' : prevTag; nextTag = nextTag === '' ? 'comment' : nextTag; if (options.decodeEntities && text && !specialContentTags(currentTag)) { text = decode(text); } if (options.collapseWhitespace) { if (!stackNoTrimWhitespace.length) { if (prevTag === 'comment') { var prevComment = buffer[buffer.length - 1]; if (prevComment.indexOf(uidIgnore) === -1) { if (!prevComment) { prevTag = charsPrevTag; } if (buffer.length > 1 && (!prevComment || !options.conservativeCollapse && / $/.test(currentChars))) { var charsIndex = buffer.length - 2; buffer[charsIndex] = buffer[charsIndex].replace(/\s+$/, function(trailingSpaces) { text = trailingSpaces + text; return ''; }); } } } if (prevTag) { if (prevTag === '/nobr' || prevTag === 'wbr') { if (/^\s/.test(text)) { var tagIndex = buffer.length - 1; while (tagIndex > 0 && buffer[tagIndex].lastIndexOf('<' + prevTag) !== 0) { tagIndex--; } trimTrailingWhitespace(tagIndex - 1, 'br'); } } else if (inlineTextTags(prevTag.charAt(0) === '/' ? prevTag.slice(1) : prevTag)) { text = collapseWhitespace(text, options, /(?:^|\s)$/.test(currentChars)); } } if (prevTag || nextTag) { text = collapseWhitespaceSmart(text, prevTag, nextTag, options); } else { text = collapseWhitespace(text, options, true, true); } if (!text && /\s$/.test(currentChars) && prevTag && prevTag.charAt(0) === '/') { trimTrailingWhitespace(buffer.length - 1, nextTag); } } if (!stackNoCollapseWhitespace.length && nextTag !== 'html' && !(prevTag && nextTag)) { text = collapseWhitespace(text, options, false, false, true); } } if (options.processScripts && specialContentTags(currentTag)) { text = processScript(text, options, currentAttrs); } if (isExecutableScript(currentTag, currentAttrs)) { text = options.minifyJS(text); } if (isStyleSheet(currentTag, currentAttrs)) { text = options.minifyCSS(text); } if (options.removeOptionalTags && text) { // <html> may be omitted if first thing inside is not comment // <body> may be omitted if first thing inside is not space, comment, <meta>, <link>, <script>, <style> or <template> if (optionalStartTag === 'html' || optionalStartTag === 'body' && !/^\s/.test(text)) { removeStartTag(); } optionalStartTag = ''; // </html> or </body> may be omitted if not followed by comment // </head>, </colgroup> or </caption> may be omitted if not followed by space or comment if (compactTags(optionalEndTag) || looseTags(optionalEndTag) && !/^\s/.test(text)) { removeEndTag(); } optionalEndTag = ''; } charsPrevTag = /^\s*$/.test(text) ? prevTag : 'comment'; if (options.decodeEntities && text && !specialContentTags(currentTag)) { // semi-colon can be omitted // https://mathiasbynens.be/notes/ambiguous-ampersands text = text.replace(/&(#?[0-9a-zA-Z]+;)/g, '&amp$1').replace(/</g, '&lt;'); } currentChars += text; if (text) { hasChars = true; } buffer.push(text); }, comment: function(text, nonStandard) { var prefix = nonStandard ? '<!' : '<!--'; var suffix = nonStandard ? '>' : '-->'; if (isConditionalComment(text)) { text = prefix + cleanConditionalComment(text, options) + suffix; } else if (options.removeComments) { if (isIgnoredComment(text, options)) { text = '<!--' + text + '-->'; } else { text = ''; } } else { text = prefix + text + suffix; } if (options.removeOptionalTags && text) { // preceding comments suppress tag omissions optionalStartTag = ''; optionalEndTag = ''; } buffer.push(text); }, doctype: function(doctype) { buffer.push(options.useShortDoctype ? '<!DOCTYPE html>' : collapseWhitespaceAll(doctype)); }, customAttrAssign: options.customAttrAssign, customAttrSurround: options.customAttrSurround }); if (options.removeOptionalTags) { // <html> may be omitted if first thing inside is not comment // <head> or <body> may be omitted if empty if (topLevelTags(optionalStartTag)) { removeStartTag(); } // except for </dt> or </thead>, end tags may be omitted if no more content in parent element if (optionalEndTag && !trailingTags(optionalEndTag)) { removeEndTag(); } } if (options.collapseWhitespace) { squashTrailingWhitespace('br'); } var str = joinResultSegments(buffer, options); if (uidPattern) { str = str.replace(uidPattern, function(match, prefix, index, suffix) { var chunk = ignoredCustomMarkupChunks[+index][0]; if (options.collapseWhitespace) { if (prefix !== '\t') { chunk = prefix + chunk; } if (suffix !== '\t') { chunk += suffix; } return collapseWhitespace(chunk, { preserveLineBreaks: options.preserveLineBreaks, conservativeCollapse: !options.trimCustomFragments }, /^[ \n\r\t\f]/.test(chunk), /[ \n\r\t\f]$/.test(chunk)); } return chunk; }); } if (uidIgnore) { str = str.replace(new RegExp('<!--' + uidIgnore + '([0-9]+)-->', 'g'), function(match, index) { return ignoredMarkupChunks[+index]; }); } options.log('minified in: ' + (Date.now() - t) + 'ms'); return str; } function joinResultSegments(results, options) { var str; var maxLineLength = options.maxLineLength; if (maxLineLength) { var token; var lines = []; var line = ''; for (var i = 0, len = results.length; i < len; i++) { token = results[i]; if (line.length + token.length < maxLineLength) { line += token; } else { lines.push(line.replace(/^\n/, '')); line = token; } } lines.push(line); str = lines.join('\n'); } else { str = results.join(''); } return options.collapseWhitespace ? collapseWhitespace(str, options, true, true) : str; } exports.minify = function(value, options) { return minify(value, options); };
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If Type(x) is String and Type(y) is Object, return x == ToPrimitive(y) es5id: 11.9.1_A7.7 description: y is object, x is primitive string ---*/ //CHECK#1 if (("1" == new Boolean(true)) !== true) { $ERROR('#1: ("1" == new Boolean(true)) === true'); } //CHECK#2 if (("-1" == new Number(-1)) !== true) { $ERROR('#2: ("-1" == new Number(-1)) === true'); } //CHECK#3 if (("x" == new String("x")) !== true) { $ERROR('#3: ("x" == new String("x")) === true'); }
require('./common/runtime.js') require('./common/vendor.js') require('./common/main.js')
Template.infoAccountModalInner.helpers({ email: function () { if (this.emails && this.emails.length) return this.emails[0].address; if (this.services) { //Iterate through services for (var serviceName in this.services) { var serviceObject = this.services[serviceName]; //If an 'id' isset then assume valid service if (serviceObject.id) { if (serviceObject.email) { return serviceObject.email; } } } } return ""; }, userInScope: function() { return Session.get('userInScope'); }, rolePairs: function() { var pairs = []; if (!this.roles) pairs.push({key: 'Roles', value: 'None'}); for (var role in this.roles) { var r = this.roles[role]; if (role === '0') { pairs.push({key: 'Roles', value: r}); } else { pairs.push({key: '-', value: r}); } } return pairs; } });
declare module "react-typekit" { declare class Typekit extends React$Component { props: { kitId: string }; } declare module.exports: typeof Typekit; }
import React, {Component, PropTypes} from 'react'; import transitions from '../styles/transitions'; import EnhancedSwitch from '../internal/EnhancedSwitch'; import RadioButtonOff from '../svg-icons/toggle/radio-button-unchecked'; import RadioButtonOn from '../svg-icons/toggle/radio-button-checked'; function getStyles(props, context) { const {radioButton} = context.muiTheme; return { icon: { height: radioButton.size, width: radioButton.size, }, target: { transition: transitions.easeOut(), position: 'absolute', opacity: 1, transform: 'scale(1)', fill: radioButton.borderColor, }, fill: { position: 'absolute', opacity: 1, transform: 'scale(0)', transformOrigin: '50% 50%', transition: transitions.easeOut(), fill: radioButton.checkedColor, }, targetWhenChecked: { opacity: 0, transform: 'scale(0)', }, fillWhenChecked: { opacity: 1, transform: 'scale(1)', }, targetWhenDisabled: { fill: radioButton.disabledColor, }, fillWhenDisabled: { fill: radioButton.disabledColor, }, label: { color: props.disabled ? radioButton.labelDisabledColor : radioButton.labelColor, }, ripple: { color: props.checked ? radioButton.checkedColor : radioButton.borderColor, }, }; } class RadioButton extends Component { static propTypes = { /** * @ignore * checked if true * Used internally by `RadioButtonGroup`. */ checked: PropTypes.bool, /** * The icon element to show when the radio button is checked. */ checkedIcon: PropTypes.element, /** * If true, the radio button is disabled. */ disabled: PropTypes.bool, /** * Override the inline-styles of the icon element. */ iconStyle: PropTypes.object, /** * Override the inline-styles of the input element. */ inputStyle: PropTypes.object, /** * @ignore * Used internally by `RadioButtonGroup`. Use the `labelPosition` property of `RadioButtonGroup` instead. * Where the label will be placed next to the radio button. */ labelPosition: PropTypes.oneOf(['left', 'right']), /** * Override the inline-styles of the label element. */ labelStyle: PropTypes.object, /** * @ignore * Callback function fired when the radio button is checked. Note that this * function will not be called if the radio button is part of a * radio button group: in this case, use the `onChange` property of * `RadioButtonGroup`. * * @param {object} event `change` event targeting the element. * @param {string} value The element's `value`. */ onCheck: PropTypes.func, /** * Override the inline-styles of the root element. */ style: PropTypes.object, /** * The icon element to show when the radio button is unchecked. */ uncheckedIcon: PropTypes.element, /** * The value of the radio button. */ value: PropTypes.any, }; static defaultProps = { checked: false, disabled: false, labelPosition: 'right', }; static contextTypes = { muiTheme: PropTypes.object.isRequired, }; // Only called when selected, not when unselected. handleSwitch = (event) => { if (this.props.onCheck) { this.props.onCheck(event, this.props.value); } }; isChecked() { return this.refs.enhancedSwitch.isSwitched(); } // Use RadioButtonGroup.setSelectedValue(newSelectionValue) to set a // RadioButton's checked value. setChecked(newCheckedValue) { this.refs.enhancedSwitch.setSwitched(newCheckedValue); } getValue() { return this.refs.enhancedSwitch.getValue(); } render() { const { checkedIcon, checked, iconStyle, labelStyle, labelPosition, onCheck, // eslint-disable-line no-unused-vars uncheckedIcon, disabled, ...other } = this.props; const styles = getStyles(this.props, this.context); const uncheckedStyles = Object.assign( styles.target, checked && styles.targetWhenChecked, iconStyle, disabled && styles.targetWhenDisabled ); const checkedStyles = Object.assign( styles.fill, checked && styles.fillWhenChecked, iconStyle, disabled && styles.fillWhenDisabled ); const uncheckedElement = React.isValidElement(uncheckedIcon) ? React.cloneElement(uncheckedIcon, { style: Object.assign(uncheckedStyles, uncheckedIcon.props.style), }) : <RadioButtonOff style={uncheckedStyles} />; const checkedElement = React.isValidElement(checkedIcon) ? React.cloneElement(checkedIcon, { style: Object.assign(checkedStyles, checkedIcon.props.style), }) : <RadioButtonOn style={checkedStyles} />; const mergedIconStyle = Object.assign(styles.icon, iconStyle); const mergedLabelStyle = Object.assign(styles.label, labelStyle); return ( <EnhancedSwitch {...other} ref="enhancedSwitch" inputType="radio" checked={checked} switched={checked} disabled={disabled} rippleColor={styles.ripple.color} iconStyle={mergedIconStyle} labelStyle={mergedLabelStyle} labelPosition={labelPosition} onSwitch={this.handleSwitch} switchElement={<div>{uncheckedElement}{checkedElement}</div>} /> ); } } export default RadioButton;
'use strict'; var _require = require('../tokenTypes'), regExpToken = _require.regExpToken, tokens = _require.tokens; var flex = require('./flex'); var font = require('./font'); var fontFamily = require('./fontFamily'); var transform = require('./transform'); var _require2 = require('./util'), directionFactory = _require2.directionFactory, anyOrderFactory = _require2.anyOrderFactory, shadowOffsetFactory = _require2.shadowOffsetFactory; var IDENT = tokens.IDENT, WORD = tokens.WORD, COLOR = tokens.COLOR; var background = function background(tokenStream) { return { $merge: { backgroundColor: tokenStream.expect(COLOR) } }; }; var border = anyOrderFactory({ borderWidth: { token: tokens.LENGTH, default: 1 }, borderColor: { token: COLOR, default: 'black' }, borderStyle: { token: regExpToken(/^(solid|dashed|dotted)$/), default: 'solid' } }); var borderColor = directionFactory({ types: [WORD], prefix: 'border', suffix: 'Color' }); var borderRadius = directionFactory({ directions: ['TopRight', 'BottomRight', 'BottomLeft', 'TopLeft'], prefix: 'border', suffix: 'Radius' }); var borderWidth = directionFactory({ prefix: 'border', suffix: 'Width' }); var margin = directionFactory({ prefix: 'margin' }); var padding = directionFactory({ prefix: 'padding' }); var flexFlow = anyOrderFactory({ flexWrap: { token: regExpToken(/(nowrap|wrap|wrap-reverse)/), default: 'nowrap' }, flexDirection: { token: regExpToken(/(row|row-reverse|column|column-reverse)/), default: 'row' } }); var fontVariant = function fontVariant(tokenStream) { return [tokenStream.expect(IDENT)]; }; var fontWeight = function fontWeight(tokenStream) { return tokenStream.expect(WORD); }; // Also match numbers as strings var shadowOffset = shadowOffsetFactory(); var textShadowOffset = shadowOffsetFactory(); module.exports = { background: background, border: border, borderColor: borderColor, borderRadius: borderRadius, borderWidth: borderWidth, flex: flex, flexFlow: flexFlow, font: font, fontFamily: fontFamily, fontVariant: fontVariant, fontWeight: fontWeight, margin: margin, padding: padding, shadowOffset: shadowOffset, textShadowOffset: textShadowOffset, transform: transform };
// Copyright 2018 Mathias Bynens. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- author: Mathias Bynens description: > Some binary properties used to be part of the Unicode property escapes proposal but were later removed. They must not be supported. esid: sec-static-semantics-unicodematchproperty-p negative: phase: parse type: SyntaxError features: [regexp-unicode-property-escapes] ---*/ $DONOTEVALUATE(); /\p{Other_Default_Ignorable_Code_Point}/u;
$(document).ready(function() { $(".container").hide(); $(".container").fadeIn('5000'); $(".showcase-wrapper").hide(); $(".showcase-wrapper").fadeIn("slow"); }); /* var toggle = false; $('.nav-toggle').on('click', function () { if (toggle == false) { $('#sidebar-wrapper').stop().animate({ 'left': '4px' }); toggle = true; } else { $('#sidebar-wrapper').stop().animate({ 'left': '250px' }); toggle = false; } }); */ $(function() { $('.project-box').click(function() { $(this).find('.post').slideToggle(); }); });
import Promise from 'bluebird'; import cheerio from 'cheerio'; import leetify from 'leet'; import R from 'ramda'; import { subCommands as helpText } from '../help'; import T from '../../translate'; const request = Promise.promisify(require('request')); const gizoogle = Promise.promisifyAll(require('gizoogle')); function leet(client, evt, suffix, lang) { if (!suffix) return Promise.resolve(T('leet_usage', lang)); return Promise.resolve(leetify.convert(suffix.toLowerCase())); } function snoop(client, evt, suffix, lang) { if (!suffix) return Promise.resolve(T('snoop_usage', lang)); return gizoogle.stringAsync(suffix.toLowerCase()); } function yoda(client, evt, phrase, lang) { if (!phrase) return Promise.resolve(T('yoda_usage', lang)); const options = { url: 'http://www.yodaspeak.co.uk/index.php', method: 'POST', form: { YodaMe: phrase, go: 'Convert to Yoda-Speak!' } }; return request(options) .then(R.prop('body')) .then(cheerio.load) .then($ => $('textarea[name="YodaSpeak"]').first().text()); } function translate(client, evt, suffix, lang) { const split_suffix = suffix.split(' '); const cmd = split_suffix[0]; split_suffix.shift(); suffix = split_suffix.join(' '); if (cmd === 'leet') return leet(client, evt, suffix, lang); if (cmd === 'snoop') return snoop(client, evt, suffix, lang); if (cmd === 'yoda') return yoda(client, evt, suffix, lang); return helpText(client, evt, 'translate', lang); } export default { leet, leetify: leet, 1337: leet, snoop, snoopify: snoop, translate, yoda: yoda, yodaify: yoda }; export const help = { translate: { prefix: false, header_text: 'translate_header_text', subcommands: [ {name: 'leet'}, {name: 'snoop'}, {name: 'yoda'} ] } };
require("ember-views/views/view"); require("ember-handlebars/ext"); /** @module ember @submodule ember-handlebars */ var set = Ember.set, get = Ember.get; /** The `Ember.Checkbox` view class renders a checkbox [input](https://developer.mozilla.org/en/HTML/Element/Input) element. It allows for binding an Ember property (`checked`) to the status of the checkbox. Example: ```handlebars {{view Ember.Checkbox checkedBinding="receiveEmail"}} ``` You can add a `label` tag yourself in the template where the `Ember.Checkbox` is being used. ```handlebars <label> {{view Ember.Checkbox classNames="applicaton-specific-checkbox"}} Some Title </label> ``` The `checked` attribute of an `Ember.Checkbox` object should always be set through the Ember object or by interacting with its rendered element representation via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will result in the checked value of the object and its element losing synchronization. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See `Ember.View`'s layout section for more information. @class Checkbox @namespace Ember @extends Ember.View */ Ember.Checkbox = Ember.View.extend({ classNames: ['ember-checkbox'], tagName: 'input', attributeBindings: ['type', 'checked', 'disabled', 'tabindex', 'name'], type: "checkbox", checked: false, disabled: false, init: function() { this._super(); this.on("change", this, this._updateElementValue); }, _updateElementValue: function() { set(this, 'checked', this.$().prop('checked')); } });
'use strict'; const common = require('../common.js'); const assert = require('assert'); const bench = common.createBenchmark(main, { n: [1e6], direction: ['start', 'end'] }); function main({ direction, n }) { const timersList = []; bench.start(); if (direction === 'start') { for (let i = 1; i <= n; i++) { timersList.push(setTimeout(cb, i)); } } else { for (let i = n; i > 0; i--) { timersList.push(setTimeout(cb, i)); } } bench.end(n); for (let j = 0; j < n; j++) { clearTimeout(timersList[j]); } } function cb() { assert.fail(`Timer ${this._idleTimeout} should not call callback`); }
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = { width: window.innerWidth, height: window.innerHeight }; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport} />; } handleResize(value) { this.setState({ viewport: value }); } }; } export default withViewport;
(function($){ $(function(){ var window_width = $(window).width(); // convert rgb to hex value string function rgb2hex(rgb) { if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; } rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); if (rgb === null) { return "N/A"; } function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } $('.dynamic-color .col').each(function () { $(this).children().each(function () { var color = $(this).css('background-color'), classes = $(this).attr('class'); $(this).html(rgb2hex(color) + " " + classes); if (classes.indexOf("darken") >= 0 || $(this).hasClass('black')) { $(this).css('color', 'rgba(255,255,255,.9'); } }); }); // Floating-Fixed table of contents setTimeout(function() { var tocWrapperHeight = 260; // Max height of ads. var tocHeight = $('.toc-wrapper .table-of-contents').length ? $('.toc-wrapper .table-of-contents').height() : 0; var socialHeight = 95; // Height of unloaded social media in footer. var bottomOffset = $('footer').offset().top - socialHeight - tocHeight - tocWrapperHeight; if ($('nav').length) { $('.toc-wrapper').pushpin({ top: $('nav').height(), bottom: bottomOffset }); } else if ($('#index-banner').length) { $('.toc-wrapper').pushpin({ top: $('#index-banner').height(), bottom: bottomOffset }); } else { $('.toc-wrapper').pushpin({ top: 0, bottom: bottomOffset }); } }, 100); // BuySellAds Detection var $bsa = $(".buysellads"), $timesToCheck = 3; function checkForChanges() { if (!$bsa.find('#carbonads').length) { $timesToCheck -= 1; if ($timesToCheck >= 0) { setTimeout(checkForChanges, 500); } else { var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\'paypal-donate\').submit();"><img src="images/donate.png" /> Help support us by turning off adblock. If you still prefer to keep adblock on for this page but still want to support us, feel free to donate. Any little bit helps.</a></form></span></div>'); $bsa.append(donateAd); } } } checkForChanges(); // Github Latest Commit if ($('.github-commit').length) { // Checks if widget div exists (Index only) $.ajax({ url: "https://api.github.com/repos/dogfalo/materialize/commits/master", dataType: "json", success: function (data) { var sha = data.sha, date = jQuery.timeago(data.commit.author.date); if (window_width < 1120) { sha = sha.substring(0,7); } $('.github-commit').find('.date').html(date); $('.github-commit').find('.sha').html(sha).attr('href', data.html_url); } }); } // Toggle Flow Text var toggleFlowTextButton = $('#flow-toggle'); toggleFlowTextButton.click( function(){ $('#flow-text-demo').children('p').each(function(){ $(this).toggleClass('flow-text'); }); }); // Toggle Containers on page var toggleContainersButton = $('#container-toggle-button'); toggleContainersButton.click(function(){ $('body .browser-window .container, .had-container').each(function(){ $(this).toggleClass('had-container'); $(this).toggleClass('container'); if ($(this).hasClass('container')) { toggleContainersButton.text("Turn off Containers"); } else { toggleContainersButton.text("Turn on Containers"); } }); }); // Detect touch screen and enable scrollbar if necessary function is_touch_device() { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } } if (is_touch_device()) { $('#nav-mobile').css({ overflow: 'auto'}); } // Set checkbox on forms.html to indeterminate var indeterminateCheckbox = document.getElementById('indeterminate-checkbox'); if (indeterminateCheckbox !== null) indeterminateCheckbox.indeterminate = true; // Plugin initialization $('.carousel.carousel-slider').carousel({full_width: true}); $('.carousel').carousel(); $('.slider').slider({full_width: true}); $('.parallax').parallax(); $('.modal-trigger').leanModal(); $('.scrollspy').scrollSpy(); $('.button-collapse').sideNav({'edge': 'left'}); $('.datepicker').pickadate({selectYears: 20}); $('select').not('.disabled').material_select(); }); // end of document ready })(jQuery); // end of jQuery name space
/* * Copyright 2013 Apigee Corporation. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* jshint node: true */ 'use strict'; var apigee = require('..'); var assert = require('assert'); var fs = require('fs'); var http = require('http'); var util = require('util'); var PORT = process.env.PORT || 33334; var svr; describe('Apigee Extensions', function() { before(function(done) { svr = http.createServer(handleRequest); svr.listen(PORT, function() { done(); }); }); after(function() { svr.close(); }); it('Mode', function() { assert.equal(apigee.getMode(), 'standalone'); }); it('Set Get', function(done) { sendRequest('/setget', function(resp) { assert.equal(resp.statusCode, 200); done(); }); }); it('Set Get Two', function(done) { sendRequest('/setgetsetget', function(resp) { assert.equal(resp.statusCode, 200); done(); }); }); it('Set Get Int', function(done) { sendRequest('/setgetint', function(resp) { assert.equal(resp.statusCode, 200); done(); }); }); it('Delete', function(done) { sendRequest('/delete', function(resp) { assert.equal(resp.statusCode, 200); done(); }); }); it('Predefined', function(done) { sendRequest('/predefined', function(resp) { assert.equal(resp.statusCode, 200); done(); }); }); }); function handleRequest(req, resp) { if (req.url === '/setget') { assert(!apigee.getVariable(req, 'testone')); apigee.setVariable(req, 'testone', 'Foo'); assert.equal(apigee.getVariable(req, 'testone'), 'Foo'); } else if (req.url === '/setgetint') { assert(!apigee.getVariable(req, 'testint')); apigee.setIntVariable(req, 'testint', 1); assert.equal(apigee.getVariable(req, 'testint'), 1); apigee.setIntVariable(req, 'testint2', 1.1); assert.equal(apigee.getVariable(req, 'testint2'), 1); apigee.setIntVariable(req, 'testint3', '123'); assert.equal(apigee.getVariable(req, 'testint3'), 123); } else if (req.url === '/setgetsetget') { assert(!apigee.getVariable(req, 'test2')); apigee.setVariable(req, 'test2', 'Foo'); assert.equal(apigee.getVariable(req, 'test2'), 'Foo'); apigee.setVariable(req, 'test2', 'Baz'); assert.equal(apigee.getVariable(req, 'test2'), 'Baz'); } else if (req.url === '/delete') { assert(!apigee.getVariable(req, 'testthree')); apigee.setVariable(req, 'testthree', 'Foo'); assert.equal(apigee.getVariable(req, 'testthree'), 'Foo'); apigee.deleteVariable(req, 'testthree'); assert(!apigee.getVariable(req, 'testthree')); assert.throws(function() { apigee.deleteVariable(req, 'client.received.start.timestamp', 'Invalid'); }); } else if (req.url === '/predefined') { assert(apigee.getVariable(req, 'client.received.start.timestamp')); assert(apigee.getVariable(req, 'client.received.end.timestamp')); assert(apigee.getVariable(req, 'client.received.start.time')); assert(apigee.getVariable(req, 'client.received.end.time')); assert.equal(typeof apigee.getVariable(req, 'client.received.start.timestamp'), 'number'); assert.equal(typeof apigee.getVariable(req, 'client.received.end.timestamp'), 'number'); assert.equal(typeof apigee.getVariable(req, 'client.received.start.time'), 'string'); assert.equal(typeof apigee.getVariable(req, 'client.received.end.time'), 'string'); assert.throws(function() { apigee.setVariable(req, 'client.received.start.timestamp', 'Invalid'); }); } else { resp.writeHead(404); return; } resp.end(); } function sendRequest(path, done) { http.get(util.format('http://localhost:%d%s', PORT, path), function(resp) { done(resp); }); }
/** * Copyright JS Foundation and other contributors, http://js.foundation * * 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 when = require("when"); var util = require("util"); var bcrypt; try { bcrypt = require('bcrypt'); } catch(e) { bcrypt = require('bcryptjs'); } var users = {}; var passwords = {}; var defaultUser = null; function authenticate() { var username = arguments[0]; if (typeof username !== 'string') { username = username.username; } var user = users[username]; if (user) { if (arguments.length === 2) { // Username/password authentication var password = arguments[1]; return when.promise(function(resolve,reject) { bcrypt.compare(password, passwords[username], function(err, res) { resolve(res?user:null); }); }); } else { // Try to extract common profile information if (arguments[0].hasOwnProperty('photos') && arguments[0].photos.length > 0) { user.image = arguments[0].photos[0].value; } return when.resolve(user); } } return when.resolve(null); } function get(username) { return when.resolve(users[username]); } function getDefaultUser() { return when.resolve(null); } var api = { get: get, authenticate: authenticate, default: getDefaultUser } function init(config) { users = {}; passwords = {}; defaultUser = null; if (config.type == "credentials" || config.type == "strategy") { if (config.users) { if (typeof config.users === "function") { api.get = config.users; } else { var us = config.users; /* istanbul ignore else */ if (!util.isArray(us)) { us = [us]; } for (var i=0;i<us.length;i++) { var u = us[i]; users[u.username] = { "username":u.username, "permissions":u.permissions }; passwords[u.username] = u.password; } } } if (config.authenticate && typeof config.authenticate === "function") { api.authenticate = config.authenticate; } else { api.authenticate = authenticate; } } if (config.default) { if (typeof config.default === "function") { api.default = config.default; } else { api.default = function() { return when.resolve({ "anonymous": true, "permissions":config.default.permissions }); } } } else { api.default = getDefaultUser; } } module.exports = { init: init, get: function(username) { return api.get(username) }, authenticate: function() { return api.authenticate.apply(null, arguments) }, default: function() { return api.default(); } };
/** * Print File.program */ "use strict"; exports.__esModule = true; exports.File = File; exports.Program = Program; exports.BlockStatement = BlockStatement; exports.Noop = Noop; function File(node, print) { print.plain(node.program); } /** * Print all nodes in a Program.body. */ function Program(node, print) { print.sequence(node.body); } /** * Print BlockStatement, collapses empty blocks, prints body. */ function BlockStatement(node, print) { if (node.body.length === 0) { this.push("{}"); } else { this.push("{"); this.newline(); print.sequence(node.body, { indent: true }); if (!this.format.retainLines) this.removeLast("\n"); this.rightBrace(); } } /** * What is my purpose? * Why am I here? * Why are any of us here? * Does any of this really matter? */ function Noop() {}
/* Language: BASIC Author: Raphaël Assénat <raph@raphnet.net> Description: Based on the BASIC reference from the Tandy 1000 guide Website: https://en.wikipedia.org/wiki/Tandy_1000 */ /** @type LanguageFn */ function basic(hljs) { return { name: 'BASIC', case_insensitive: true, illegal: '^\.', // Support explicitly typed variables that end with $%! or #. keywords: { $pattern: '[a-zA-Z][a-zA-Z0-9_$%!#]*', keyword: 'ABS ASC AND ATN AUTO|0 BEEP BLOAD|10 BSAVE|10 CALL CALLS CDBL CHAIN CHDIR CHR$|10 CINT CIRCLE ' + 'CLEAR CLOSE CLS COLOR COM COMMON CONT COS CSNG CSRLIN CVD CVI CVS DATA DATE$ ' + 'DEFDBL DEFINT DEFSNG DEFSTR DEF|0 SEG USR DELETE DIM DRAW EDIT END ENVIRON ENVIRON$ ' + 'EOF EQV ERASE ERDEV ERDEV$ ERL ERR ERROR EXP FIELD FILES FIX FOR|0 FRE GET GOSUB|10 GOTO ' + 'HEX$ IF THEN ELSE|0 INKEY$ INP INPUT INPUT# INPUT$ INSTR IMP INT IOCTL IOCTL$ KEY ON ' + 'OFF LIST KILL LEFT$ LEN LET LINE LLIST LOAD LOC LOCATE LOF LOG LPRINT USING LSET ' + 'MERGE MID$ MKDIR MKD$ MKI$ MKS$ MOD NAME NEW NEXT NOISE NOT OCT$ ON OR PEN PLAY STRIG OPEN OPTION ' + 'BASE OUT PAINT PALETTE PCOPY PEEK PMAP POINT POKE POS PRINT PRINT] PSET PRESET ' + 'PUT RANDOMIZE READ REM RENUM RESET|0 RESTORE RESUME RETURN|0 RIGHT$ RMDIR RND RSET ' + 'RUN SAVE SCREEN SGN SHELL SIN SOUND SPACE$ SPC SQR STEP STICK STOP STR$ STRING$ SWAP ' + 'SYSTEM TAB TAN TIME$ TIMER TROFF TRON TO USR VAL VARPTR VARPTR$ VIEW WAIT WHILE ' + 'WEND WIDTH WINDOW WRITE XOR' }, contains: [ hljs.QUOTE_STRING_MODE, hljs.COMMENT('REM', '$', { relevance: 10 }), hljs.COMMENT('\'', '$', { relevance: 0 }), { // Match line numbers className: 'symbol', begin: '^[0-9]+ ', relevance: 10 }, { // Match typed numeric constants (1000, 12.34!, 1.2e5, 1.5#, 1.2D2) className: 'number', begin: '\\b\\d+(\\.\\d+)?([edED]\\d+)?[#\!]?', relevance: 0 }, { // Match hexadecimal numbers (&Hxxxx) className: 'number', begin: '(&[hH][0-9a-fA-F]{1,4})' }, { // Match octal numbers (&Oxxxxxx) className: 'number', begin: '(&[oO][0-7]{1,6})' } ] }; } module.exports = basic;
/* * BrainBrowser: Web-based Neurological Visualization Tools * (https://brainbrowser.cbrain.mcgill.ca) * * Copyright (C) 2011 * The Royal Institution for the Advancement of Learning * McGill University * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Author: Tarek Sherif <tsherif@gmail.com> (http://tareksherif.ca/) * Author: Nicolas Kassis */ /** * @doc overview * @name index * * @description * The BrainBrowser Surface Viewer is a tool for displaying and manipulating 3D datasets in real * time. Basic usage consists of calling the **start()** method of the **SurfaceViewer** module, * which takes a callback function as its second argument, and then using the **viewer** object passed * to that callback function to control how models are displayed: * ```js * BrainBrowser.SurfaceViewer.start("brainbrowser", function(viewer) { * * //Add an event listener. * viewer.addEventListener("displaymodel", function() { * console.log("We have a model!"); * }); * * // Start rendering the scene. * viewer.render(); * * // Load a model into the scene. * viewer.loadModelFromURL("/models/brain_surface.obj"); * * // Hook viewer behaviour into UI. * $("#wireframe").change(function(e) { * viewer.setWireframe($(this).is(":checked")); * }); * * }); * ``` */ /** * @doc overview * @name Configuration * * @description * The Surface Viewer can be configured using the **set** and **get** * methods of the **BrainBrowser.config** object. The only configuration * parameter that must be manually set is **worker\_dir** which indicates * the path to the directory where the Web Worker scripts are stored: * * ```js * BrainBrowser.config.set("worker_dir", "js/brainbrowser/workers"); * ``` * Configuration parameters used internally by the Surface Viewer also * include **model\_types** and **intensity\_data\_types** which are used to * associate a Web Worker with each supported file type. Any other parameters * can be used without issue to create custom configuration for a given * app. * * Configuration parameters can be retrieved using the **get** method: * * ```js * var worker_dir = BrainBrowser.config.get("worker_dir"); * ``` * * If the requested parameter does not exist, **null** will be returned. * * Configuration parameters can be namespaced, using a "." to separate namespaces, * so for example: * * ```js * BrainBrowser.set("color_maps.spectral.name", "Spectral"); * ``` * * will set the **name** property in the **spectral** namespace of the * **color_maps** namespace. Namespaces are implemented as objects, so * if a namespace is requested with **get**, the namespace object will be * returned. Using the previous **set**, the following **get**: * * ```js * BrainBrowser.get("color_maps.spectral"); * ``` * * would return the object: * * ```js * { name: "Spectral" } * ``` * */ /** * @doc overview * @name Object Model * * @description * Data parsers producing models to be read by BrainBrowser must * output their data according to the following object model: * ```js * { * type: ("line" | "polygon"), * name: "...", * vertices: [...], * normals: [...], * colors: [...], * shapes: [ * { * name: "...", * color: [...], * indices: [...] * }, * { * name: "...", * color: [...], * indices: [...] * } * ] * } * ``` * * Assuming a model with **n** vertices: * * * **type** (optional) is a string indicating whether the model consists * of line or triangle data. Default: "polygon". * * **name** (optional) is a string identifier for the model. Default: * the name of the file that the data was parsed from. * * **vertices** is a flat array of vertex **x**, **y**, **z** coordinates. * Size: **n** X 3. * * **normals** (optional) is a flat array of vertex normal vector **x**, * **y**, **z** components. Size: **n** X 3. If a **normals** array is not * provided, the Surface Viewer will attempt to appoximate the normals based * on the vertex data. * * **colors** (optional) is a flat array of **r**, **g**, **b**, **a** color * values. Size: **n** X 4 or 4. If a 4-element array is given, that color * will be used for the entire model. If no color data is provided vertex * colors will all be set to gray. * * **shapes** is an array containing objects describing the different * shapes the model represents. Each object will contain an **indices** * property which contains an array of indices pointing into the * **vertices**, **colors** and **normals** arrays, indicating how to * assemble them into triangles or line pieces. For **polygon** models, * each triplet of indices should describe a triangle. For **line** models, * each pair of indices should describe a line segment. Optionally, each * shape can also be given a **color** property, which indicates the color * of the shape (overriding model and vertex colors at the top level). The * color should be given as a 4-element array indicating **r**, **g**, **b**, * **a** color values. An optional **name** property can also be given to * identify the shape. If no **name** is provided, the **name** property * defaults to a value based on the name of the file that contained the model * and the shape's index number. */ (function() { "use strict"; var SurfaceViewer = BrainBrowser.SurfaceViewer = { /** * @doc function * @name SurfaceViewer.static methods:start * @param {string} element ID of a DOM element, or the DOM element itself, * into which the viewer will be inserted. * @param {function} callback Callback function to which the viewer object * will be passed after creation. * @description * The start() function is the main point of entry to the Surface Viewer. * It creates a viewer object that is then passed to the callback function * supplied by the user. * * ```js * BrainBrowser.SurfaceViewer.start("brainbrowser", function(viewer) { * * //Add an event listener. * viewer.addEventListener("displaymodel", function() { * console.log("We have a model!"); * }); * * // Start rendering the scene. * viewer.render(); * * // Load a model into the scene. * viewer.loadModelFromURL("/models/brain_surface.obj"); * * // Hook viewer behaviour into UI. * $("#wireframe").change(function(e) { * viewer.setWireframe($(this).is(":checked")); * }); * * }); * ``` */ start: function(element, callback) { console.log("BrainBrowser Surface Viewer v" + BrainBrowser.version); /** * @doc object * @name viewer * @property {DOMElement} dom_element The DOM element where the viewer * will be inserted. * @property {THREE.Object3D} model The currently loaded surface model. * @property {object} model_data Parameters about the current model that * were actually parsed from the source file. * @property {object} mouse Object tracking the mouse **x** and **y** coordinates * of the mouse on the viewer canvas. * @property {object} touches Object tracking the **x** and **y** coordinates * of all touches currently active on the canvas. * @property {boolean} updated Whether the canvas should redrawn on the next * render loop. * @property {float} zoom The zoom level (default: 1.0). * @property {object} autorotate Automatic rotations around the **x**, **y** * and **z** axes can be set. * @property {object} annotations Current annotations. * * @description * The viewer object encapsulates all functionality of the Surface Viewer. * Handlers can be attached to the **viewer** object to listen * for certain events occuring over the viewer's lifetime. Currently, the * following viewer events can be listened for: * * * **displaymodel** A new model has been displayed on the viewer. * * **loadintensitydata** New intensity data has been loaded. * * **updateintensitydata** The intensity data has been updated. * * **changeintensityrange** The intensity data range has been modified. * * **updatecolors** The model's colors have been updated. * * **loadcolormap** A new color map has been loaded. * * **blendcolormaps** Two color maps have been loaded and blended. * * **clearscreen** The viewer has been cleared of objects. * * **draw** The scene has been redrawn. * * To listen for an event, simply use the **viewer.addEventListener()** method with * with the event name and a callback funtion: * * ```js * viewer.addEventListener("displaymodel", function() { * console.log("Model displayed!"); * }); * ``` */ var attributes = {}; // Element where the viewer canvas will be loaded. var dom_element; if (typeof element === "string") { dom_element = document.getElementById(element); } else { dom_element = element; } var viewer = { dom_element: dom_element, model: null, // Scene graph root. Created in rendering module. model_data: null, // Descriptions of all models. Created in loading module. mouse: BrainBrowser.utils.captureMouse(dom_element), touches: BrainBrowser.utils.captureTouch(dom_element), updated: true, zoom: 1, autorotate: { x: false, y: false, z: false }, /** * @doc function * @name viewer.attributes:getAttribute * @param {string} name Name of the attribute to retrieve. * * @description * Retrieve the value of an attribute. * * The viewer object can maintain an arbitrary set of key-value * to aid in the functioning of various parts of the system. * ```js * viewer.getAttribute("fix_color_range"); * ``` * * Currently, the following attributes are used by the Surface Viewer: * * * **fix\_color\_range** Maintain the current intensity range, even if new data is * loaded. */ getAttribute: function(name) { return attributes[name]; }, /** * @doc function * @name viewer.attributes:setAttribute * @param {string} name Name of the attribute to retrieve. * @param {any} value Value to set the attribute to. * * @description * Set the value of an attribute. * * The viewer object can maintain an arbitrary set of key-value * pairs to aid in the functioning of various parts of the system. * ```js * viewer.setAttribute("fix_color_range", false); * ``` * * Currently, the following attributes are used by the Surface Viewer: * * * **fix\_color\_range** Maintain the current intensity range, even if new data is * loaded. */ setAttribute: function(name, value) { attributes[name] = value; }, /** * @doc function * @name viewer.viewer:getVertex * @param {number} index Index of the vertex. * @returns {THREE.Vertex3} The vertex. * * @description * Get the vertex at the given index * ```js * viewer.getVertex(2356); * ``` * * If more than one model file has been loaded, refer to the appropriate * model using the **model_name** option: * ```js * viewer.getVertex(2356, { model_name: "brain.obj" }); * ``` */ getVertex: function(index, options) { options = options || {}; var vertices = viewer.model_data.get(options.model_name).vertices; var i = index * 3; return new SurfaceViewer.THREE.Vector3(vertices[i], vertices[i+1], vertices[i+2]); }, }; ////////////////////////////// // Load modules. ////////////////////////////// /** * @doc object * @name viewer.events:displaymodel * * @description * Triggered when a new model is displayed on the viewer. The following information * will be passed in the event object: * * * **event.model**: the visualized model as a THREE.Object3D object. * * **event.model\_data**: the data that the model represents. * * **event.new\_shapes**: an array of newly added shapes as THREE.Object3D objects. * * ```js * viewer.addEventListener("displaymodel", function(event) { * //... * }); * ``` */ /** * @doc object * @name viewer.events:loadintensitydata * * @description * Triggered when a new intensity is loaded. The following information * will be passed in the event object: * * * **event.model\_data**: the model data with which the intensity data is associated. * * **event.intensity\_data**: the loaded intensity data. * * ```js * viewer.addEventListener("loadintensitydata", function(event) { * //... * }); * ``` */ /** * @doc object * @name viewer.events:loadcolormap * * @description * Triggered when a new color map has finished loading. The following information * will be passed in the event object: * * * **event.color\_map**: the loaded color map. * * ```js * viewer.addEventListener("loadcolormap", function(event) { * //... * }); * ``` */ /** * @doc object * @name viewer.events:clearscreen * * @description * Triggered when the screen is cleared. No special information is * passed in the event object. * * ```js * viewer.addEventListener("clearscreen", function(event) { * //... * }); * ``` */ /** * @doc object * @name viewer.events:updateintensitydata * * @description * Triggered when the intensity is updated. The following information * will be passed in the event object: * * * **event.model\_data**: the model data on which the intensity data was updated. * * **event.intensity\_data**: the intensity data that was updated. * * **event.index**: the index at which the intensity value was updated. * * **event.value**: the new intensity value. * * ```js * viewer.addEventListener("updateintensitydata", function(event) { * //... * }); * ``` */ /** * @doc object * @name viewer.events:changeintensityrange * * @description * Triggered when the intensity range changes. The following information * will be passed in the event object: * * * **event.model\_data**: the model data on which the intensity data was updated. * * **event.intensity\_data**: the intensity data that was updated. * * **event.min**: the new minimum intensity value. * * **event.max**: the new maximum intensity value. * * ```js * viewer.addEventListener("changeintensityrange", function(event) { * //... * }); * ``` */ /** * @doc object * @name viewer.events:updatecolors * * @description * Triggered when model's colors are udpated. The following information * will be passed in the event object: * * * **event.model\_data**: the model data on representing the model that was updated. * * **event.intensity\_data**: the intensity data used to update the colors. * * **event.colors**: newly created array of colors. * * **event.blend**: was the the color array created by blending multiple intensity sets? * * ```js * viewer.addEventListener("updatecolors", function(event) { * //... * }); * ``` */ /** * @doc object * @name viewer.events:blendcolors * * @description * Triggered when multiple sets of intensity data have been loaded and blended. * The following information will be passed in the event object: * * * **event.model\_data**: the model data on representing the model that was updated. * * **event.intensity\_data**: the intensity data used to update the colors. * * **event.colors**: newly created array of colors. * * ```js * viewer.addEventListener("blendcolors", function(event) { * //... * }); * ``` * */ /** * @doc object * @name viewer.events:draw * * @description * Triggered when the scene is redrawn. The following information * will be passed in the event object: * * * **event.renderer**: the three.js renderer being used to draw the scene. * * **event.scene**: the THREE.Scene object representing the scene. * * **event.camera**: the THREE.PerspectiveCamera object being used to draw the scene. * * ```js * viewer.addEventListener("draw", function(event) { * //... * }); * ``` */ /** * @name viewer.events:zoom * * @description * Triggered when the user changes the zoom level of the viewer (scroll or touch events). * The following information will be passed in the event object: * * * **event.zoom**: the new zoom level. * * ```js * viewer.addEventListener("zoom", function(event) { * //... * }); * ``` * */ Object.keys(SurfaceViewer.modules).forEach(function(m) { SurfaceViewer.modules[m](viewer); }); BrainBrowser.events.addEventModel(viewer); // Trigger a redraw on any event. BrainBrowser.events.addEventListener("*", function(event_name) { if (event_name !== "draw") { viewer.updated = true; } }); ////////////////////////////////////////////////////// // Prepare workers and pass SurfaceViewer instance // to calling application. ////////////////////////////////////////////////////// setupWorkers(function() { callback(viewer); }); return viewer; } }; // Standard modules. SurfaceViewer.modules = {}; // URLS for Web Workers. // May be network or Blob URLs SurfaceViewer.worker_urls = {}; // Configuration for built-in parsers. BrainBrowser.config.set("model_types.json.worker", "json.worker.js"); BrainBrowser.config.set("model_types.mniobj.worker", "mniobj.worker.js"); BrainBrowser.config.set("model_types.wavefrontobj.worker", "wavefrontobj.worker.js"); BrainBrowser.config.set("model_types.freesurferbin.worker", "freesurferbin.worker.js"); BrainBrowser.config.set("model_types.freesurferbin.binary", true); BrainBrowser.config.set("model_types.freesurferasc.worker", "freesurferasc.worker.js"); BrainBrowser.config.set("model_types.gifti.worker", "gifti.worker.js"); BrainBrowser.config.set("intensity_data_types.text.worker", "text.intensity.worker.js"); BrainBrowser.config.set("intensity_data_types.freesurferbin.worker", "freesurferbin.intensity.worker.js"); BrainBrowser.config.set("intensity_data_types.freesurferbin.binary", true); BrainBrowser.config.set("intensity_data_types.freesurferasc.worker", "freesurferasc.intensity.worker.js"); BrainBrowser.config.set("intensity_data_types.gifti.worker", "gifti.worker.js"); // Build worker URLs and attempt to inline // them using Blob URLs if possible. function setupWorkers(callback) { var worker_dir = BrainBrowser.config.get("worker_dir"); var error_message; if (worker_dir === null) { error_message = "error in SurfaceViewer configuration.\n" + "BrainBrowser configuration parameter 'worker_dir' not defined.\n" + "Use 'BrainBrowser.config.set(\"worker_dir\", ...)' to set it."; BrainBrowser.events.triggerEvent("error", { message: error_message }); throw new Error(error_message); } var workers = { deindex: "deindex.worker.js", wireframe: "wireframe.worker.js" }; var workers_loaded = 0; var worker_names; var model_types = BrainBrowser.config.get("model_types"); var intensity_data_types = BrainBrowser.config.get("intensity_data_types"); if (model_types !== null) { Object.keys(model_types).forEach(function(type) { workers[type + "_model"] = model_types[type].worker; }); } if (intensity_data_types !== null) { Object.keys(intensity_data_types).forEach(function(type) { workers[type + "_intensity"] = intensity_data_types[type].worker; }); } worker_names = Object.keys(workers); if (worker_names.length === 0) { callback(); return; } if (window.URL && window.URL.createObjectURL) { worker_names.forEach(function(name) { var url = worker_dir + "/" + workers[name]; var request = new XMLHttpRequest(); var status; request.open("GET", url); request.onreadystatechange = function() { if (request.readyState === 4){ status = request.status; // Based on jQuery's "success" codes. if(status >= 200 && status < 300 || status === 304) { SurfaceViewer.worker_urls[name] = BrainBrowser.utils.createDataURL(request.response, "application/javascript"); } else { SurfaceViewer.worker_urls[name] = url; } if (++workers_loaded === worker_names.length) { callback(); } } }; request.send(); }); } else { worker_names.forEach(function(name) { SurfaceViewer.worker_urls[name] = worker_dir + "/" + workers[name]; }); callback(); } } })();
export function JSXAttribute(node: Object) { this.print(node.name, node); if (node.value) { this.token("="); this.print(node.value, node); } } export function JSXIdentifier(node: Object) { this.word(node.name); } export function JSXNamespacedName(node: Object) { this.print(node.namespace, node); this.token(":"); this.print(node.name, node); } export function JSXMemberExpression(node: Object) { this.print(node.object, node); this.token("."); this.print(node.property, node); } export function JSXSpreadAttribute(node: Object) { this.token("{"); this.token("..."); this.print(node.argument, node); this.token("}"); } export function JSXExpressionContainer(node: Object) { this.token("{"); this.print(node.expression, node); this.token("}"); } export function JSXSpreadChild(node: Object) { this.token("{"); this.token("..."); this.print(node.expression, node); this.token("}"); } export function JSXText(node: Object) { const raw = this.getPossibleRaw(node); if (raw != null) { this.token(raw); } else { this.token(node.value); } } export function JSXElement(node: Object) { const open = node.openingElement; this.print(open, node); if (open.selfClosing) return; this.indent(); for (const child of (node.children: Array<Object>)) { this.print(child, node); } this.dedent(); this.print(node.closingElement, node); } function spaceSeparator() { this.space(); } export function JSXOpeningElement(node: Object) { this.token("<"); this.print(node.name, node); this.print(node.typeParameters, node); // TS if (node.attributes.length > 0) { this.space(); this.printJoin(node.attributes, node, { separator: spaceSeparator }); } if (node.selfClosing) { this.space(); this.token("/>"); } else { this.token(">"); } } export function JSXClosingElement(node: Object) { this.token("</"); this.print(node.name, node); this.token(">"); } export function JSXEmptyExpression(node: Object) { this.printInnerComments(node); } export function JSXFragment(node: Object) { this.print(node.openingFragment, node); this.indent(); for (const child of (node.children: Array<Object>)) { this.print(child, node); } this.dedent(); this.print(node.closingFragment, node); } export function JSXOpeningFragment() { this.token("<"); this.token(">"); } export function JSXClosingFragment() { this.token("</"); this.token(">"); }
/* Copyright 2013-2015 ASIAL CORPORATION 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. */ import util from '../ons/util'; import autoStyle from '../ons/autostyle'; import ModifierUtil from '../ons/internal/modifier-util'; import BaseElement from './base/base-element'; import contentReady from '../ons/content-ready'; const defaultClassName = 'list-item'; const scheme = { '.list-item': 'list-item--*', '.list-item__left': 'list-item--*__left', '.list-item__center': 'list-item--*__center', '.list-item__right': 'list-item--*__right', '.list-item__label': 'list-item--*__label', '.list-item__title': 'list-item--*__title', '.list-item__subtitle': 'list-item--*__subtitle', '.list-item__thumbnail': 'list-item--*__thumbnail', '.list-item__icon': 'list-item--*__icon' }; /** * @element ons-list-item * @category list * @modifier tappable * [en]Make the list item change appearance when it's tapped. On iOS it is better to use the "tappable" and "tap-background-color" attribute for better behavior when scrolling.[/en] * [ja]タップやクリックした時に効果が表示されるようになります。[/ja] * @modifier chevron * [en]Display a chevron at the right end of the list item and make it change appearance when tapped.[/en] * [ja][/ja] * @modifier longdivider * [en]Displays a long horizontal divider between items.[/en] * [ja][/ja] * @modifier nodivider * [en]Removes the divider between list items.[/en] * [ja][/ja] * @modifier material * [en]Display a Material Design list item.[/en] * [ja][/ja] * @description * [en] * Component that represents each item in a list. The list item is composed of three parts that are represented with the `left`, `center` and `right` classes. These classes can be used to ensure that the content of the list items is properly aligned. * * ``` * <ons-list-item> * <div class="left">Left</div> * <div class="center">Center</div> * <div class="right">Right</div> * </ons-list-item> * ``` * * There is also a number of classes (prefixed with `list-item__*`) that help when putting things like icons and thumbnails into the list items. * [/en] * [ja][/ja] * @seealso ons-list * [en]ons-list component[/en] * [ja]ons-listコンポーネント[/ja] * @seealso ons-list-header * [en]ons-list-header component[/en] * [ja]ons-list-headerコンポーネント[/ja] * @guide lists * [en]Using lists[/en] * [ja]リストを使う[/ja] * @codepen yxcCt * @tutorial vanilla/Reference/list * @example * <ons-list-item> * <div class="left"> * <ons-icon icon="md-face" class="list-item__icon"></ons-icon> * </div> * <div class="center"> * <div class="list-item__title">Title</div> * <div class="list-item__subtitle">Subtitle</div> * </div> * <div class="right"> * <ons-switch></ons-switch> * </div> * </ons-list-item> */ export default class ListItemElement extends BaseElement { /** * @attribute modifier * @type {String} * @description * [en]The appearance of the list item.[/en] * [ja]各要素の表現を指定します。[/ja] */ /** * @attribute lock-on-drag * @type {String} * @description * [en]Prevent vertical scrolling when the user drags horizontally.[/en] * [ja]この属性があると、ユーザーがこの要素を横方向にドラッグしている時に、縦方向のスクロールが起きないようになります。[/ja] */ /** * @attribute tappable * @type {Boolean} * @description * [en]Makes the element react to taps.[/en] * [ja][/ja] */ /** * @attribute tap-background-color * @type {Color} * @description * [en] Changes the background color when tapped. For this to work, the attribute "tappable" needs to be set. The default color is "#d9d9d9". It will display as a ripple effect on Android.[/en] * [ja][/ja] */ constructor() { super(); contentReady(this, () => { this._compile(); }); } _compile() { autoStyle.prepare(this); this.classList.add(defaultClassName); let left, center, right; for (let i = 0; i < this.children.length; i++) { const el = this.children[i]; if (el.classList.contains('left')) { el.classList.add('list-item__left'); left = el; } else if (el.classList.contains('center')) { center = el; } else if (el.classList.contains('right')) { el.classList.add('list-item__right'); right = el; } } if (!center) { center = document.createElement('div'); if (!left && !right) { while (this.childNodes[0]) { center.appendChild(this.childNodes[0]); } } else { for (let i = this.childNodes.length - 1; i >= 0; i--) { const el = this.childNodes[i]; if (el !== left && el !== right) { center.insertBefore(el, center.firstChild); } } } this.insertBefore(center, right || null); } center.classList.add('center'); center.classList.add('list-item__center'); this._updateRipple(); ModifierUtil.initModifier(this, scheme); } static get observedAttributes() { return ['modifier', 'class', 'ripple']; } attributeChangedCallback(name, last, current) { switch (name) { case 'class': util.restoreClass(this, defaultClassName, scheme); break; case 'modifier': ModifierUtil.onModifierChanged(last, current, this, scheme); break; case 'ripple': this._updateRipple(); break; } } connectedCallback() { this.addEventListener('drag', this._onDrag); this.addEventListener('touchstart', this._onTouch); this.addEventListener('mousedown', this._onTouch); this.addEventListener('touchend', this._onRelease); this.addEventListener('touchmove', this._onRelease); this.addEventListener('touchcancel', this._onRelease); this.addEventListener('mouseup', this._onRelease); this.addEventListener('mouseout', this._onRelease); this.addEventListener('touchleave', this._onRelease); this._originalBackgroundColor = this.style.backgroundColor; this.tapped = false; } disconnectedCallback() { this.removeEventListener('drag', this._onDrag); this.removeEventListener('touchstart', this._onTouch); this.removeEventListener('mousedown', this._onTouch); this.removeEventListener('touchend', this._onRelease); this.removeEventListener('touchmove', this._onRelease); this.removeEventListener('touchcancel', this._onRelease); this.removeEventListener('mouseup', this._onRelease); this.removeEventListener('mouseout', this._onRelease); this.removeEventListener('touchleave', this._onRelease); } get _transition() { return 'background-color 0.0s linear 0.02s, box-shadow 0.0s linear 0.02s'; } get _tappable() { return this.hasAttribute('tappable'); } get _tapBackgroundColor() { return this.getAttribute('tap-background-color') || '#d9d9d9'; } _updateRipple() { util.updateRipple(this); } _onDrag(event) { const gesture = event.gesture; // Prevent vertical scrolling if the users pans left or right. if (this._shouldLockOnDrag() && ['left', 'right'].indexOf(gesture.direction) > -1) { gesture.preventDefault(); } } _onTouch() { if (this.tapped) { return; } this.tapped = true; this.style.transition = this._transition; this.style.webkitTransition = this._transition; this.style.MozTransition = this._transition; if (this._tappable) { if (this.style.backgroundColor) { this._originalBackgroundColor = this.style.backgroundColor; } this.style.backgroundColor = this._tapBackgroundColor; this.style.boxShadow = `0px -1px 0px 0px ${this._tapBackgroundColor}`; } } _onRelease() { this.tapped = false; this.style.transition = ''; this.style.webkitTransition = ''; this.style.MozTransition = ''; this.style.backgroundColor = this._originalBackgroundColor || ''; this.style.boxShadow = ''; } _shouldLockOnDrag() { return this.hasAttribute('lock-on-drag'); } } customElements.define('ons-list-item', ListItemElement);
'use strict'; import 'array.from'; export const html = (strings, ...values) => { let str = ''; if(Array.isArray(strings)){ for(let i = 0; i < strings.length; i++){ if(strings[i]) str += strings[i]; if(values[i]) str += values[i]; } }else{ str = strings; } let doc = new DOMParser().parseFromString(str.trim(), 'text/html'); return doc.body.firstChild; }; export const prepend = ($parent, $element) => { let $first = $parent.children[0]; $parent.insertBefore($element, $first); }; export const $ = selector => { let result; if(selector === 'body'){ return document.body; }else if(selector === 'head'){ return document.head; }else if(/^[\#.]?[\w-]+$/.test(selector)){ if(selector[0] === '#'){ return document.getElementById(selector.slice(1)); }else if(selector[0] === '.'){ result = document.getElementsByClassName(selector.slice(1)); }else{ result = document.getElementsByTagName(selector); } }else{ result = document.querySelectorAll(selector); } let elements = [...result]; if(elements.length === 1) return elements[0]; return elements; };
'use strict'; const path = require('path'); const SilentError = require('silent-error'); const stringUtil = require('ember-cli-string-utils'); const pathUtil = require('ember-cli-path-utils'); const getPathOption = require('ember-cli-get-component-path-option'); const normalizeEntityName = require('ember-cli-normalize-entity-name'); const { EOL } = require('os'); const { has } = require('@ember/edition-utils'); const OCTANE = has('octane'); // TODO: this should be reading from the @ember/canary-features module // need to refactor broccoli/features.js to be able to work more similarly // to https://github.com/emberjs/data/pull/6231 const EMBER_GLIMMER_SET_COMPONENT_TEMPLATE = true; // intentionally avoiding use-edition-detector module.exports = { description: 'Generates a component class.', availableOptions: [ { name: 'path', type: String, default: 'components', aliases: [{ 'no-path': '' }], }, { name: 'component-class', type: ['@ember/component', '@glimmer/component', '@ember/component/template-only'], default: OCTANE ? '@glimmer/component' : '@ember/component', aliases: [ { cc: '@ember/component' }, { gc: '@glimmer/component' }, { tc: '@ember/component/template-only' }, ], }, { name: 'component-structure', type: OCTANE ? ['flat', 'nested', 'classic'] : ['classic'], default: OCTANE ? 'flat' : 'classic', aliases: OCTANE ? [{ fs: 'flat' }, { ns: 'nested' }, { cs: 'classic' }] : [{ cs: 'classic' }], }, ], init() { this._super && this._super.init.apply(this, arguments); let isOctane = has('octane'); this.availableOptions.forEach((option) => { if (option.name === 'component-class') { if (isOctane) { option.default = '@glimmer/component'; } else { option.default = '@ember/component'; } } else if (option.name === 'component-structure') { if (isOctane) { option.type = ['flat', 'nested', 'classic']; option.default = 'flat'; option.aliases = [{ fs: 'flat' }, { ns: 'nested' }, { cs: 'classic' }]; } else { option.type = ['classic']; option.default = 'classic'; option.aliases = [{ cs: 'classic' }]; } } }); this.EMBER_GLIMMER_SET_COMPONENT_TEMPLATE = EMBER_GLIMMER_SET_COMPONENT_TEMPLATE || isOctane; }, install() { if (!this.EMBER_GLIMMER_SET_COMPONENT_TEMPLATE) { throw new SilentError( 'Usage of `ember generate component-class` is only available on canary' ); } return this._super.install.apply(this, arguments); }, fileMapTokens(options) { let commandOptions = this.options; if (commandOptions.pod) { return { __path__() { return path.join(options.podPath, options.locals.path, options.dasherizedModuleName); }, __name__() { return 'component'; }, }; } else if ( commandOptions.componentStructure === 'classic' || commandOptions.componentStructure === 'flat' ) { return { __path__() { return 'components'; }, }; } else if (commandOptions.componentStructure === 'nested') { return { __path__() { return `components/${options.dasherizedModuleName}`; }, __name__() { return 'index'; }, }; } }, normalizeEntityName(entityName) { return normalizeEntityName( entityName.replace(/\.js$/, '') //Prevent generation of ".js.js" files ); }, locals(options) { let sanitizedModuleName = options.entity.name.replace(/\//g, '-'); let classifiedModuleName = stringUtil.classify(sanitizedModuleName); let templatePath = ''; let importComponent = ''; let importTemplate = ''; let defaultExport = ''; // if we're in an addon, build import statement if (options.project.isEmberCLIAddon() || (options.inRepoAddon && !options.inDummy)) { if (options.pod) { templatePath = './template'; } else { templatePath = pathUtil.getRelativeParentPath(options.entity.name) + 'templates/components/' + stringUtil.dasherize(options.entity.name); } } let componentClass = options.componentClass; switch (componentClass) { case '@ember/component': importComponent = `import Component from '@ember/component';`; if (templatePath) { importTemplate = `import layout from '${templatePath}';${EOL}`; defaultExport = `Component.extend({${EOL} layout${EOL}});`; } else { defaultExport = `Component.extend({${EOL}});`; } break; case '@glimmer/component': importComponent = `import Component from '@glimmer/component';`; defaultExport = `class ${classifiedModuleName}Component extends Component {\n}`; break; case '@ember/component/template-only': importComponent = `import templateOnly from '@ember/component/template-only';`; defaultExport = `templateOnly();`; break; } return { importTemplate, importComponent, defaultExport, path: getPathOption(options), componentClass, }; }, };
/** @license * @pnp/logging v1.1.5-0 - pnp - light-weight, subscribable logging framework * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https:github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ /** * Class used to subscribe ILogListener and log messages throughout an application * */ var Logger = /** @class */ (function () { function Logger() { } Object.defineProperty(Logger, "activeLogLevel", { /** * Gets or sets the active log level to apply for log filtering */ get: function () { return Logger.instance.activeLogLevel; }, set: function (value) { Logger.instance.activeLogLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(Logger, "instance", { get: function () { if (Logger._instance === undefined || Logger._instance === null) { Logger._instance = new LoggerImpl(); } return Logger._instance; }, enumerable: true, configurable: true }); /** * Adds ILogListener instances to the set of subscribed listeners * * @param listeners One or more listeners to subscribe to this log */ Logger.subscribe = function () { var listeners = []; for (var _i = 0; _i < arguments.length; _i++) { listeners[_i] = arguments[_i]; } listeners.map(function (listener) { return Logger.instance.subscribe(listener); }); }; /** * Clears the subscribers collection, returning the collection before modifiction */ Logger.clearSubscribers = function () { return Logger.instance.clearSubscribers(); }; Object.defineProperty(Logger, "count", { /** * Gets the current subscriber count */ get: function () { return Logger.instance.count; }, enumerable: true, configurable: true }); /** * Writes the supplied string to the subscribed listeners * * @param message The message to write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Info) */ Logger.write = function (message, level) { if (level === void 0) { level = 1 /* Info */; } Logger.instance.log({ level: level, message: message }); }; /** * Writes the supplied string to the subscribed listeners * * @param json The json object to stringify and write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Info) */ Logger.writeJSON = function (json, level) { if (level === void 0) { level = 1 /* Info */; } this.write(JSON.stringify(json), level); }; /** * Logs the supplied entry to the subscribed listeners * * @param entry The message to log */ Logger.log = function (entry) { Logger.instance.log(entry); }; /** * Logs an error object to the subscribed listeners * * @param err The error object */ Logger.error = function (err) { Logger.instance.log({ data: err, level: 3 /* Error */, message: err.message }); }; return Logger; }()); var LoggerImpl = /** @class */ (function () { function LoggerImpl(activeLogLevel, subscribers) { if (activeLogLevel === void 0) { activeLogLevel = 2 /* Warning */; } if (subscribers === void 0) { subscribers = []; } this.activeLogLevel = activeLogLevel; this.subscribers = subscribers; } LoggerImpl.prototype.subscribe = function (listener) { this.subscribers.push(listener); }; LoggerImpl.prototype.clearSubscribers = function () { var s = this.subscribers.slice(0); this.subscribers.length = 0; return s; }; Object.defineProperty(LoggerImpl.prototype, "count", { get: function () { return this.subscribers.length; }, enumerable: true, configurable: true }); LoggerImpl.prototype.write = function (message, level) { if (level === void 0) { level = 1 /* Info */; } this.log({ level: level, message: message }); }; LoggerImpl.prototype.log = function (entry) { if (entry !== undefined && this.activeLogLevel <= entry.level) { this.subscribers.map(function (subscriber) { return subscriber.log(entry); }); } }; return LoggerImpl; }()); /** * A set of logging levels */ var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Verbose"] = 0] = "Verbose"; LogLevel[LogLevel["Info"] = 1] = "Info"; LogLevel[LogLevel["Warning"] = 2] = "Warning"; LogLevel[LogLevel["Error"] = 3] = "Error"; LogLevel[LogLevel["Off"] = 99] = "Off"; })(LogLevel || (LogLevel = {})); /** * Implementation of LogListener which logs to the console * */ var ConsoleListener = /** @class */ (function () { function ConsoleListener() { } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ ConsoleListener.prototype.log = function (entry) { var msg = this.format(entry); switch (entry.level) { case 0 /* Verbose */: case 1 /* Info */: console.log(msg); break; case 2 /* Warning */: console.warn(msg); break; case 3 /* Error */: console.error(msg); break; } }; /** * Formats the message * * @param entry The information to format into a string */ ConsoleListener.prototype.format = function (entry) { var msg = []; msg.push("Message: " + entry.message); if (entry.data !== undefined) { msg.push(" Data: " + JSON.stringify(entry.data)); } return msg.join(""); }; return ConsoleListener; }()); /** * Implementation of LogListener which logs to the supplied function * */ var FunctionListener = /** @class */ (function () { /** * Creates a new instance of the FunctionListener class * * @constructor * @param method The method to which any logging data will be passed */ function FunctionListener(method) { this.method = method; } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ FunctionListener.prototype.log = function (entry) { this.method(entry); }; return FunctionListener; }()); export { Logger, LogLevel, ConsoleListener, FunctionListener }; //# sourceMappingURL=logging.es5.js.map
//>>built define("dojox/grid/nls/DataGrid_ja-jp",{"dijit/nls/loading":{"loadingState":"ロード中...","errorState":"エラーが発生しました。","_localized":{}}});
define(function(require) { var Backbone = require('backbone'), d3 = require('d3'), util = require('summary/util'); require('date'); var CStat = Backbone.Model.extend({ url: '/apps/dbwipes/api/column_distribution/', defaults: function() { return { col: null, type: null, // time | timestamp | date | num | str stats: [], // { val:, count:, range:} xdomain: [], // (min, max) or [list of discrete vals] ydomain: [], selection: [], // subset of domain ready: false, scorpion: false // is the selection based on scorpion predicates // or manually selected? } }, initialize: function(attrs) { this.set('id', CStat.id_++); }, fetch: function(options) { var _this = this; this.trigger('fetch:start'); this.attributes.ready = false; options || (options = { data: {} }); var complete = options.complete; var f = function(resp) { _this.trigger('fetch:end'); if (complete) complete(model, resp, options); }; options.complete = f; return Backbone.Model.prototype.fetch.call(this, options); }, parse: function(resp) { var data = resp.data; var type = data.type, stats = data.stats, _this = this; if (util.isNum(type)) { type = data.type = 'num'; } if (util.isStr(type)) { type = data.type = 'str'; } if (util.isTime(type)){ // ensure vals and ranges are date objects _.each(stats, function(d) { if (type == 'time') { d.val = '2000-01-01T' + d.val; d.range = _.map(d.range, function(v) { return '2000-01-01T'+v; }); } d.val = new Date(d.val); d.range = _.map(d.range, function(v) {return new Date(v);}) }) } stats = _.sortBy(stats, 'val'); var getx = function(d) { return d.val; }, gety = function(d) { return d.count }, xdomain = util.getXDomain(stats, type, getx), ydomain = [ d3.min(stats, gety), d3.max(stats, gety) ]; if (ydomain[0] == ydomain[1] || ydomain[0] > 0) ydomain[0] = 0; return { stats: stats, type: type, xdomain: xdomain, ydomain: ydomain, selection: [], ready: true }; }, validate: function(attrs, opts) { if (!attrs.col) return "col can't be null"; if (!attrs.type) return "type can't be null" }, toJSON: function() { var type = this.get('type'); var vals = _.pluck(this.get('selection'), 'range'); if (vals.length > 0) { if (util.isStr(type)) { vals = vals.map(function(v) { return _.flatten([v])[0]; }); } else { vals = [d3.min(_.pluck(vals, 0)), d3.max(_.pluck(vals,1))]; console.log(['cstat.json', vals]) if (util.isTime(type)) { if (type == 'time') vals = vals.map(function(v) { return "'" + v.toLocaleTimeString() + "'"; }); else vals = vals.map(function(v) { return "'" + v.toISOString() + "'"; }); } } } return { col: this.get('col'), type: this.get('type'), vals: vals }; }, toSQLWhere: function() { var sel = this.get('selection'); if (sel.length == 0) return null; var vals = []; _.each(sel, function(d) { vals = vals.concat(d.range); }); vals = _.uniq(vals); var SQL = util.toWhereClause( this.get('col'), this.get('type'), vals ); if (SQL == '' || SQL == null) return null; return SQL; } }); CStat.id_ = 0; return CStat; });