diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000..52369be1e3 --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +libraries/ diff --git a/.eslintrc.yml b/.eslintrc.yml index 4110862a11..b215e15800 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -2,3 +2,26 @@ env: es6: true browser: true amd: true + +rules: + block-spacing: ["error"] + brace-style: ["error"] + comma-dangle: ["error", "never"] + comma-spacing: ["error"] + eol-last: ["off"] + indent: ["error", 4, { "SwitchCase": 1 }] + keyword-spacing: ["error"] + line-comment-position: ["off"] + max-statements-per-line: ["error"] + no-empty: ["error"] + no-extra-semi: ["error"] + no-floating-decimal: ["error"] + no-multi-spaces: ["error"] + no-multiple-empty-lines: ["error", { "max": 1 }] + no-trailing-spaces: ["error"] + no-void: ["off"] + one-var: ["error", "never"] + padding-line-between-statements: ["off"] + semi: ["off"] + space-before-blocks: ["error"] + yoda: ["off"] diff --git a/.github/stale.yml b/.github/stale.yml index e478e25d21..e61e0ed476 100644 --- a/.github/stale.yml +++ b/.github/stale.yml @@ -8,6 +8,7 @@ exemptLabels: - future - feature - enhancement + - confirmed # Label to use when marking an issue as stale staleLabel: stale # Comment to post when marking an issue as stale. Set to `false` to disable diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 08782c2883..e0855c1e09 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -30,6 +30,8 @@ - [Nickbert7](https://github.com/Nickbert7) - [ferferga](https://github.com/ferferga) - [bilde2910](https://github.com/bilde2910) + - [Daniel Hartung](https://github.com/dhartung) + - [Ryan Hartzell](https://github.com/ryan-hartzell) # Emby Contributors diff --git a/package.json b/package.json index bcbdd3dacc..8eea3ca247 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "repository": "https://github.com/jellyfin/jellyfin-web", "license": "GPL-2.0-or-later", "devDependencies": { + "clean-webpack-plugin": "^3.0.0", "copy-webpack-plugin": "^5.0.3", "css-loader": "^2.1.0", "eslint": "^5.16.0", @@ -16,15 +17,22 @@ "webpack-merge": "^4.2.2" }, "dependencies": { + "alameda": "^1.3.0", + "document-register-element": "^0.5.4", "flv.js": "^1.5.0", "hls.js": "^0.12.4", "howler": "^2.1.2", "jquery": "^3.4.1", "jstree": "^3.3.7", "libjass": "^0.11.0", + "native-promise-only": "^0.8.0-a", + "requirejs": "^2.3.5", + "resize-observer-polyfill": "^1.5.1", "shaka-player": "^2.5.5", "sortablejs": "^1.9.0", - "swiper": "^3.4.2" + "swiper": "^3.4.2", + "webcomponents.js-2": "^0.7.24", + "whatwg-fetch": "^1.1.1" }, "scripts": { "serve": "webpack-dev-server --config webpack.dev.js --open", diff --git a/src/bower_components/alameda/alameda.js b/src/bower_components/alameda/alameda.js deleted file mode 100644 index 4ac0f7496b..0000000000 --- a/src/bower_components/alameda/alameda.js +++ /dev/null @@ -1,419 +0,0 @@ -var requirejs, require, define; -! function(global, Promise, undef) { - function commentReplace(match, singlePrefix) { - return singlePrefix || "" - } - - function hasProp(obj, prop) { - return hasOwn.call(obj, prop) - } - - function getOwn(obj, prop) { - return obj && hasProp(obj, prop) && obj[prop] - } - - function obj() { - return Object.create(null) - } - - function eachProp(obj, func) { - var prop; - for (prop in obj) - if (hasProp(obj, prop) && func(obj[prop], prop)) break - } - - function mixin(target, source, force, deepStringMixin) { - return source && eachProp(source, function(value, prop) { - !force && hasProp(target, prop) || (!deepStringMixin || "object" != typeof value || !value || Array.isArray(value) || "function" == typeof value || value instanceof RegExp ? target[prop] = value : (target[prop] || (target[prop] = {}), mixin(target[prop], value, force, deepStringMixin))) - }), target - } - - function getGlobal(value) { - if (!value) return value; - var g = global; - return value.split(".").forEach(function(part) { - g = g[part] - }), g - } - - function newContext(contextName) { - function trimDots(ary) { - var i, part, length = ary.length; - for (i = 0; i < length; i++) - if ("." === (part = ary[i])) ary.splice(i, 1), i -= 1; - else if (".." === part) { - if (0 === i || 1 === i && ".." === ary[2] || ".." === ary[i - 1]) continue; - i > 0 && (ary.splice(i - 1, 2), i -= 2) - } - } - - function normalize(name, baseName, applyMap) { - var mapValue, nameParts, i, j, nameSegment, lastIndex, foundMap, foundI, foundStarMap, starI, baseParts = baseName && baseName.split("/"), - normalizedBaseParts = baseParts, - map = config.map, - starMap = map && map["*"]; - if (name && (name = name.split("/"), lastIndex = name.length - 1, config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex]) && (name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, "")), "." === name[0].charAt(0) && baseParts && (normalizedBaseParts = baseParts.slice(0, baseParts.length - 1), name = normalizedBaseParts.concat(name)), trimDots(name), name = name.join("/")), applyMap && map && (baseParts || starMap)) { - nameParts = name.split("/"); - outerLoop: for (i = nameParts.length; i > 0; i -= 1) { - if (nameSegment = nameParts.slice(0, i).join("/"), baseParts) - for (j = baseParts.length; j > 0; j -= 1) - if ((mapValue = getOwn(map, baseParts.slice(0, j).join("/"))) && (mapValue = getOwn(mapValue, nameSegment))) { - foundMap = mapValue, foundI = i; - break outerLoop - }! foundStarMap && starMap && getOwn(starMap, nameSegment) && (foundStarMap = getOwn(starMap, nameSegment), starI = i) - }!foundMap && foundStarMap && (foundMap = foundStarMap, foundI = starI), foundMap && (nameParts.splice(0, foundI, foundMap), name = nameParts.join("/")) - } - return getOwn(config.pkgs, name) || name - } - - function makeShimExports(value) { - function fn() { - var ret; - return value.init && (ret = value.init.apply(global, arguments)), ret || value.exports && getGlobal(value.exports) - } - return fn - } - - function takeQueue(anonId) { - var i, id, args, shim; - for (i = 0; i < queue.length; i += 1) { - if ("string" != typeof queue[i][0]) { - if (!anonId) break; - queue[i].unshift(anonId), anonId = undef - } - args = queue.shift(), id = args[0], i -= 1, id in defined || id in waiting || (id in deferreds ? main.apply(undef, args) : waiting[id] = args) - } - anonId && (shim = getOwn(config.shim, anonId) || {}, main(anonId, shim.deps || [], shim.exportsFn)) - } - - function makeRequire(relName, topLevel) { - var req = function(deps, callback, errback, alt) { - var name, cfg; - if (topLevel && takeQueue(), "string" == typeof deps) { - if (handlers[deps]) return handlers[deps](relName); - if (!((name = makeMap(deps, relName, !0).id) in defined)) throw new Error("Not loaded: " + name); - return defined[name] - } - return deps && !Array.isArray(deps) && (cfg = deps, deps = undef, Array.isArray(callback) && (deps = callback, callback = errback, errback = alt), topLevel) ? req.config(cfg)(deps, callback, errback) : (callback = callback || function() { - return slice.call(arguments, 0) - }, asyncResolve.then(function() { - return takeQueue(), main(undef, deps || [], callback, errback, relName) - })) - }; - return req.isBrowser = "undefined" != typeof document && "undefined" != typeof navigator, req.nameToUrl = function(moduleName, ext, skipExt) { - var paths, syms, i, parentModule, url, parentPath, bundleId, pkgMain = getOwn(config.pkgs, moduleName); - if (pkgMain && (moduleName = pkgMain), bundleId = getOwn(bundlesMap, moduleName)) return req.nameToUrl(bundleId, ext, skipExt); - if (urlRegExp.test(moduleName)) url = moduleName + (ext || ""); - else { - for (paths = config.paths, syms = moduleName.split("/"), i = syms.length; i > 0; i -= 1) - if (parentModule = syms.slice(0, i).join("/"), parentPath = getOwn(paths, parentModule)) { - Array.isArray(parentPath) && (parentPath = parentPath[0]), syms.splice(0, i, parentPath); - break - } url = syms.join("/"), url += ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? "" : ".js"), url = ("/" === url.charAt(0) || url.match(/^[\w\+\.\-]+:/) ? "" : config.baseUrl) + url - } - return config.urlArgs && !/^blob\:/.test(url) ? url + config.urlArgs(moduleName, url) : url - }, req.toUrl = function(moduleNamePlusExt) { - var ext, index = moduleNamePlusExt.lastIndexOf("."), - segment = moduleNamePlusExt.split("/")[0], - isRelative = "." === segment || ".." === segment; - return -1 !== index && (!isRelative || index > 1) && (ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length), moduleNamePlusExt = moduleNamePlusExt.substring(0, index)), req.nameToUrl(normalize(moduleNamePlusExt, relName), ext, !0) - }, req.defined = function(id) { - return makeMap(id, relName, !0).id in defined - }, req.specified = function(id) { - return (id = makeMap(id, relName, !0).id) in defined || id in deferreds - }, req - } - - function resolve(name, d, value) { - name && (defined[name] = value, requirejs.onResourceLoad && requirejs.onResourceLoad(context, d.map, d.deps)), d.finished = !0, d.resolve(value) - } - - function reject(d, err) { - d.finished = !0, d.rejected = !0, d.reject(err) - } - - function makeNormalize(relName) { - return function(name) { - return normalize(name, relName, !0) - } - } - - function defineModule(d) { - d.factoryCalled = !0; - var ret, name = d.map.id; - try { - ret = context.execCb(name, d.factory, d.values, defined[name]) - } catch (err) { - return reject(d, err) - } - name ? ret === undef && (d.cjsModule ? ret = d.cjsModule.exports : d.usingExports && (ret = defined[name])) : requireDeferreds.splice(requireDeferreds.indexOf(d), 1), resolve(name, d, ret) - } - - function depFinished(val, i) { - this.rejected || this.depDefined[i] || (this.depDefined[i] = !0, this.depCount += 1, this.values[i] = val, this.depending || this.depCount !== this.depMax || defineModule(this)) - } - - function makeDefer(name, calculatedMap) { - var d = {}; - return d.promise = new Promise(function(resolve, reject) { - d.resolve = resolve, d.reject = function(err) { - name || requireDeferreds.splice(requireDeferreds.indexOf(d), 1), reject(err) - } - }), d.map = name ? calculatedMap || makeMap(name) : {}, d.depCount = 0, d.depMax = 0, d.values = [], d.depDefined = [], d.depFinished = depFinished, d.map.pr && (d.deps = [makeMap(d.map.pr)]), d - } - - function getDefer(name, calculatedMap) { - var d; - return name ? (d = name in deferreds && deferreds[name]) || (d = deferreds[name] = makeDefer(name, calculatedMap)) : (d = makeDefer(), requireDeferreds.push(d)), d - } - - function makeErrback(d, name) { - return function(err) { - d.rejected || (err.dynaId || (err.dynaId = "id" + (errCount += 1), err.requireModules = [name]), reject(d, err)) - } - } - - function waitForDep(depMap, relName, d, i) { - d.depMax += 1, callDep(depMap, relName).then(function(val) { - d.depFinished(val, i) - }, makeErrback(d, depMap.id)).catch(makeErrback(d, d.map.id)) - } - - function makeLoad(id) { - function load(value) { - fromTextCalled || resolve(id, getDefer(id), value) - } - var fromTextCalled; - return load.error = function(err) { - reject(getDefer(id), err) - }, load.fromText = function(text, textAlt) { - var execError, d = getDefer(id), - map = makeMap(makeMap(id).n), - plainId = map.id; - fromTextCalled = !0, d.factory = function(p, val) { - return val - }, textAlt && (text = textAlt), hasProp(config.config, id) && (config.config[plainId] = config.config[id]); - try { - req.exec(text) - } catch (e) { - execError = new Error("fromText eval for " + plainId + " failed: " + e), execError.requireType = "fromtexteval", reject(d, execError) - } - takeQueue(plainId), d.deps = [map], waitForDep(map, null, d, d.deps.length) - }, load - } - - function callPlugin(plugin, map, relName) { - plugin.load(map.n, makeRequire(relName), makeLoad(map.id), config) - } - - function splitPrefix(name) { - var prefix, index = name ? name.indexOf("!") : -1; - return index > -1 && (prefix = name.substring(0, index), name = name.substring(index + 1, name.length)), [prefix, name] - } - - function breakCycle(d, traced, processed) { - var id = d.map.id; - traced[id] = !0, !d.finished && d.deps && d.deps.forEach(function(depMap) { - var depId = depMap.id, - dep = !hasProp(handlers, depId) && getDefer(depId, depMap); - !dep || dep.finished || processed[depId] || (hasProp(traced, depId) ? d.deps.forEach(function(depMap, i) { - depMap.id === depId && d.depFinished(defined[depId], i) - }) : breakCycle(dep, traced, processed)) - }), processed[id] = !0 - } - - function check(d) { - var err, mid, dfd, notFinished = [], - waitInterval = 1e3 * config.waitSeconds, - expired = waitInterval && startTime + waitInterval < (new Date).getTime(); - if (0 === loadCount && (d ? d.finished || breakCycle(d, {}, {}) : requireDeferreds.length && requireDeferreds.forEach(function(d) { - breakCycle(d, {}, {}) - })), expired) { - for (mid in deferreds) dfd = deferreds[mid], dfd.finished || notFinished.push(dfd.map.id); - err = new Error("Timeout for modules: " + notFinished), err.requireModules = notFinished, err.requireType = "timeout", notFinished.forEach(function(id) { - reject(getDefer(id), err) - }) - } else(loadCount || requireDeferreds.length) && (checkingLater || (checkingLater = !0, setTimeout(function() { - checkingLater = !1, check() - }, 70))) - } - - function delayedError(e) { - console.log(e.stack); - return setTimeout(function() { - e.dynaId && trackedErrors[e.dynaId] || (trackedErrors[e.dynaId] = !0, req.onError(e)) - }), e - } - var req, main, makeMap, callDep, handlers, checkingLater, load, context, defined = obj(), - waiting = obj(), - config = { - waitSeconds: 7, - baseUrl: "./", - paths: {}, - bundles: {}, - pkgs: {}, - shim: {}, - config: {} - }, - mapCache = obj(), - requireDeferreds = [], - deferreds = obj(), - calledDefine = obj(), - calledPlugin = obj(), - loadCount = 0, - startTime = (new Date).getTime(), - errCount = 0, - trackedErrors = obj(), - urlFetched = obj(), - bundlesMap = obj(), - asyncResolve = Promise.resolve(undefined); - return load = "function" == typeof importScripts ? function(map) { - var url = map.url; - urlFetched[url] || (urlFetched[url] = !0, getDefer(map.id), importScripts(url), takeQueue(map.id)) - } : function(map) { - var script, id = map.id, - url = map.url; - urlFetched[url] || (urlFetched[url] = !0, script = document.createElement("script"), script.setAttribute("data-requiremodule", id), script.type = config.scriptType || "text/javascript", script.charset = "utf-8", script.async = !0, loadCount += 1, script.addEventListener("load", function() { - loadCount -= 1, takeQueue(id) - }, !1), script.addEventListener("error", function() { - loadCount -= 1; - var err, pathConfig = getOwn(config.paths, id); - if (pathConfig && Array.isArray(pathConfig) && pathConfig.length > 1) { - script.parentNode.removeChild(script), pathConfig.shift(); - var d = getDefer(id); - d.map = makeMap(id), d.map.url = req.nameToUrl(id), load(d.map) - } else err = new Error("Load failed: " + id + ": " + script.src), err.requireModules = [id], err.requireType = "scripterror", reject(getDefer(id), err) - }, !1), script.src = url, 10 === document.documentMode ? asap.then(function() { - document.head.appendChild(script) - }) : document.head.appendChild(script)) - }, callDep = function(map, relName) { - var args, bundleId, name = map.id, - shim = config.shim[name]; - if (name in waiting) args = waiting[name], delete waiting[name], main.apply(undef, args); - else if (!(name in deferreds)) - if (map.pr) { - if (!(bundleId = getOwn(bundlesMap, name))) return callDep(makeMap(map.pr)).then(function(plugin) { - var newMap = map.prn ? map : makeMap(name, relName, !0), - newId = newMap.id, - shim = getOwn(config.shim, newId); - return newId in calledPlugin || (calledPlugin[newId] = !0, shim && shim.deps ? req(shim.deps, function() { - callPlugin(plugin, newMap, relName) - }) : callPlugin(plugin, newMap, relName)), getDefer(newId).promise - }); - map.url = req.nameToUrl(bundleId), load(map) - } else shim && shim.deps ? req(shim.deps, function() { - load(map) - }) : load(map); - return getDefer(name).promise - }, makeMap = function(name, relName, applyMap) { - if ("string" != typeof name) return name; - var plugin, url, parts, prefix, result, prefixNormalized, cacheKey = name + " & " + (relName || "") + " & " + !!applyMap; - return parts = splitPrefix(name), prefix = parts[0], name = parts[1], !prefix && cacheKey in mapCache ? mapCache[cacheKey] : (prefix && (prefix = normalize(prefix, relName, applyMap), plugin = prefix in defined && defined[prefix]), prefix ? plugin && plugin.normalize ? (name = plugin.normalize(name, makeNormalize(relName)), prefixNormalized = !0) : name = -1 === name.indexOf("!") ? normalize(name, relName, applyMap) : name : (name = normalize(name, relName, applyMap), parts = splitPrefix(name), prefix = parts[0], name = parts[1], url = req.nameToUrl(name)), result = { - id: prefix ? prefix + "!" + name : name, - n: name, - pr: prefix, - url: url, - prn: prefix && prefixNormalized - }, prefix || (mapCache[cacheKey] = result), result) - }, handlers = { - require: function(name) { - return makeRequire(name) - }, - exports: function(name) { - var e = defined[name]; - return void 0 !== e ? e : defined[name] = {} - }, - module: function(name) { - return { - id: name, - uri: "", - exports: handlers.exports(name), - config: function() { - return getOwn(config.config, name) || {} - } - } - } - }, main = function(name, deps, factory, errback, relName) { - if (name) { - if (name in calledDefine) return; - calledDefine[name] = !0 - } - var d = getDefer(name); - return deps && !Array.isArray(deps) && (factory = deps, deps = []), deps = deps ? slice.call(deps, 0) : null, errback || (hasProp(config, "defaultErrback") ? config.defaultErrback && (errback = config.defaultErrback) : errback = delayedError), errback && d.promise.catch(errback), relName = relName || name, "function" == typeof factory ? (!deps.length && factory.length && (factory.toString().replace(commentRegExp, commentReplace).replace(cjsRequireRegExp, function(match, dep) { - deps.push(dep) - }), deps = (1 === factory.length ? ["require"] : ["require", "exports", "module"]).concat(deps)), d.factory = factory, d.deps = deps, d.depending = !0, deps.forEach(function(depName, i) { - var depMap; - deps[i] = depMap = makeMap(depName, relName, !0), depName = depMap.id, "require" === depName ? d.values[i] = handlers.require(name) : "exports" === depName ? (d.values[i] = handlers.exports(name), d.usingExports = !0) : "module" === depName ? d.values[i] = d.cjsModule = handlers.module(name) : void 0 === depName ? d.values[i] = void 0 : waitForDep(depMap, relName, d, i) - }), d.depending = !1, d.depCount === d.depMax && defineModule(d)) : name && resolve(name, d, factory), startTime = (new Date).getTime(), name || check(d), d.promise - }, req = makeRequire(null, !0), req.config = function(cfg) { - if (cfg.context && cfg.context !== contextName) { - var existingContext = getOwn(contexts, cfg.context); - return existingContext ? existingContext.req.config(cfg) : newContext(cfg.context).config(cfg) - } - if (mapCache = obj(), cfg.baseUrl && "/" !== cfg.baseUrl.charAt(cfg.baseUrl.length - 1) && (cfg.baseUrl += "/"), "string" == typeof cfg.urlArgs) { - var urlArgs = cfg.urlArgs; - cfg.urlArgs = function(id, url) { - return (-1 === url.indexOf("?") ? "?" : "&") + urlArgs - } - } - var shim = config.shim, - objs = { - paths: !0, - bundles: !0, - config: !0, - map: !0 - }; - return eachProp(cfg, function(value, prop) { - objs[prop] ? (config[prop] || (config[prop] = {}), mixin(config[prop], value, !0, !0)) : config[prop] = value - }), cfg.bundles && eachProp(cfg.bundles, function(value, prop) { - value.forEach(function(v) { - v !== prop && (bundlesMap[v] = prop) - }) - }), cfg.shim && (eachProp(cfg.shim, function(value, id) { - Array.isArray(value) && (value = { - deps: value - }), !value.exports && !value.init || value.exportsFn || (value.exportsFn = makeShimExports(value)), shim[id] = value - }), config.shim = shim), cfg.packages && cfg.packages.forEach(function(pkgObj) { - var location, name; - pkgObj = "string" == typeof pkgObj ? { - name: pkgObj - } : pkgObj, name = pkgObj.name, location = pkgObj.location, location && (config.paths[name] = pkgObj.location), config.pkgs[name] = pkgObj.name + "/" + (pkgObj.main || "main").replace(currDirRegExp, "").replace(jsSuffixRegExp, "") - }), (cfg.deps || cfg.callback) && req(cfg.deps, cfg.callback), req - }, req.onError = function(err) { - throw err - }, context = { - id: contextName, - defined: defined, - waiting: waiting, - config: config, - deferreds: deferreds, - req: req, - execCb: function(name, callback, args, exports) { - return callback.apply(exports, args) - } - }, contexts[contextName] = context, req - } - if (!Promise) throw new Error("No Promise implementation available"); - var topReq, dataMain, src, subPath, bootstrapConfig = requirejs || require, - hasOwn = Object.prototype.hasOwnProperty, - contexts = {}, - queue = [], - currDirRegExp = /^\.\//, - urlRegExp = /^\/|\:|\?|\.js$/, - commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/gm, - cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, - jsSuffixRegExp = /\.js$/, - slice = Array.prototype.slice; - if ("function" != typeof requirejs) { - var asap = Promise.resolve(void 0); - requirejs = topReq = newContext("_"), "function" != typeof require && (require = topReq), topReq.exec = function(text) { - return eval(text) - }, topReq.contexts = contexts, define = function() { - queue.push(slice.call(arguments, 0)) - }, define.amd = { - jQuery: !0 - }, bootstrapConfig && topReq.config(bootstrapConfig), topReq.isBrowser && !contexts._.config.skipDataMain && (dataMain = document.querySelectorAll("script[data-main]")[0], (dataMain = dataMain && dataMain.getAttribute("data-main")) && (dataMain = dataMain.replace(jsSuffixRegExp, ""), bootstrapConfig && bootstrapConfig.baseUrl || -1 !== dataMain.indexOf("!") || (src = dataMain.split("/"), dataMain = src.pop(), subPath = src.length ? src.join("/") + "/" : "./", topReq.config({ - baseUrl: subPath - })), topReq([dataMain]))) - } -}(this, "undefined" != typeof Promise ? Promise : void 0); diff --git a/src/bower_components/apiclient/connectionmanager.js b/src/bower_components/apiclient/connectionmanager.js deleted file mode 100644 index 8724300658..0000000000 --- a/src/bower_components/apiclient/connectionmanager.js +++ /dev/null @@ -1,747 +0,0 @@ -define(["events", "apiclient", "appStorage"], function(events, apiClientFactory, appStorage) { - "use strict"; - - function getServerAddress(server, mode) { - switch (mode) { - case ConnectionMode.Local: - return server.LocalAddress; - case ConnectionMode.Manual: - return server.ManualAddress; - case ConnectionMode.Remote: - return server.RemoteAddress; - default: - return server.ManualAddress || server.LocalAddress || server.RemoteAddress - } - } - - function paramsToString(params) { - var values = []; - for (var key in params) { - var value = params[key]; - null !== value && void 0 !== value && "" !== value && values.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)) - } - return values.join("&") - } - - function resolveFailure(instance, resolve) { - resolve({ - State: "Unavailable", - ConnectUser: instance.connectUser() - }) - } - - function mergeServers(credentialProvider, list1, list2) { - for (var i = 0, length = list2.length; i < length; i++) credentialProvider.addOrUpdateServer(list1, list2[i]); - return list1 - } - - function updateServerInfo(server, systemInfo) { - server.Name = systemInfo.ServerName, systemInfo.Id && (server.Id = systemInfo.Id), systemInfo.LocalAddress && (server.LocalAddress = systemInfo.LocalAddress) - } - - function getEmbyServerUrl(baseUrl, handler) { - return baseUrl + "/" + handler - } - - function getFetchPromise(request) { - var headers = request.headers || {}; - "json" === request.dataType && (headers.accept = "application/json"); - var fetchRequest = { - headers: headers, - method: request.type, - credentials: "same-origin" - }, - contentType = request.contentType; - return request.data && ("string" == typeof request.data ? fetchRequest.body = request.data : (fetchRequest.body = paramsToString(request.data), contentType = contentType || "application/x-www-form-urlencoded; charset=UTF-8")), contentType && (headers["Content-Type"] = contentType), request.timeout ? fetchWithTimeout(request.url, fetchRequest, request.timeout) : fetch(request.url, fetchRequest) - } - - function fetchWithTimeout(url, options, timeoutMs) { - return console.log("fetchWithTimeout: timeoutMs: " + timeoutMs + ", url: " + url), new Promise(function(resolve, reject) { - var timeout = setTimeout(reject, timeoutMs); - options = options || {}, options.credentials = "same-origin", fetch(url, options).then(function(response) { - clearTimeout(timeout), console.log("fetchWithTimeout: succeeded connecting to url: " + url), resolve(response) - }, function(error) { - clearTimeout(timeout), console.log("fetchWithTimeout: timed out connecting to url: " + url), reject() - }) - }) - } - - function ajax(request) { - if (!request) throw new Error("Request cannot be null"); - return request.headers = request.headers || {}, console.log("ConnectionManager requesting url: " + request.url), getFetchPromise(request).then(function(response) { - return console.log("ConnectionManager response status: " + response.status + ", url: " + request.url), response.status < 400 ? "json" === request.dataType || "application/json" === request.headers.accept ? response.json() : response : Promise.reject(response) - }, function(err) { - throw console.log("ConnectionManager request failed to url: " + request.url), err - }) - } - - function getConnectUrl(handler) { - return "https://connect.emby.media/service/" + handler - } - - function replaceAll(originalString, strReplace, strWith) { - var reg = new RegExp(strReplace, "ig"); - return originalString.replace(reg, strWith) - } - - function normalizeAddress(address) { - return address = address.trim(), 0 !== address.toLowerCase().indexOf("http") && (address = "http://" + address), address = replaceAll(address, "Http:", "http:"), address = replaceAll(address, "Https:", "https:") - } - - function stringEqualsIgnoreCase(str1, str2) { - return (str1 || "").toLowerCase() === (str2 || "").toLowerCase() - } - - function compareVersions(a, b) { - a = a.split("."), b = b.split("."); - for (var i = 0, length = Math.max(a.length, b.length); i < length; i++) { - var aVal = parseInt(a[i] || "0"), - bVal = parseInt(b[i] || "0"); - if (aVal < bVal) return -1; - if (aVal > bVal) return 1 - } - return 0 - } - var defaultTimeout = 2e4, - ConnectionMode = { - Local: 0, - Remote: 1, - Manual: 2 - }, - ConnectionManager = function(credentialProvider, appName, appVersion, deviceName, deviceId, capabilities, devicePixelRatio) { - function onConnectUserSignIn(user) { - connectUser = user, events.trigger(self, "connectusersignedin", [user]) - } - - function onAuthenticated(apiClient, result, options, saveCredentials) { - var credentials = credentialProvider.credentials(), - servers = credentials.Servers.filter(function(s) { - return s.Id === result.ServerId - }), - server = servers.length ? servers[0] : apiClient.serverInfo(); - return !1 !== options.updateDateLastAccessed && (server.DateLastAccessed = (new Date).getTime()), server.Id = result.ServerId, saveCredentials ? (server.UserId = result.User.Id, server.AccessToken = result.AccessToken) : (server.UserId = null, server.AccessToken = null), credentialProvider.addOrUpdateServer(credentials.Servers, server), credentialProvider.credentials(credentials), apiClient.enableAutomaticBitrateDetection = options.enableAutomaticBitrateDetection, apiClient.serverInfo(server), afterConnected(apiClient, options), onLocalUserSignIn(server, apiClient.serverAddress(), result.User) - } - - function afterConnected(apiClient, options) { - options = options || {}, !1 !== options.reportCapabilities && apiClient.reportCapabilities(capabilities), apiClient.enableAutomaticBitrateDetection = options.enableAutomaticBitrateDetection, !1 !== options.enableWebSocket && (console.log("calling apiClient.ensureWebSocket"), apiClient.ensureWebSocket()) - } - - function onLocalUserSignIn(server, serverUrl, user) { - return self._getOrAddApiClient(server, serverUrl), (self.onLocalUserSignedIn ? self.onLocalUserSignedIn.call(self, user) : Promise.resolve()).then(function() { - events.trigger(self, "localusersignedin", [user]) - }) - } - - function ensureConnectUser(credentials) { - return connectUser && connectUser.Id === credentials.ConnectUserId ? Promise.resolve() : credentials.ConnectUserId && credentials.ConnectAccessToken ? (connectUser = null, getConnectUser(credentials.ConnectUserId, credentials.ConnectAccessToken).then(function(user) { - return onConnectUserSignIn(user), Promise.resolve() - }, function() { - return Promise.resolve() - })) : Promise.resolve() - } - - function getConnectUser(userId, accessToken) { - if (!userId) throw new Error("null userId"); - if (!accessToken) throw new Error("null accessToken"); - return ajax({ - type: "GET", - url: "https://connect.emby.media/service/user?id=" + userId, - dataType: "json", - headers: { - "X-Application": appName + "/" + appVersion, - "X-Connect-UserToken": accessToken - } - }) - } - - function addAuthenticationInfoFromConnect(server, serverUrl, credentials) { - if (!server.ExchangeToken) throw new Error("server.ExchangeToken cannot be null"); - if (!credentials.ConnectUserId) throw new Error("credentials.ConnectUserId cannot be null"); - var url = getEmbyServerUrl(serverUrl, "Connect/Exchange?format=json&ConnectUserId=" + credentials.ConnectUserId), - auth = 'MediaBrowser Client="' + appName + '", Device="' + deviceName + '", DeviceId="' + deviceId + '", Version="' + appVersion + '"'; - return ajax({ - type: "GET", - url: url, - dataType: "json", - headers: { - "X-MediaBrowser-Token": server.ExchangeToken, - "X-Emby-Authorization": auth - } - }).then(function(auth) { - return server.UserId = auth.LocalUserId, server.AccessToken = auth.AccessToken, auth - }, function() { - return server.UserId = null, server.AccessToken = null, Promise.reject() - }) - } - - function validateAuthentication(server, serverUrl) { - return ajax({ - type: "GET", - url: getEmbyServerUrl(serverUrl, "System/Info"), - dataType: "json", - headers: { - "X-MediaBrowser-Token": server.AccessToken - } - }).then(function(systemInfo) { - return updateServerInfo(server, systemInfo), Promise.resolve() - }, function() { - return server.UserId = null, server.AccessToken = null, Promise.resolve() - }) - } - - function getImageUrl(localUser) { - if (connectUser && connectUser.ImageUrl) return { - url: connectUser.ImageUrl - }; - if (localUser && localUser.PrimaryImageTag) { - return { - url: self.getApiClient(localUser).getUserImageUrl(localUser.Id, { - tag: localUser.PrimaryImageTag, - type: "Primary" - }), - supportsParams: !0 - } - } - return { - url: null, - supportsParams: !1 - } - } - - function logoutOfServer(apiClient) { - var serverInfo = apiClient.serverInfo() || {}, - logoutInfo = { - serverId: serverInfo.Id - }; - return apiClient.logout().then(function() { - events.trigger(self, "localusersignedout", [logoutInfo]) - }, function() { - events.trigger(self, "localusersignedout", [logoutInfo]) - }) - } - - function getConnectServers(credentials) { - return console.log("Begin getConnectServers"), credentials.ConnectAccessToken && credentials.ConnectUserId ? ajax({ - type: "GET", - url: "https://connect.emby.media/service/servers?userId=" + credentials.ConnectUserId, - dataType: "json", - headers: { - "X-Application": appName + "/" + appVersion, - "X-Connect-UserToken": credentials.ConnectAccessToken - } - }).then(function(servers) { - return servers.map(function(i) { - return { - ExchangeToken: i.AccessKey, - ConnectServerId: i.Id, - Id: i.SystemId, - Name: i.Name, - RemoteAddress: i.Url, - LocalAddress: i.LocalAddress, - UserLinkType: "guest" === (i.UserType || "").toLowerCase() ? "Guest" : "LinkedUser" - } - }) - }, function() { - return credentials.Servers.slice(0).filter(function(s) { - return s.ExchangeToken - }) - }) : Promise.resolve([]) - } - - function filterServers(servers, connectServers) { - return servers.filter(function(server) { - return !server.ExchangeToken || connectServers.filter(function(connectServer) { - return server.Id === connectServer.Id - }).length > 0 - }) - } - - function findServers() { - return new Promise(function(resolve, reject) { - var onFinish = function(foundServers) { - var servers = foundServers.map(function(foundServer) { - var info = { - Id: foundServer.Id, - LocalAddress: convertEndpointAddressToManualAddress(foundServer) || foundServer.Address, - Name: foundServer.Name - }; - return info.LastConnectionMode = info.ManualAddress ? ConnectionMode.Manual : ConnectionMode.Local, info - }); - resolve(servers) - }; - - if (window.NativeShell && typeof window.NativeShell.findServers === 'function') { - window.NativeShell.findServers(1e3).then(onFinish, function() { - onFinish([]) - }); - } else { - resolve([]); - } - }); - } - - function convertEndpointAddressToManualAddress(info) { - if (info.Address && info.EndpointAddress) { - var address = info.EndpointAddress.split(":")[0], - parts = info.Address.split(":"); - if (parts.length > 1) { - var portString = parts[parts.length - 1]; - isNaN(parseInt(portString)) || (address += ":" + portString) - } - return normalizeAddress(address) - } - return null - } - - function getTryConnectPromise(url, connectionMode, state, resolve, reject) { - console.log("getTryConnectPromise " + url), ajax({ - url: getEmbyServerUrl(url, "system/info/public"), - timeout: defaultTimeout, - type: "GET", - dataType: "json" - }).then(function(result) { - state.resolved || (state.resolved = !0, console.log("Reconnect succeeded to " + url), resolve({ - url: url, - connectionMode: connectionMode, - data: result - })) - }, function() { - state.resolved || (console.log("Reconnect failed to " + url), ++state.rejects >= state.numAddresses && reject()) - }) - } - - function tryReconnect(serverInfo) { - var addresses = [], - addressesStrings = []; - return !serverInfo.manualAddressOnly && serverInfo.LocalAddress && -1 === addressesStrings.indexOf(serverInfo.LocalAddress) && (addresses.push({ - url: serverInfo.LocalAddress, - mode: ConnectionMode.Local, - timeout: 0 - }), addressesStrings.push(addresses[addresses.length - 1].url)), serverInfo.ManualAddress && -1 === addressesStrings.indexOf(serverInfo.ManualAddress) && (addresses.push({ - url: serverInfo.ManualAddress, - mode: ConnectionMode.Manual, - timeout: 100 - }), addressesStrings.push(addresses[addresses.length - 1].url)), !serverInfo.manualAddressOnly && serverInfo.RemoteAddress && -1 === addressesStrings.indexOf(serverInfo.RemoteAddress) && (addresses.push({ - url: serverInfo.RemoteAddress, - mode: ConnectionMode.Remote, - timeout: 200 - }), addressesStrings.push(addresses[addresses.length - 1].url)), console.log("tryReconnect: " + addressesStrings.join("|")), new Promise(function(resolve, reject) { - var state = {}; - state.numAddresses = addresses.length, state.rejects = 0, addresses.map(function(url) { - setTimeout(function() { - state.resolved || getTryConnectPromise(url.url, url.mode, state, resolve, reject) - }, url.timeout) - }) - }) - } - - function onSuccessfulConnection(server, systemInfo, connectionMode, serverUrl, options, resolve) { - var credentials = credentialProvider.credentials(); - options = options || {}, credentials.ConnectAccessToken && !1 !== options.enableAutoLogin ? ensureConnectUser(credentials).then(function() { - server.ExchangeToken ? addAuthenticationInfoFromConnect(server, serverUrl, credentials).then(function() { - afterConnectValidated(server, credentials, systemInfo, connectionMode, serverUrl, !0, options, resolve) - }, function() { - afterConnectValidated(server, credentials, systemInfo, connectionMode, serverUrl, !0, options, resolve) - }) : afterConnectValidated(server, credentials, systemInfo, connectionMode, serverUrl, !0, options, resolve) - }) : afterConnectValidated(server, credentials, systemInfo, connectionMode, serverUrl, !0, options, resolve) - } - - function afterConnectValidated(server, credentials, systemInfo, connectionMode, serverUrl, verifyLocalAuthentication, options, resolve) { - if (options = options || {}, !1 === options.enableAutoLogin) server.UserId = null, server.AccessToken = null; - else if (verifyLocalAuthentication && server.AccessToken && !1 !== options.enableAutoLogin) return void validateAuthentication(server, serverUrl).then(function() { - afterConnectValidated(server, credentials, systemInfo, connectionMode, serverUrl, !1, options, resolve) - }); - updateServerInfo(server, systemInfo), server.LastConnectionMode = connectionMode, !1 !== options.updateDateLastAccessed && (server.DateLastAccessed = (new Date).getTime()), credentialProvider.addOrUpdateServer(credentials.Servers, server), credentialProvider.credentials(credentials); - var result = { - Servers: [] - }; - result.ApiClient = self._getOrAddApiClient(server, serverUrl), result.ApiClient.setSystemInfo(systemInfo), result.State = server.AccessToken && !1 !== options.enableAutoLogin ? "SignedIn" : "ServerSignIn", result.Servers.push(server), result.ApiClient.enableAutomaticBitrateDetection = options.enableAutomaticBitrateDetection, result.ApiClient.updateServerInfo(server, serverUrl); - var resolveActions = function() { - resolve(result), events.trigger(self, "connected", [result]) - }; - "SignedIn" === result.State ? (afterConnected(result.ApiClient, options), result.ApiClient.getCurrentUser().then(function(user) { - onLocalUserSignIn(server, serverUrl, user).then(resolveActions, resolveActions) - }, resolveActions)) : resolveActions() - } - - function getCacheKey(feature, apiClient, options) { - options = options || {}; - var viewOnly = options.viewOnly, - cacheKey = "regInfo-" + apiClient.serverId(); - return viewOnly && (cacheKey += "-viewonly"), cacheKey - } - - function addAppInfoToConnectRequest(request) { - request.headers = request.headers || {}, request.headers["X-Application"] = appName + "/" + appVersion - } - - function exchangePin(pinInfo) { - if (!pinInfo) throw new Error("pinInfo cannot be null"); - var request = { - type: "POST", - url: getConnectUrl("pin/authenticate"), - data: { - deviceId: pinInfo.DeviceId, - pin: pinInfo.Pin - }, - dataType: "json" - }; - return addAppInfoToConnectRequest(request), ajax(request) - } - console.log("Begin ConnectionManager constructor"); - var self = this; - this._apiClients = []; - var connectUser; - self.connectUser = function() { - return connectUser - }, self._minServerVersion = "3.2.33", self.appVersion = function() { - return appVersion - }, self.appName = function() { - return appName - }, self.capabilities = function() { - return capabilities - }, self.deviceId = function() { - return deviceId - }, self.credentialProvider = function() { - return credentialProvider - }, self.connectUserId = function() { - return credentialProvider.credentials().ConnectUserId - }, self.connectToken = function() { - return credentialProvider.credentials().ConnectAccessToken - }, self.getServerInfo = function(id) { - return credentialProvider.credentials().Servers.filter(function(s) { - return s.Id === id - })[0] - }, self.getLastUsedServer = function() { - var servers = credentialProvider.credentials().Servers; - return servers.sort(function(a, b) { - return (b.DateLastAccessed || 0) - (a.DateLastAccessed || 0) - }), servers.length ? servers[0] : null - }, self.addApiClient = function(apiClient) { - self._apiClients.push(apiClient); - var existingServers = credentialProvider.credentials().Servers.filter(function(s) { - return stringEqualsIgnoreCase(s.ManualAddress, apiClient.serverAddress()) || stringEqualsIgnoreCase(s.LocalAddress, apiClient.serverAddress()) || stringEqualsIgnoreCase(s.RemoteAddress, apiClient.serverAddress()) - }), - existingServer = existingServers.length ? existingServers[0] : apiClient.serverInfo(); - if (existingServer.DateLastAccessed = (new Date).getTime(), existingServer.LastConnectionMode = ConnectionMode.Manual, existingServer.ManualAddress = apiClient.serverAddress(), apiClient.manualAddressOnly && (existingServer.manualAddressOnly = !0), apiClient.serverInfo(existingServer), apiClient.onAuthenticated = function(instance, result) { - return onAuthenticated(instance, result, {}, !0) - }, !existingServers.length) { - var credentials = credentialProvider.credentials(); - credentials.Servers = [existingServer], credentialProvider.credentials(credentials) - } - events.trigger(self, "apiclientcreated", [apiClient]) - }, self.clearData = function() { - console.log("connection manager clearing data"), connectUser = null; - var credentials = credentialProvider.credentials(); - credentials.ConnectAccessToken = null, credentials.ConnectUserId = null, credentials.Servers = [], credentialProvider.credentials(credentials) - }, self._getOrAddApiClient = function(server, serverUrl) { - var apiClient = self.getApiClient(server.Id); - return apiClient || (apiClient = new apiClientFactory(serverUrl, appName, appVersion, deviceName, deviceId, devicePixelRatio), self._apiClients.push(apiClient), apiClient.serverInfo(server), apiClient.onAuthenticated = function(instance, result) { - return onAuthenticated(instance, result, {}, !0) - }, events.trigger(self, "apiclientcreated", [apiClient])), console.log("returning instance from getOrAddApiClient"), apiClient - }, self.getOrCreateApiClient = function(serverId) { - var credentials = credentialProvider.credentials(), - servers = credentials.Servers.filter(function(s) { - return stringEqualsIgnoreCase(s.Id, serverId) - }); - if (!servers.length) throw new Error("Server not found: " + serverId); - var server = servers[0]; - return self._getOrAddApiClient(server, getServerAddress(server, server.LastConnectionMode)) - }, self.user = function(apiClient) { - return new Promise(function(resolve, reject) { - function onLocalUserDone(e) { - var image = getImageUrl(localUser); - resolve({ - localUser: localUser, - name: connectUser ? connectUser.Name : localUser ? localUser.Name : null, - imageUrl: image.url, - supportsImageParams: image.supportsParams, - connectUser: connectUser - }) - } - - function onEnsureConnectUserDone() { - apiClient && apiClient.getCurrentUserId() ? apiClient.getCurrentUser().then(function(u) { - localUser = u, onLocalUserDone() - }, onLocalUserDone) : onLocalUserDone() - } - var localUser, credentials = credentialProvider.credentials(); - !credentials.ConnectUserId || !credentials.ConnectAccessToken || apiClient && apiClient.getCurrentUserId() ? onEnsureConnectUserDone() : ensureConnectUser(credentials).then(onEnsureConnectUserDone, onEnsureConnectUserDone) - }) - }, self.logout = function() { - console.log("begin connectionManager loguot"); - for (var promises = [], i = 0, length = self._apiClients.length; i < length; i++) { - var apiClient = self._apiClients[i]; - apiClient.accessToken() && promises.push(logoutOfServer(apiClient)) - } - return Promise.all(promises).then(function() { - for (var credentials = credentialProvider.credentials(), servers = credentials.Servers.filter(function(u) { - return "Guest" !== u.UserLinkType - }), j = 0, numServers = servers.length; j < numServers; j++) { - var server = servers[j]; - server.UserId = null, server.AccessToken = null, server.ExchangeToken = null - } - credentials.Servers = servers, credentials.ConnectAccessToken = null, credentials.ConnectUserId = null, credentialProvider.credentials(credentials), connectUser && (connectUser = null, events.trigger(self, "connectusersignedout")) - }) - }, self.getSavedServers = function() { - var credentials = credentialProvider.credentials(), - servers = credentials.Servers.slice(0); - return servers.sort(function(a, b) { - return (b.DateLastAccessed || 0) - (a.DateLastAccessed || 0) - }), servers - }, self.getAvailableServers = function() { - console.log("Begin getAvailableServers"); - var credentials = credentialProvider.credentials(); - return Promise.all([getConnectServers(credentials), findServers()]).then(function(responses) { - var connectServers = responses[0], - foundServers = responses[1], - servers = credentials.Servers.slice(0); - return mergeServers(credentialProvider, servers, foundServers), mergeServers(credentialProvider, servers, connectServers), servers = filterServers(servers, connectServers), servers.sort(function(a, b) { - return (b.DateLastAccessed || 0) - (a.DateLastAccessed || 0) - }), credentials.Servers = servers, credentialProvider.credentials(credentials), servers - }) - }, self.connectToServers = function(servers, options) { - console.log("Begin connectToServers, with " + servers.length + " servers"); - var firstServer = servers.length ? servers[0] : null; - return firstServer ? self.connectToServer(firstServer, options).then(function(result) { - return "Unavailable" === result.State && (result.State = "ServerSelection"), console.log("resolving connectToServers with result.State: " + result.State), result - }) : Promise.resolve({ - Servers: servers, - State: servers.length || self.connectUser() ? "ServerSelection" : "ConnectSignIn", - ConnectUser: self.connectUser() - }) - }, self.connectToServer = function(server, options) { - return console.log("begin connectToServer"), new Promise(function(resolve, reject) { - options = options || {}, tryReconnect(server).then(function(result) { - var serverUrl = result.url, - connectionMode = result.connectionMode; - result = result.data, 1 === compareVersions(self.minServerVersion(), result.Version) ? (console.log("minServerVersion requirement not met. Server version: " + result.Version), resolve({ - State: "ServerUpdateNeeded", - Servers: [server] - })) : server.Id && result.Id !== server.Id ? (console.log("http request succeeded, but found a different server Id than what was expected"), resolveFailure(self, resolve)) : onSuccessfulConnection(server, result, connectionMode, serverUrl, options, resolve) - }, function() { - resolveFailure(self, resolve) - }) - }) - }, self.connectToAddress = function(address, options) { - function onFail() { - return console.log("connectToAddress " + address + " failed"), Promise.resolve({ - State: "Unavailable", - ConnectUser: instance.connectUser() - }) - } - if (!address) return Promise.reject(); - address = normalizeAddress(address); - var instance = this, - server = { - ManualAddress: address, - LastConnectionMode: ConnectionMode.Manual - }; - return self.connectToServer(server, options).catch(onFail) - }, self.loginToConnect = function(username, password) { - return username && password ? ajax({ - type: "POST", - url: "https://connect.emby.media/service/user/authenticate", - data: { - nameOrEmail: username, - rawpw: password - }, - dataType: "json", - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - headers: { - "X-Application": appName + "/" + appVersion - } - }).then(function(result) { - var credentials = credentialProvider.credentials(); - return credentials.ConnectAccessToken = result.AccessToken, credentials.ConnectUserId = result.User.Id, credentialProvider.credentials(credentials), onConnectUserSignIn(result.User), result - }) : Promise.reject() - }, self.signupForConnect = function(options) { - var email = options.email, - username = options.username, - password = options.password, - passwordConfirm = options.passwordConfirm; - if (!email) return Promise.reject({ - errorCode: "invalidinput" - }); - if (!username) return Promise.reject({ - errorCode: "invalidinput" - }); - if (!password) return Promise.reject({ - errorCode: "invalidinput" - }); - if (!passwordConfirm) return Promise.reject({ - errorCode: "passwordmatch" - }); - if (password !== passwordConfirm) return Promise.reject({ - errorCode: "passwordmatch" - }); - var data = { - email: email, - userName: username, - rawpw: password - }; - return options.grecaptcha && (data.grecaptcha = options.grecaptcha), ajax({ - type: "POST", - url: "https://connect.emby.media/service/register", - data: data, - dataType: "json", - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - headers: { - "X-Application": appName + "/" + appVersion, - "X-CONNECT-TOKEN": "CONNECT-REGISTER" - } - }).catch(function(response) { - try { - return response.json() - } catch (err) { - throw err - } - }).then(function(result) { - if (result && result.Status) return "SUCCESS" === result.Status ? Promise.resolve(result) : Promise.reject({ - errorCode: result.Status - }); - Promise.reject() - }) - }, self.getUserInvitations = function() { - var connectToken = self.connectToken(); - if (!connectToken) throw new Error("null connectToken"); - if (!self.connectUserId()) throw new Error("null connectUserId"); - return ajax({ - type: "GET", - url: "https://connect.emby.media/service/servers?userId=" + self.connectUserId() + "&status=Waiting", - dataType: "json", - headers: { - "X-Connect-UserToken": connectToken, - "X-Application": appName + "/" + appVersion - } - }) - }, self.deleteServer = function(serverId) { - if (!serverId) throw new Error("null serverId"); - var server = credentialProvider.credentials().Servers.filter(function(s) { - return s.Id === serverId - }); - return server = server.length ? server[0] : null, new Promise(function(resolve, reject) { - function onDone() { - var credentials = credentialProvider.credentials(); - credentials.Servers = credentials.Servers.filter(function(s) { - return s.Id !== serverId - }), credentialProvider.credentials(credentials), resolve() - } - if (!server.ConnectServerId) return void onDone(); - var connectToken = self.connectToken(), - connectUserId = self.connectUserId(); - if (!connectToken || !connectUserId) return void onDone(); - ajax({ - type: "DELETE", - url: "https://connect.emby.media/service/serverAuthorizations?serverId=" + server.ConnectServerId + "&userId=" + connectUserId, - headers: { - "X-Connect-UserToken": connectToken, - "X-Application": appName + "/" + appVersion - } - }).then(onDone, onDone) - }) - }, self.rejectServer = function(serverId) { - var connectToken = self.connectToken(); - if (!serverId) throw new Error("null serverId"); - if (!connectToken) throw new Error("null connectToken"); - if (!self.connectUserId()) throw new Error("null connectUserId"); - var url = "https://connect.emby.media/service/serverAuthorizations?serverId=" + serverId + "&userId=" + self.connectUserId(); - return fetch(url, { - method: "DELETE", - headers: { - "X-Connect-UserToken": connectToken, - "X-Application": appName + "/" + appVersion - } - }) - }, self.acceptServer = function(serverId) { - var connectToken = self.connectToken(); - if (!serverId) throw new Error("null serverId"); - if (!connectToken) throw new Error("null connectToken"); - if (!self.connectUserId()) throw new Error("null connectUserId"); - return ajax({ - type: "GET", - url: "https://connect.emby.media/service/ServerAuthorizations/accept?serverId=" + serverId + "&userId=" + self.connectUserId(), - headers: { - "X-Connect-UserToken": connectToken, - "X-Application": appName + "/" + appVersion - } - }) - }, self.resetRegistrationInfo = function(apiClient) { - var cacheKey = getCacheKey("themes", apiClient, { - viewOnly: !0 - }); - appStorage.removeItem(cacheKey), cacheKey = getCacheKey("themes", apiClient, { - viewOnly: !1 - }), appStorage.removeItem(cacheKey) - }, self.getRegistrationInfo = function(feature, apiClient, options) { - var cacheKey = getCacheKey(feature, apiClient, options); - appStorage.setItem(cacheKey, JSON.stringify({ - lastValidDate: new Date().getTime(), - deviceId: self.deviceId() - })); - return Promise.resolve(); - }, self.createPin = function() { - var request = { - type: "POST", - url: getConnectUrl("pin"), - data: { - deviceId: deviceId - }, - dataType: "json" - }; - return addAppInfoToConnectRequest(request), ajax(request) - }, self.getPinStatus = function(pinInfo) { - if (!pinInfo) throw new Error("pinInfo cannot be null"); - var queryString = { - deviceId: pinInfo.DeviceId, - pin: pinInfo.Pin - }, - request = { - type: "GET", - url: getConnectUrl("pin") + "?" + paramsToString(queryString), - dataType: "json" - }; - return addAppInfoToConnectRequest(request), ajax(request) - }, self.exchangePin = function(pinInfo) { - if (!pinInfo) throw new Error("pinInfo cannot be null"); - return exchangePin(pinInfo).then(function(result) { - var credentials = credentialProvider.credentials(); - return credentials.ConnectAccessToken = result.AccessToken, credentials.ConnectUserId = result.UserId, credentialProvider.credentials(credentials), ensureConnectUser(credentials) - }) - } - }; - return ConnectionManager.prototype.connect = function(options) { - console.log("Begin connect"); - var instance = this; - return instance.getAvailableServers().then(function(servers) { - return instance.connectToServers(servers, options) - }) - }, ConnectionManager.prototype.isLoggedIntoConnect = function() { - return !(!this.connectToken() || !this.connectUserId()) - }, ConnectionManager.prototype.getApiClients = function() { - for (var servers = this.getSavedServers(), i = 0, length = servers.length; i < length; i++) { - var server = servers[i]; - server.Id && this._getOrAddApiClient(server, getServerAddress(server, server.LastConnectionMode)) - } - return this._apiClients - }, ConnectionManager.prototype.getApiClient = function(item) { - if (!item) throw new Error("item or serverId cannot be null"); - return item.ServerId && (item = item.ServerId), this._apiClients.filter(function(a) { - var serverInfo = a.serverInfo(); - return !serverInfo || serverInfo.Id === item - })[0] - }, ConnectionManager.prototype.minServerVersion = function(val) { - return val && (this._minServerVersion = val), this._minServerVersion - }, ConnectionManager.prototype.handleMessageReceived = function(msg) { - var serverId = msg.ServerId; - if (serverId) { - var apiClient = this.getApiClient(serverId); - if (apiClient) { - if ("string" == typeof msg.Data) try { - msg.Data = JSON.parse(msg.Data) - } catch (err) {} - apiClient.handleMessageReceived(msg) - } - } - }, ConnectionManager -}); diff --git a/src/bower_components/document-register-element/basic.html b/src/bower_components/document-register-element/basic.html deleted file mode 100644 index 713a029e4c..0000000000 --- a/src/bower_components/document-register-element/basic.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - testing my-element - - - - - - some content - - \ No newline at end of file diff --git a/src/bower_components/document-register-element/build/document-register-element.js b/src/bower_components/document-register-element/build/document-register-element.js deleted file mode 100644 index 57fe40a366..0000000000 --- a/src/bower_components/document-register-element/build/document-register-element.js +++ /dev/null @@ -1,246 +0,0 @@ -/*! (C) WebReflection Mit Style License */ -(function(e, t, n, r) { - "use strict"; - - function rt(e, t) { - for (var n = 0, r = e.length; n < r; n++) vt(e[n], t) - } - - function it(e) { - for (var t = 0, n = e.length, r; t < n; t++) r = e[t], nt(r, b[ot(r)]) - } - - function st(e) { - return function(t) { - j(t) && (vt(t, e), rt(t.querySelectorAll(w), e)) - } - } - - function ot(e) { - var t = e.getAttribute("is"), - n = e.nodeName.toUpperCase(), - r = S.call(y, t ? v + t.toUpperCase() : d + n); - return t && -1 < r && !ut(n, t) ? -1 : r - } - - function ut(e, t) { - return -1 < w.indexOf(e + '[is="' + t + '"]') - } - - function at(e) { - var t = e.currentTarget, - n = e.attrChange, - r = e.attrName, - i = e.target; - Q && (!i || i === t) && t.attributeChangedCallback && r !== "style" && e.prevValue !== e.newValue && t.attributeChangedCallback(r, n === e[a] ? null : e.prevValue, n === e[l] ? null : e.newValue) - } - - function ft(e) { - var t = st(e); - return function(e) { - X.push(t, e.target) - } - } - - function lt(e) { - K && (K = !1, e.currentTarget.removeEventListener(h, lt)), rt((e.target || t).querySelectorAll(w), e.detail === o ? o : s), B && pt() - } - - function ct(e, t) { - var n = this; - q.call(n, e, t), G.call(n, { - target: n - }) - } - - function ht(e, t) { - D(e, t), et ? et.observe(e, z) : (J && (e.setAttribute = ct, e[i] = Z(e), e.addEventListener(p, G)), e.addEventListener(c, at)), e.createdCallback && Q && (e.created = !0, e.createdCallback(), e.created = !1) - } - - function pt() { - for (var e, t = 0, n = F.length; t < n; t++) e = F[t], E.contains(e) || (n--, F.splice(t--, 1), vt(e, o)) - } - - function dt(e) { - throw new Error("A " + e + " type is already registered") - } - - function vt(e, t) { - var n, r = ot(e); - 1 < r && (tt(e, b[r]), r = 0, t === s && !e[s] ? (e[o] = !1, e[s] = !0, r = 1, B && S.call(F, e) < 0 && F.push(e)) : t === o && !e[o] && (e[s] = !1, e[o] = !0, r = 1), r && (n = e[t + "Callback"]) && n.call(e)) - } - if (r in t) return; - var i = "__" + r + (Math.random() * 1e5 >> 0), - s = "attached", - o = "detached", - u = "extends", - a = "ADDITION", - f = "MODIFICATION", - l = "REMOVAL", - c = "DOMAttrModified", - h = "DOMContentLoaded", - p = "DOMSubtreeModified", - d = "<", - v = "=", - m = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/, - g = ["ANNOTATION-XML", "COLOR-PROFILE", "FONT-FACE", "FONT-FACE-SRC", "FONT-FACE-URI", "FONT-FACE-FORMAT", "FONT-FACE-NAME", "MISSING-GLYPH"], - y = [], - b = [], - w = "", - E = t.documentElement, - S = y.indexOf || function(e) { - for (var t = this.length; t-- && this[t] !== e;); - return t - }, - x = n.prototype, - T = x.hasOwnProperty, - N = x.isPrototypeOf, - C = n.defineProperty, - k = n.getOwnPropertyDescriptor, - L = n.getOwnPropertyNames, - A = n.getPrototypeOf, - O = n.setPrototypeOf, - M = !!n.__proto__, - _ = n.create || function mt(e) { - return e ? (mt.prototype = e, new mt) : this - }, - D = O || (M ? function(e, t) { - return e.__proto__ = t, e - } : L && k ? function() { - function e(e, t) { - for (var n, r = L(t), i = 0, s = r.length; i < s; i++) n = r[i], T.call(e, n) || C(e, n, k(t, n)) - } - return function(t, n) { - do e(t, n); while ((n = A(n)) && !N.call(n, t)); - return t - } - }() : function(e, t) { - for (var n in t) e[n] = t[n]; - return e - }), - P = e.MutationObserver || e.WebKitMutationObserver, - H = (e.HTMLElement || e.Element || e.Node).prototype, - B = !N.call(H, E), - j = B ? function(e) { - return e.nodeType === 1 - } : function(e) { - return N.call(H, e) - }, - F = B && [], - I = H.cloneNode, - q = H.setAttribute, - R = H.removeAttribute, - U = t.createElement, - z = P && { - attributes: !0, - characterData: !0, - attributeOldValue: !0 - }, - W = P || function(e) { - J = !1, E.removeEventListener(c, W) - }, - X, V = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.msRequestAnimationFrame || function(e) { - setTimeout(e, 10) - }, - $ = !1, - J = !0, - K = !0, - Q = !0, - G, Y, Z, et, tt, nt; - O || M ? (tt = function(e, t) { - N.call(t, e) || ht(e, t) - }, nt = ht) : (tt = function(e, t) { - e[i] || (e[i] = n(!0), ht(e, t)) - }, nt = tt), B ? (J = !1, function() { - var e = k(H, "addEventListener"), - t = e.value, - n = function(e) { - var t = new CustomEvent(c, { - bubbles: !0 - }); - t.attrName = e, t.prevValue = this.getAttribute(e), t.newValue = null, t[l] = t.attrChange = 2, R.call(this, e), this.dispatchEvent(t) - }, - r = function(e, t) { - var n = this.hasAttribute(e), - r = n && this.getAttribute(e), - i = new CustomEvent(c, { - bubbles: !0 - }); - q.call(this, e, t), i.attrName = e, i.prevValue = n ? r : null, i.newValue = t, n ? i[f] = i.attrChange = 1 : i[a] = i.attrChange = 0, this.dispatchEvent(i) - }, - s = function(e) { - var t = e.currentTarget, - n = t[i], - r = e.propertyName, - s; - n.hasOwnProperty(r) && (n = n[r], s = new CustomEvent(c, { - bubbles: !0 - }), s.attrName = n.name, s.prevValue = n.value || null, s.newValue = n.value = t[r] || null, s.prevValue == null ? s[a] = s.attrChange = 0 : s[f] = s.attrChange = 1, t.dispatchEvent(s)) - }; - e.value = function(e, o, u) { - e === c && this.attributeChangedCallback && this.setAttribute !== r && (this[i] = { - className: { - name: "class", - value: this.className - } - }, this.setAttribute = r, this.removeAttribute = n, t.call(this, "propertychange", s)), t.call(this, e, o, u) - }, C(H, "addEventListener", e) - }()) : P || (E.addEventListener(c, W), E.setAttribute(i, 1), E.removeAttribute(i), J && (G = function(e) { - var t = this, - n, r, s; - if (t === e.target) { - n = t[i], t[i] = r = Z(t); - for (s in r) { - if (!(s in n)) return Y(0, t, s, n[s], r[s], a); - if (r[s] !== n[s]) return Y(1, t, s, n[s], r[s], f) - } - for (s in n) - if (!(s in r)) return Y(2, t, s, n[s], r[s], l) - } - }, Y = function(e, t, n, r, i, s) { - var o = { - attrChange: e, - currentTarget: t, - attrName: n, - prevValue: r, - newValue: i - }; - o[s] = e, at(o) - }, Z = function(e) { - for (var t, n, r = {}, i = e.attributes, s = 0, o = i.length; s < o; s++) t = i[s], n = t.name, n !== "setAttribute" && (r[n] = t.value); - return r - })), t[r] = function(n, r) { - c = n.toUpperCase(), $ || ($ = !0, P ? (et = function(e, t) { - function n(e, t) { - for (var n = 0, r = e.length; n < r; t(e[n++])); - } - return new P(function(r) { - for (var i, s, o, u = 0, a = r.length; u < a; u++) i = r[u], i.type === "childList" ? (n(i.addedNodes, e), n(i.removedNodes, t)) : (s = i.target, Q && s.attributeChangedCallback && i.attributeName !== "style" && (o = s.getAttribute(i.attributeName), o !== i.oldValue && s.attributeChangedCallback(i.attributeName, i.oldValue, o))) - }) - }(st(s), st(o)), et.observe(t, { - childList: !0, - subtree: !0 - })) : (X = [], V(function E() { - while (X.length) X.shift().call(null, X.shift()); - V(E) - }), t.addEventListener("DOMNodeInserted", ft(s)), t.addEventListener("DOMNodeRemoved", ft(o))), t.addEventListener(h, lt), t.addEventListener("readystatechange", lt), t.createElement = function(e, n) { - var r = U.apply(t, arguments), - i = "" + e, - s = S.call(y, (n ? v : d) + (n || i).toUpperCase()), - o = -1 < s; - return n && (r.setAttribute("is", n = n.toLowerCase()), o && (o = ut(i.toUpperCase(), n))), Q = !t.createElement.innerHTMLHelper, o && nt(r, b[s]), r - }, H.cloneNode = function(e) { - var t = I.call(this, !!e), - n = ot(t); - return -1 < n && nt(t, b[n]), e && it(t.querySelectorAll(w)), t - }), -2 < S.call(y, v + c) + S.call(y, d + c) && dt(n); - if (!m.test(c) || -1 < S.call(g, c)) throw new Error("The type " + n + " is invalid"); - var i = function() { - return f ? t.createElement(l, c) : t.createElement(l) - }, - a = r || x, - f = T.call(a, u), - l = f ? r[u].toUpperCase() : c, - c, p; - return f && -1 < S.call(y, d + l) && dt(l), p = y.push((f ? v : d) + c) - 1, w = w.concat(w.length ? "," : "", f ? l + '[is="' + n.toLowerCase() + '"]' : l), i.prototype = b[p] = T.call(a, "prototype") ? a.prototype : _(H), rt(t.querySelectorAll(w), s), i - } -})(window, document, Object, "registerElement"); \ No newline at end of file diff --git a/src/bower_components/fetch/fetch.js b/src/bower_components/fetch/fetch.js deleted file mode 100644 index cd40b3ed2d..0000000000 --- a/src/bower_components/fetch/fetch.js +++ /dev/null @@ -1,263 +0,0 @@ -! function(self) { - "use strict"; - - function normalizeName(name) { - if ("string" != typeof name && (name = String(name)), /[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) throw new TypeError("Invalid character in header field name"); - return name.toLowerCase() - } - - function normalizeValue(value) { - return "string" != typeof value && (value = String(value)), value - } - - function iteratorFor(items) { - var iterator = { - next: function() { - var value = items.shift(); - return { - done: void 0 === value, - value: value - } - } - }; - return support.iterable && (iterator[Symbol.iterator] = function() { - return iterator - }), iterator - } - - function Headers(headers) { - this.map = {}, headers instanceof Headers ? headers.forEach(function(value, name) { - this.append(name, value) - }, this) : headers && Object.getOwnPropertyNames(headers).forEach(function(name) { - this.append(name, headers[name]) - }, this) - } - - function consumed(body) { - if (body.bodyUsed) return Promise.reject(new TypeError("Already read")); - body.bodyUsed = !0 - } - - function fileReaderReady(reader) { - return new Promise(function(resolve, reject) { - reader.onload = function() { - resolve(reader.result) - }, reader.onerror = function() { - reject(reader.error) - } - }) - } - - function readBlobAsArrayBuffer(blob) { - var reader = new FileReader, - promise = fileReaderReady(reader); - return reader.readAsArrayBuffer(blob), promise - } - - function readBlobAsText(blob) { - var reader = new FileReader, - promise = fileReaderReady(reader); - return reader.readAsText(blob), promise - } - - function readArrayBufferAsText(buf) { - for (var view = new Uint8Array(buf), chars = new Array(view.length), i = 0; i < view.length; i++) chars[i] = String.fromCharCode(view[i]); - return chars.join("") - } - - function bufferClone(buf) { - if (buf.slice) return buf.slice(0); - var view = new Uint8Array(buf.byteLength); - return view.set(new Uint8Array(buf)), view.buffer - } - - function Body() { - return this.bodyUsed = !1, this._initBody = function(body) { - if (this._bodyInit = body, body) - if ("string" == typeof body) this._bodyText = body; - else if (support.blob && Blob.prototype.isPrototypeOf(body)) this._bodyBlob = body; - else if (support.formData && FormData.prototype.isPrototypeOf(body)) this._bodyFormData = body; - else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) this._bodyText = body.toString(); - else if (support.arrayBuffer && support.blob && isDataView(body)) this._bodyArrayBuffer = bufferClone(body.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer]); - else { - if (!support.arrayBuffer || !ArrayBuffer.prototype.isPrototypeOf(body) && !isArrayBufferView(body)) throw new Error("unsupported BodyInit type"); - this._bodyArrayBuffer = bufferClone(body) - } else this._bodyText = ""; - this.headers.get("content-type") || ("string" == typeof body ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : support.searchParams && URLSearchParams.prototype.isPrototypeOf(body) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8")) - }, support.blob && (this.blob = function() { - var rejected = consumed(this); - if (rejected) return rejected; - if (this._bodyBlob) return Promise.resolve(this._bodyBlob); - if (this._bodyArrayBuffer) return Promise.resolve(new Blob([this._bodyArrayBuffer])); - if (this._bodyFormData) throw new Error("could not read FormData body as blob"); - return Promise.resolve(new Blob([this._bodyText])) - }, this.arrayBuffer = function() { - return this._bodyArrayBuffer ? consumed(this) || Promise.resolve(this._bodyArrayBuffer) : this.blob().then(readBlobAsArrayBuffer) - }), this.text = function() { - var rejected = consumed(this); - if (rejected) return rejected; - if (this._bodyBlob) return readBlobAsText(this._bodyBlob); - if (this._bodyArrayBuffer) return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)); - if (this._bodyFormData) throw new Error("could not read FormData body as text"); - return Promise.resolve(this._bodyText) - }, support.formData && (this.formData = function() { - return this.text().then(decode) - }), this.json = function() { - return this.text().then(JSON.parse) - }, this - } - - function normalizeMethod(method) { - var upcased = method.toUpperCase(); - return methods.indexOf(upcased) > -1 ? upcased : method - } - - function Request(input, options) { - options = options || {}; - var body = options.body; - if ("string" == typeof input) this.url = input; - else { - if (input.bodyUsed) throw new TypeError("Already read"); - this.url = input.url, this.credentials = input.credentials, options.headers || (this.headers = new Headers(input.headers)), this.method = input.method, this.mode = input.mode, body || null == input._bodyInit || (body = input._bodyInit, input.bodyUsed = !0) - } - if (this.credentials = options.credentials || this.credentials || "omit", !options.headers && this.headers || (this.headers = new Headers(options.headers)), this.method = normalizeMethod(options.method || this.method || "GET"), this.mode = options.mode || this.mode || null, this.referrer = null, ("GET" === this.method || "HEAD" === this.method) && body) throw new TypeError("Body not allowed for GET or HEAD requests"); - this._initBody(body) - } - - function decode(body) { - var form = new FormData; - return body.trim().split("&").forEach(function(bytes) { - if (bytes) { - var split = bytes.split("="), - name = split.shift().replace(/\+/g, " "), - value = split.join("=").replace(/\+/g, " "); - form.append(decodeURIComponent(name), decodeURIComponent(value)) - } - }), form - } - - function parseHeaders(rawHeaders) { - var headers = new Headers; - return rawHeaders.split("\r\n").forEach(function(line) { - var parts = line.split(":"), - key = parts.shift().trim(); - if (key) { - var value = parts.join(":").trim(); - headers.append(key, value) - } - }), headers - } - - function Response(bodyInit, options) { - options || (options = {}), this.type = "default", this.status = "status" in options ? options.status : 200, this.ok = this.status >= 200 && this.status < 300, this.statusText = "statusText" in options ? options.statusText : "OK", this.headers = new Headers(options.headers), this.url = options.url || "", this._initBody(bodyInit) - } - if (!self.fetch) { - var support = { - searchParams: "URLSearchParams" in self, - iterable: "Symbol" in self && "iterator" in Symbol, - blob: "FileReader" in self && "Blob" in self && function() { - try { - return new Blob, !0 - } catch (e) { - return !1 - } - }(), - formData: "FormData" in self, - arrayBuffer: "ArrayBuffer" in self - }; - if (support.arrayBuffer) var viewClasses = ["[object Int8Array]", "[object Uint8Array]", "[object Uint8ClampedArray]", "[object Int16Array]", "[object Uint16Array]", "[object Int32Array]", "[object Uint32Array]", "[object Float32Array]", "[object Float64Array]"], - isDataView = function(obj) { - return obj && DataView.prototype.isPrototypeOf(obj) - }, - isArrayBufferView = ArrayBuffer.isView || function(obj) { - return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 - }; - Headers.prototype.append = function(name, value) { - name = normalizeName(name), value = normalizeValue(value); - var list = this.map[name]; - list || (list = [], this.map[name] = list), list.push(value) - }, Headers.prototype.delete = function(name) { - delete this.map[normalizeName(name)] - }, Headers.prototype.get = function(name) { - var values = this.map[normalizeName(name)]; - return values ? values[0] : null - }, Headers.prototype.getAll = function(name) { - return this.map[normalizeName(name)] || [] - }, Headers.prototype.has = function(name) { - return this.map.hasOwnProperty(normalizeName(name)) - }, Headers.prototype.set = function(name, value) { - this.map[normalizeName(name)] = [normalizeValue(value)] - }, Headers.prototype.forEach = function(callback, thisArg) { - Object.getOwnPropertyNames(this.map).forEach(function(name) { - this.map[name].forEach(function(value) { - callback.call(thisArg, value, name, this) - }, this) - }, this) - }, Headers.prototype.keys = function() { - var items = []; - return this.forEach(function(value, name) { - items.push(name) - }), iteratorFor(items) - }, Headers.prototype.values = function() { - var items = []; - return this.forEach(function(value) { - items.push(value) - }), iteratorFor(items) - }, Headers.prototype.entries = function() { - var items = []; - return this.forEach(function(value, name) { - items.push([name, value]) - }), iteratorFor(items) - }, support.iterable && (Headers.prototype[Symbol.iterator] = Headers.prototype.entries); - var methods = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]; - Request.prototype.clone = function() { - return new Request(this, { - body: this._bodyInit - }) - }, Body.call(Request.prototype), Body.call(Response.prototype), Response.prototype.clone = function() { - return new Response(this._bodyInit, { - status: this.status, - statusText: this.statusText, - headers: new Headers(this.headers), - url: this.url - }) - }, Response.error = function() { - var response = new Response(null, { - status: 0, - statusText: "" - }); - return response.type = "error", response - }; - var redirectStatuses = [301, 302, 303, 307, 308]; - Response.redirect = function(url, status) { - if (-1 === redirectStatuses.indexOf(status)) throw new RangeError("Invalid status code"); - return new Response(null, { - status: status, - headers: { - location: url - } - }) - }, self.Headers = Headers, self.Request = Request, self.Response = Response, self.fetch = function(input, init) { - return new Promise(function(resolve, reject) { - var request = new Request(input, init), - xhr = new XMLHttpRequest; - xhr.onload = function() { - var options = { - status: xhr.status, - statusText: xhr.statusText, - headers: parseHeaders(xhr.getAllResponseHeaders() || "") - }; - options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL"); - var body = "response" in xhr ? xhr.response : xhr.responseText; - resolve(new Response(body, options)) - }, xhr.onerror = function() { - reject(new TypeError("Network request failed")) - }, xhr.ontimeout = function() { - reject(new TypeError("Network request failed")) - }, xhr.open(request.method, request.url, !0), "include" === request.credentials && (xhr.withCredentials = !0), "responseType" in xhr && support.blob && (xhr.responseType = "blob"), request.headers.forEach(function(value, name) { - xhr.setRequestHeader(name, value) - }), xhr.send(void 0 === request._bodyInit ? null : request._bodyInit) - }) - }, self.fetch.polyfill = !0 - } -}("undefined" != typeof self ? self : this); \ No newline at end of file diff --git a/src/bower_components/native-promise-only/lib/npo.src.js b/src/bower_components/native-promise-only/lib/npo.src.js deleted file mode 100644 index 1c8cb07867..0000000000 --- a/src/bower_components/native-promise-only/lib/npo.src.js +++ /dev/null @@ -1,373 +0,0 @@ -/*! Native Promise Only - v0.8.0-a (c) Kyle Simpson - MIT License: http://getify.mit-license.org -*/ - -(function UMD(name,context,definition){ - // special form of UMD for polyfilling across evironments - context[name] = definition(); - if (typeof module != "undefined" && module.exports) { module.exports = context[name]; } - else if (typeof define == "function" && define.amd) { define(function $AMD$(){ return context[name]; }); } -})("Promise",typeof global != "undefined" ? global : this,function DEF(){ - /*jshint validthis:true */ - "use strict"; - - var builtInProp, cycle, scheduling_queue, - ToString = Object.prototype.toString, - timer = (typeof setImmediate != "undefined") ? - function timer(fn) { return setImmediate(fn); } : - setTimeout - ; - - // dammit, IE8. - try { - Object.defineProperty({},"x",{}); - builtInProp = function builtInProp(obj,name,val,config) { - return Object.defineProperty(obj,name,{ - value: val, - writable: true, - configurable: config !== false - }); - }; - } - catch (err) { - builtInProp = function builtInProp(obj,name,val) { - obj[name] = val; - return obj; - }; - } - - // Note: using a queue instead of array for efficiency - scheduling_queue = (function Queue() { - var first, last, item; - - function Item(fn,self) { - this.fn = fn; - this.self = self; - this.next = void 0; - } - - return { - add: function add(fn,self) { - item = new Item(fn,self); - if (last) { - last.next = item; - } - else { - first = item; - } - last = item; - item = void 0; - }, - drain: function drain() { - var f = first; - first = last = cycle = void 0; - - while (f) { - f.fn.call(f.self); - f = f.next; - } - } - }; - })(); - - function schedule(fn,self) { - scheduling_queue.add(fn,self); - if (!cycle) { - cycle = timer(scheduling_queue.drain); - } - } - - // promise duck typing - function isThenable(o) { - var _then, o_type = typeof o; - - if (o != null && - ( - o_type == "object" || o_type == "function" - ) - ) { - _then = o.then; - } - return typeof _then == "function" ? _then : false; - } - - function notify() { - for (var i=0; i 0) { - schedule(notify,self); - } - } - } - catch (err) { - reject.call(new MakeDefWrapper(self),err); - } - } - - function reject(msg) { - var self = this; - - // already triggered? - if (self.triggered) { return; } - - self.triggered = true; - - // unwrap - if (self.def) { - self = self.def; - } - - self.msg = msg; - self.state = 2; - if (self.chain.length > 0) { - schedule(notify,self); - } - } - - function iteratePromises(Constructor,arr,resolver,rejecter) { - for (var idx=0; idx -1 && (!ary[i] || !func(ary[i], i, ary)); i -= 1); - } - } - - function hasProp(obj, prop) { - return hasOwn.call(obj, prop) - } - - function getOwn(obj, prop) { - return hasProp(obj, prop) && obj[prop] - } - - function eachProp(obj, func) { - var prop; - for (prop in obj) - if (hasProp(obj, prop) && func(obj[prop], prop)) break - } - - function mixin(target, source, force, deepStringMixin) { - return source && eachProp(source, function(value, prop) { - !force && hasProp(target, prop) || (!deepStringMixin || "object" != typeof value || !value || isArray(value) || isFunction(value) || value instanceof RegExp ? target[prop] = value : (target[prop] || (target[prop] = {}), mixin(target[prop], value, force, deepStringMixin))) - }), target - } - - function bind(obj, fn) { - return function() { - return fn.apply(obj, arguments) - } - } - - function scripts() { - return document.getElementsByTagName("script") - } - - function defaultOnError(err) { - throw err - } - - function getGlobal(value) { - if (!value) return value; - var g = global; - return each(value.split("."), function(part) { - g = g[part] - }), g - } - - function makeError(id, msg, err, requireModules) { - var e = new Error(msg + "\nhttp://requirejs.org/docs/errors.html#" + id); - return e.requireType = id, e.requireModules = requireModules, err && (e.originalError = err), e - } - - function newContext(contextName) { - function trimDots(ary) { - var i, part; - for (i = 0; i < ary.length; i++) - if ("." === (part = ary[i])) ary.splice(i, 1), i -= 1; - else if (".." === part) { - if (0 === i || 1 === i && ".." === ary[2] || ".." === ary[i - 1]) continue; - i > 0 && (ary.splice(i - 1, 2), i -= 2) - } - } - - function normalize(name, baseName, applyMap) { - var mapValue, nameParts, i, j, nameSegment, lastIndex, foundMap, foundI, foundStarMap, starI, normalizedBaseParts, baseParts = baseName && baseName.split("/"), - map = config.map, - starMap = map && map["*"]; - if (name && (name = name.split("/"), lastIndex = name.length - 1, config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex]) && (name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, "")), "." === name[0].charAt(0) && baseParts && (normalizedBaseParts = baseParts.slice(0, baseParts.length - 1), name = normalizedBaseParts.concat(name)), trimDots(name), name = name.join("/")), applyMap && map && (baseParts || starMap)) { - nameParts = name.split("/"); - outerLoop: for (i = nameParts.length; i > 0; i -= 1) { - if (nameSegment = nameParts.slice(0, i).join("/"), baseParts) - for (j = baseParts.length; j > 0; j -= 1) - if ((mapValue = getOwn(map, baseParts.slice(0, j).join("/"))) && (mapValue = getOwn(mapValue, nameSegment))) { - foundMap = mapValue, foundI = i; - break outerLoop - }! foundStarMap && starMap && getOwn(starMap, nameSegment) && (foundStarMap = getOwn(starMap, nameSegment), starI = i) - }!foundMap && foundStarMap && (foundMap = foundStarMap, foundI = starI), foundMap && (nameParts.splice(0, foundI, foundMap), name = nameParts.join("/")) - } - return getOwn(config.pkgs, name) || name - } - - function removeScript(name) { - isBrowser && each(scripts(), function(scriptNode) { - if (scriptNode.getAttribute("data-requiremodule") === name && scriptNode.getAttribute("data-requirecontext") === context.contextName) return scriptNode.parentNode.removeChild(scriptNode), !0 - }) - } - - function hasPathFallback(id) { - var pathConfig = getOwn(config.paths, id); - if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) return pathConfig.shift(), context.require.undef(id), context.makeRequire(null, { - skipMap: !0 - })([id]), !0 - } - - function splitPrefix(name) { - var prefix, index = name ? name.indexOf("!") : -1; - return index > -1 && (prefix = name.substring(0, index), name = name.substring(index + 1, name.length)), [prefix, name] - } - - function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { - var url, pluginModule, suffix, nameParts, prefix = null, - parentName = parentModuleMap ? parentModuleMap.name : null, - originalName = name, - isDefine = !0, - normalizedName = ""; - return name || (isDefine = !1, name = "_@r" + (requireCounter += 1)), nameParts = splitPrefix(name), prefix = nameParts[0], name = nameParts[1], prefix && (prefix = normalize(prefix, parentName, applyMap), pluginModule = getOwn(defined, prefix)), name && (prefix ? normalizedName = isNormalized ? name : pluginModule && pluginModule.normalize ? pluginModule.normalize(name, function(name) { - return normalize(name, parentName, applyMap) - }) : -1 === name.indexOf("!") ? normalize(name, parentName, applyMap) : name : (normalizedName = normalize(name, parentName, applyMap), nameParts = splitPrefix(normalizedName), prefix = nameParts[0], normalizedName = nameParts[1], isNormalized = !0, url = context.nameToUrl(normalizedName))), suffix = !prefix || pluginModule || isNormalized ? "" : "_unnormalized" + (unnormalizedCounter += 1), { - prefix: prefix, - name: normalizedName, - parentMap: parentModuleMap, - unnormalized: !!suffix, - url: url, - originalName: originalName, - isDefine: isDefine, - id: (prefix ? prefix + "!" + normalizedName : normalizedName) + suffix - } - } - - function getModule(depMap) { - var id = depMap.id, - mod = getOwn(registry, id); - return mod || (mod = registry[id] = new context.Module(depMap)), mod - } - - function on(depMap, name, fn) { - var id = depMap.id, - mod = getOwn(registry, id); - !hasProp(defined, id) || mod && !mod.defineEmitComplete ? (mod = getModule(depMap), mod.error && "error" === name ? fn(mod.error) : mod.on(name, fn)) : "defined" === name && fn(defined[id]) - } - - function onError(err, errback) { - var ids = err.requireModules, - notified = !1; - errback ? errback(err) : (each(ids, function(id) { - var mod = getOwn(registry, id); - mod && (mod.error = err, mod.events.error && (notified = !0, mod.emit("error", err))) - }), notified || req.onError(err)) - } - - function takeGlobalQueue() { - globalDefQueue.length && (each(globalDefQueue, function(queueItem) { - var id = queueItem[0]; - "string" == typeof id && (context.defQueueMap[id] = !0), defQueue.push(queueItem) - }), globalDefQueue = []) - } - - function cleanRegistry(id) { - delete registry[id], delete enabledRegistry[id] - } - - function breakCycle(mod, traced, processed) { - var id = mod.map.id; - mod.error ? mod.emit("error", mod.error) : (traced[id] = !0, each(mod.depMaps, function(depMap, i) { - var depId = depMap.id, - dep = getOwn(registry, depId); - !dep || mod.depMatched[i] || processed[depId] || (getOwn(traced, depId) ? (mod.defineDep(i, defined[depId]), mod.check()) : breakCycle(dep, traced, processed)) - }), processed[id] = !0) - } - - function checkLoaded() { - var err, usingPathFallback, waitInterval = 1e3 * config.waitSeconds, - expired = waitInterval && context.startTime + waitInterval < (new Date).getTime(), - noLoads = [], - reqCalls = [], - stillLoading = !1, - needCycleCheck = !0; - if (!inCheckLoaded) { - if (inCheckLoaded = !0, eachProp(enabledRegistry, function(mod) { - var map = mod.map, - modId = map.id; - if (mod.enabled && (map.isDefine || reqCalls.push(mod), !mod.error)) - if (!mod.inited && expired) hasPathFallback(modId) ? (usingPathFallback = !0, stillLoading = !0) : (noLoads.push(modId), removeScript(modId)); - else if (!mod.inited && mod.fetched && map.isDefine && (stillLoading = !0, !map.prefix)) return needCycleCheck = !1 - }), expired && noLoads.length) return err = makeError("timeout", "Load timeout for modules: " + noLoads, null, noLoads), err.contextName = context.contextName, onError(err); - needCycleCheck && each(reqCalls, function(mod) { - breakCycle(mod, {}, {}) - }), expired && !usingPathFallback || !stillLoading || !isBrowser && !isWebWorker || checkLoadedTimeoutId || (checkLoadedTimeoutId = setTimeout(function() { - checkLoadedTimeoutId = 0, checkLoaded() - }, 50)), inCheckLoaded = !1 - } - } - - function callGetModule(args) { - hasProp(defined, args[0]) || getModule(makeModuleMap(args[0], null, !0)).init(args[1], args[2]) - } - - function removeListener(node, func, name, ieName) { - node.detachEvent && !isOpera ? ieName && node.detachEvent(ieName, func) : node.removeEventListener(name, func, !1) - } - - function getScriptData(evt) { - var node = evt.currentTarget || evt.srcElement; - return removeListener(node, context.onScriptLoad, "load", "onreadystatechange"), removeListener(node, context.onScriptError, "error"), { - node: node, - id: node && node.getAttribute("data-requiremodule") - } - } - - function intakeDefines() { - var args; - for (takeGlobalQueue(); defQueue.length;) { - if (args = defQueue.shift(), null === args[0]) return onError(makeError("mismatch", "Mismatched anonymous define() module: " + args[args.length - 1])); - callGetModule(args) - } - context.defQueueMap = {} - } - var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { - waitSeconds: 7, - baseUrl: "./", - paths: {}, - bundles: {}, - pkgs: {}, - shim: {}, - config: {} - }, - registry = {}, - enabledRegistry = {}, - undefEvents = {}, - defQueue = [], - defined = {}, - urlFetched = {}, - bundlesMap = {}, - requireCounter = 1, - unnormalizedCounter = 1; - return handlers = { - require: function(mod) { - return mod.require ? mod.require : mod.require = context.makeRequire(mod.map) - }, - exports: function(mod) { - if (mod.usingExports = !0, mod.map.isDefine) return mod.exports ? defined[mod.map.id] = mod.exports : mod.exports = defined[mod.map.id] = {} - }, - module: function(mod) { - return mod.module ? mod.module : mod.module = { - id: mod.map.id, - uri: mod.map.url, - config: function() { - return getOwn(config.config, mod.map.id) || {} - }, - exports: mod.exports || (mod.exports = {}) - } - } - }, Module = function(map) { - this.events = getOwn(undefEvents, map.id) || {}, this.map = map, this.shim = getOwn(config.shim, map.id), this.depExports = [], this.depMaps = [], this.depMatched = [], this.pluginMaps = {}, this.depCount = 0 - }, Module.prototype = { - init: function(depMaps, factory, errback, options) { - options = options || {}, this.inited || (this.factory = factory, errback ? this.on("error", errback) : this.events.error && (errback = bind(this, function(err) { - this.emit("error", err) - })), this.depMaps = depMaps && depMaps.slice(0), this.errback = errback, this.inited = !0, this.ignore = options.ignore, options.enabled || this.enabled ? this.enable() : this.check()) - }, - defineDep: function(i, depExports) { - this.depMatched[i] || (this.depMatched[i] = !0, this.depCount -= 1, this.depExports[i] = depExports) - }, - fetch: function() { - if (!this.fetched) { - this.fetched = !0, context.startTime = (new Date).getTime(); - var map = this.map; - if (!this.shim) return map.prefix ? this.callPlugin() : this.load(); - context.makeRequire(this.map, { - enableBuildCallback: !0 - })(this.shim.deps || [], bind(this, function() { - return map.prefix ? this.callPlugin() : this.load() - })) - } - }, - load: function() { - var url = this.map.url; - urlFetched[url] || (urlFetched[url] = !0, context.load(this.map.id, url)) - }, - check: function() { - if (this.enabled && !this.enabling) { - var err, cjsModule, id = this.map.id, - depExports = this.depExports, - exports = this.exports, - factory = this.factory; - if (this.inited) { - if (this.error) this.emit("error", this.error); - else if (!this.defining) { - if (this.defining = !0, this.depCount < 1 && !this.defined) { - if (isFunction(factory)) { - if (this.events.error && this.map.isDefine || req.onError !== defaultOnError) try { - exports = context.execCb(id, factory, depExports, exports) - } catch (e) { - err = e - } else exports = context.execCb(id, factory, depExports, exports); - if (this.map.isDefine && void 0 === exports && (cjsModule = this.module, cjsModule ? exports = cjsModule.exports : this.usingExports && (exports = this.exports)), err) return err.requireMap = this.map, err.requireModules = this.map.isDefine ? [this.map.id] : null, err.requireType = this.map.isDefine ? "define" : "require", onError(this.error = err) - } else exports = factory; - if (this.exports = exports, this.map.isDefine && !this.ignore && (defined[id] = exports, req.onResourceLoad)) { - var resLoadMaps = []; - each(this.depMaps, function(depMap) { - resLoadMaps.push(depMap.normalizedMap || depMap) - }), req.onResourceLoad(context, this.map, resLoadMaps) - } - cleanRegistry(id), this.defined = !0 - } - this.defining = !1, this.defined && !this.defineEmitted && (this.defineEmitted = !0, this.emit("defined", this.exports), this.defineEmitComplete = !0) - } - } else hasProp(context.defQueueMap, id) || this.fetch() - } - }, - callPlugin: function() { - var map = this.map, - id = map.id, - pluginMap = makeModuleMap(map.prefix); - this.depMaps.push(pluginMap), on(pluginMap, "defined", bind(this, function(plugin) { - var load, normalizedMap, normalizedMod, bundleId = getOwn(bundlesMap, this.map.id), - name = this.map.name, - parentName = this.map.parentMap ? this.map.parentMap.name : null, - localRequire = context.makeRequire(map.parentMap, { - enableBuildCallback: !0 - }); - return this.map.unnormalized ? (plugin.normalize && (name = plugin.normalize(name, function(name) { - return normalize(name, parentName, !0) - }) || ""), normalizedMap = makeModuleMap(map.prefix + "!" + name, this.map.parentMap, !0), on(normalizedMap, "defined", bind(this, function(value) { - this.map.normalizedMap = normalizedMap, this.init([], function() { - return value - }, null, { - enabled: !0, - ignore: !0 - }) - })), void((normalizedMod = getOwn(registry, normalizedMap.id)) && (this.depMaps.push(normalizedMap), this.events.error && normalizedMod.on("error", bind(this, function(err) { - this.emit("error", err) - })), normalizedMod.enable()))) : bundleId ? (this.map.url = context.nameToUrl(bundleId), void this.load()) : (load = bind(this, function(value) { - this.init([], function() { - return value - }, null, { - enabled: !0 - }) - }), load.error = bind(this, function(err) { - this.inited = !0, this.error = err, err.requireModules = [id], eachProp(registry, function(mod) { - 0 === mod.map.id.indexOf(id + "_unnormalized") && cleanRegistry(mod.map.id) - }), onError(err) - }), load.fromText = bind(this, function(text, textAlt) { - var moduleName = map.name, - moduleMap = makeModuleMap(moduleName), - hasInteractive = useInteractive; - textAlt && (text = textAlt), hasInteractive && (useInteractive = !1), getModule(moduleMap), hasProp(config.config, id) && (config.config[moduleName] = config.config[id]); - try { - req.exec(text) - } catch (e) { - return onError(makeError("fromtexteval", "fromText eval for " + id + " failed: " + e, e, [id])) - } - hasInteractive && (useInteractive = !0), this.depMaps.push(moduleMap), context.completeLoad(moduleName), localRequire([moduleName], load) - }), void plugin.load(map.name, localRequire, load, config)) - })), context.enable(pluginMap, this), this.pluginMaps[pluginMap.id] = pluginMap - }, - enable: function() { - enabledRegistry[this.map.id] = this, this.enabled = !0, this.enabling = !0, each(this.depMaps, bind(this, function(depMap, i) { - var id, mod, handler; - if ("string" == typeof depMap) { - if (depMap = makeModuleMap(depMap, this.map.isDefine ? this.map : this.map.parentMap, !1, !this.skipMap), this.depMaps[i] = depMap, handler = getOwn(handlers, depMap.id)) return void(this.depExports[i] = handler(this)); - this.depCount += 1, on(depMap, "defined", bind(this, function(depExports) { - this.undefed || (this.defineDep(i, depExports), this.check()) - })), this.errback ? on(depMap, "error", bind(this, this.errback)) : this.events.error && on(depMap, "error", bind(this, function(err) { - this.emit("error", err) - })) - } - id = depMap.id, mod = registry[id], hasProp(handlers, id) || !mod || mod.enabled || context.enable(depMap, this) - })), eachProp(this.pluginMaps, bind(this, function(pluginMap) { - var mod = getOwn(registry, pluginMap.id); - mod && !mod.enabled && context.enable(pluginMap, this) - })), this.enabling = !1, this.check() - }, - on: function(name, cb) { - var cbs = this.events[name]; - cbs || (cbs = this.events[name] = []), cbs.push(cb) - }, - emit: function(name, evt) { - each(this.events[name], function(cb) { - cb(evt) - }), "error" === name && delete this.events[name] - } - }, context = { - config: config, - contextName: contextName, - registry: registry, - defined: defined, - urlFetched: urlFetched, - defQueue: defQueue, - defQueueMap: {}, - Module: Module, - makeModuleMap: makeModuleMap, - nextTick: req.nextTick, - onError: onError, - configure: function(cfg) { - if (cfg.baseUrl && "/" !== cfg.baseUrl.charAt(cfg.baseUrl.length - 1) && (cfg.baseUrl += "/"), "string" == typeof cfg.urlArgs) { - var urlArgs = cfg.urlArgs; - cfg.urlArgs = function(id, url) { - return (-1 === url.indexOf("?") ? "?" : "&") + urlArgs - } - } - var shim = config.shim, - objs = { - paths: !0, - bundles: !0, - config: !0, - map: !0 - }; - eachProp(cfg, function(value, prop) { - objs[prop] ? (config[prop] || (config[prop] = {}), mixin(config[prop], value, !0, !0)) : config[prop] = value - }), cfg.bundles && eachProp(cfg.bundles, function(value, prop) { - each(value, function(v) { - v !== prop && (bundlesMap[v] = prop) - }) - }), cfg.shim && (eachProp(cfg.shim, function(value, id) { - isArray(value) && (value = { - deps: value - }), !value.exports && !value.init || value.exportsFn || (value.exportsFn = context.makeShimExports(value)), shim[id] = value - }), config.shim = shim), cfg.packages && each(cfg.packages, function(pkgObj) { - var location, name; - pkgObj = "string" == typeof pkgObj ? { - name: pkgObj - } : pkgObj, name = pkgObj.name, location = pkgObj.location, location && (config.paths[name] = pkgObj.location), config.pkgs[name] = pkgObj.name + "/" + (pkgObj.main || "main").replace(currDirRegExp, "").replace(jsSuffixRegExp, "") - }), eachProp(registry, function(mod, id) { - mod.inited || mod.map.unnormalized || (mod.map = makeModuleMap(id, null, !0)) - }), (cfg.deps || cfg.callback) && context.require(cfg.deps || [], cfg.callback) - }, - makeShimExports: function(value) { - function fn() { - var ret; - return value.init && (ret = value.init.apply(global, arguments)), ret || value.exports && getGlobal(value.exports) - } - return fn - }, - makeRequire: function(relMap, options) { - function localRequire(deps, callback, errback) { - var id, map, requireMod; - return options.enableBuildCallback && callback && isFunction(callback) && (callback.__requireJsBuild = !0), "string" == typeof deps ? isFunction(callback) ? onError(makeError("requireargs", "Invalid require call"), errback) : relMap && hasProp(handlers, deps) ? handlers[deps](registry[relMap.id]) : req.get ? req.get(context, deps, relMap, localRequire) : (map = makeModuleMap(deps, relMap, !1, !0), id = map.id, hasProp(defined, id) ? defined[id] : onError(makeError("notloaded", 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? "" : ". Use require([])")))) : (intakeDefines(), context.nextTick(function() { - intakeDefines(), requireMod = getModule(makeModuleMap(null, relMap)), requireMod.skipMap = options.skipMap, requireMod.init(deps, callback, errback, { - enabled: !0 - }), checkLoaded() - }), localRequire) - } - return options = options || {}, mixin(localRequire, { - isBrowser: isBrowser, - toUrl: function(moduleNamePlusExt) { - var ext, index = moduleNamePlusExt.lastIndexOf("."), - segment = moduleNamePlusExt.split("/")[0], - isRelative = "." === segment || ".." === segment; - return -1 !== index && (!isRelative || index > 1) && (ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length), moduleNamePlusExt = moduleNamePlusExt.substring(0, index)), context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, !0), ext, !0) - }, - defined: function(id) { - return hasProp(defined, makeModuleMap(id, relMap, !1, !0).id) - }, - specified: function(id) { - return id = makeModuleMap(id, relMap, !1, !0).id, hasProp(defined, id) || hasProp(registry, id) - } - }), relMap || (localRequire.undef = function(id) { - takeGlobalQueue(); - var map = makeModuleMap(id, relMap, !0), - mod = getOwn(registry, id); - mod.undefed = !0, removeScript(id), delete defined[id], delete urlFetched[map.url], delete undefEvents[id], eachReverse(defQueue, function(args, i) { - args[0] === id && defQueue.splice(i, 1) - }), delete context.defQueueMap[id], mod && (mod.events.defined && (undefEvents[id] = mod.events), cleanRegistry(id)) - }), localRequire - }, - enable: function(depMap) { - getOwn(registry, depMap.id) && getModule(depMap).enable() - }, - completeLoad: function(moduleName) { - var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, - shExports = shim.exports; - for (takeGlobalQueue(); defQueue.length;) { - if (args = defQueue.shift(), null === args[0]) { - if (args[0] = moduleName, found) break; - found = !0 - } else args[0] === moduleName && (found = !0); - callGetModule(args) - } - if (context.defQueueMap = {}, mod = getOwn(registry, moduleName), !found && !hasProp(defined, moduleName) && mod && !mod.inited) { - if (!(!config.enforceDefine || shExports && getGlobal(shExports))) return hasPathFallback(moduleName) ? void 0 : onError(makeError("nodefine", "No define call for " + moduleName, null, [moduleName])); - callGetModule([moduleName, shim.deps || [], shim.exportsFn]) - } - checkLoaded() - }, - nameToUrl: function(moduleName, ext, skipExt) { - var paths, syms, i, parentModule, url, parentPath, bundleId, pkgMain = getOwn(config.pkgs, moduleName); - if (pkgMain && (moduleName = pkgMain), bundleId = getOwn(bundlesMap, moduleName)) return context.nameToUrl(bundleId, ext, skipExt); - if (req.jsExtRegExp.test(moduleName)) url = moduleName + (ext || ""); - else { - for (paths = config.paths, syms = moduleName.split("/"), i = syms.length; i > 0; i -= 1) - if (parentModule = syms.slice(0, i).join("/"), parentPath = getOwn(paths, parentModule)) { - isArray(parentPath) && (parentPath = parentPath[0]), syms.splice(0, i, parentPath); - break - } url = syms.join("/"), url += ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? "" : ".js"), url = ("/" === url.charAt(0) || url.match(/^[\w\+\.\-]+:/) ? "" : config.baseUrl) + url - } - return config.urlArgs && !/^blob\:/.test(url) ? url + config.urlArgs(moduleName, url) : url - }, - load: function(id, url) { - req.load(context, id, url) - }, - execCb: function(name, callback, args, exports) { - return callback.apply(exports, args) - }, - onScriptLoad: function(evt) { - if ("load" === evt.type || readyRegExp.test((evt.currentTarget || evt.srcElement).readyState)) { - interactiveScript = null; - var data = getScriptData(evt); - context.completeLoad(data.id) - } - }, - onScriptError: function(evt) { - var data = getScriptData(evt); - if (!hasPathFallback(data.id)) { - var parents = []; - return eachProp(registry, function(value, key) { - 0 !== key.indexOf("_@r") && each(value.depMaps, function(depMap) { - if (depMap.id === data.id) return parents.push(key), !0 - }) - }), onError(makeError("scripterror", 'Script error for "' + data.id + (parents.length ? '", needed by: ' + parents.join(", ") : '"'), evt, [data.id])) - } - } - }, context.require = context.makeRequire(), context - } - - function getInteractiveScript() { - return interactiveScript && "interactive" === interactiveScript.readyState ? interactiveScript : (eachReverse(scripts(), function(script) { - if ("interactive" === script.readyState) return interactiveScript = script - }), interactiveScript) - } - var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, version = "2.3.5", - commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/gm, - cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, - jsSuffixRegExp = /\.js$/, - currDirRegExp = /^\.\//, - op = Object.prototype, - ostring = op.toString, - hasOwn = op.hasOwnProperty, - isBrowser = !("undefined" == typeof window || "undefined" == typeof navigator || !window.document), - isWebWorker = !isBrowser && "undefined" != typeof importScripts, - readyRegExp = isBrowser && "PLAYSTATION 3" === navigator.platform ? /^complete$/ : /^(complete|loaded)$/, - defContextName = "_", - isOpera = "undefined" != typeof opera && "[object Opera]" === opera.toString(), - contexts = {}, - cfg = {}, - globalDefQueue = [], - useInteractive = !1; - if (void 0 === define) { - if (void 0 !== requirejs) { - if (isFunction(requirejs)) return; - cfg = requirejs, requirejs = void 0 - } - void 0 === require || isFunction(require) || (cfg = require, require = void 0), req = requirejs = function(deps, callback, errback, optional) { - var context, config, contextName = defContextName; - return isArray(deps) || "string" == typeof deps || (config = deps, isArray(callback) ? (deps = callback, callback = errback, errback = optional) : deps = []), config && config.context && (contextName = config.context), context = getOwn(contexts, contextName), context || (context = contexts[contextName] = req.s.newContext(contextName)), config && context.configure(config), context.require(deps, callback, errback) - }, req.config = function(config) { - return req(config) - }, req.nextTick = void 0 !== setTimeout ? function(fn) { - setTimeout(fn, 4) - } : function(fn) { - fn() - }, require || (require = req), req.version = version, req.jsExtRegExp = /^\/|:|\?|\.js$/, req.isBrowser = isBrowser, s = req.s = { - contexts: contexts, - newContext: newContext - }, req({}), each(["toUrl", "undef", "defined", "specified"], function(prop) { - req[prop] = function() { - var ctx = contexts[defContextName]; - return ctx.require[prop].apply(ctx, arguments) - } - }), isBrowser && (head = s.head = document.getElementsByTagName("head")[0], (baseElement = document.getElementsByTagName("base")[0]) && (head = s.head = baseElement.parentNode)), req.onError = defaultOnError, req.createNode = function(config, moduleName, url) { - var node = config.xhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "html:script") : document.createElement("script"); - return node.type = config.scriptType || "text/javascript", node.charset = "utf-8", node.async = !0, node - }, req.load = function(context, moduleName, url) { - var node, config = context && context.config || {}; - if (isBrowser) return node = req.createNode(config, moduleName, url), node.setAttribute("data-requirecontext", context.contextName), node.setAttribute("data-requiremodule", moduleName), !node.attachEvent || node.attachEvent.toString && node.attachEvent.toString().indexOf("[native code") < 0 || isOpera ? (node.addEventListener("load", context.onScriptLoad, !1), node.addEventListener("error", context.onScriptError, !1)) : (useInteractive = !0, node.attachEvent("onreadystatechange", context.onScriptLoad)), node.src = url, config.onNodeCreated && config.onNodeCreated(node, config, moduleName, url), currentlyAddingScript = node, baseElement ? head.insertBefore(node, baseElement) : head.appendChild(node), currentlyAddingScript = null, node; - if (isWebWorker) try { - setTimeout(function() {}, 0), importScripts(url), context.completeLoad(moduleName) - } catch (e) { - context.onError(makeError("importscripts", "importScripts failed for " + moduleName + " at " + url, e, [moduleName])) - } - }, isBrowser && !cfg.skipDataMain && eachReverse(scripts(), function(script) { - if (head || (head = script.parentNode), dataMain = script.getAttribute("data-main")) return mainScript = dataMain, cfg.baseUrl || -1 !== mainScript.indexOf("!") || (src = mainScript.split("/"), mainScript = src.pop(), subPath = src.length ? src.join("/") + "/" : "./", cfg.baseUrl = subPath), mainScript = mainScript.replace(jsSuffixRegExp, ""), req.jsExtRegExp.test(mainScript) && (mainScript = dataMain), cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript], !0 - }), define = function(name, deps, callback) { - var node, context; - "string" != typeof name && (callback = deps, deps = name, name = null), isArray(deps) || (callback = deps, deps = null), !deps && isFunction(callback) && (deps = [], callback.length && (callback.toString().replace(commentRegExp, commentReplace).replace(cjsRequireRegExp, function(match, dep) { - deps.push(dep) - }), deps = (1 === callback.length ? ["require"] : ["require", "exports", "module"]).concat(deps))), useInteractive && (node = currentlyAddingScript || getInteractiveScript()) && (name || (name = node.getAttribute("data-requiremodule")), context = contexts[node.getAttribute("data-requirecontext")]), context ? (context.defQueue.push([name, deps, callback]), context.defQueueMap[name] = !0) : globalDefQueue.push([name, deps, callback]) - }, define.amd = { - jQuery: !0 - }, req.exec = function(text) { - return eval(text) - }, req(cfg) - } -}(this, "undefined" == typeof setTimeout ? void 0 : setTimeout); \ No newline at end of file diff --git a/src/bower_components/resize-observer-polyfill/ResizeObserver.js b/src/bower_components/resize-observer-polyfill/ResizeObserver.js deleted file mode 100644 index d9f152c827..0000000000 --- a/src/bower_components/resize-observer-polyfill/ResizeObserver.js +++ /dev/null @@ -1,939 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.ResizeObserver = factory()); -}(this, (function () { 'use strict'; - -/** - * A collection of shims that provide minimal functionality of the ES6 collections. - * - * These implementations are not meant to be used outside of the ResizeObserver - * modules as they cover only a limited range of use cases. - */ -/* eslint-disable require-jsdoc, valid-jsdoc */ -var MapShim = (function () { - if (typeof Map !== 'undefined') { - return Map; - } - - /** - * Returns index in provided array that matches the specified key. - * - * @param {Array} arr - * @param {*} key - * @returns {number} - */ - function getIndex(arr, key) { - var result = -1; - - arr.some(function (entry, index) { - if (entry[0] === key) { - result = index; - - return true; - } - - return false; - }); - - return result; - } - - return (function () { - function anonymous() { - this.__entries__ = []; - } - - var prototypeAccessors = { size: { configurable: true } }; - - /** - * @returns {boolean} - */ - prototypeAccessors.size.get = function () { - return this.__entries__.length; - }; - - /** - * @param {*} key - * @returns {*} - */ - anonymous.prototype.get = function (key) { - var index = getIndex(this.__entries__, key); - var entry = this.__entries__[index]; - - return entry && entry[1]; - }; - - /** - * @param {*} key - * @param {*} value - * @returns {void} - */ - anonymous.prototype.set = function (key, value) { - var index = getIndex(this.__entries__, key); - - if (~index) { - this.__entries__[index][1] = value; - } else { - this.__entries__.push([key, value]); - } - }; - - /** - * @param {*} key - * @returns {void} - */ - anonymous.prototype.delete = function (key) { - var entries = this.__entries__; - var index = getIndex(entries, key); - - if (~index) { - entries.splice(index, 1); - } - }; - - /** - * @param {*} key - * @returns {void} - */ - anonymous.prototype.has = function (key) { - return !!~getIndex(this.__entries__, key); - }; - - /** - * @returns {void} - */ - anonymous.prototype.clear = function () { - this.__entries__.splice(0); - }; - - /** - * @param {Function} callback - * @param {*} [ctx=null] - * @returns {void} - */ - anonymous.prototype.forEach = function (callback, ctx) { - var this$1 = this; - if ( ctx === void 0 ) ctx = null; - - for (var i = 0, list = this$1.__entries__; i < list.length; i += 1) { - var entry = list[i]; - - callback.call(ctx, entry[1], entry[0]); - } - }; - - Object.defineProperties( anonymous.prototype, prototypeAccessors ); - - return anonymous; - }()); -})(); - -/** - * Detects whether window and document objects are available in current environment. - */ -var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document; - -// Returns global object of a current environment. -var global$1 = (function () { - if (typeof global !== 'undefined' && global.Math === Math) { - return global; - } - - if (typeof self !== 'undefined' && self.Math === Math) { - return self; - } - - if (typeof window !== 'undefined' && window.Math === Math) { - return window; - } - - // eslint-disable-next-line no-new-func - return Function('return this')(); -})(); - -/** - * A shim for the requestAnimationFrame which falls back to the setTimeout if - * first one is not supported. - * - * @returns {number} Requests' identifier. - */ -var requestAnimationFrame$1 = (function () { - if (typeof requestAnimationFrame === 'function') { - // It's required to use a bounded function because IE sometimes throws - // an "Invalid calling object" error if rAF is invoked without the global - // object on the left hand side. - return requestAnimationFrame.bind(global$1); - } - - return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); }; -})(); - -// Defines minimum timeout before adding a trailing call. -var trailingTimeout = 2; - -/** - * Creates a wrapper function which ensures that provided callback will be - * invoked only once during the specified delay period. - * - * @param {Function} callback - Function to be invoked after the delay period. - * @param {number} delay - Delay after which to invoke callback. - * @returns {Function} - */ -var throttle = function (callback, delay) { - var leadingCall = false, - trailingCall = false, - lastCallTime = 0; - - /** - * Invokes the original callback function and schedules new invocation if - * the "proxy" was called during current request. - * - * @returns {void} - */ - function resolvePending() { - if (leadingCall) { - leadingCall = false; - - callback(); - } - - if (trailingCall) { - proxy(); - } - } - - /** - * Callback invoked after the specified delay. It will further postpone - * invocation of the original function delegating it to the - * requestAnimationFrame. - * - * @returns {void} - */ - function timeoutCallback() { - requestAnimationFrame$1(resolvePending); - } - - /** - * Schedules invocation of the original function. - * - * @returns {void} - */ - function proxy() { - var timeStamp = Date.now(); - - if (leadingCall) { - // Reject immediately following calls. - if (timeStamp - lastCallTime < trailingTimeout) { - return; - } - - // Schedule new call to be in invoked when the pending one is resolved. - // This is important for "transitions" which never actually start - // immediately so there is a chance that we might miss one if change - // happens amids the pending invocation. - trailingCall = true; - } else { - leadingCall = true; - trailingCall = false; - - setTimeout(timeoutCallback, delay); - } - - lastCallTime = timeStamp; - } - - return proxy; -}; - -// Minimum delay before invoking the update of observers. -var REFRESH_DELAY = 20; - -// A list of substrings of CSS properties used to find transition events that -// might affect dimensions of observed elements. -var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight']; - -// Check if MutationObserver is available. -var mutationObserverSupported = typeof MutationObserver !== 'undefined'; - -/** - * Singleton controller class which handles updates of ResizeObserver instances. - */ -var ResizeObserverController = function() { - this.connected_ = false; - this.mutationEventsAdded_ = false; - this.mutationsObserver_ = null; - this.observers_ = []; - - this.onTransitionEnd_ = this.onTransitionEnd_.bind(this); - this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY); -}; - -/** - * Adds observer to observers list. - * - * @param {ResizeObserverSPI} observer - Observer to be added. - * @returns {void} - */ - - -/** - * Holds reference to the controller's instance. - * - * @private {ResizeObserverController} - */ - - -/** - * Keeps reference to the instance of MutationObserver. - * - * @private {MutationObserver} - */ - -/** - * Indicates whether DOM listeners have been added. - * - * @private {boolean} - */ -ResizeObserverController.prototype.addObserver = function (observer) { - if (!~this.observers_.indexOf(observer)) { - this.observers_.push(observer); - } - - // Add listeners if they haven't been added yet. - if (!this.connected_) { - this.connect_(); - } -}; - -/** - * Removes observer from observers list. - * - * @param {ResizeObserverSPI} observer - Observer to be removed. - * @returns {void} - */ -ResizeObserverController.prototype.removeObserver = function (observer) { - var observers = this.observers_; - var index = observers.indexOf(observer); - - // Remove observer if it's present in registry. - if (~index) { - observers.splice(index, 1); - } - - // Remove listeners if controller has no connected observers. - if (!observers.length && this.connected_) { - this.disconnect_(); - } -}; - -/** - * Invokes the update of observers. It will continue running updates insofar - * it detects changes. - * - * @returns {void} - */ -ResizeObserverController.prototype.refresh = function () { - var changesDetected = this.updateObservers_(); - - // Continue running updates if changes have been detected as there might - // be future ones caused by CSS transitions. - if (changesDetected) { - this.refresh(); - } -}; - -/** - * Updates every observer from observers list and notifies them of queued - * entries. - * - * @private - * @returns {boolean} Returns "true" if any observer has detected changes in - * dimensions of it's elements. - */ -ResizeObserverController.prototype.updateObservers_ = function () { - // Collect observers that have active observations. - var activeObservers = this.observers_.filter(function (observer) { - return observer.gatherActive(), observer.hasActive(); - }); - - // Deliver notifications in a separate cycle in order to avoid any - // collisions between observers, e.g. when multiple instances of - // ResizeObserver are tracking the same element and the callback of one - // of them changes content dimensions of the observed target. Sometimes - // this may result in notifications being blocked for the rest of observers. - activeObservers.forEach(function (observer) { return observer.broadcastActive(); }); - - return activeObservers.length > 0; -}; - -/** - * Initializes DOM listeners. - * - * @private - * @returns {void} - */ -ResizeObserverController.prototype.connect_ = function () { - // Do nothing if running in a non-browser environment or if listeners - // have been already added. - if (!isBrowser || this.connected_) { - return; - } - - // Subscription to the "Transitionend" event is used as a workaround for - // delayed transitions. This way it's possible to capture at least the - // final state of an element. - document.addEventListener('transitionend', this.onTransitionEnd_); - - window.addEventListener('resize', this.refresh); - window.addEventListener('orientationchange', this.refresh); - - if (mutationObserverSupported) { - this.mutationsObserver_ = new MutationObserver(this.refresh); - - this.mutationsObserver_.observe(document, { - attributes: true, - childList: true, - characterData: true, - subtree: true - }); - } else { - document.addEventListener('DOMSubtreeModified', this.refresh); - - this.mutationEventsAdded_ = true; - } - - this.connected_ = true; -}; - -/** - * Removes DOM listeners. - * - * @private - * @returns {void} - */ -ResizeObserverController.prototype.disconnect_ = function () { - // Do nothing if running in a non-browser environment or if listeners - // have been already removed. - if (!isBrowser || !this.connected_) { - return; - } - - document.removeEventListener('transitionend', this.onTransitionEnd_); - window.removeEventListener('resize', this.refresh); - window.removeEventListener('orientationchange', this.refresh); - - if (this.mutationsObserver_) { - this.mutationsObserver_.disconnect(); - } - - if (this.mutationEventsAdded_) { - document.removeEventListener('DOMSubtreeModified', this.refresh); - } - - this.mutationsObserver_ = null; - this.mutationEventsAdded_ = false; - this.connected_ = false; -}; - -/** - * "Transitionend" event handler. - * - * @private - * @param {TransitionEvent} event - * @returns {void} - */ -ResizeObserverController.prototype.onTransitionEnd_ = function (ref) { - var propertyName = ref.propertyName; if ( propertyName === void 0 ) propertyName = ''; - - // Detect whether transition may affect dimensions of an element. - var isReflowProperty = transitionKeys.some(function (key) { - return !!~propertyName.indexOf(key); - }); - - if (isReflowProperty) { - this.refresh(); - } -}; - -/** - * Returns instance of the ResizeObserverController. - * - * @returns {ResizeObserverController} - */ -ResizeObserverController.getInstance = function () { - if (!this.instance_) { - this.instance_ = new ResizeObserverController(); - } - - return this.instance_; -}; - -ResizeObserverController.instance_ = null; - -/** - * Defines non-writable/enumerable properties of the provided target object. - * - * @param {Object} target - Object for which to define properties. - * @param {Object} props - Properties to be defined. - * @returns {Object} Target object. - */ -var defineConfigurable = (function (target, props) { - for (var i = 0, list = Object.keys(props); i < list.length; i += 1) { - var key = list[i]; - - Object.defineProperty(target, key, { - value: props[key], - enumerable: false, - writable: false, - configurable: true - }); - } - - return target; -}); - -/** - * Returns the global object associated with provided element. - * - * @param {Object} target - * @returns {Object} - */ -var getWindowOf = (function (target) { - // Assume that the element is an instance of Node, which means that it - // has the "ownerDocument" property from which we can retrieve a - // corresponding global object. - var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView; - - // Return the local global object if it's not possible extract one from - // provided element. - return ownerGlobal || global$1; -}); - -// Placeholder of an empty content rectangle. -var emptyRect = createRectInit(0, 0, 0, 0); - -/** - * Converts provided string to a number. - * - * @param {number|string} value - * @returns {number} - */ -function toFloat(value) { - return parseFloat(value) || 0; -} - -/** - * Extracts borders size from provided styles. - * - * @param {CSSStyleDeclaration} styles - * @param {...string} positions - Borders positions (top, right, ...) - * @returns {number} - */ -function getBordersSize(styles) { - var positions = [], len = arguments.length - 1; - while ( len-- > 0 ) positions[ len ] = arguments[ len + 1 ]; - - return positions.reduce(function (size, position) { - var value = styles['border-' + position + '-width']; - - return size + toFloat(value); - }, 0); -} - -/** - * Extracts paddings sizes from provided styles. - * - * @param {CSSStyleDeclaration} styles - * @returns {Object} Paddings box. - */ -function getPaddings(styles) { - var positions = ['top', 'right', 'bottom', 'left']; - var paddings = {}; - - for (var i = 0, list = positions; i < list.length; i += 1) { - var position = list[i]; - - var value = styles['padding-' + position]; - - paddings[position] = toFloat(value); - } - - return paddings; -} - -/** - * Calculates content rectangle of provided SVG element. - * - * @param {SVGGraphicsElement} target - Element content rectangle of which needs - * to be calculated. - * @returns {DOMRectInit} - */ -function getSVGContentRect(target) { - var bbox = target.getBBox(); - - return createRectInit(0, 0, bbox.width, bbox.height); -} - -/** - * Calculates content rectangle of provided HTMLElement. - * - * @param {HTMLElement} target - Element for which to calculate the content rectangle. - * @returns {DOMRectInit} - */ -function getHTMLElementContentRect(target) { - - var rect = target.getBoundingClientRect(); - return createRectInit(rect.left, rect.top, rect.width, rect.height); -} - -/** - * Checks whether provided element is a document element (). - * - * @param {Element} target - Element to be checked. - * @returns {boolean} - */ -function isDocumentElement(target) { - return target === getWindowOf(target).document.documentElement; -} - -/** - * Calculates an appropriate content rectangle for provided html or svg element. - * - * @param {Element} target - Element content rectangle of which needs to be calculated. - * @returns {DOMRectInit} - */ -function getContentRect(target) { - if (!isBrowser) { - return emptyRect; - } - - return getHTMLElementContentRect(target); -} - -/** - * Creates rectangle with an interface of the DOMRectReadOnly. - * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly - * - * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions. - * @returns {DOMRectReadOnly} - */ -function createReadOnlyRect(ref) { - var x = ref.x; - var y = ref.y; - var width = ref.width; - var height = ref.height; - - // If DOMRectReadOnly is available use it as a prototype for the rectangle. - var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object; - var rect = Object.create(Constr.prototype); - - // Rectangle's properties are not writable and non-enumerable. - defineConfigurable(rect, { - x: x, y: y, width: width, height: height, - top: y, - right: x + width, - bottom: height + y, - left: x - }); - - return rect; -} - -/** - * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates. - * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit - * - * @param {number} x - X coordinate. - * @param {number} y - Y coordinate. - * @param {number} width - Rectangle's width. - * @param {number} height - Rectangle's height. - * @returns {DOMRectInit} - */ -function createRectInit(x, y, width, height) { - return { x: x, y: y, width: width, height: height }; -} - -/** - * Class that is responsible for computations of the content rectangle of - * provided DOM element and for keeping track of it's changes. - */ -var ResizeObservation = function(target) { - this.broadcastWidth = 0; - this.broadcastHeight = 0; - this.contentRect_ = createRectInit(0, 0, 0, 0); - - this.target = target; -}; - -/** - * Updates content rectangle and tells whether it's width or height properties - * have changed since the last broadcast. - * - * @returns {boolean} - */ - - -/** - * Reference to the last observed content rectangle. - * - * @private {DOMRectInit} - */ - - -/** - * Broadcasted width of content rectangle. - * - * @type {number} - */ -ResizeObservation.prototype.isActive = function () { - var rect = getContentRect(this.target); - - this.contentRect_ = rect; - return rect.width !== this.broadcastWidth || rect.height !== this.broadcastHeight; -}; - -/** - * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data - * from the corresponding properties of the last observed content rectangle. - * - * @returns {DOMRectInit} Last observed content rectangle. - */ -ResizeObservation.prototype.broadcastRect = function () { - var rect = this.contentRect_; - - this.broadcastWidth = rect.width; - this.broadcastHeight = rect.height; - - return rect; -}; - -var ResizeObserverEntry = function(target, rectInit) { - var contentRect = createReadOnlyRect(rectInit); - - // According to the specification following properties are not writable - // and are also not enumerable in the native implementation. - // - // Property accessors are not being used as they'd require to define a - // private WeakMap storage which may cause memory leaks in browsers that - // don't support this type of collections. - defineConfigurable(this, { target: target, contentRect: contentRect }); -}; - -var ResizeObserverSPI = function(callback, controller, callbackCtx) { - this.activeObservations_ = []; - this.observations_ = new MapShim(); - - if (typeof callback !== 'function') { - throw new TypeError('The callback provided as parameter 1 is not a function.'); - } - - this.callback_ = callback; - this.controller_ = controller; - this.callbackCtx_ = callbackCtx; -}; - -/** - * Starts observing provided element. - * - * @param {Element} target - Element to be observed. - * @returns {void} - */ - - -/** - * Registry of the ResizeObservation instances. - * - * @private {Map} - */ - - -/** - * Public ResizeObserver instance which will be passed to the callback - * function and used as a value of it's "this" binding. - * - * @private {ResizeObserver} - */ - -/** - * Collection of resize observations that have detected changes in dimensions - * of elements. - * - * @private {Array} - */ -ResizeObserverSPI.prototype.observe = function (target) { - if (!arguments.length) { - throw new TypeError('1 argument required, but only 0 present.'); - } - - // Do nothing if current environment doesn't have the Element interface. - if (typeof Element === 'undefined' || !(Element instanceof Object)) { - return; - } - - if (!(target instanceof getWindowOf(target).Element)) { - throw new TypeError('parameter 1 is not of type "Element".'); - } - - var observations = this.observations_; - - // Do nothing if element is already being observed. - if (observations.has(target)) { - return; - } - - observations.set(target, new ResizeObservation(target)); - - this.controller_.addObserver(this); - - // Force the update of observations. - this.controller_.refresh(); -}; - -/** - * Stops observing provided element. - * - * @param {Element} target - Element to stop observing. - * @returns {void} - */ -ResizeObserverSPI.prototype.unobserve = function (target) { - if (!arguments.length) { - throw new TypeError('1 argument required, but only 0 present.'); - } - - // Do nothing if current environment doesn't have the Element interface. - if (typeof Element === 'undefined' || !(Element instanceof Object)) { - return; - } - - if (!(target instanceof getWindowOf(target).Element)) { - throw new TypeError('parameter 1 is not of type "Element".'); - } - - var observations = this.observations_; - - // Do nothing if element is not being observed. - if (!observations.has(target)) { - return; - } - - observations.delete(target); - - if (!observations.size) { - this.controller_.removeObserver(this); - } -}; - -/** - * Stops observing all elements. - * - * @returns {void} - */ -ResizeObserverSPI.prototype.disconnect = function () { - this.clearActive(); - this.observations_.clear(); - this.controller_.removeObserver(this); -}; - -/** - * Collects observation instances the associated element of which has changed - * it's content rectangle. - * - * @returns {void} - */ -ResizeObserverSPI.prototype.gatherActive = function () { - var this$1 = this; - - this.clearActive(); - - this.observations_.forEach(function (observation) { - if (observation.isActive()) { - this$1.activeObservations_.push(observation); - } - }); -}; - -/** - * Invokes initial callback function with a list of ResizeObserverEntry - * instances collected from active resize observations. - * - * @returns {void} - */ -ResizeObserverSPI.prototype.broadcastActive = function () { - // Do nothing if observer doesn't have active observations. - if (!this.hasActive()) { - return; - } - - var ctx = this.callbackCtx_; - - // Create ResizeObserverEntry instance for every active observation. - var entries = this.activeObservations_.map(function (observation) { - return new ResizeObserverEntry(observation.target, observation.broadcastRect()); - }); - - this.callback_.call(ctx, entries, ctx); - this.clearActive(); -}; - -/** - * Clears the collection of active observations. - * - * @returns {void} - */ -ResizeObserverSPI.prototype.clearActive = function () { - this.activeObservations_.splice(0); -}; - -/** - * Tells whether observer has active observations. - * - * @returns {boolean} - */ -ResizeObserverSPI.prototype.hasActive = function () { - return this.activeObservations_.length > 0; -}; - -// Registry of internal observers. If WeakMap is not available use current shim -// for the Map collection as it has all required methods and because WeakMap -// can't be fully polyfilled anyway. -var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim(); - -/** - * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation - * exposing only those methods and properties that are defined in the spec. - */ -var ResizeObserver = function(callback) { - if (!(this instanceof ResizeObserver)) { - throw new TypeError('Cannot call a class as a function.'); - } - if (!arguments.length) { - throw new TypeError('1 argument required, but only 0 present.'); - } - - var controller = ResizeObserverController.getInstance(); - var observer = new ResizeObserverSPI(callback, controller, this); - - observers.set(this, observer); -}; - -// Expose public methods of ResizeObserver. -['observe', 'unobserve', 'disconnect'].forEach(function (method) { - ResizeObserver.prototype[method] = function () { - return (ref = observers.get(this))[method].apply(ref, arguments); - var ref; - }; -}); - -var index = (function () { - // Export existing implementation if available. - if (typeof global$1.ResizeObserver !== 'undefined') { - return global$1.ResizeObserver; - } - - return ResizeObserver; -})(); - -return index; - -}))); diff --git a/src/bower_components/webcomponentsjs/webcomponents-lite.min.js b/src/bower_components/webcomponentsjs/webcomponents-lite.min.js deleted file mode 100644 index 163ef436fc..0000000000 --- a/src/bower_components/webcomponentsjs/webcomponents-lite.min.js +++ /dev/null @@ -1,1571 +0,0 @@ -/** - * @license - * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. - * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt - * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt - * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt - * Code distributed by Google as part of the polymer project is also - * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt - */ -// @version 0.7.24 -! function() { - window.WebComponents = window.WebComponents || { - flags: {} - }; - var e = "webcomponents-lite.js", - t = document.querySelector('script[src*="' + e + '"]'), - n = {}; - if (!n.noOpts) { - if (location.search.slice(1).split("&").forEach(function(e) { - var t, o = e.split("="); - o[0] && (t = o[0].match(/wc-(.+)/)) && (n[t[1]] = o[1] || !0) - }), t) - for (var o, r = 0; o = t.attributes[r]; r++) "src" !== o.name && (n[o.name] = o.value || !0); - if (n.log && n.log.split) { - var i = n.log.split(","); - n.log = {}, i.forEach(function(e) { - n.log[e] = !0 - }) - } else n.log = {} - } - n.register && (window.CustomElements = window.CustomElements || { - flags: {} - }, window.CustomElements.flags.register = n.register), WebComponents.flags = n -}(), -function(e) { - "use strict"; - - function t(e) { - return void 0 !== h[e] - } - - function n() { - s.call(this), this._isInvalid = !0 - } - - function o(e) { - return "" == e && n.call(this), e.toLowerCase() - } - - function r(e) { - var t = e.charCodeAt(0); - return t > 32 && t < 127 && [34, 35, 60, 62, 63, 96].indexOf(t) == -1 ? e : encodeURIComponent(e) - } - - function i(e) { - var t = e.charCodeAt(0); - return t > 32 && t < 127 && [34, 35, 60, 62, 96].indexOf(t) == -1 ? e : encodeURIComponent(e) - } - - function a(e, a, s) { - function c(e) { - g.push(e) - } - var d = a || "scheme start", - l = 0, - u = "", - w = !1, - _ = !1, - g = []; - e: for (; - (e[l - 1] != p || 0 == l) && !this._isInvalid;) { - var b = e[l]; - switch (d) { - case "scheme start": - if (!b || !m.test(b)) { - if (a) { - c("Invalid scheme."); - break e - } - u = "", d = "no scheme"; - continue - } - u += b.toLowerCase(), d = "scheme"; - break; - case "scheme": - if (b && v.test(b)) u += b.toLowerCase(); - else { - if (":" != b) { - if (a) { - if (p == b) break e; - c("Code point not allowed in scheme: " + b); - break e - } - u = "", l = 0, d = "no scheme"; - continue - } - if (this._scheme = u, u = "", a) break e; - t(this._scheme) && (this._isRelative = !0), d = "file" == this._scheme ? "relative" : this._isRelative && s && s._scheme == this._scheme ? "relative or authority" : this._isRelative ? "authority first slash" : "scheme data" - } - break; - case "scheme data": - "?" == b ? (this._query = "?", d = "query") : "#" == b ? (this._fragment = "#", d = "fragment") : p != b && "\t" != b && "\n" != b && "\r" != b && (this._schemeData += r(b)); - break; - case "no scheme": - if (s && t(s._scheme)) { - d = "relative"; - continue - } - c("Missing scheme."), n.call(this); - break; - case "relative or authority": - if ("/" != b || "/" != e[l + 1]) { - c("Expected /, got: " + b), d = "relative"; - continue - } - d = "authority ignore slashes"; - break; - case "relative": - if (this._isRelative = !0, "file" != this._scheme && (this._scheme = s._scheme), p == b) { - this._host = s._host, this._port = s._port, this._path = s._path.slice(), this._query = s._query, this._username = s._username, this._password = s._password; - break e - } - if ("/" == b || "\\" == b) "\\" == b && c("\\ is an invalid code point."), d = "relative slash"; - else if ("?" == b) this._host = s._host, this._port = s._port, this._path = s._path.slice(), this._query = "?", this._username = s._username, this._password = s._password, d = "query"; - else { - if ("#" != b) { - var y = e[l + 1], - E = e[l + 2]; - ("file" != this._scheme || !m.test(b) || ":" != y && "|" != y || p != E && "/" != E && "\\" != E && "?" != E && "#" != E) && (this._host = s._host, this._port = s._port, this._username = s._username, this._password = s._password, this._path = s._path.slice(), this._path.pop()), d = "relative path"; - continue - } - this._host = s._host, this._port = s._port, this._path = s._path.slice(), this._query = s._query, this._fragment = "#", this._username = s._username, this._password = s._password, d = "fragment" - } - break; - case "relative slash": - if ("/" != b && "\\" != b) { - "file" != this._scheme && (this._host = s._host, this._port = s._port, this._username = s._username, this._password = s._password), d = "relative path"; - continue - } - "\\" == b && c("\\ is an invalid code point."), d = "file" == this._scheme ? "file host" : "authority ignore slashes"; - break; - case "authority first slash": - if ("/" != b) { - c("Expected '/', got: " + b), d = "authority ignore slashes"; - continue - } - d = "authority second slash"; - break; - case "authority second slash": - if (d = "authority ignore slashes", "/" != b) { - c("Expected '/', got: " + b); - continue - } - break; - case "authority ignore slashes": - if ("/" != b && "\\" != b) { - d = "authority"; - continue - } - c("Expected authority, got: " + b); - break; - case "authority": - if ("@" == b) { - w && (c("@ already seen."), u += "%40"), w = !0; - for (var L = 0; L < u.length; L++) { - var N = u[L]; - if ("\t" != N && "\n" != N && "\r" != N) - if (":" != N || null !== this._password) { - var M = r(N); - null !== this._password ? this._password += M : this._username += M - } else this._password = ""; - else c("Invalid whitespace in authority.") - } - u = "" - } else { - if (p == b || "/" == b || "\\" == b || "?" == b || "#" == b) { - l -= u.length, u = "", d = "host"; - continue - } - u += b - } - break; - case "file host": - if (p == b || "/" == b || "\\" == b || "?" == b || "#" == b) { - 2 != u.length || !m.test(u[0]) || ":" != u[1] && "|" != u[1] ? 0 == u.length ? d = "relative path start" : (this._host = o.call(this, u), u = "", d = "relative path start") : d = "relative path"; - continue - } - "\t" == b || "\n" == b || "\r" == b ? c("Invalid whitespace in file host.") : u += b; - break; - case "host": - case "hostname": - if (":" != b || _) { - if (p == b || "/" == b || "\\" == b || "?" == b || "#" == b) { - if (this._host = o.call(this, u), u = "", d = "relative path start", a) break e; - continue - } - "\t" != b && "\n" != b && "\r" != b ? ("[" == b ? _ = !0 : "]" == b && (_ = !1), u += b) : c("Invalid code point in host/hostname: " + b) - } else if (this._host = o.call(this, u), u = "", d = "port", "hostname" == a) break e; - break; - case "port": - if (/[0-9]/.test(b)) u += b; - else { - if (p == b || "/" == b || "\\" == b || "?" == b || "#" == b || a) { - if ("" != u) { - var T = parseInt(u, 10); - T != h[this._scheme] && (this._port = T + ""), u = "" - } - if (a) break e; - d = "relative path start"; - continue - } - "\t" == b || "\n" == b || "\r" == b ? c("Invalid code point in port: " + b) : n.call(this) - } - break; - case "relative path start": - if ("\\" == b && c("'\\' not allowed in path."), d = "relative path", "/" != b && "\\" != b) continue; - break; - case "relative path": - if (p != b && "/" != b && "\\" != b && (a || "?" != b && "#" != b)) "\t" != b && "\n" != b && "\r" != b && (u += r(b)); - else { - "\\" == b && c("\\ not allowed in relative path."); - var O; - (O = f[u.toLowerCase()]) && (u = O), ".." == u ? (this._path.pop(), "/" != b && "\\" != b && this._path.push("")) : "." == u && "/" != b && "\\" != b ? this._path.push("") : "." != u && ("file" == this._scheme && 0 == this._path.length && 2 == u.length && m.test(u[0]) && "|" == u[1] && (u = u[0] + ":"), this._path.push(u)), u = "", "?" == b ? (this._query = "?", d = "query") : "#" == b && (this._fragment = "#", d = "fragment") - } - break; - case "query": - a || "#" != b ? p != b && "\t" != b && "\n" != b && "\r" != b && (this._query += i(b)) : (this._fragment = "#", d = "fragment"); - break; - case "fragment": - p != b && "\t" != b && "\n" != b && "\r" != b && (this._fragment += b) - } - l++ - } - } - - function s() { - this._scheme = "", this._schemeData = "", this._username = "", this._password = null, this._host = "", this._port = "", this._path = [], this._query = "", this._fragment = "", this._isInvalid = !1, this._isRelative = !1 - } - - function c(e, t) { - void 0 === t || t instanceof c || (t = new c(String(t))), this._url = e, s.call(this); - var n = e.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ""); - a.call(this, n, null, t) - } - var d = !1; - if (!e.forceJURL) try { - var l = new URL("b", "http://a"); - l.pathname = "c%20d", d = "http://a/c%20d" === l.href - } catch (u) {} - if (!d) { - var h = Object.create(null); - h.ftp = 21, h.file = 0, h.gopher = 70, h.http = 80, h.https = 443, h.ws = 80, h.wss = 443; - var f = Object.create(null); - f["%2e"] = ".", f[".%2e"] = "..", f["%2e."] = "..", f["%2e%2e"] = ".."; - var p = void 0, - m = /[a-zA-Z]/, - v = /[a-zA-Z0-9\+\-\.]/; - c.prototype = { - toString: function() { - return this.href - }, - get href() { - if (this._isInvalid) return this._url; - var e = ""; - return "" == this._username && null == this._password || (e = this._username + (null != this._password ? ":" + this._password : "") + "@"), this.protocol + (this._isRelative ? "//" + e + this.host : "") + this.pathname + this._query + this._fragment - }, - set href(e) { - s.call(this), a.call(this, e) - }, - get protocol() { - return this._scheme + ":" - }, - set protocol(e) { - this._isInvalid || a.call(this, e + ":", "scheme start") - }, - get host() { - return this._isInvalid ? "" : this._port ? this._host + ":" + this._port : this._host - }, - set host(e) { - !this._isInvalid && this._isRelative && a.call(this, e, "host") - }, - get hostname() { - return this._host - }, - set hostname(e) { - !this._isInvalid && this._isRelative && a.call(this, e, "hostname") - }, - get port() { - return this._port - }, - set port(e) { - !this._isInvalid && this._isRelative && a.call(this, e, "port") - }, - get pathname() { - return this._isInvalid ? "" : this._isRelative ? "/" + this._path.join("/") : this._schemeData - }, - set pathname(e) { - !this._isInvalid && this._isRelative && (this._path = [], a.call(this, e, "relative path start")) - }, - get search() { - return this._isInvalid || !this._query || "?" == this._query ? "" : this._query - }, - set search(e) { - !this._isInvalid && this._isRelative && (this._query = "?", "?" == e[0] && (e = e.slice(1)), a.call(this, e, "query")) - }, - get hash() { - return this._isInvalid || !this._fragment || "#" == this._fragment ? "" : this._fragment - }, - set hash(e) { - this._isInvalid || (this._fragment = "#", "#" == e[0] && (e = e.slice(1)), a.call(this, e, "fragment")) - }, - get origin() { - var e; - if (this._isInvalid || !this._scheme) return ""; - switch (this._scheme) { - case "data": - case "file": - case "javascript": - case "mailto": - return "null" - } - return e = this.host, e ? this._scheme + "://" + e : "" - } - }; - var w = e.URL; - w && (c.createObjectURL = function(e) { - return w.createObjectURL.apply(w, arguments) - }, c.revokeObjectURL = function(e) { - w.revokeObjectURL(e) - }), e.URL = c - } -}(self), "undefined" == typeof WeakMap && ! function() { - var e = Object.defineProperty, - t = Date.now() % 1e9, - n = function() { - this.name = "__st" + (1e9 * Math.random() >>> 0) + (t++ + "__") - }; - n.prototype = { - set: function(t, n) { - var o = t[this.name]; - return o && o[0] === t ? o[1] = n : e(t, this.name, { - value: [t, n], - writable: !0 - }), this - }, - get: function(e) { - var t; - return (t = e[this.name]) && t[0] === e ? t[1] : void 0 - }, - "delete": function(e) { - var t = e[this.name]; - return !(!t || t[0] !== e) && (t[0] = t[1] = void 0, !0) - }, - has: function(e) { - var t = e[this.name]; - return !!t && t[0] === e - } - }, window.WeakMap = n - }(), - function(e) { - function t(e) { - b.push(e), g || (g = !0, m(o)) - } - - function n(e) { - return window.ShadowDOMPolyfill && window.ShadowDOMPolyfill.wrapIfNeeded(e) || e - } - - function o() { - g = !1; - var e = b; - b = [], e.sort(function(e, t) { - return e.uid_ - t.uid_ - }); - var t = !1; - e.forEach(function(e) { - var n = e.takeRecords(); - r(e), n.length && (e.callback_(n, e), t = !0) - }), t && o() - } - - function r(e) { - e.nodes_.forEach(function(t) { - var n = v.get(t); - n && n.forEach(function(t) { - t.observer === e && t.removeTransientObservers() - }) - }) - } - - function i(e, t) { - for (var n = e; n; n = n.parentNode) { - var o = v.get(n); - if (o) - for (var r = 0; r < o.length; r++) { - var i = o[r], - a = i.options; - if (n === e || a.subtree) { - var s = t(a); - s && i.enqueue(s) - } - } - } - } - - function a(e) { - this.callback_ = e, this.nodes_ = [], this.records_ = [], this.uid_ = ++y - } - - function s(e, t) { - this.type = e, this.target = t, this.addedNodes = [], this.removedNodes = [], this.previousSibling = null, this.nextSibling = null, this.attributeName = null, this.attributeNamespace = null, this.oldValue = null - } - - function c(e) { - var t = new s(e.type, e.target); - return t.addedNodes = e.addedNodes.slice(), t.removedNodes = e.removedNodes.slice(), t.previousSibling = e.previousSibling, t.nextSibling = e.nextSibling, t.attributeName = e.attributeName, t.attributeNamespace = e.attributeNamespace, t.oldValue = e.oldValue, t - } - - function d(e, t) { - return E = new s(e, t) - } - - function l(e) { - return L ? L : (L = c(E), L.oldValue = e, L) - } - - function u() { - E = L = void 0 - } - - function h(e) { - return e === L || e === E - } - - function f(e, t) { - return e === t ? e : L && h(e) ? L : null - } - - function p(e, t, n) { - this.observer = e, this.target = t, this.options = n, this.transientObservedNodes = [] - } - if (!e.JsMutationObserver) { - var m, v = new WeakMap; - if (/Trident|Edge/.test(navigator.userAgent)) m = setTimeout; - else if (window.setImmediate) m = window.setImmediate; - else { - var w = [], - _ = String(Math.random()); - window.addEventListener("message", function(e) { - if (e.data === _) { - var t = w; - w = [], t.forEach(function(e) { - e() - }) - } - }), m = function(e) { - w.push(e), window.postMessage(_, "*") - } - } - var g = !1, - b = [], - y = 0; - a.prototype = { - observe: function(e, t) { - if (e = n(e), !t.childList && !t.attributes && !t.characterData || t.attributeOldValue && !t.attributes || t.attributeFilter && t.attributeFilter.length && !t.attributes || t.characterDataOldValue && !t.characterData) throw new SyntaxError; - var o = v.get(e); - o || v.set(e, o = []); - for (var r, i = 0; i < o.length; i++) - if (o[i].observer === this) { - r = o[i], r.removeListeners(), r.options = t; - break - } r || (r = new p(this, e, t), o.push(r), this.nodes_.push(e)), r.addListeners() - }, - disconnect: function() { - this.nodes_.forEach(function(e) { - for (var t = v.get(e), n = 0; n < t.length; n++) { - var o = t[n]; - if (o.observer === this) { - o.removeListeners(), t.splice(n, 1); - break - } - } - }, this), this.records_ = [] - }, - takeRecords: function() { - var e = this.records_; - return this.records_ = [], e - } - }; - var E, L; - p.prototype = { - enqueue: function(e) { - var n = this.observer.records_, - o = n.length; - if (n.length > 0) { - var r = n[o - 1], - i = f(r, e); - if (i) return void(n[o - 1] = i) - } else t(this.observer); - n[o] = e - }, - addListeners: function() { - this.addListeners_(this.target) - }, - addListeners_: function(e) { - var t = this.options; - t.attributes && e.addEventListener("DOMAttrModified", this, !0), t.characterData && e.addEventListener("DOMCharacterDataModified", this, !0), t.childList && e.addEventListener("DOMNodeInserted", this, !0), (t.childList || t.subtree) && e.addEventListener("DOMNodeRemoved", this, !0) - }, - removeListeners: function() { - this.removeListeners_(this.target) - }, - removeListeners_: function(e) { - var t = this.options; - t.attributes && e.removeEventListener("DOMAttrModified", this, !0), t.characterData && e.removeEventListener("DOMCharacterDataModified", this, !0), t.childList && e.removeEventListener("DOMNodeInserted", this, !0), (t.childList || t.subtree) && e.removeEventListener("DOMNodeRemoved", this, !0) - }, - addTransientObserver: function(e) { - if (e !== this.target) { - this.addListeners_(e), this.transientObservedNodes.push(e); - var t = v.get(e); - t || v.set(e, t = []), t.push(this) - } - }, - removeTransientObservers: function() { - var e = this.transientObservedNodes; - this.transientObservedNodes = [], e.forEach(function(e) { - this.removeListeners_(e); - for (var t = v.get(e), n = 0; n < t.length; n++) - if (t[n] === this) { - t.splice(n, 1); - break - } - }, this) - }, - handleEvent: function(e) { - switch (e.stopImmediatePropagation(), e.type) { - case "DOMAttrModified": - var t = e.attrName, - n = e.relatedNode.namespaceURI, - o = e.target, - r = new d("attributes", o); - r.attributeName = t, r.attributeNamespace = n; - var a = e.attrChange === MutationEvent.ADDITION ? null : e.prevValue; - i(o, function(e) { - if (e.attributes && (!e.attributeFilter || !e.attributeFilter.length || e.attributeFilter.indexOf(t) !== -1 || e.attributeFilter.indexOf(n) !== -1)) return e.attributeOldValue ? l(a) : r - }); - break; - case "DOMCharacterDataModified": - var o = e.target, - r = d("characterData", o), - a = e.prevValue; - i(o, function(e) { - if (e.characterData) return e.characterDataOldValue ? l(a) : r - }); - break; - case "DOMNodeRemoved": - this.addTransientObserver(e.target); - case "DOMNodeInserted": - var s, c, h = e.target; - "DOMNodeInserted" === e.type ? (s = [h], c = []) : (s = [], c = [h]); - var f = h.previousSibling, - p = h.nextSibling, - r = d("childList", e.target.parentNode); - r.addedNodes = s, r.removedNodes = c, r.previousSibling = f, r.nextSibling = p, i(e.relatedNode, function(e) { - if (e.childList) return r - }) - } - u() - } - }, e.JsMutationObserver = a, e.MutationObserver || (e.MutationObserver = a, a._isPolyfilled = !0) - } - }(self), - function() { - function e(e) { - switch (e) { - case "&": - return "&"; - case "<": - return "<"; - case ">": - return ">"; - case " ": - return " " - } - } - - function t(t) { - return t.replace(u, e) - } - var n = "undefined" == typeof HTMLTemplateElement; - /Trident/.test(navigator.userAgent) && ! function() { - var e = document.importNode; - document.importNode = function() { - var t = e.apply(document, arguments); - if (t.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { - var n = document.createDocumentFragment(); - return n.appendChild(t), n - } - return t - } - }(); - var o = function() { - if (!n) { - var e = document.createElement("template"), - t = document.createElement("template"); - t.content.appendChild(document.createElement("div")), e.content.appendChild(t); - var o = e.cloneNode(!0); - return 0 === o.content.childNodes.length || 0 === o.content.firstChild.content.childNodes.length - } - }(), - r = "template", - i = function() {}; - if (n) { - var a = document.implementation.createHTMLDocument("template"), - s = !0, - c = document.createElement("style"); - c.textContent = r + "{display:none;}"; - var d = document.head; - d.insertBefore(c, d.firstElementChild), i.prototype = Object.create(HTMLElement.prototype), i.decorate = function(e) { - if (!e.content) { - e.content = a.createDocumentFragment(); - for (var n; n = e.firstChild;) e.content.appendChild(n); - if (e.cloneNode = function(e) { - return i.cloneNode(this, e) - }, s) try { - Object.defineProperty(e, "innerHTML", { - get: function() { - for (var e = "", n = this.content.firstChild; n; n = n.nextSibling) e += n.outerHTML || t(n.data); - return e - }, - set: function(e) { - for (a.body.innerHTML = e, i.bootstrap(a); this.content.firstChild;) this.content.removeChild(this.content.firstChild); - for (; a.body.firstChild;) this.content.appendChild(a.body.firstChild) - }, - configurable: !0 - }) - } catch (o) { - s = !1 - } - i.bootstrap(e.content) - } - }, i.bootstrap = function(e) { - for (var t, n = e.querySelectorAll(r), o = 0, a = n.length; o < a && (t = n[o]); o++) i.decorate(t) - }, document.addEventListener("DOMContentLoaded", function() { - i.bootstrap(document) - }); - var l = document.createElement; - document.createElement = function() { - "use strict"; - var e = l.apply(document, arguments); - return "template" === e.localName && i.decorate(e), e - }; - var u = /[&\u00A0<>]/g - } - if (n || o) { - var h = Node.prototype.cloneNode; - i.cloneNode = function(e, t) { - var n = h.call(e, !1); - return this.decorate && this.decorate(n), t && (n.content.appendChild(h.call(e.content, !0)), this.fixClonedDom(n.content, e.content)), n - }, i.fixClonedDom = function(e, t) { - if (t.querySelectorAll) - for (var n, o, i = t.querySelectorAll(r), a = e.querySelectorAll(r), s = 0, c = a.length; s < c; s++) o = i[s], n = a[s], this.decorate && this.decorate(o), n.parentNode.replaceChild(o.cloneNode(!0), n) - }; - var f = document.importNode; - Node.prototype.cloneNode = function(e) { - var t = h.call(this, e); - return e && i.fixClonedDom(t, this), t - }, document.importNode = function(e, t) { - if (e.localName === r) return i.cloneNode(e, t); - var n = f.call(document, e, t); - return t && i.fixClonedDom(n, e), n - }, o && (HTMLTemplateElement.prototype.cloneNode = function(e) { - return i.cloneNode(this, e) - }) - } - n && (window.HTMLTemplateElement = i) - }(), - function(e) { - "use strict"; - if (!window.performance || !window.performance.now) { - var t = Date.now(); - window.performance = { - now: function() { - return Date.now() - t - } - } - } - window.requestAnimationFrame || (window.requestAnimationFrame = function() { - var e = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; - return e ? function(t) { - return e(function() { - t(performance.now()) - }) - } : function(e) { - return window.setTimeout(e, 1e3 / 60) - } - }()), window.cancelAnimationFrame || (window.cancelAnimationFrame = function() { - return window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function(e) { - clearTimeout(e) - } - }()); - var n = function() { - var e = document.createEvent("Event"); - return e.initEvent("foo", !0, !0), e.preventDefault(), e.defaultPrevented - }(); - if (!n) { - var o = Event.prototype.preventDefault; - Event.prototype.preventDefault = function() { - this.cancelable && (o.call(this), Object.defineProperty(this, "defaultPrevented", { - get: function() { - return !0 - }, - configurable: !0 - })) - } - } - var r = /Trident/.test(navigator.userAgent); - if ((!window.CustomEvent || r && "function" != typeof window.CustomEvent) && (window.CustomEvent = function(e, t) { - t = t || {}; - var n = document.createEvent("CustomEvent"); - return n.initCustomEvent(e, Boolean(t.bubbles), Boolean(t.cancelable), t.detail), n - }, window.CustomEvent.prototype = window.Event.prototype), !window.Event || r && "function" != typeof window.Event) { - var i = window.Event; - window.Event = function(e, t) { - t = t || {}; - var n = document.createEvent("Event"); - return n.initEvent(e, Boolean(t.bubbles), Boolean(t.cancelable)), n - }, window.Event.prototype = i.prototype - } - }(window.WebComponents), window.HTMLImports = window.HTMLImports || { - flags: {} - }, - function(e) { - function t(e, t) { - t = t || p, o(function() { - i(e, t) - }, t) - } - - function n(e) { - return "complete" === e.readyState || e.readyState === w - } - - function o(e, t) { - if (n(t)) e && e(); - else { - var r = function() { - "complete" !== t.readyState && t.readyState !== w || (t.removeEventListener(_, r), o(e, t)) - }; - t.addEventListener(_, r) - } - } - - function r(e) { - e.target.__loaded = !0 - } - - function i(e, t) { - function n() { - c == d && e && e({ - allImports: s, - loadedImports: l, - errorImports: u - }) - } - - function o(e) { - r(e), l.push(this), c++, n() - } - - function i(e) { - u.push(this), c++, n() - } - var s = t.querySelectorAll("link[rel=import]"), - c = 0, - d = s.length, - l = [], - u = []; - if (d) - for (var h, f = 0; f < d && (h = s[f]); f++) a(h) ? (l.push(this), c++, n()) : (h.addEventListener("load", o), h.addEventListener("error", i)); - else n() - } - - function a(e) { - return u ? e.__loaded || e["import"] && "loading" !== e["import"].readyState : e.__importParsed - } - - function s(e) { - for (var t, n = 0, o = e.length; n < o && (t = e[n]); n++) c(t) && d(t) - } - - function c(e) { - return "link" === e.localName && "import" === e.rel - } - - function d(e) { - var t = e["import"]; - t ? r({ - target: e - }) : (e.addEventListener("load", r), e.addEventListener("error", r)) - } - var l = "import", - u = Boolean(l in document.createElement("link")), - h = Boolean(window.ShadowDOMPolyfill), - f = function(e) { - return h ? window.ShadowDOMPolyfill.wrapIfNeeded(e) : e - }, - p = f(document), - m = { - get: function() { - var e = window.HTMLImports.currentScript || document.currentScript || ("complete" !== document.readyState ? document.scripts[document.scripts.length - 1] : null); - return f(e) - }, - configurable: !0 - }; - Object.defineProperty(document, "_currentScript", m), Object.defineProperty(p, "_currentScript", m); - var v = /Trident/.test(navigator.userAgent), - w = v ? "complete" : "interactive", - _ = "readystatechange"; - u && (new MutationObserver(function(e) { - for (var t, n = 0, o = e.length; n < o && (t = e[n]); n++) t.addedNodes && s(t.addedNodes) - }).observe(document.head, { - childList: !0 - }), function() { - if ("loading" === document.readyState) - for (var e, t = document.querySelectorAll("link[rel=import]"), n = 0, o = t.length; n < o && (e = t[n]); n++) d(e) - }()), t(function(e) { - window.HTMLImports.ready = !0, window.HTMLImports.readyTime = (new Date).getTime(); - var t = p.createEvent("CustomEvent"); - t.initCustomEvent("HTMLImportsLoaded", !0, !0, e), p.dispatchEvent(t) - }), e.IMPORT_LINK_TYPE = l, e.useNative = u, e.rootDocument = p, e.whenReady = t, e.isIE = v - }(window.HTMLImports), - function(e) { - var t = [], - n = function(e) { - t.push(e) - }, - o = function() { - t.forEach(function(t) { - t(e) - }) - }; - e.addModule = n, e.initializeModules = o - }(window.HTMLImports), window.HTMLImports.addModule(function(e) { - var t = /(url\()([^)]*)(\))/g, - n = /(@import[\s]+(?!url\())([^;]*)(;)/g, - o = { - resolveUrlsInStyle: function(e, t) { - var n = e.ownerDocument, - o = n.createElement("a"); - return e.textContent = this.resolveUrlsInCssText(e.textContent, t, o), e - }, - resolveUrlsInCssText: function(e, o, r) { - var i = this.replaceUrls(e, r, o, t); - return i = this.replaceUrls(i, r, o, n) - }, - replaceUrls: function(e, t, n, o) { - return e.replace(o, function(e, o, r, i) { - var a = r.replace(/["']/g, ""); - return n && (a = new URL(a, n).href), t.href = a, a = t.href, o + "'" + a + "'" + i - }) - } - }; - e.path = o - }), window.HTMLImports.addModule(function(e) { - var t = { - async: !0, - ok: function(e) { - return e.status >= 200 && e.status < 300 || 304 === e.status || 0 === e.status - }, - load: function(n, o, r) { - var i = new XMLHttpRequest; - return (e.flags.debug || e.flags.bust) && (n += "?" + Math.random()), i.open("GET", n, t.async), i.addEventListener("readystatechange", function(e) { - if (4 === i.readyState) { - var n = null; - try { - var a = i.getResponseHeader("Location"); - a && (n = "/" === a.substr(0, 1) ? location.origin + a : a) - } catch (e) { - console.error(e.message) - } - o.call(r, !t.ok(i) && i, i.response || i.responseText, n) - } - }), i.send(), i - }, - loadDocument: function(e, t, n) { - this.load(e, t, n).responseType = "document" - } - }; - e.xhr = t - }), window.HTMLImports.addModule(function(e) { - var t = e.xhr, - n = e.flags, - o = function(e, t) { - this.cache = {}, this.onload = e, this.oncomplete = t, this.inflight = 0, this.pending = {} - }; - o.prototype = { - addNodes: function(e) { - this.inflight += e.length; - for (var t, n = 0, o = e.length; n < o && (t = e[n]); n++) this.require(t); - this.checkDone() - }, - addNode: function(e) { - this.inflight++, this.require(e), this.checkDone() - }, - require: function(e) { - var t = e.src || e.href; - e.__nodeUrl = t, this.dedupe(t, e) || this.fetch(t, e) - }, - dedupe: function(e, t) { - if (this.pending[e]) return this.pending[e].push(t), !0; - return this.cache[e] ? (this.onload(e, t, this.cache[e]), this.tail(), !0) : (this.pending[e] = [t], !1) - }, - fetch: function(e, o) { - if (n.load && console.log("fetch", e, o), e) - if (e.match(/^data:/)) { - var r = e.split(","), - i = r[0], - a = r[1]; - a = i.indexOf(";base64") > -1 ? atob(a) : decodeURIComponent(a), setTimeout(function() { - this.receive(e, o, null, a) - }.bind(this), 0) - } else { - var s = function(t, n, r) { - this.receive(e, o, t, n, r) - }.bind(this); - t.load(e, s) - } - else setTimeout(function() { - this.receive(e, o, { - error: "href must be specified" - }, null) - }.bind(this), 0) - }, - receive: function(e, t, n, o, r) { - this.cache[e] = o; - for (var i, a = this.pending[e], s = 0, c = a.length; s < c && (i = a[s]); s++) this.onload(e, i, o, n, r), this.tail(); - this.pending[e] = null - }, - tail: function() { - --this.inflight, this.checkDone() - }, - checkDone: function() { - this.inflight || this.oncomplete() - } - }, e.Loader = o - }), window.HTMLImports.addModule(function(e) { - var t = function(e) { - this.addCallback = e, this.mo = new MutationObserver(this.handler.bind(this)) - }; - t.prototype = { - handler: function(e) { - for (var t, n = 0, o = e.length; n < o && (t = e[n]); n++) "childList" === t.type && t.addedNodes.length && this.addedNodes(t.addedNodes) - }, - addedNodes: function(e) { - this.addCallback && this.addCallback(e); - for (var t, n = 0, o = e.length; n < o && (t = e[n]); n++) t.children && t.children.length && this.addedNodes(t.children) - }, - observe: function(e) { - this.mo.observe(e, { - childList: !0, - subtree: !0 - }) - } - }, e.Observer = t - }), window.HTMLImports.addModule(function(e) { - function t(e) { - return "link" === e.localName && e.rel === l - } - - function n(e) { - var t = o(e); - return "data:text/javascript;charset=utf-8," + encodeURIComponent(t) - } - - function o(e) { - return e.textContent + r(e) - } - - function r(e) { - var t = e.ownerDocument; - t.__importedScripts = t.__importedScripts || 0; - var n = e.ownerDocument.baseURI, - o = t.__importedScripts ? "-" + t.__importedScripts : ""; - return t.__importedScripts++, "\n//# sourceURL=" + n + o + ".js\n" - } - - function i(e) { - var t = e.ownerDocument.createElement("style"); - return t.textContent = e.textContent, a.resolveUrlsInStyle(t), t - } - var a = e.path, - s = e.rootDocument, - c = e.flags, - d = e.isIE, - l = e.IMPORT_LINK_TYPE, - u = "link[rel=" + l + "]", - h = { - documentSelectors: u, - importsSelectors: [u, "link[rel=stylesheet]:not([type])", "style:not([type])", "script:not([type])", 'script[type="application/javascript"]', 'script[type="text/javascript"]'].join(","), - map: { - link: "parseLink", - script: "parseScript", - style: "parseStyle" - }, - dynamicElements: [], - parseNext: function() { - var e = this.nextToParse(); - e && this.parse(e) - }, - parse: function(e) { - if (this.isParsed(e)) return void(c.parse && console.log("[%s] is already parsed", e.localName)); - var t = this[this.map[e.localName]]; - t && (this.markParsing(e), t.call(this, e)) - }, - parseDynamic: function(e, t) { - this.dynamicElements.push(e), t || this.parseNext() - }, - markParsing: function(e) { - c.parse && console.log("parsing", e), this.parsingElement = e - }, - markParsingComplete: function(e) { - e.__importParsed = !0, this.markDynamicParsingComplete(e), e.__importElement && (e.__importElement.__importParsed = !0, this.markDynamicParsingComplete(e.__importElement)), this.parsingElement = null, c.parse && console.log("completed", e) - }, - markDynamicParsingComplete: function(e) { - var t = this.dynamicElements.indexOf(e); - t >= 0 && this.dynamicElements.splice(t, 1) - }, - parseImport: function(e) { - if (e["import"] = e.__doc, window.HTMLImports.__importsParsingHook && window.HTMLImports.__importsParsingHook(e), e["import"] && (e["import"].__importParsed = !0), this.markParsingComplete(e), e.__resource && !e.__error ? e.dispatchEvent(new CustomEvent("load", { - bubbles: !1 - })) : e.dispatchEvent(new CustomEvent("error", { - bubbles: !1 - })), e.__pending) - for (var t; e.__pending.length;) t = e.__pending.shift(), t && t({ - target: e - }); - this.parseNext() - }, - parseLink: function(e) { - t(e) ? this.parseImport(e) : (e.href = e.href, this.parseGeneric(e)) - }, - parseStyle: function(e) { - var t = e; - e = i(e), t.__appliedElement = e, e.__importElement = t, this.parseGeneric(e) - }, - parseGeneric: function(e) { - this.trackElement(e), this.addElementToDocument(e) - }, - rootImportForElement: function(e) { - for (var t = e; t.ownerDocument.__importLink;) t = t.ownerDocument.__importLink; - return t - }, - addElementToDocument: function(e) { - var t = this.rootImportForElement(e.__importElement || e); - t.parentNode.insertBefore(e, t) - }, - trackElement: function(e, t) { - var n = this, - o = function(r) { - e.removeEventListener("load", o), e.removeEventListener("error", o), t && t(r), n.markParsingComplete(e), n.parseNext() - }; - if (e.addEventListener("load", o), e.addEventListener("error", o), d && "style" === e.localName) { - var r = !1; - if (e.textContent.indexOf("@import") == -1) r = !0; - else if (e.sheet) { - r = !0; - for (var i, a = e.sheet.cssRules, s = a ? a.length : 0, c = 0; c < s && (i = a[c]); c++) i.type === CSSRule.IMPORT_RULE && (r = r && Boolean(i.styleSheet)) - } - r && setTimeout(function() { - e.dispatchEvent(new CustomEvent("load", { - bubbles: !1 - })) - }) - } - }, - parseScript: function(t) { - var o = document.createElement("script"); - o.__importElement = t, o.src = t.src ? t.src : n(t), e.currentScript = t, this.trackElement(o, function(t) { - o.parentNode && o.parentNode.removeChild(o), e.currentScript = null - }), this.addElementToDocument(o) - }, - nextToParse: function() { - return this._mayParse = [], !this.parsingElement && (this.nextToParseInDoc(s) || this.nextToParseDynamic()) - }, - nextToParseInDoc: function(e, n) { - if (e && this._mayParse.indexOf(e) < 0) { - this._mayParse.push(e); - for (var o, r = e.querySelectorAll(this.parseSelectorsForNode(e)), i = 0, a = r.length; i < a && (o = r[i]); i++) - if (!this.isParsed(o)) return this.hasResource(o) ? t(o) ? this.nextToParseInDoc(o.__doc, o) : o : void 0 - } - return n - }, - nextToParseDynamic: function() { - return this.dynamicElements[0] - }, - parseSelectorsForNode: function(e) { - var t = e.ownerDocument || e; - return t === s ? this.documentSelectors : this.importsSelectors - }, - isParsed: function(e) { - return e.__importParsed - }, - needsDynamicParsing: function(e) { - return this.dynamicElements.indexOf(e) >= 0 - }, - hasResource: function(e) { - return !t(e) || void 0 !== e.__doc - } - }; - e.parser = h, e.IMPORT_SELECTOR = u - }), window.HTMLImports.addModule(function(e) { - function t(e) { - return n(e, a) - } - - function n(e, t) { - return "link" === e.localName && e.getAttribute("rel") === t - } - - function o(e) { - return !!Object.getOwnPropertyDescriptor(e, "baseURI") - } - - function r(e, t) { - var n = document.implementation.createHTMLDocument(a); - n._URL = t; - var r = n.createElement("base"); - r.setAttribute("href", t), n.baseURI || o(n) || Object.defineProperty(n, "baseURI", { - value: t - }); - var i = n.createElement("meta"); - return i.setAttribute("charset", "utf-8"), n.head.appendChild(i), n.head.appendChild(r), n.body.innerHTML = e, window.HTMLTemplateElement && HTMLTemplateElement.bootstrap && HTMLTemplateElement.bootstrap(n), n - } - var i = e.flags, - a = e.IMPORT_LINK_TYPE, - s = e.IMPORT_SELECTOR, - c = e.rootDocument, - d = e.Loader, - l = e.Observer, - u = e.parser, - h = { - documents: {}, - documentPreloadSelectors: s, - importsPreloadSelectors: [s].join(","), - loadNode: function(e) { - f.addNode(e) - }, - loadSubtree: function(e) { - var t = this.marshalNodes(e); - f.addNodes(t) - }, - marshalNodes: function(e) { - return e.querySelectorAll(this.loadSelectorsForNode(e)) - }, - loadSelectorsForNode: function(e) { - var t = e.ownerDocument || e; - return t === c ? this.documentPreloadSelectors : this.importsPreloadSelectors - }, - loaded: function(e, n, o, a, s) { - if (i.load && console.log("loaded", e, n), n.__resource = o, n.__error = a, t(n)) { - var c = this.documents[e]; - void 0 === c && (c = a ? null : r(o, s || e), c && (c.__importLink = n, this.bootDocument(c)), this.documents[e] = c), n.__doc = c - } - u.parseNext() - }, - bootDocument: function(e) { - this.loadSubtree(e), this.observer.observe(e), u.parseNext() - }, - loadedAll: function() { - u.parseNext() - } - }, - f = new d(h.loaded.bind(h), h.loadedAll.bind(h)); - if (h.observer = new l, !document.baseURI) { - var p = { - get: function() { - var e = document.querySelector("base"); - return e ? e.href : window.location.href - }, - configurable: !0 - }; - Object.defineProperty(document, "baseURI", p), Object.defineProperty(c, "baseURI", p) - } - e.importer = h, e.importLoader = f - }), window.HTMLImports.addModule(function(e) { - var t = e.parser, - n = e.importer, - o = { - added: function(e) { - for (var o, r, i, a, s = 0, c = e.length; s < c && (a = e[s]); s++) o || (o = a.ownerDocument, r = t.isParsed(o)), i = this.shouldLoadNode(a), i && n.loadNode(a), this.shouldParseNode(a) && r && t.parseDynamic(a, i) - }, - shouldLoadNode: function(e) { - return 1 === e.nodeType && r.call(e, n.loadSelectorsForNode(e)) - }, - shouldParseNode: function(e) { - return 1 === e.nodeType && r.call(e, t.parseSelectorsForNode(e)) - } - }; - n.observer.addCallback = o.added.bind(o); - var r = HTMLElement.prototype.matches || HTMLElement.prototype.matchesSelector || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector || HTMLElement.prototype.msMatchesSelector - }), - function(e) { - function t() { - window.HTMLImports.importer.bootDocument(o) - } - var n = e.initializeModules; - e.isIE; - if (!e.useNative) { - n(); - var o = e.rootDocument; - "complete" === document.readyState || "interactive" === document.readyState && !window.attachEvent ? t() : document.addEventListener("DOMContentLoaded", t) - } - }(window.HTMLImports), window.CustomElements = window.CustomElements || { - flags: {} - }, - function(e) { - var t = e.flags, - n = [], - o = function(e) { - n.push(e) - }, - r = function() { - n.forEach(function(t) { - t(e) - }) - }; - e.addModule = o, e.initializeModules = r, e.hasNative = Boolean(document.registerElement), e.isIE = /Trident/.test(navigator.userAgent), e.useNative = !t.register && e.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || window.HTMLImports.useNative) - }(window.CustomElements), window.CustomElements.addModule(function(e) { - function t(e, t) { - n(e, function(e) { - return !!t(e) || void o(e, t) - }), o(e, t) - } - - function n(e, t, o) { - var r = e.firstElementChild; - if (!r) - for (r = e.firstChild; r && r.nodeType !== Node.ELEMENT_NODE;) r = r.nextSibling; - for (; r;) t(r, o) !== !0 && n(r, t, o), r = r.nextElementSibling; - return null - } - - function o(e, n) { - for (var o = e.shadowRoot; o;) t(o, n), o = o.olderShadowRoot - } - - function r(e, t) { - i(e, t, []) - } - - function i(e, t, n) { - if (e = window.wrap(e), !(n.indexOf(e) >= 0)) { - n.push(e); - for (var o, r = e.querySelectorAll("link[rel=" + a + "]"), s = 0, c = r.length; s < c && (o = r[s]); s++) o["import"] && i(o["import"], t, n); - t(e) - } - } - var a = window.HTMLImports ? window.HTMLImports.IMPORT_LINK_TYPE : "none"; - e.forDocumentTree = r, e.forSubtree = t - }), window.CustomElements.addModule(function(e) { - function t(e, t) { - return n(e, t) || o(e, t) - } - - function n(t, n) { - return !!e.upgrade(t, n) || void(n && a(t)) - } - - function o(e, t) { - g(e, function(e) { - if (n(e, t)) return !0 - }) - } - - function r(e) { - L.push(e), E || (E = !0, setTimeout(i)) - } - - function i() { - E = !1; - for (var e, t = L, n = 0, o = t.length; n < o && (e = t[n]); n++) e(); - L = [] - } - - function a(e) { - y ? r(function() { - s(e); - }) : s(e) - } - - function s(e) { - e.__upgraded__ && !e.__attached && (e.__attached = !0, e.attachedCallback && e.attachedCallback()) - } - - function c(e) { - d(e), g(e, function(e) { - d(e) - }) - } - - function d(e) { - y ? r(function() { - l(e) - }) : l(e) - } - - function l(e) { - e.__upgraded__ && e.__attached && (e.__attached = !1, e.detachedCallback && e.detachedCallback()) - } - - function u(e) { - for (var t = e, n = window.wrap(document); t;) { - if (t == n) return !0; - t = t.parentNode || t.nodeType === Node.DOCUMENT_FRAGMENT_NODE && t.host - } - } - - function h(e) { - if (e.shadowRoot && !e.shadowRoot.__watched) { - _.dom && console.log("watching shadow-root for: ", e.localName); - for (var t = e.shadowRoot; t;) m(t), t = t.olderShadowRoot - } - } - - function f(e, n) { - if (_.dom) { - var o = n[0]; - if (o && "childList" === o.type && o.addedNodes && o.addedNodes) { - for (var r = o.addedNodes[0]; r && r !== document && !r.host;) r = r.parentNode; - var i = r && (r.URL || r._URL || r.host && r.host.localName) || ""; - i = i.split("/?").shift().split("/").pop() - } - console.group("mutations (%d) [%s]", n.length, i || "") - } - var a = u(e); - n.forEach(function(e) { - "childList" === e.type && (N(e.addedNodes, function(e) { - e.localName && t(e, a) - }), N(e.removedNodes, function(e) { - e.localName && c(e) - })) - }), _.dom && console.groupEnd() - } - - function p(e) { - for (e = window.wrap(e), e || (e = window.wrap(document)); e.parentNode;) e = e.parentNode; - var t = e.__observer; - t && (f(e, t.takeRecords()), i()) - } - - function m(e) { - if (!e.__observer) { - var t = new MutationObserver(f.bind(this, e)); - t.observe(e, { - childList: !0, - subtree: !0 - }), e.__observer = t - } - } - - function v(e) { - e = window.wrap(e), _.dom && console.group("upgradeDocument: ", e.baseURI.split("/").pop()); - var n = e === window.wrap(document); - t(e, n), m(e), _.dom && console.groupEnd() - } - - function w(e) { - b(e, v) - } - var _ = e.flags, - g = e.forSubtree, - b = e.forDocumentTree, - y = window.MutationObserver._isPolyfilled && _["throttle-attached"]; - e.hasPolyfillMutations = y, e.hasThrottledAttached = y; - var E = !1, - L = [], - N = Array.prototype.forEach.call.bind(Array.prototype.forEach), - M = Element.prototype.createShadowRoot; - M && (Element.prototype.createShadowRoot = function() { - var e = M.call(this); - return window.CustomElements.watchShadow(this), e - }), e.watchShadow = h, e.upgradeDocumentTree = w, e.upgradeDocument = v, e.upgradeSubtree = o, e.upgradeAll = t, e.attached = a, e.takeRecords = p - }), window.CustomElements.addModule(function(e) { - function t(t, o) { - if ("template" === t.localName && window.HTMLTemplateElement && HTMLTemplateElement.decorate && HTMLTemplateElement.decorate(t), !t.__upgraded__ && t.nodeType === Node.ELEMENT_NODE) { - var r = t.getAttribute("is"), - i = e.getRegisteredDefinition(t.localName) || e.getRegisteredDefinition(r); - if (i && (r && i.tag == t.localName || !r && !i["extends"])) return n(t, i, o) - } - } - - function n(t, n, r) { - return a.upgrade && console.group("upgrade:", t.localName), n.is && t.setAttribute("is", n.is), o(t, n), t.__upgraded__ = !0, i(t), r && e.attached(t), e.upgradeSubtree(t, r), a.upgrade && console.groupEnd(), t - } - - function o(e, t) { - Object.__proto__ ? e.__proto__ = t.prototype : (r(e, t.prototype, t["native"]), e.__proto__ = t.prototype) - } - - function r(e, t, n) { - for (var o = {}, r = t; r !== n && r !== HTMLElement.prototype;) { - for (var i, a = Object.getOwnPropertyNames(r), s = 0; i = a[s]; s++) o[i] || (Object.defineProperty(e, i, Object.getOwnPropertyDescriptor(r, i)), o[i] = 1); - r = Object.getPrototypeOf(r) - } - } - - function i(e) { - e.createdCallback && e.createdCallback() - } - var a = e.flags; - e.upgrade = t, e.upgradeWithDefinition = n, e.implementPrototype = o - }), window.CustomElements.addModule(function(e) { - function t(t, o) { - var c = o || {}; - if (!t) throw new Error("document.registerElement: first argument `name` must not be empty"); - if (t.indexOf("-") < 0) throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(t) + "'."); - if (r(t)) throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(t) + "'. The type name is invalid."); - if (d(t)) throw new Error("DuplicateDefinitionError: a type with name '" + String(t) + "' is already registered"); - return c.prototype || (c.prototype = Object.create(HTMLElement.prototype)), c.__name = t.toLowerCase(), c["extends"] && (c["extends"] = c["extends"].toLowerCase()), c.lifecycle = c.lifecycle || {}, c.ancestry = i(c["extends"]), a(c), s(c), n(c.prototype), l(c.__name, c), c.ctor = u(c), c.ctor.prototype = c.prototype, c.prototype.constructor = c.ctor, e.ready && v(document), c.ctor - } - - function n(e) { - if (!e.setAttribute._polyfilled) { - var t = e.setAttribute; - e.setAttribute = function(e, n) { - o.call(this, e, n, t) - }; - var n = e.removeAttribute; - e.removeAttribute = function(e) { - o.call(this, e, null, n) - }, e.setAttribute._polyfilled = !0 - } - } - - function o(e, t, n) { - e = e.toLowerCase(); - var o = this.getAttribute(e); - n.apply(this, arguments); - var r = this.getAttribute(e); - this.attributeChangedCallback && r !== o && this.attributeChangedCallback(e, o, r) - } - - function r(e) { - for (var t = 0; t < y.length; t++) - if (e === y[t]) return !0 - } - - function i(e) { - var t = d(e); - return t ? i(t["extends"]).concat([t]) : [] - } - - function a(e) { - for (var t, n = e["extends"], o = 0; t = e.ancestry[o]; o++) n = t.is && t.tag; - e.tag = n || e.__name, n && (e.is = e.__name) - } - - function s(e) { - if (!Object.__proto__) { - var t = HTMLElement.prototype; - if (e.is) { - var n = document.createElement(e.tag); - t = Object.getPrototypeOf(n) - } - for (var o, r = e.prototype, i = !1; r;) r == t && (i = !0), o = Object.getPrototypeOf(r), o && (r.__proto__ = o), r = o; - i || console.warn(e.tag + " prototype not found in prototype chain for " + e.is), e["native"] = t - } - } - - function c(e) { - return _(N(e.tag), e) - } - - function d(e) { - if (e) return E[e.toLowerCase()] - } - - function l(e, t) { - E[e] = t - } - - function u(e) { - return function() { - return c(e) - } - } - - function h(e, t, n) { - return e === L ? f(t, n) : M(e, t) - } - - function f(e, t) { - e && (e = e.toLowerCase()), t && (t = t.toLowerCase()); - var n = d(t || e); - if (n) { - if (e == n.tag && t == n.is) return new n.ctor; - if (!t && !n.is) return new n.ctor - } - var o; - return t ? (o = f(e), o.setAttribute("is", t), o) : (o = N(e), e.indexOf("-") >= 0 && g(o, HTMLElement), o) - } - - function p(e, t) { - var n = e[t]; - e[t] = function() { - var e = n.apply(this, arguments); - return w(e), e - } - } - var m, v = (e.isIE, e.upgradeDocumentTree), - w = e.upgradeAll, - _ = e.upgradeWithDefinition, - g = e.implementPrototype, - b = e.useNative, - y = ["annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph"], - E = {}, - L = "http://www.w3.org/1999/xhtml", - N = document.createElement.bind(document), - M = document.createElementNS.bind(document); - m = Object.__proto__ || b ? function(e, t) { - return e instanceof t - } : function(e, t) { - if (e instanceof t) return !0; - for (var n = e; n;) { - if (n === t.prototype) return !0; - n = n.__proto__ - } - return !1 - }, p(Node.prototype, "cloneNode"), p(document, "importNode"), document.registerElement = t, document.createElement = f, document.createElementNS = h, e.registry = E, e["instanceof"] = m, e.reservedTagList = y, e.getRegisteredDefinition = d, document.register = document.registerElement - }), - function(e) { - function t() { - i(window.wrap(document)), window.CustomElements.ready = !0; - var e = window.requestAnimationFrame || function(e) { - setTimeout(e, 16) - }; - e(function() { - setTimeout(function() { - window.CustomElements.readyTime = Date.now(), window.HTMLImports && (window.CustomElements.elapsed = window.CustomElements.readyTime - window.HTMLImports.readyTime), document.dispatchEvent(new CustomEvent("WebComponentsReady", { - bubbles: !0 - })) - }) - }) - } - var n = e.useNative, - o = e.initializeModules; - e.isIE; - if (n) { - var r = function() {}; - e.watchShadow = r, e.upgrade = r, e.upgradeAll = r, e.upgradeDocumentTree = r, e.upgradeSubtree = r, e.takeRecords = r, e["instanceof"] = function(e, t) { - return e instanceof t - } - } else o(); - var i = e.upgradeDocumentTree, - a = e.upgradeDocument; - if (window.wrap || (window.ShadowDOMPolyfill ? (window.wrap = window.ShadowDOMPolyfill.wrapIfNeeded, window.unwrap = window.ShadowDOMPolyfill.unwrapIfNeeded) : window.wrap = window.unwrap = function(e) { - return e - }), window.HTMLImports && (window.HTMLImports.__importsParsingHook = function(e) { - e["import"] && a(wrap(e["import"])) - }), "complete" === document.readyState || e.flags.eager) t(); - else if ("interactive" !== document.readyState || window.attachEvent || window.HTMLImports && !window.HTMLImports.ready) { - var s = window.HTMLImports && !window.HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded"; - window.addEventListener(s, t) - } else t() - }(window.CustomElements), - function(e) { - var t = document.createElement("style"); - t.textContent = "body {transition: opacity ease-in 0.2s; } \nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \n"; - var n = document.querySelector("head"); - n.insertBefore(t, n.firstChild) - }(window.WebComponents); \ No newline at end of file diff --git a/src/bundle.js b/src/bundle.js index 86e10aab7d..6931b34dd0 100644 --- a/src/bundle.js +++ b/src/bundle.js @@ -4,41 +4,89 @@ // Use define from require.js not webpack's define var _define = window.define; +// document-register-element +var docRegister = require("document-register-element"); +_define("document-register-element", function() { + return docRegister; +}); + +// fetch +var fetch = require("whatwg-fetch"); +_define("fetch", function() { + return fetch +}); + // flvjs var flvjs = require("flv.js"); -_define("flvjs", function() { return flvjs; }); +_define("flvjs", function() { + return flvjs; +}); // jstree var jstree = require("jstree"); require("jstree/dist/themes/default/style.css"); -_define("jstree", function() { return jstree; }); +_define("jstree", function() { + return jstree; +}); // jquery var jquery = require("jquery"); -_define("jQuery", function() { return jquery; }); +_define("jQuery", function() { + return jquery; +}); // hlsjs var hlsjs = require("hls.js"); -_define("hlsjs", function() { return hlsjs; }); +_define("hlsjs", function() { + return hlsjs; +}); // howler var howler = require("howler"); -_define("howler", function() { return howler; }); +_define("howler", function() { + return howler; +}); + +// native-promise-only +var nativePromise = require("native-promise-only"); +_define("native-promise-only", function() { + return nativePromise; +}); + +// resize-observer-polyfill +var resize = require("resize-observer-polyfill"); +_define("resize-observer-polyfill", function() { + return resize; +}); // shaka var shaka = require("shaka-player"); -_define("shaka", function() { return shaka; }); +_define("shaka", function() { + return shaka; +}); // swiper var swiper = require("swiper"); require("swiper/dist/css/swiper.min.css"); -_define("swiper", function() { return swiper; }); +_define("swiper", function() { + return swiper; +}); // sortable var sortable = require("sortablejs"); -_define("sortable", function() { return sortable; }); +_define("sortable", function() { + return sortable; +}); + +// webcomponents +var webcomponents = require("webcomponents.js-2"); +_define("webcomponents", function() { + return webcomponents +}); // libjass var libjass = require("libjass"); require("libjass/libjass.css"); -_define("libjass", function() { return libjass; }); +_define("libjass", function() { + return libjass; +}); diff --git a/src/components/accessschedule/accessschedule.js b/src/components/accessschedule/accessschedule.js index cce626ae78..2f4be8b2a7 100644 --- a/src/components/accessschedule/accessschedule.js +++ b/src/components/accessschedule/accessschedule.js @@ -1,19 +1,33 @@ -define(["dialogHelper", "datetime", "emby-select", "paper-icon-button-light", "formDialogStyle"], function(dialogHelper, datetime) { +define(["dialogHelper", "datetime", "emby-select", "paper-icon-button-light", "formDialogStyle"], function (dialogHelper, datetime) { "use strict"; function getDisplayTime(hours) { - var minutes = 0, - pct = hours % 1; - return pct && (minutes = parseInt(60 * pct)), datetime.getDisplayTime(new Date(2e3, 1, 1, hours, minutes, 0, 0)) + var minutes = 0; + var pct = hours % 1; + + if (pct) { + minutes = parseInt(60 * pct); + } + + return datetime.getDisplayTime(new Date(2000, 1, 1, hours, minutes, 0, 0)); } function populateHours(context) { - for (var html = "", i = 0; i < 24; i++) html += '"; - html += '", context.querySelector("#selectStart").innerHTML = html, context.querySelector("#selectEnd").innerHTML = html + var html = ""; + + for (var i = 0; i < 24; i++) { + html += '"; + } + + html += '"; + context.querySelector("#selectStart").innerHTML = html; + context.querySelector("#selectEnd").innerHTML = html; } function loadSchedule(context, schedule) { - context.querySelector("#selectDay").value = schedule.DayOfWeek || "Sunday", context.querySelector("#selectStart").value = schedule.StartHour || 0, context.querySelector("#selectEnd").value = schedule.EndHour || 0 + context.querySelector("#selectDay").value = schedule.DayOfWeek || "Sunday"; + context.querySelector("#selectStart").value = schedule.StartHour || 0; + context.querySelector("#selectEnd").value = schedule.EndHour || 0; } function submitSchedule(context, options) { @@ -22,30 +36,54 @@ define(["dialogHelper", "datetime", "emby-select", "paper-icon-button-light", "f StartHour: context.querySelector("#selectStart").value, EndHour: context.querySelector("#selectEnd").value }; - if (parseFloat(updatedSchedule.StartHour) >= parseFloat(updatedSchedule.EndHour)) return void alert(Globalize.translate("ErrorMessageStartHourGreaterThanEnd")); - context.submitted = !0, options.schedule = Object.assign(options.schedule, updatedSchedule), dialogHelper.close(context) + + if (parseFloat(updatedSchedule.StartHour) >= parseFloat(updatedSchedule.EndHour)) { + return void alert(Globalize.translate("ErrorMessageStartHourGreaterThanEnd")); + } + + context.submitted = true; + options.schedule = Object.assign(options.schedule, updatedSchedule); + dialogHelper.close(context); } + return { - show: function(options) { - return new Promise(function(resolve, reject) { - var xhr = new XMLHttpRequest; - xhr.open("GET", "components/accessschedule/accessschedule.template.html", !0), xhr.onload = function(e) { - var template = this.response, - dlg = dialogHelper.createDialog({ - removeOnClose: !0, - size: "small" - }); + show: function (options) { + return new Promise(function (resolve, reject) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", "components/accessschedule/accessschedule.template.html", true); + + xhr.onload = function (e) { + var template = this.response; + var dlg = dialogHelper.createDialog({ + removeOnClose: true, + size: "small" + }); dlg.classList.add("formDialog"); var html = ""; - html += Globalize.translateDocument(template), dlg.innerHTML = html, populateHours(dlg), loadSchedule(dlg, options.schedule), dialogHelper.open(dlg), dlg.addEventListener("close", function() { - dlg.submitted ? resolve(options.schedule) : reject() - }), dlg.querySelector(".btnCancel").addEventListener("click", function(e) { - dialogHelper.close(dlg) - }), dlg.querySelector("form").addEventListener("submit", function(e) { - return submitSchedule(dlg, options), e.preventDefault(), !1 - }) - }, xhr.send() - }) + html += Globalize.translateDocument(template); + dlg.innerHTML = html; + populateHours(dlg); + loadSchedule(dlg, options.schedule); + dialogHelper.open(dlg); + dlg.addEventListener("close", function () { + if (dlg.submitted) { + resolve(options.schedule); + } else { + reject(); + } + }); + dlg.querySelector(".btnCancel").addEventListener("click", function (e) { + dialogHelper.close(dlg); + }); + dlg.querySelector("form").addEventListener("submit", function (e) { + submitSchedule(dlg, options); + e.preventDefault(); + return false; + }); + }; + + xhr.send(); + }); } - } -}); \ No newline at end of file + }; +}); diff --git a/src/components/actionsheet/actionsheet.js b/src/components/actionsheet/actionsheet.js index 54b6aeddf2..46a7cedf1e 100644 --- a/src/components/actionsheet/actionsheet.js +++ b/src/components/actionsheet/actionsheet.js @@ -139,7 +139,9 @@ define(['dialogHelper', 'layoutManager', 'globalize', 'browser', 'dom', 'emby-bu style += "min-width:" + minWidth + "px;"; } - var i, length, option; + var i; + var length; + var option; var renderIcon = false; var icons = []; var itemIcon; @@ -225,8 +227,7 @@ define(['dialogHelper', 'layoutManager', 'globalize', 'browser', 'dom', 'emby-bu if (itemIcon) { html += '' + itemIcon + ''; - } - else if (renderIcon && !center) { + } else if (renderIcon && !center) { html += ''; } diff --git a/src/components/activitylog.js b/src/components/activitylog.js index 2556680a6a..e02fb0c868 100644 --- a/src/components/activitylog.js +++ b/src/components/activitylog.js @@ -1,15 +1,17 @@ -define(["events", "globalize", "dom", "datetime", "userSettings", "serverNotifications", "connectionManager", "emby-button", "listViewStyle"], function(events, globalize, dom, datetime, userSettings, serverNotifications, connectionManager) { +define(["events", "globalize", "dom", "datetime", "userSettings", "serverNotifications", "connectionManager", "emby-button", "listViewStyle"], function (events, globalize, dom, datetime, userSettings, serverNotifications, connectionManager) { "use strict"; function getEntryHtml(entry, apiClient) { var html = ""; html += '
'; var color = "#00a4dc"; - var icon = "notifications"; + var icon = "notifications"; + if ("Error" == entry.Severity || "Fatal" == entry.Severity || "Warn" == entry.Severity) { color = "#cc0000"; icon = "notification_important"; } + if (entry.UserId && entry.UserPrimaryImageTag) { html += '' + icon + ''; } - html += '
', html += '
', html += entry.Name, html += "
", html += '
'; - var date = datetime.parseISO8601Date(entry.Date, !0); - return html += datetime.toLocaleString(date).toLowerCase(), html += "
", html += '
', html += entry.ShortOverview || "", html += "
", html += "
", entry.Overview && (html += ''), html += "
" + + html += '
'; + html += '
'; + html += entry.Name; + html += "
"; + html += '
'; + var date = datetime.parseISO8601Date(entry.Date, true); + html += datetime.toLocaleString(date).toLowerCase(); + html += "
"; + html += '
'; + html += entry.ShortOverview || ""; + html += "
"; + html += "
"; + + if (entry.Overview) { + html += ''; + } + + return html += ""; } function renderList(elem, apiClient, result, startIndex, limit) { - elem.innerHTML = result.Items.map(function(i) { - return getEntryHtml(i, apiClient) - }).join("") + elem.innerHTML = result.Items.map(function (i) { + return getEntryHtml(i, apiClient); + }).join(""); } function reloadData(instance, elem, apiClient, startIndex, limit) { - null == startIndex && (startIndex = parseInt(elem.getAttribute("data-activitystartindex") || "0")), limit = limit || parseInt(elem.getAttribute("data-activitylimit") || "7"); - var minDate = new Date, - hasUserId = "false" !== elem.getAttribute("data-useractivity"); - hasUserId ? minDate.setTime(minDate.getTime() - 864e5) : minDate.setTime(minDate.getTime() - 6048e5), ApiClient.getJSON(ApiClient.getUrl("System/ActivityLog/Entries", { + if (null == startIndex) { + startIndex = parseInt(elem.getAttribute("data-activitystartindex") || "0"); + } + + limit = limit || parseInt(elem.getAttribute("data-activitylimit") || "7"); + var minDate = new Date(); + var hasUserId = "false" !== elem.getAttribute("data-useractivity"); + + if (hasUserId) { + minDate.setTime(minDate.getTime() - 24 * 60 * 60 * 1000); // one day back + } else { + minDate.setTime(minDate.getTime() - 7 * 24 * 60 * 60 * 1000); // one week back + } + + ApiClient.getJSON(ApiClient.getUrl("System/ActivityLog/Entries", { startIndex: startIndex, limit: limit, minDate: minDate.toISOString(), hasUserId: hasUserId - })).then(function(result) { - if (elem.setAttribute("data-activitystartindex", startIndex), elem.setAttribute("data-activitylimit", limit), !startIndex) { + })).then(function (result) { + elem.setAttribute("data-activitystartindex", startIndex); + elem.setAttribute("data-activitylimit", limit); + if (!startIndex) { var activityContainer = dom.parentWithClass(elem, "activityContainer"); - activityContainer && (result.Items.length ? activityContainer.classList.remove("hide") : activityContainer.classList.add("hide")) + + if (activityContainer) { + if (result.Items.length) { + activityContainer.classList.remove("hide"); + } else { + activityContainer.classList.add("hide"); + } + } } - instance.items = result.Items, renderList(elem, apiClient, result, startIndex, limit) - }) + + instance.items = result.Items; + renderList(elem, apiClient, result, startIndex, limit); + }); } function onActivityLogUpdate(e, apiClient, data) { var options = this.options; - options && options.serverId === apiClient.serverId() && reloadData(this, options.element, apiClient) + + if (options && options.serverId === apiClient.serverId()) { + reloadData(this, options.element, apiClient); + } } function onListClick(e) { var btnEntryInfo = dom.parentWithClass(e.target, "btnEntryInfo"); + if (btnEntryInfo) { - var id = btnEntryInfo.getAttribute("data-id"), - items = this.items; + var id = btnEntryInfo.getAttribute("data-id"); + var items = this.items; + if (items) { - var item = items.filter(function(i) { - return i.Id.toString() === id + var item = items.filter(function (i) { + return i.Id.toString() === id; })[0]; - item && showItemOverview(item) + + if (item) { + showItemOverview(item); + } } } } function showItemOverview(item) { - require(["alert"], function(alert) { + require(["alert"], function (alert) { alert({ text: item.Overview - }) - }) + }); + }); } function ActivityLog(options) { this.options = options; var element = options.element; - element.classList.add("activityLogListWidget"), element.addEventListener("click", onListClick.bind(this)); + element.classList.add("activityLogListWidget"); + element.addEventListener("click", onListClick.bind(this)); var apiClient = connectionManager.getApiClient(options.serverId); reloadData(this, element, apiClient); var onUpdate = onActivityLogUpdate.bind(this); - this.updateFn = onUpdate, events.on(serverNotifications, "ActivityLogEntry", onUpdate), apiClient.sendMessage("ActivityLogEntryStart", "0,1500") + this.updateFn = onUpdate; + events.on(serverNotifications, "ActivityLogEntry", onUpdate); + apiClient.sendMessage("ActivityLogEntryStart", "0,1500"); } - return ActivityLog.prototype.destroy = function() { + + ActivityLog.prototype.destroy = function () { var options = this.options; + if (options) { options.element.classList.remove("activityLogListWidget"); - connectionManager.getApiClient(options.serverId).sendMessage("ActivityLogEntryStop", "0,1500") + connectionManager.getApiClient(options.serverId).sendMessage("ActivityLogEntryStop", "0,1500"); } + var onUpdate = this.updateFn; - onUpdate && events.off(serverNotifications, "ActivityLogEntry", onUpdate), this.items = null, this.options = null - }, ActivityLog + + if (onUpdate) { + events.off(serverNotifications, "ActivityLogEntry", onUpdate); + } + + this.items = null; + this.options = null; + }; + + return ActivityLog; }); diff --git a/src/components/alert.js b/src/components/alert.js index 6cf7fea75d..8a4dc11c20 100644 --- a/src/components/alert.js +++ b/src/components/alert.js @@ -35,7 +35,7 @@ define(['browser', 'dialog', 'globalize'], function (browser, dialog, globalize) if (result === 'ok') { return Promise.resolve(); } - + return Promise.reject(); }); } diff --git a/src/components/alphapicker/alphapicker.js b/src/components/alphapicker/alphapicker.js index 4cf77f451a..ac2ea9e676 100644 --- a/src/components/alphapicker/alphapicker.js +++ b/src/components/alphapicker/alphapicker.js @@ -50,9 +50,7 @@ define(['focusManager', 'layoutManager', 'dom', 'css!./style.css', 'paper-icon-b var vertical = element.classList.contains('alphaPicker-vertical'); - if (vertical) { - - } else { + if (!vertical) { element.classList.add('focuscontainer-x'); } @@ -230,7 +228,8 @@ define(['focusManager', 'layoutManager', 'dom', 'css!./style.css', 'paper-icon-b AlphaPicker.prototype.value = function (value, applyValue) { var element = this.options.element; - var btn, selected; + var btn; + var selected; if (value !== undefined) { if (value != null) { diff --git a/src/components/apphost.js b/src/components/apphost.js index e67d795227..ad3540e210 100644 --- a/src/components/apphost.js +++ b/src/components/apphost.js @@ -313,7 +313,7 @@ define(["appSettings", "browser", "events", "htmlMediaHelper"], function (appSet var deviceId; var deviceName; var appName = "Jellyfin Web"; - var appVersion = "10.4.0"; + var appVersion = "10.5.0"; var visibilityChange; var visibilityState; diff --git a/src/components/cardbuilder/card.css b/src/components/cardbuilder/card.css index 942e05c77a..1414fd8391 100644 --- a/src/components/cardbuilder/card.css +++ b/src/components/cardbuilder/card.css @@ -26,24 +26,12 @@ button { font-weight: inherit !important; } -.card-nofocustransform { +.card:not(.show-animation) { contain: layout style paint; } .itemsContainer { display: flex; - margin-left: -0.6em; - margin-right: -0.6em; -} - -/* TODO replace this with a proper fix */ -/* doesnt work on mobile devices */ -/* negative margin fixes annoying misalignment with cards and title */ -@media all and (max-width:50em) { - .itemsContainer { - margin-left: 0; - margin-right: 0; - } } .vertical-list { @@ -98,20 +86,21 @@ button { contain: layout style; } -.cardBox-withfocuscontent-large { +.card.show-focus:not(.show-animation) .cardBox { margin: .4em; } -.card-focuscontent-large { +.card.show-focus:not(.show-animation) .cardBox.visualCardBox, +.card.show-focus:not(.show-animation) .cardBox:not(.visualCardBox) .cardScalable { border: .5em solid transparent; } -.cardBox-focustransform { +.card.show-animation .cardBox { will-change: transform; transition: transform 200ms ease-out; } -.card:focus > .cardBox-focustransform { +.card.show-animation:focus > .cardBox { transform: scale(1.18, 1.18); } @@ -363,9 +352,6 @@ button { vertical-align: middle; font-family: inherit; font-size: inherit; - /*display: flex; - align-items: center; - justify-content: center;*/ } .textActionButton:hover { diff --git a/src/components/cardbuilder/cardBuilder.js b/src/components/cardbuilder/cardBuilder.js index d91802dc71..6e9340e1b8 100644 --- a/src/components/cardbuilder/cardBuilder.js +++ b/src/components/cardbuilder/cardBuilder.js @@ -3,7 +3,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana 'use strict'; var devicePixelRatio = window.devicePixelRatio || 1; - var enableFocusTransfrom = !browser.slow && !browser.edge; + var enableFocusTransform = !browser.slow && !browser.edge; function getCardsHtml(items, options) { if (arguments.length === 1) { @@ -321,7 +321,8 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana var apiClient; var lastServerId; - var i, length; + var i; + var length; for (i = 0, length = items.length; i < length; i++) { @@ -339,19 +340,14 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana if (options.indexBy === 'PremiereDate') { if (item.PremiereDate) { try { - newIndexValue = datetime.toLocaleDateString(datetime.parseISO8601Date(item.PremiereDate), { weekday: 'long', month: 'long', day: 'numeric' }); - } catch (err) { + console.log('error parsing timestamp for premiere date'); } } - } - - else if (options.indexBy === 'ProductionYear') { + } else if (options.indexBy === 'ProductionYear') { newIndexValue = item.ProductionYear; - } - - else if (options.indexBy === 'CommunityRating') { + } else if (options.indexBy === 'CommunityRating') { newIndexValue = item.CommunityRating ? (Math.floor(item.CommunityRating) + (item.CommunityRating % 1 >= 0.5 ? 0.5 : 0)) + '+' : null; } @@ -571,22 +567,19 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana coverImage = (Math.abs(primaryImageAspectRatio - uiAspect) / uiAspect) <= 0.2; } } - } - else if (item.ParentPrimaryImageTag) { + } else if (item.ParentPrimaryImageTag) { imgUrl = apiClient.getScaledImageUrl(item.ParentPrimaryImageItemId, { type: "Primary", tag: item.ParentPrimaryImageTag }); - } - else if (item.SeriesPrimaryImageTag) { + } else if (item.SeriesPrimaryImageTag) { imgUrl = apiClient.getScaledImageUrl(item.SeriesId, { type: "Primary", tag: item.SeriesPrimaryImageTag }); - } - else if (item.AlbumId && item.AlbumPrimaryImageTag) { + } else if (item.AlbumId && item.AlbumPrimaryImageTag) { width = primaryImageAspectRatio ? Math.round(height * primaryImageAspectRatio) : null; @@ -601,16 +594,14 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana coverImage = (Math.abs(primaryImageAspectRatio - uiAspect) / uiAspect) <= 0.2; } } - } - else if (item.Type === 'Season' && item.ImageTags && item.ImageTags.Thumb) { + } else if (item.Type === 'Season' && item.ImageTags && item.ImageTags.Thumb) { imgUrl = apiClient.getScaledImageUrl(item.Id, { type: "Thumb", tag: item.ImageTags.Thumb }); - } - else if (item.BackdropImageTags && item.BackdropImageTags.length) { + } else if (item.BackdropImageTags && item.BackdropImageTags.length) { imgUrl = apiClient.getScaledImageUrl(item.Id, { type: "Backdrop", @@ -681,7 +672,8 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana var html = ''; var valid = 0; - var i, length; + var i; + var length; for (i = 0, length = lines.length; i < length; i++) { @@ -745,8 +737,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana date = datetime.parseISO8601Date(item.EndDate); airTimeText += ' - ' + datetime.getDisplayTime(date); } - } - catch (e) { + } catch (e) { console.log("Error parsing date: " + item.StartDate); } } @@ -794,8 +785,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana } else { lines.push(item.SeriesName); } - } - else { + } else { if (isUsingLiveTvNaming(item)) { @@ -976,8 +966,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana if (options.showSeriesTimerChannel) { if (item.RecordAnyChannel) { lines.push(globalize.translate('AllChannels')); - } - else { + } else { lines.push(item.ChannelName || globalize.translate('OneChannel')); } } @@ -985,8 +974,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana if (options.showPersonRoleOrType) { if (item.Role) { lines.push('as ' + item.Role); - } - else if (item.Type) { + } else if (item.Type) { lines.push(globalize.translate('' + item.Type)); } else { lines.push(''); @@ -1060,8 +1048,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana counts.push(childText); - } - else if (item.Type === 'Genre' || item.Type === 'Studio') { + } else if (item.Type === 'Genre' || item.Type === 'Studio') { if (item.MovieCount) { @@ -1140,8 +1127,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana if (item.IsPremiere) { html += '
' + globalize.translate('Premiere') + '
'; - } - else if (item.IsSeries && !item.IsRepeat) { + } else if (item.IsSeries && !item.IsRepeat) { html += '
' + globalize.translate('AttributeNew') + '
'; } //else if (item.IsRepeat) { @@ -1176,8 +1162,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana if (action === 'play' && item.IsFolder) { // If this hard-coding is ever removed make sure to test nested photo albums action = 'link'; - } - else if (item.MediaType === 'Photo') { + } else if (item.MediaType === 'Photo') { action = 'play'; } @@ -1203,6 +1188,8 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana shape = shape || 'mixedSquare'; } + // TODO move card creation code to Card component + var className = 'card'; if (shape) { @@ -1221,8 +1208,12 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana className += ' card-hoverable'; } - if (!enableFocusTransfrom || !layoutManager.tv) { - className += ' card-nofocustransform'; + if (layoutManager.tv) { + className += ' show-focus'; + + if (enableFocusTransform) { + className += ' show-animation'; + } } var imgInfo = getCardImageUrl(item, apiClient, options, shape); @@ -1250,23 +1241,6 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana var cardBoxClass = options.cardLayout ? 'cardBox visualCardBox' : 'cardBox'; - if (layoutManager.tv) { - - if (enableFocusTransfrom) { - cardBoxClass += ' cardBox-focustransform cardBox-withfocuscontent'; - } else { - cardBoxClass += ' cardBox-withfocuscontent-large'; - } - - if (options.cardLayout) { - cardBoxClass += ' card-focuscontent'; - - if (!enableFocusTransfrom) { - cardBoxClass += ' card-focuscontent-large'; - } - } - } - var footerCssClass; var progressHtml = indicators.getProgressBarHtml(item); @@ -1283,8 +1257,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana height: logoHeight, tag: item.ChannelPrimaryImageTag }); - } - else if (options.showLogo && item.ParentLogoImageTag) { + } else if (options.showLogo && item.ParentLogoImageTag) { logoUrl = apiClient.getScaledImageUrl(item.ParentLogoItemId, { type: "Logo", height: logoHeight, @@ -1299,8 +1272,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana footerCssClass = progressHtml ? 'innerCardFooter fullInnerCardFooter' : 'innerCardFooter'; innerCardFooter += getCardFooterText(item, apiClient, options, showTitle, forceName, overlayText, imgUrl, footerCssClass, progressHtml, logoUrl, false); footerOverlayed = true; - } - else if (progressHtml) { + } else if (progressHtml) { innerCardFooter += '
'; innerCardFooter += progressHtml; innerCardFooter += '
'; @@ -1385,15 +1357,6 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana var cardScalableClass = 'cardScalable'; - if (layoutManager.tv && !options.cardLayout) { - - cardScalableClass += ' card-focuscontent'; - - if (!enableFocusTransfrom) { - cardScalableClass += ' card-focuscontent-large'; - } - } - cardImageContainerOpen = '
' + cardImageContainerOpen; cardBoxClose = '
'; cardScalableClose = '
'; @@ -1414,8 +1377,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana indicatorsHtml += indicators.getChildCountIndicatorHtml(item, { minCount: 1 }); - } - else { + } else { indicatorsHtml += indicators.getPlayedIndicatorHtml(item); } @@ -1676,8 +1638,7 @@ define(['datetime', 'imageLoader', 'connectionManager', 'itemHelper', 'focusMana } itemProgressBar.innerHTML = progressHtml; - } - else { + } else { itemProgressBar = card.querySelector('.itemProgressBar'); if (itemProgressBar) { diff --git a/src/components/cardbuilder/chaptercardbuilder.js b/src/components/cardbuilder/chaptercardbuilder.js index 900f4befc1..0f42e14584 100644 --- a/src/components/cardbuilder/chaptercardbuilder.js +++ b/src/components/cardbuilder/chaptercardbuilder.js @@ -1,12 +1,20 @@ define(['datetime', 'imageLoader', 'connectionManager', 'layoutManager', 'browser'], function (datetime, imageLoader, connectionManager, layoutManager, browser) { 'use strict'; + var enableFocusTransform = !browser.slow && !browser.edge; + function buildChapterCardsHtml(item, chapters, options) { + // TODO move card creation code to Card component + var className = 'card itemAction chapterCard'; - if (layoutManager.tv && (browser.animate || browser.edge)) { - className += ' card-focusscale'; + if (layoutManager.tv) { + className += ' show-focus'; + + if (enableFocusTransform) { + className += ' show-animation'; + } } var mediaStreams = ((item.MediaSources || [])[0] || {}).MediaStreams || []; @@ -92,19 +100,6 @@ define(['datetime', 'imageLoader', 'connectionManager', 'layoutManager', 'browse var cardBoxCssClass = 'cardBox'; var cardScalableClass = 'cardScalable'; - if (layoutManager.tv) { - var enableFocusTransfrom = !browser.slow && !browser.edge; - - cardScalableClass += ' card-focuscontent'; - - if (enableFocusTransfrom) { - cardBoxCssClass += ' cardBox-focustransform cardBox-withfocuscontent'; - } else { - cardBoxCssClass += ' cardBox-withfocuscontent-large'; - cardScalableClass += ' card-focuscontent-large'; - } - } - var html = ''; return html; @@ -137,4 +132,4 @@ define(['datetime', 'imageLoader', 'connectionManager', 'layoutManager', 'browse buildChapterCards: buildChapterCards }; -}); \ No newline at end of file +}); diff --git a/src/components/channelmapper/channelmapper.js b/src/components/channelmapper/channelmapper.js index 2abf7e2c9e..841a6a81af 100644 --- a/src/components/channelmapper/channelmapper.js +++ b/src/components/channelmapper/channelmapper.js @@ -1,10 +1,16 @@ -define(["dialogHelper", "loading", "connectionManager", "globalize", "actionsheet", "emby-input", "paper-icon-button-light", "emby-button", "listViewStyle", "material-icons", "formDialogStyle"], function(dialogHelper, loading, connectionManager, globalize, actionsheet) { +define(["dialogHelper", "loading", "connectionManager", "globalize", "actionsheet", "emby-input", "paper-icon-button-light", "emby-button", "listViewStyle", "material-icons", "formDialogStyle"], function (dialogHelper, loading, connectionManager, globalize, actionsheet) { "use strict"; - return function(options) { + + return function (options) { function parentWithClass(elem, className) { - for (; !elem.classList || !elem.classList.contains(className);) - if (!(elem = elem.parentNode)) return null; - return elem + while (!elem.classList || !elem.classList.contains(className)) { + elem = elem.parentNode; + if (!elem) { + return null; + } + } + + return elem; } function mapChannel(button, channelId, providerChannelId) { @@ -19,33 +25,35 @@ define(["dialogHelper", "loading", "connectionManager", "globalize", "actionshee providerChannelId: providerChannelId }, dataType: "json" - }).then(function(mapping) { + }).then(function (mapping) { var listItem = parentWithClass(button, "listItem"); - button.setAttribute("data-providerid", mapping.ProviderChannelId), listItem.querySelector(".secondary").innerHTML = getMappingSecondaryName(mapping, currentMappingOptions.ProviderName), loading.hide() - }) + button.setAttribute("data-providerid", mapping.ProviderChannelId); + listItem.querySelector(".secondary").innerHTML = getMappingSecondaryName(mapping, currentMappingOptions.ProviderName); + loading.hide(); + }); } function onChannelsElementClick(e) { var btnMap = parentWithClass(e.target, "btnMap"); + if (btnMap) { var channelId = btnMap.getAttribute("data-id"); var providerChannelId = btnMap.getAttribute("data-providerid"); - var menuItems = currentMappingOptions.ProviderChannels.map(function(m) { + var menuItems = currentMappingOptions.ProviderChannels.map(function (m) { return { name: m.Name, id: m.Id, selected: m.Id.toLowerCase() === providerChannelId.toLowerCase() - } + }; }).sort(function (a, b) { return a.name.localeCompare(b.name); }); - actionsheet.show({ positionTo: btnMap, items: menuItems - }).then(function(newChannelId) { - mapChannel(btnMap, channelId, newChannelId) - }) + }).then(function (newChannelId) { + mapChannel(btnMap, channelId, newChannelId); + }); } } @@ -53,47 +61,87 @@ define(["dialogHelper", "loading", "connectionManager", "globalize", "actionshee var apiClient = connectionManager.getApiClient(serverId); return apiClient.getJSON(apiClient.getUrl("LiveTv/ChannelMappingOptions", { providerId: providerId - })) + })); } function getMappingSecondaryName(mapping, providerName) { - return (mapping.ProviderChannelName || "") + " - " + providerName + return (mapping.ProviderChannelName || "") + " - " + providerName; } function getTunerChannelHtml(channel, providerName) { var html = ""; - return html += '
', html += 'dvr', html += '
', html += '

', html += channel.Name, html += "

", html += '
', channel.ProviderChannelName && (html += getMappingSecondaryName(channel, providerName)), html += "
", html += "
", html += '', html += "
" + html += '
'; + html += 'dvr'; + html += '
'; + html += '

'; + html += channel.Name; + html += "

"; + html += '
'; + + if (channel.ProviderChannelName) { + html += getMappingSecondaryName(channel, providerName); + } + + html += "
"; + html += "
"; + html += ''; + return html += "
"; } function getEditorHtml() { var html = ""; - return html += '
', html += '
', html += '
', html += "

" + globalize.translate("HeaderChannels") + "

", html += '
', html += "
", html += "
", html += "
", html += "
" + html += '
'; + html += '
'; + html += '
'; + html += "

" + globalize.translate("HeaderChannels") + "

"; + html += '
'; + html += "
"; + html += "
"; + html += "
"; + return html += "
"; } function initEditor(dlg, options) { - getChannelMappingOptions(options.serverId, options.providerId).then(function(result) { + getChannelMappingOptions(options.serverId, options.providerId).then(function (result) { currentMappingOptions = result; var channelsElement = dlg.querySelector(".channels"); - channelsElement.innerHTML = result.TunerChannels.map(function(channel) { - return getTunerChannelHtml(channel, result.ProviderName) - }).join(""), channelsElement.addEventListener("click", onChannelsElementClick) - }) + channelsElement.innerHTML = result.TunerChannels.map(function (channel) { + return getTunerChannelHtml(channel, result.ProviderName); + }).join(""); + channelsElement.addEventListener("click", onChannelsElementClick); + }); } - var currentMappingOptions, self = this; - self.show = function() { + + var currentMappingOptions; + var self = this; + + self.show = function () { var dialogOptions = { - removeOnClose: !0 + removeOnClose: true }; dialogOptions.size = "small"; var dlg = dialogHelper.createDialog(dialogOptions); - dlg.classList.add("formDialog"), dlg.classList.add("ui-body-a"), dlg.classList.add("background-theme-a"); - var html = "", - title = globalize.translate("MapChannels"); - return html += '
', html += '', html += '

', html += title, html += "

", html += "
", html += getEditorHtml(), dlg.innerHTML = html, initEditor(dlg, options), dlg.querySelector(".btnCancel").addEventListener("click", function() { - dialogHelper.close(dlg) - }), new Promise(function(resolve, reject) { - dlg.addEventListener("close", resolve), dialogHelper.open(dlg) - }) - } - } + dlg.classList.add("formDialog"); + dlg.classList.add("ui-body-a"); + dlg.classList.add("background-theme-a"); + var html = ""; + var title = globalize.translate("MapChannels"); + html += '
'; + html += ''; + html += '

'; + html += title; + html += "

"; + html += "
"; + html += getEditorHtml(); + dlg.innerHTML = html; + initEditor(dlg, options); + dlg.querySelector(".btnCancel").addEventListener("click", function () { + dialogHelper.close(dlg); + }); + return new Promise(function (resolve, reject) { + dlg.addEventListener("close", resolve); + dialogHelper.open(dlg); + }); + }; + }; }); diff --git a/src/components/chromecast/chromecasthelpers.js b/src/components/chromecast/chromecasthelpers.js index 0beba824c0..9d6f811cb1 100644 --- a/src/components/chromecast/chromecasthelpers.js +++ b/src/components/chromecast/chromecasthelpers.js @@ -5,7 +5,7 @@ define(['events'], function (events) { // // https://github.com/ravisorg/LinkParser // - // Locate and extract almost any URL within a string. Handles protocol-less domains, IPv4 and + // Locate and extract almost any URL within a string. Handles protocol-less domains, IPv4 and // IPv6, unrecognised TLDs, and more. // // This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. @@ -14,26 +14,26 @@ define(['events'], function (events) { // Original URL regex from the Android android.text.util.Linkify function, found here: // http://stackoverflow.com/a/19696443 - // - // However there were problems with it, most probably related to the fact it was + // + // However there were problems with it, most probably related to the fact it was // written in 2007, and it's been highly modified. - // - // 1) I didn't like the fact that it was tied to specific TLDs, since new ones + // + // 1) I didn't like the fact that it was tied to specific TLDs, since new ones // are being added all the time it wouldn't be reasonable to expect developer to // be continually updating their regular expressions. - // - // 2) It didn't allow unicode characters in the domains which are now allowed in + // + // 2) It didn't allow unicode characters in the domains which are now allowed in // many languages, (including some IDN TLDs). Again these are constantly being // added to and it doesn't seem reasonable to hard-code them. Note this ended up // not being possible in standard JS due to the way it handles multibyte strings. // It is possible using XRegExp, however a big performance hit results. Disabled // for now. - // + // // 3) It didn't allow for IPv6 hostnames // IPv6 regex from http://stackoverflow.com/a/17871737 // // 4) It was very poorly commented - // + // // 5) It wasn't as smart as it could have been about what should be part of a // URL and what should be part of human language. @@ -102,8 +102,8 @@ define(['events'], function (events) { + "|(?:\\%[a-f0-9]{2})" // some characters are much more likely to be used AFTER a url and // were not intended to be included in the url itself. Mostly end - // of sentence type things. It's also likely that the URL would - // still work if any of these characters were missing from the end + // of sentence type things. It's also likely that the URL would + // still work if any of these characters were missing from the end // because we parsed it incorrectly. For these characters to be accepted // they must be followed by another character that we're reasonably // sure is part of the url diff --git a/src/components/chromecast/chromecastplayer.js b/src/components/chromecast/chromecastplayer.js index f3f7e6b865..7302b74124 100644 --- a/src/components/chromecast/chromecastplayer.js +++ b/src/components/chromecast/chromecastplayer.js @@ -479,8 +479,7 @@ define(['appSettings', 'userSettings', 'playbackManager', 'connectionManager', ' TotalRecordCount: 1 }; }); - } - else { + } else { query.Limit = query.Limit || 100; query.ExcludeLocationTypes = "Virtual"; @@ -752,8 +751,7 @@ define(['appSettings', 'userSettings', 'playbackManager', 'connectionManager', ' ChromecastPlayer.prototype.volumeDown = function () { var vol = this._castPlayer.session.receiver.volume.level; - if (vol == null) - { + if (vol == null) { vol = 0.5; } vol -= 0.05; @@ -776,8 +774,7 @@ define(['appSettings', 'userSettings', 'playbackManager', 'connectionManager', ' ChromecastPlayer.prototype.volumeUp = function () { var vol = this._castPlayer.session.receiver.volume.level; - if (vol == null) - { + if (vol == null) { vol = 0.5; } vol += 0.05; diff --git a/src/components/dialog/dialog.js b/src/components/dialog/dialog.js index 4f13b2d1bb..cfb5821b38 100644 --- a/src/components/dialog/dialog.js +++ b/src/components/dialog/dialog.js @@ -51,7 +51,8 @@ define(['dialogHelper', 'dom', 'layoutManager', 'scrollHelper', 'globalize', 're dlg.querySelector('.dialogContentInner').classList.add('hide'); } - var i, length; + var i; + var length; var html = ''; var hasDescriptions = false; diff --git a/src/components/dialogHelper/dialogHelper.js b/src/components/dialogHelper/dialogHelper.js index 36bb23bfd7..bddd839760 100644 --- a/src/components/dialogHelper/dialogHelper.js +++ b/src/components/dialogHelper/dialogHelper.js @@ -18,8 +18,7 @@ define(['appRouter', 'focusManager', 'browser', 'layoutManager', 'inputManager', if (layoutManager.tv) { if (dlg.classList.contains('scrollX')) { centerFocus(dlg, true, false); - } - else if (dlg.classList.contains('smoothScrollY')) { + } else if (dlg.classList.contains('smoothScrollY')) { centerFocus(dlg, false, false); } } @@ -168,8 +167,8 @@ define(['appRouter', 'focusManager', 'browser', 'layoutManager', 'inputManager', close(dlg); } }, { - passive: true - }); + passive: true + }); } function isHistoryEnabled(dlg) { @@ -433,8 +432,7 @@ define(['appRouter', 'focusManager', 'browser', 'layoutManager', 'inputManager', if (layoutManager.tv) { centerFocus(dlg, true, true); } - } - else if (options.scrollY !== false) { + } else if (options.scrollY !== false) { dlg.classList.add('smoothScrollY'); if (layoutManager.tv) { diff --git a/src/components/directorybrowser/directorybrowser.js b/src/components/directorybrowser/directorybrowser.js index aac45f86d6..9a3aed1045 100644 --- a/src/components/directorybrowser/directorybrowser.js +++ b/src/components/directorybrowser/directorybrowser.js @@ -115,7 +115,7 @@ define(['loading', 'dialogHelper', 'dom', 'listViewStyle', 'emby-input', 'paper- var readOnlyAttribute = options.pathReadOnly ? " readonly" : ""; html += ''; html += ""; - if (!readOnlyAttribute) { + if (!readOnlyAttribute) { html += ''; } html += ""; @@ -188,9 +188,9 @@ define(['loading', 'dialogHelper', 'dom', 'listViewStyle', 'emby-input', 'paper- var path = lnkPath.getAttribute("data-path"); if (lnkPath.classList.contains("lnkFile")) { content.querySelector("#txtDirectoryPickerPath").value = path; - } else { + } else { refreshDirectoryBrowser(content, path, fileOptions, true) - }; + } } }); @@ -254,10 +254,10 @@ define(['loading', 'dialogHelper', 'dom', 'listViewStyle', 'emby-input', 'paper- var systemInfo = responses[0]; var initialPath = responses[1]; var dlg = dialogHelper.createDialog({ - size: "medium-tall", - removeOnClose: true, - scrollY: false - }); + size: "medium-tall", + removeOnClose: true, + scrollY: false + }); dlg.classList.add("ui-body-a"); dlg.classList.add("background-theme-a"); dlg.classList.add("directoryPicker"); diff --git a/src/components/dom.js b/src/components/dom.js index ea8902b98e..da03b87428 100644 --- a/src/components/dom.js +++ b/src/components/dom.js @@ -68,7 +68,9 @@ define([], function () { } }); window.addEventListener("test", null, opts); - } catch (e) { } + } catch (e) { + console.log('error checking capture support'); + } function addEventListenerWithOptions(target, type, handler, options) { var optionsOrCapture = options; @@ -116,8 +118,8 @@ define([], function () { return _animationEvent; } - var t, - el = document.createElement("div"); + var t; + var el = document.createElement("div"); var animations = { "animation": "animationend", "OAnimation": "oAnimationEnd", @@ -146,8 +148,8 @@ define([], function () { return _transitionEvent; } - var t, - el = document.createElement("div"); + var t; + var el = document.createElement("div"); var transitions = { "transition": "transitionend", "OTransition": "oTransitionEnd", diff --git a/src/components/emby-input/emby-input.js b/src/components/emby-input/emby-input.js index acc9154318..7d2ea63a0d 100644 --- a/src/components/emby-input/emby-input.js +++ b/src/components/emby-input/emby-input.js @@ -28,11 +28,12 @@ define(['layoutManager', 'browser', 'dom', 'css!./emby-input', 'registerElement' } EmbyInputPrototype.createdCallback = function () { - if (!this.id) { this.id = 'embyinput' + inputId; inputId++; - } if (this.classList.contains('emby-input')) { + } + + if (this.classList.contains('emby-input')) { return; } diff --git a/src/components/emby-progressring/emby-progressring.js b/src/components/emby-progressring/emby-progressring.js index 7148079a19..80c5458528 100644 --- a/src/components/emby-progressring/emby-progressring.js +++ b/src/components/emby-progressring/emby-progressring.js @@ -47,8 +47,7 @@ define(['require', 'css!./emby-progressring', 'registerElement'], function (requ this.querySelector('.animate-25-50-b').style.transform = 'rotate(-90deg)'; this.querySelector('.animate-50-75-b').style.transform = 'rotate(-90deg)'; this.querySelector('.animate-75-100-b').style.transform = 'rotate(-90deg)'; - } - else if (progress >= 25 && progress < 50) { + } else if (progress >= 25 && progress < 50) { angle = -90 + ((progress - 25) / 100) * 360; @@ -57,8 +56,7 @@ define(['require', 'css!./emby-progressring', 'registerElement'], function (requ this.querySelector('.animate-50-75-b').style.transform = 'rotate(-90deg)'; this.querySelector('.animate-75-100-b').style.transform = 'rotate(-90deg)'; - } - else if (progress >= 50 && progress < 75) { + } else if (progress >= 50 && progress < 75) { angle = -90 + ((progress - 50) / 100) * 360; this.querySelector('.animate-0-25-b').style.transform = 'none'; @@ -66,8 +64,7 @@ define(['require', 'css!./emby-progressring', 'registerElement'], function (requ this.querySelector('.animate-50-75-b').style.transform = 'rotate(' + angle + 'deg)'; this.querySelector('.animate-75-100-b').style.transform = 'rotate(-90deg)'; - } - else if (progress >= 75 && progress <= 100) { + } else if (progress >= 75 && progress <= 100) { angle = -90 + ((progress - 75) / 100) * 360; this.querySelector('.animate-0-25-b').style.transform = 'none'; @@ -85,7 +82,6 @@ define(['require', 'css!./emby-progressring', 'registerElement'], function (requ EmbyProgressRing.detachedCallback = function () { - var observer = this.observer; if (observer) { diff --git a/src/components/emby-scroller/emby-scroller.css b/src/components/emby-scroller/emby-scroller.css index f060882f7b..1e0b05b83c 100644 --- a/src/components/emby-scroller/emby-scroller.css +++ b/src/components/emby-scroller/emby-scroller.css @@ -7,6 +7,17 @@ margin-right: 3.3%; } +/* align first card in scroller to heading */ +.emby-scroller .card:first-of-type > .cardBox { + margin-left: 0; +} + +/* align heading for normal item containers */ +/* still not ideal solution but better than the last method */ +.verticalSection > .itemsContainer .cardBox { + margin-left: 0; +} + @media all and (max-width:50em) { .emby-scroller { padding-left: 3.3%; diff --git a/src/components/emby-slider/emby-slider.css b/src/components/emby-slider/emby-slider.css index bd258d3bc5..b173f5c511 100644 --- a/src/components/emby-slider/emby-slider.css +++ b/src/components/emby-slider/emby-slider.css @@ -87,6 +87,10 @@ _:-ms-input-placeholder { transform: scale(1.6); } +.mdl-slider.show-focus:focus::-webkit-slider-thumb { + transform: scale(1.6); +} + .slider-no-webkit-thumb::-webkit-slider-thumb { opacity: 0 !important; } diff --git a/src/components/emby-slider/emby-slider.js b/src/components/emby-slider/emby-slider.js index 1ca1448ea1..c340e79359 100644 --- a/src/components/emby-slider/emby-slider.js +++ b/src/components/emby-slider/emby-slider.js @@ -19,6 +19,11 @@ define(['browser', 'dom', 'layoutManager', 'css!./emby-slider', 'registerElement function updateValues() { + // Do not update values when dragging with keyboard to keep current progress for reference + if (!!this.keyboardDragging) { + return; + } + var range = this; var value = range.value; @@ -82,6 +87,9 @@ define(['browser', 'dom', 'layoutManager', 'css!./emby-slider', 'registerElement if (!layoutManager.mobile) { this.classList.add('mdl-slider-hoverthumb'); } + if (layoutManager.tv) { + this.classList.add('show-focus'); + } var containerElement = this.parentNode; containerElement.classList.add('mdl-slider-container'); @@ -177,6 +185,108 @@ define(['browser', 'dom', 'layoutManager', 'css!./emby-slider', 'registerElement } }; + /** + * Keyboard dragging timeout. + * After this delay "change" event will be fired. + */ + var KeyboardDraggingTimeout = 1000; + + /** + * Keyboard dragging timer. + */ + var keyboardDraggingTimer; + + /** + * Start keyboard dragging. + * + * @param {Object} elem slider itself + */ + function startKeyboardDragging(elem) { + elem.keyboardDragging = true; + + clearTimeout(keyboardDraggingTimer); + keyboardDraggingTimer = setTimeout(function () { + finishKeyboardDragging(elem); + }, KeyboardDraggingTimeout); + } + + /** + * Finish keyboard dragging. + * + * @param {Object} elem slider itself + */ + function finishKeyboardDragging(elem) { + clearTimeout(keyboardDraggingTimer); + keyboardDraggingTimer = undefined; + + elem.keyboardDragging = false; + + var event = new Event('change', { + bubbles: true, + cancelable: false + }); + elem.dispatchEvent(event); + } + + /** + * Do step by delta. + * + * @param {Object} elem slider itself + * @param {number} delta step amount + */ + function stepKeyboard(elem, delta) { + startKeyboardDragging(elem); + + elem.value = Math.max(elem.min, Math.min(elem.max, parseFloat(elem.value) + delta)); + + var event = new Event('input', { + bubbles: true, + cancelable: false + }); + elem.dispatchEvent(event); + } + + /** + * Handle KeyDown event + */ + function onKeyDown(e) { + switch (e.key) { + case 'ArrowLeft': + case 'Left': + stepKeyboard(this, -this.keyboardStepDown || -1); + e.preventDefault(); + e.stopPropagation(); + break; + case 'ArrowRight': + case 'Right': + stepKeyboard(this, this.keyboardStepUp || 1); + e.preventDefault(); + e.stopPropagation(); + break; + } + } + + /** + * Enable keyboard dragging. + */ + EmbySliderPrototype.enableKeyboardDragging = function () { + if (!this.keyboardDraggingEnabled) { + this.addEventListener('keydown', onKeyDown); + this.keyboardDraggingEnabled = true; + } + } + + /** + * Set steps for keyboard input. + * + * @param {number} stepDown step to reduce + * @param {number} stepUp step to increase + */ + EmbySliderPrototype.setKeyboardSteps = function (stepDown, stepUp) { + this.keyboardStepDown = stepDown || stepUp || 1; + this.keyboardStepUp = stepUp || stepDown || 1; + } + function setRange(elem, startPercent, endPercent) { var style = elem.style; diff --git a/src/components/emby-tabs/emby-tabs.js b/src/components/emby-tabs/emby-tabs.js index d88b111060..9fedf0bfe9 100644 --- a/src/components/emby-tabs/emby-tabs.js +++ b/src/components/emby-tabs/emby-tabs.js @@ -10,23 +10,6 @@ define(['dom', 'scroller', 'browser', 'layoutManager', 'focusManager', 'register newButton.classList.add(activeButtonClass); } - function getFocusCallback(tabs, e) { - return function () { - onClick.call(tabs, e); - }; - } - - function onFocus(e) { - - if (layoutManager.tv) { - - if (this.focusTimeout) { - clearTimeout(this.focusTimeout); - } - this.focusTimeout = setTimeout(getFocusCallback(this, e), 700); - } - } - function getTabPanel(tabs, index) { return null; @@ -87,10 +70,6 @@ define(['dom', 'scroller', 'browser', 'layoutManager', 'focusManager', 'register function onClick(e) { - if (this.focusTimeout) { - clearTimeout(this.focusTimeout); - } - var tabs = this; var current = tabs.querySelector('.' + activeButtonClass); @@ -163,7 +142,7 @@ define(['dom', 'scroller', 'browser', 'layoutManager', 'focusManager', 'register tabs.classList.add('scrollX'); tabs.classList.add('hiddenScrollX'); tabs.classList.add('smoothScrollX'); - } + } } EmbyTabs.createdCallback = function () { @@ -177,10 +156,6 @@ define(['dom', 'scroller', 'browser', 'layoutManager', 'focusManager', 'register dom.addEventListener(this, 'click', onClick, { passive: true }); - dom.addEventListener(this, 'focus', onFocus, { - passive: true, - capture: true - }); }; EmbyTabs.focus = function () { @@ -237,10 +212,6 @@ define(['dom', 'scroller', 'browser', 'layoutManager', 'focusManager', 'register dom.removeEventListener(this, 'click', onClick, { passive: true }); - dom.removeEventListener(this, 'focus', onFocus, { - passive: true, - capture: true - }); }; function getSelectedTabButton(elem) { diff --git a/src/components/emby-textarea/emby-textarea.js b/src/components/emby-textarea/emby-textarea.js index 7dec1f0955..c500db6e1f 100644 --- a/src/components/emby-textarea/emby-textarea.js +++ b/src/components/emby-textarea/emby-textarea.js @@ -14,9 +14,9 @@ define(['layoutManager', 'browser', 'css!./emby-textarea', 'registerElement', 'e * @returns {number} */ self.getOffset = function (textarea) { - var style = window.getComputedStyle(textarea, null), - props = ['paddingTop', 'paddingBottom'], - offset = 0; + var style = window.getComputedStyle(textarea, null); + var props = ['paddingTop', 'paddingBottom']; + var offset = 0; for (var i = 0; i < props.length; i++) { offset += parseInt(style[props[i]]); @@ -43,13 +43,13 @@ define(['layoutManager', 'browser', 'css!./emby-textarea', 'registerElement', 'e textarea.rows = 3; return; } - var newHeight = 0, hasGrown = false; + var newHeight = 0; + var hasGrown = false; if ((textarea.scrollHeight - offset) > self.maxAllowedHeight) { textarea.style.overflowY = 'scroll'; newHeight = self.maxAllowedHeight; - } - else { + } else { textarea.style.overflowY = 'hidden'; textarea.style.height = 'auto'; newHeight = textarea.scrollHeight/* - offset*/; diff --git a/src/components/favoriteitems.js b/src/components/favoriteitems.js index 396d4d3c22..c84d84f585 100644 --- a/src/components/favoriteitems.js +++ b/src/components/favoriteitems.js @@ -1,20 +1,20 @@ -define(["loading", "libraryBrowser", "cardBuilder", "dom", "apphost", "imageLoader", "globalize", "layoutManager", "scrollStyles", "emby-itemscontainer"], function(loading, libraryBrowser, cardBuilder, dom, appHost, imageLoader, globalize, layoutManager) { +define(["loading", "libraryBrowser", "cardBuilder", "dom", "apphost", "imageLoader", "globalize", "layoutManager", "scrollStyles", "emby-itemscontainer"], function (loading, libraryBrowser, cardBuilder, dom, appHost, imageLoader, globalize, layoutManager) { "use strict"; function enableScrollX() { - return !layoutManager.desktop + return !layoutManager.desktop; } function getThumbShape() { - return enableScrollX() ? "overflowBackdrop" : "backdrop" + return enableScrollX() ? "overflowBackdrop" : "backdrop"; } function getPosterShape() { - return enableScrollX() ? "overflowPortrait" : "portrait" + return enableScrollX() ? "overflowPortrait" : "portrait"; } function getSquareShape() { - return enableScrollX() ? "overflowSquare" : "square" + return enableScrollX() ? "overflowSquare" : "square"; } function getSections() { @@ -23,147 +23,208 @@ define(["loading", "libraryBrowser", "cardBuilder", "dom", "apphost", "imageLoad types: "Movie", id: "favoriteMovies", shape: getPosterShape(), - showTitle: !1, - overlayPlayButton: !0 + showTitle: false, + overlayPlayButton: true }, { name: "HeaderFavoriteShows", types: "Series", id: "favoriteShows", shape: getPosterShape(), - showTitle: !1, - overlayPlayButton: !0 + showTitle: false, + overlayPlayButton: true }, { name: "HeaderFavoriteEpisodes", types: "Episode", id: "favoriteEpisode", shape: getThumbShape(), - preferThumb: !1, - showTitle: !0, - showParentTitle: !0, - overlayPlayButton: !0, - overlayText: !1, - centerText: !0 + preferThumb: false, + showTitle: true, + showParentTitle: true, + overlayPlayButton: true, + overlayText: false, + centerText: true }, { name: "HeaderFavoriteVideos", types: "Video,MusicVideo", id: "favoriteVideos", shape: getThumbShape(), - preferThumb: !0, - showTitle: !0, - overlayPlayButton: !0, - overlayText: !1, - centerText: !0 + preferThumb: true, + showTitle: true, + overlayPlayButton: true, + overlayText: false, + centerText: true }, { name: "HeaderFavoriteArtists", types: "MusicArtist", id: "favoriteArtists", shape: getSquareShape(), - preferThumb: !1, - showTitle: !0, - overlayText: !1, - showParentTitle: !1, - centerText: !0, - overlayPlayButton: !0, - coverImage: !0 + preferThumb: false, + showTitle: true, + overlayText: false, + showParentTitle: false, + centerText: true, + overlayPlayButton: true, + coverImage: true }, { name: "HeaderFavoriteAlbums", types: "MusicAlbum", id: "favoriteAlbums", shape: getSquareShape(), - preferThumb: !1, - showTitle: !0, - overlayText: !1, - showParentTitle: !0, - centerText: !0, - overlayPlayButton: !0, - coverImage: !0 + preferThumb: false, + showTitle: true, + overlayText: false, + showParentTitle: true, + centerText: true, + overlayPlayButton: true, + coverImage: true }, { name: "HeaderFavoriteSongs", types: "Audio", id: "favoriteSongs", shape: getSquareShape(), - preferThumb: !1, - showTitle: !0, - overlayText: !1, - showParentTitle: !0, - centerText: !0, - overlayMoreButton: !0, + preferThumb: false, + showTitle: true, + overlayText: false, + showParentTitle: true, + centerText: true, + overlayMoreButton: true, action: "instantmix", - coverImage: !0 - }] + coverImage: true + }]; } function loadSection(elem, userId, topParentId, section, isSingleSection) { - var screenWidth = dom.getWindowSize().innerWidth, - options = { - SortBy: "SortName", - SortOrder: "Ascending", - Filters: "IsFavorite", - Recursive: !0, - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - CollapseBoxSetItems: !1, - ExcludeLocationTypes: "Virtual", - EnableTotalRecordCount: !1 - }; - topParentId && (options.ParentId = topParentId), isSingleSection || (options.Limit = screenWidth >= 1920 ? 10 : screenWidth >= 1440 ? 8 : 6, enableScrollX() && (options.Limit = 20)); + var screenWidth = dom.getWindowSize().innerWidth; + var options = { + SortBy: "SortName", + SortOrder: "Ascending", + Filters: "IsFavorite", + Recursive: true, + Fields: "PrimaryImageAspectRatio,BasicSyncInfo", + CollapseBoxSetItems: false, + ExcludeLocationTypes: "Virtual", + EnableTotalRecordCount: false + }; + + if (topParentId) { + options.ParentId = topParentId; + } + + if (!isSingleSection) { + options.Limit = screenWidth >= 1920 ? 10 : screenWidth >= 1440 ? 8 : 6; + + if (enableScrollX()) { + options.Limit = 20; + } + } + var promise; - return "MusicArtist" === section.types ? promise = ApiClient.getArtists(userId, options) : (options.IncludeItemTypes = section.types, promise = ApiClient.getItems(userId, options)), promise.then(function(result) { + + if ("MusicArtist" === section.types) { + promise = ApiClient.getArtists(userId, options); + } else { + options.IncludeItemTypes = section.types; + promise = ApiClient.getItems(userId, options); + } + + return promise.then(function (result) { var html = ""; + if (result.Items.length) { if (html += '
', !layoutManager.tv && options.Limit && result.Items.length >= options.Limit) { - html += '', html += '

', html += globalize.translate(section.name), html += "

", html += '', html += "
" - } else html += '

' + globalize.translate(section.name) + "

"; - if (html += "
", enableScrollX()) { + html += ''; + html += '

'; + html += globalize.translate(section.name); + html += "

"; + html += ''; + html += "
"; + } else { + html += '

' + globalize.translate(section.name) + "

"; + } + + html += ""; + if (enableScrollX()) { var scrollXClass = "scrollX hiddenScrollX"; - layoutManager.tv && (scrollXClass += " smoothScrollX"), html += '
' - } else html += '
'; - var supportsImageAnalysis = appHost.supports("imageanalysis"), - cardLayout = (appHost.preferVisualCards || supportsImageAnalysis) && section.autoCardLayout && section.showTitle; - cardLayout = !1, html += cardBuilder.getCardsHtml(result.Items, { + if (layoutManager.tv) { + scrollXClass += " smoothScrollX"; + } + + html += '
'; + } else { + html += '
'; + } + + var supportsImageAnalysis = appHost.supports("imageanalysis"); + var cardLayout = (appHost.preferVisualCards || supportsImageAnalysis) && section.autoCardLayout && section.showTitle; + cardLayout = false; + html += cardBuilder.getCardsHtml(result.Items, { preferThumb: section.preferThumb, shape: section.shape, centerText: section.centerText && !cardLayout, - overlayText: !1 !== section.overlayText, + overlayText: false !== section.overlayText, showTitle: section.showTitle, showParentTitle: section.showParentTitle, - scalable: !0, + scalable: true, coverImage: section.coverImage, overlayPlayButton: section.overlayPlayButton, overlayMoreButton: section.overlayMoreButton && !cardLayout, action: section.action, allowBottomPadding: !enableScrollX(), cardLayout: cardLayout - }), html += "
" + }); + html += "
"; } - elem.innerHTML = html, imageLoader.lazyChildren(elem) - }) + + elem.innerHTML = html; + imageLoader.lazyChildren(elem); + }); } function loadSections(page, userId, topParentId, types) { loading.show(); - var sections = getSections(), - sectionid = getParameterByName("sectionid"); - sectionid && (sections = sections.filter(function(s) { - return s.id === sectionid - })), types && (sections = sections.filter(function(s) { - return -1 !== types.indexOf(s.id) - })); - var i, length, elem = page.querySelector(".favoriteSections"); + var sections = getSections(); + var sectionid = getParameterByName("sectionid"); + + if (sectionid) { + sections = sections.filter(function (s) { + return s.id === sectionid; + }); + } + + if (types) { + sections = sections.filter(function (s) { + return -1 !== types.indexOf(s.id); + }); + } + + var i; + var length; + var elem = page.querySelector(".favoriteSections"); + if (!elem.innerHTML) { var html = ""; - for (i = 0, length = sections.length; i < length; i++) html += '
'; - elem.innerHTML = html + + for (i = 0, length = sections.length; i < length; i++) { + html += '
'; + } + + elem.innerHTML = html; } + var promises = []; + for (i = 0, length = sections.length; i < length; i++) { var section = sections[i]; - elem = page.querySelector(".section" + section.id), promises.push(loadSection(elem, userId, topParentId, section, 1 === sections.length)) + elem = page.querySelector(".section" + section.id); + promises.push(loadSection(elem, userId, topParentId, section, 1 === sections.length)); } - Promise.all(promises).then(function() { - loading.hide() - }) + + Promise.all(promises).then(function () { + loading.hide(); + }); } + return { render: loadSections - } + }; }); diff --git a/src/components/filtermenu/filtermenu.js b/src/components/filtermenu/filtermenu.js index 89457aa4e6..2f18223d41 100644 --- a/src/components/filtermenu/filtermenu.js +++ b/src/components/filtermenu/filtermenu.js @@ -94,7 +94,8 @@ define(['require', 'dom', 'focusManager', 'dialogHelper', 'loading', 'apphost', context.querySelector('form').addEventListener('submit', onSubmit); var elems = context.querySelectorAll('.simpleFilter'); - var i, length; + var i; + var length; for (i = 0, length = elems.length; i < length; i++) { @@ -137,7 +138,8 @@ define(['require', 'dom', 'focusManager', 'dialogHelper', 'loading', 'apphost', function saveValues(context, settings, settingsKey) { var elems = context.querySelectorAll('.simpleFilter'); - var i, length; + var i; + var length; for (i = 0, length = elems.length; i < length; i++) { if (elems[i].tagName === 'INPUT') { diff --git a/src/components/focusManager.js b/src/components/focusManager.js index 8c2f0ad442..ec23a151c2 100644 --- a/src/components/focusManager.js +++ b/src/components/focusManager.js @@ -99,7 +99,7 @@ define(['dom'], function (dom) { return normalizeFocusable(elem, originalElement); } - // Determines if a focusable element can be focused at a given point in time + // Determines if a focusable element can be focused at a given point in time function isCurrentlyFocusableInternal(elem) { // http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom @@ -110,7 +110,7 @@ define(['dom'], function (dom) { return true; } - // Determines if a focusable element can be focused at a given point in time + // Determines if a focusable element can be focused at a given point in time function isCurrentlyFocusable(elem) { if (elem.disabled) { @@ -181,21 +181,18 @@ define(['dom'], function (dom) { if (classList.contains('focuscontainer-left')) { return true; } - } - else if (direction === 1) { + } else if (direction === 1) { if (classList.contains('focuscontainer-x')) { return true; } if (classList.contains('focuscontainer-right')) { return true; } - } - else if (direction === 2) { + } else if (direction === 2) { if (classList.contains('focuscontainer-y')) { return true; } - } - else if (direction === 3) { + } else if (direction === 3) { if (classList.contains('focuscontainer-y')) { return true; } @@ -275,14 +272,14 @@ define(['dom'], function (dom) { var rect = getOffset(activeElement); // Get elements and work out x/y points - var cache = [], - point1x = parseFloat(rect.left) || 0, - point1y = parseFloat(rect.top) || 0, - point2x = parseFloat(point1x + rect.width - 1) || point1x, - point2y = parseFloat(point1y + rect.height - 1) || point1y, - // Shortcuts to help with compression - min = Math.min, - max = Math.max; + var cache = []; + var point1x = parseFloat(rect.left) || 0; + var point1y = parseFloat(rect.top) || 0; + var point2x = parseFloat(point1x + rect.width - 1) || point1x; + var point2y = parseFloat(point1y + rect.height - 1) || point1y; + // Shortcuts to help with compression + var min = Math.min; + var max = Math.max; var sourceMidX = rect.left + (rect.width / 2); var sourceMidY = rect.top + (rect.height / 2); @@ -357,10 +354,10 @@ define(['dom'], function (dom) { break; } - var x = elementRect.left, - y = elementRect.top, - x2 = x + elementRect.width - 1, - y2 = y + elementRect.height - 1; + var x = elementRect.left; + var y = elementRect.top; + var x2 = x + elementRect.width - 1; + var y2 = y + elementRect.height - 1; var intersectX = intersects(point1x, point2x, x, x2); var intersectY = intersects(point1y, point2y, y, y2); @@ -470,7 +467,9 @@ define(['dom'], function (dom) { var elems = container.querySelectorAll(focusableSelector); var list = []; - var i, length, elem; + var i; + var length; + var elem; for (i = 0, length = elems.length; i < length; i++) { @@ -513,32 +512,24 @@ define(['dom'], function (dom) { focusableParent: focusableParent, getFocusableElements: getFocusableElements, moveLeft: function (sourceElement, options) { - var container = options ? options.container : null; var focusableElements = options ? options.focusableElements : null; nav(sourceElement, 0, container, focusableElements); - }, moveRight: function (sourceElement, options) { - var container = options ? options.container : null; var focusableElements = options ? options.focusableElements : null; nav(sourceElement, 1, container, focusableElements); - }, moveUp: function (sourceElement, options) { - var container = options ? options.container : null; var focusableElements = options ? options.focusableElements : null; nav(sourceElement, 2, container, focusableElements); - }, moveDown: function (sourceElement, options) { - var container = options ? options.container : null; var focusableElements = options ? options.focusableElements : null; nav(sourceElement, 3, container, focusableElements); - }, sendText: sendText, isCurrentlyFocusable: isCurrentlyFocusable, diff --git a/src/components/fullscreenManager.js b/src/components/fullscreenManager.js index 360986cc54..8ae31073a2 100644 --- a/src/components/fullscreenManager.js +++ b/src/components/fullscreenManager.js @@ -55,7 +55,7 @@ define(['events', 'dom', 'apphost', 'browser'], function (events, dom, appHost, return document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen || - document.msFullscreenElement || /* IE/Edge syntax */ + document.msFullscreenElement || /* IE/Edge syntax */ document.fullscreenElement || /* Standard syntax */ document.webkitFullscreenElement || /* Chrome, Safari and Opera syntax */ document.mozFullScreenElement; /* Firefox syntax */ diff --git a/src/components/groupedcards.js b/src/components/groupedcards.js index a6b1946526..ad638ecdd9 100644 --- a/src/components/groupedcards.js +++ b/src/components/groupedcards.js @@ -1,32 +1,45 @@ -define(["dom", "appRouter", "connectionManager"], function(dom, appRouter, connectionManager) { +define(["dom", "appRouter", "connectionManager"], function (dom, appRouter, connectionManager) { "use strict"; function onGroupedCardClick(e, card) { - var itemId = card.getAttribute("data-id"), - serverId = card.getAttribute("data-serverid"), - apiClient = connectionManager.getApiClient(serverId), - userId = apiClient.getCurrentUserId(), - playedIndicator = card.querySelector(".playedIndicator"), - playedIndicatorHtml = playedIndicator ? playedIndicator.innerHTML : null, - options = { - Limit: parseInt(playedIndicatorHtml || "10"), - Fields: "PrimaryImageAspectRatio,DateCreated", - ParentId: itemId, - GroupItems: !1 - }, - actionableParent = dom.parentWithTag(e.target, ["A", "BUTTON", "INPUT"]); - if (!actionableParent || actionableParent.classList.contains("cardContent")) return apiClient.getJSON(apiClient.getUrl("Users/" + userId + "/Items/Latest", options)).then(function(items) { - if (1 === items.length) return void appRouter.showItem(items[0]); - var url = "itemdetails.html?id=" + itemId + "&serverId=" + serverId; - Dashboard.navigate(url) - }), e.stopPropagation(), e.preventDefault(), !1 + var itemId = card.getAttribute("data-id"); + var serverId = card.getAttribute("data-serverid"); + var apiClient = connectionManager.getApiClient(serverId); + var userId = apiClient.getCurrentUserId(); + var playedIndicator = card.querySelector(".playedIndicator"); + var playedIndicatorHtml = playedIndicator ? playedIndicator.innerHTML : null; + var options = { + Limit: parseInt(playedIndicatorHtml || "10"), + Fields: "PrimaryImageAspectRatio,DateCreated", + ParentId: itemId, + GroupItems: false + }; + var actionableParent = dom.parentWithTag(e.target, ["A", "BUTTON", "INPUT"]); + + if (!actionableParent || actionableParent.classList.contains("cardContent")) { + apiClient.getJSON(apiClient.getUrl("Users/" + userId + "/Items/Latest", options)).then(function (items) { + if (1 === items.length) { + return void appRouter.showItem(items[0]); + } + + var url = "itemdetails.html?id=" + itemId + "&serverId=" + serverId; + Dashboard.navigate(url); + }); + e.stopPropagation(); + e.preventDefault(); + return false; + } } function onItemsContainerClick(e) { var groupedCard = dom.parentWithClass(e.target, "groupedCard"); - groupedCard && onGroupedCardClick(e, groupedCard) + + if (groupedCard) { + onGroupedCardClick(e, groupedCard); + } } + return { onItemsContainerClick: onItemsContainerClick - } -}); \ No newline at end of file + }; +}); diff --git a/src/components/guide/guide-settings.js b/src/components/guide/guide-settings.js index 47eb026db8..9ee43be9f1 100644 --- a/src/components/guide/guide-settings.js +++ b/src/components/guide/guide-settings.js @@ -39,7 +39,8 @@ define(['dialogHelper', 'globalize', 'userSettings', 'layoutManager', 'connectio function save(context) { - var i, length; + var i; + var length; var chkIndicators = context.querySelectorAll('.chkIndicator'); for (i = 0, length = chkIndicators.length; i < length; i++) { @@ -62,7 +63,8 @@ define(['dialogHelper', 'globalize', 'userSettings', 'layoutManager', 'connectio function load(context) { - var i, length; + var i; + var length; var chkIndicators = context.querySelectorAll('.chkIndicator'); for (i = 0, length = chkIndicators.length; i < length; i++) { diff --git a/src/components/guide/guide.js b/src/components/guide/guide.js index d299d7fd7c..1e9484caf8 100644 --- a/src/components/guide/guide.js +++ b/src/components/guide/guide.js @@ -277,7 +277,7 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', var nextDay = new Date(date.getTime() + msPerDay - 2000); // Normally we'd want to just let responsive css handle this, - // but since mobile browsers are often underpowered, + // but since mobile browsers are often underpowered, // it can help performance to get them out of the markup var allowIndicators = dom.getWindowSize().innerWidth >= 600; @@ -392,27 +392,20 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', } function parseDates(program) { - if (!program.StartDateLocal) { try { - program.StartDateLocal = datetime.parseISO8601Date(program.StartDate, { toLocal: true }); - } catch (err) { - + console.log('error parsing timestamp for start date'); } - } if (!program.EndDateLocal) { try { - program.EndDateLocal = datetime.parseISO8601Date(program.EndDate, { toLocal: true }); - } catch (err) { - + console.log('error parsing timestamp for end date'); } - } return null; @@ -424,16 +417,13 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', if (item.Type === 'SeriesTimer') { return ''; - } - else if (item.TimerId || item.SeriesTimerId) { + } else if (item.TimerId || item.SeriesTimerId) { status = item.Status || 'Cancelled'; - } - else if (item.Type === 'Timer') { + } else if (item.Type === 'Timer') { status = item.Status; - } - else { + } else { return ''; } @@ -529,11 +519,9 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', } else if (program.IsMovie) { displayInnerContent = displayMovieContent; accentCssClass = 'movie'; - } - else if (program.IsSeries) { + } else if (program.IsSeries) { displayInnerContent = displaySeriesContent; - } - else { + } else { displayInnerContent = displayMovieContent && displayNewsContent && displaySportsContent && displayKidsContent && displaySeriesContent; } @@ -569,14 +557,11 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', var indicatorHtml = null; if (program.IsLive && options.showLiveIndicator) { indicatorHtml = '' + globalize.translate('Live') + ''; - } - else if (program.IsPremiere && options.showPremiereIndicator) { + } else if (program.IsPremiere && options.showPremiereIndicator) { indicatorHtml = '' + globalize.translate('Premiere') + ''; - } - else if (program.IsSeries && !program.IsRepeat && options.showNewIndicator) { + } else if (program.IsSeries && !program.IsRepeat && options.showNewIndicator) { indicatorHtml = '' + globalize.translate('AttributeNew') + ''; - } - else if (program.IsSeries && program.IsRepeat && options.showRepeatIndicator) { + } else if (program.IsSeries && program.IsRepeat && options.showRepeatIndicator) { indicatorHtml = '' + globalize.translate('Repeat') + ''; } html += indicatorHtml || ''; @@ -614,7 +599,6 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', return html; } - function renderChannelHeaders(context, channels, apiClient) { var html = ''; @@ -1079,17 +1063,13 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', scrollHelper.toStart(programGrid, programCell, true, true); } - } - - else if (lastFocusDirection === 'right') { + } else if (lastFocusDirection === 'right') { if (programCell) { scrollHelper.toCenter(programGrid, programCell, true, true); } - } - - else if (lastFocusDirection === 'up' || lastFocusDirection === 'down') { + } else if (lastFocusDirection === 'up' || lastFocusDirection === 'down') { var verticalScroller = dom.parentWithClass(target, 'guideVerticalScroller'); if (verticalScroller) { @@ -1195,14 +1175,14 @@ define(['require', 'inputManager', 'browser', 'globalize', 'connectionManager', dom.addEventListener(programGrid, 'scroll', function (e) { onProgramGridScroll(context, this, timeslotHeaders); }, { - passive: true - }); + passive: true + }); dom.addEventListener(timeslotHeaders, 'scroll', function () { onTimeslotHeadersScroll(context, this); }, { - passive: true - }); + passive: true + }); programGrid.addEventListener('click', onProgramGridClick); diff --git a/src/components/headroom/headroom.js b/src/components/headroom/headroom.js index a3cc5b0435..9c058a8e82 100644 --- a/src/components/headroom/headroom.js +++ b/src/components/headroom/headroom.js @@ -255,8 +255,8 @@ define(['dom', 'layoutManager', 'browser', 'css!./headroom'], function (dom, lay * @return {bool} true if should unpin, false otherwise */ this.shouldUnpin = function (currentScrollY) { - var scrollingDown = currentScrollY > this.lastKnownScrollY, - pastOffset = currentScrollY >= this.offset; + var scrollingDown = currentScrollY > this.lastKnownScrollY; + var pastOffset = currentScrollY >= this.offset; return scrollingDown && pastOffset; }; @@ -267,8 +267,8 @@ define(['dom', 'layoutManager', 'browser', 'css!./headroom'], function (dom, lay * @return {bool} true if should pin, false otherwise */ this.shouldPin = function (currentScrollY) { - var scrollingUp = currentScrollY < this.lastKnownScrollY, - pastOffset = currentScrollY <= this.offset; + var scrollingUp = currentScrollY < this.lastKnownScrollY; + var pastOffset = currentScrollY <= this.offset; return scrollingUp || pastOffset; }; @@ -290,11 +290,9 @@ define(['dom', 'layoutManager', 'browser', 'css!./headroom'], function (dom, lay if (currentScrollY <= (isTv ? 120 : 10)) { this.clear(); - } - else if (this.shouldUnpin(currentScrollY)) { + } else if (this.shouldUnpin(currentScrollY)) { this.unpin(); - } - else if (this.shouldPin(currentScrollY)) { + } else if (this.shouldPin(currentScrollY)) { var toleranceExceeded = Math.abs(currentScrollY - lastKnownScrollY) >= 14; @@ -310,7 +308,6 @@ define(['dom', 'layoutManager', 'browser', 'css!./headroom'], function (dom, lay this.lastKnownScrollY = currentScrollY; }; - if (browser.supportsCssAnimation()) { for (var i = 0, length = this.elems.length; i < length; i++) { this.elems[i].classList.add(this.initialClass); diff --git a/src/components/homescreensettings/homescreensettings.js b/src/components/homescreensettings/homescreensettings.js index e881edbdbd..dc7769be36 100644 --- a/src/components/homescreensettings/homescreensettings.js +++ b/src/components/homescreensettings/homescreensettings.js @@ -57,8 +57,7 @@ define(['require', 'apphost', 'layoutManager', 'focusManager', 'globalize', 'loa name: globalize.translate('Collections'), value: 'collections' }); - } - else if (type === 'tvshows') { + } else if (type === 'tvshows') { list.push({ name: globalize.translate('Shows'), @@ -78,8 +77,7 @@ define(['require', 'apphost', 'layoutManager', 'focusManager', 'globalize', 'loa name: globalize.translate('Favorites'), value: 'favorites' }); - } - else if (type === 'music') { + } else if (type === 'music') { list.push({ name: globalize.translate('Suggestions'), @@ -111,8 +109,7 @@ define(['require', 'apphost', 'layoutManager', 'focusManager', 'globalize', 'loa name: globalize.translate('Genres'), value: 'genres' }); - } - else if (type === 'livetv') { + } else if (type === 'livetv') { list.push({ name: globalize.translate('Suggestions'), @@ -256,7 +253,6 @@ define(['require', 'apphost', 'layoutManager', 'focusManager', 'globalize', 'loa html += '
'; } - return html; } @@ -330,6 +326,7 @@ define(['require', 'apphost', 'layoutManager', 'focusManager', 'globalize', 'loa if (next) { viewItem.parentNode.removeChild(viewItem); next.parentNode.insertBefore(viewItem, next.nextSibling); + focusManager.focus(e.target); } } else { @@ -339,6 +336,7 @@ define(['require', 'apphost', 'layoutManager', 'focusManager', 'globalize', 'loa if (prev) { viewItem.parentNode.removeChild(viewItem); prev.parentNode.insertBefore(viewItem, prev); + focusManager.focus(e.target); } } } @@ -382,7 +380,8 @@ define(['require', 'apphost', 'layoutManager', 'focusManager', 'globalize', 'loa var viewItems = context.querySelectorAll('.viewItem'); var orderedViews = []; - var i, length; + var i; + var length; for (i = 0, length = viewItems.length; i < length; i++) { orderedViews.push(viewItems[i].getAttribute('data-viewid')); } diff --git a/src/components/homesections/homesections.js b/src/components/homesections/homesections.js index d2106c93bd..0c92f34e3d 100644 --- a/src/components/homesections/homesections.js +++ b/src/components/homesections/homesections.js @@ -1,4 +1,4 @@ -define(['connectionManager', 'cardBuilder', 'appSettings', 'dom', 'apphost', 'layoutManager', 'imageLoader', 'globalize', 'itemShortcuts', 'itemHelper', 'appRouter', 'scripts/imagehelper','paper-icon-button-light', 'emby-itemscontainer', 'emby-scroller', 'emby-button', 'css!./homesections'], function (connectionManager, cardBuilder, appSettings, dom, appHost, layoutManager, imageLoader, globalize, itemShortcuts, itemHelper, appRouter, imageHelper) { +define(['connectionManager', 'cardBuilder', 'appSettings', 'dom', 'apphost', 'layoutManager', 'imageLoader', 'globalize', 'itemShortcuts', 'itemHelper', 'appRouter', 'scripts/imagehelper', 'paper-icon-button-light', 'emby-itemscontainer', 'emby-scroller', 'emby-button', 'css!./homesections'], function (connectionManager, cardBuilder, appSettings, dom, appHost, layoutManager, imageLoader, globalize, itemShortcuts, itemHelper, appRouter, imageHelper) { 'use strict'; function getDefaultSection(index) { @@ -83,7 +83,8 @@ define(['connectionManager', 'cardBuilder', 'appSettings', 'dom', 'apphost', 'la function resume(elem, options) { var elems = elem.querySelectorAll('.itemsContainer'); - var i, length; + var i; + var length; var promises = []; for (i = 0, length = elems.length; i < length; i++) { @@ -560,31 +561,31 @@ define(['connectionManager', 'cardBuilder', 'appSettings', 'dom', 'apphost', 'la if (enableScrollX()) { html += '
'; - html += '
'; + html += '
'; } else { - html += '
'; + html += '
'; } - html += '' + globalize.translate('Programs') + ''; - html += '' + globalize.translate('Guide') + ''; - html += '' + globalize.translate('Recordings') + ''; - html += '' + globalize.translate('Schedule') + ''; - html += '' + globalize.translate('Series') + ''; diff --git a/src/components/htmlMediaHelper.js b/src/components/htmlMediaHelper.js index bba0ec2daf..86f05dabfa 100644 --- a/src/components/htmlMediaHelper.js +++ b/src/components/htmlMediaHelper.js @@ -12,7 +12,6 @@ define(['appSettings', 'browser', 'events'], function (appSettings, browser, eve } function getCrossOriginValue(mediaSource) { - if (mediaSource.IsRemote) { return null; } @@ -97,7 +96,8 @@ define(['appSettings', 'browser', 'events'], function (appSettings, browser, eve return true; } - var recoverDecodingErrorDate, recoverSwapAudioCodecDate; + var recoverDecodingErrorDate; + var recoverSwapAudioCodecDate; function handleHlsJsMediaError(instance, reject) { var hlsPlayer = instance._hlsPlayer; @@ -144,7 +144,8 @@ define(['appSettings', 'browser', 'events'], function (appSettings, browser, eve events.trigger(instance, 'error', [ { type: type - }]); + } + ]); } function isValidDuration(duration) { @@ -156,7 +157,6 @@ define(['appSettings', 'browser', 'events'], function (appSettings, browser, eve } function setCurrentTimeIfNeeded(element, seconds) { - if (Math.abs(element.currentTime || 0, seconds) <= 1) { element.currentTime = seconds; } @@ -354,9 +354,7 @@ define(['appSettings', 'browser', 'events'], function (appSettings, browser, eve } else { onErrorInternal(instance, 'network'); } - } - - else { + } else { console.log("fatal network error encountered, try to recover"); hls.startLoad(); } diff --git a/src/components/htmlaudioplayer/plugin.js b/src/components/htmlaudioplayer/plugin.js index daf22790a6..1b41cc544d 100644 --- a/src/components/htmlaudioplayer/plugin.js +++ b/src/components/htmlaudioplayer/plugin.js @@ -52,7 +52,7 @@ define(['events', 'browser', 'require', 'apphost', 'appSettings', 'htmlMediaHelp function supportsFade() { if (browser.tv) { - // Not working on tizen. + // Not working on tizen. // We could possibly enable on other tv's, but all smart tv browsers tend to be pretty primitive return false; } @@ -168,7 +168,6 @@ define(['events', 'browser', 'require', 'apphost', 'appSettings', 'htmlMediaHelp }); }); - }, function () { elem.autoplay = true; diff --git a/src/components/htmlvideoplayer/plugin.js b/src/components/htmlvideoplayer/plugin.js index 27e02349c0..5b498d47ff 100644 --- a/src/components/htmlvideoplayer/plugin.js +++ b/src/components/htmlvideoplayer/plugin.js @@ -298,10 +298,10 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa type: 'flv', url: url }, - { - seekType: 'range', - lazyLoad: false - }); + { + seekType: 'range', + lazyLoad: false + }); flvPlayer.attachMediaElement(elem); flvPlayer.load(); @@ -420,7 +420,7 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa function onMediaManagerLoadMedia(event) { if (self._castPlayer) { - self._castPlayer.unload(); // Must unload before starting again. + self._castPlayer.unload(); // Must unload before starting again. } self._castPlayer = null; @@ -532,12 +532,8 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa } else*/ if (browser.chromecast && val.indexOf('.m3u8') !== -1 && options.mediaSource.RunTimeTicks) { return setCurrentSrcChromecast(self, elem, options, val); - } - - else if (htmlMediaHelper.enableHlsJsPlayer(options.mediaSource.RunTimeTicks, 'Video') && val.indexOf('.m3u8') !== -1) { - + } else if (htmlMediaHelper.enableHlsJsPlayer(options.mediaSource.RunTimeTicks, 'Video') && val.indexOf('.m3u8') !== -1) { return setSrcWithHlsJs(self, elem, options, val); - } else if (options.playMethod !== 'Transcode' && options.mediaSource.Container === 'flv') { return setSrcWithFlvJs(self, elem, options, val); @@ -575,43 +571,41 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa self.setSubtitleOffset = function(offset) { var offsetValue = parseFloat(offset); - var videoElement = self._mediaElement; - var mediaStreamTextTracks = getMediaStreamTextTracks(self._currentPlayOptions.mediaSource); - Array.from(videoElement.textTracks) - .filter(function(trackElement) { - if (customTrackIndex === -1 ) { + // if .ass currently rendering + if (currentAssRenderer) { + updateCurrentTrackOffset(offsetValue); + } else { + var videoElement = self._mediaElement; + var mediaStreamTextTracks = getMediaStreamTextTracks(self._currentPlayOptions.mediaSource); + + Array.from(videoElement.textTracks) + .filter(function(trackElement) { // get showing .vtt textTacks - return trackElement.mode === 'showing'; - } else { - // get current .ass textTrack - return ("textTrack" + customTrackIndex) === trackElement.id; - } - }) - .forEach(function(trackElement) { + return trackElement.mode === 'showing'; + }) + .forEach(function(trackElement) { - var track = mediaStreamTextTracks.filter(function(stream) { - return ("textTrack" + stream.Index) === trackElement.id; - })[0]; + var track = customTrackIndex === -1 ? null : mediaStreamTextTracks.filter(function (t) { + return t.Index === customTrackIndex; + })[0]; - if(track) { - offsetValue = updateCurrentTrackOffset(offsetValue); - var format = (track.Codec || '').toLowerCase(); - if (format !== 'ass' && format !== 'ssa') { - setVttSubtitleOffset(trackElement, offsetValue); - } - } else { - console.log("No available track, cannot apply offset : " + offsetValue); - } + if (track) { + offsetValue = updateCurrentTrackOffset(offsetValue); + setVttSubtitleOffset(trackElement, offsetValue); + } else { + console.log("No available track, cannot apply offset : " + offsetValue); + } - }); + }); + } }; function updateCurrentTrackOffset(offsetValue) { var relativeOffset = offsetValue; var newTrackOffset = offsetValue; - if(currentTrackOffset){ + if (currentTrackOffset) { relativeOffset -= currentTrackOffset; } currentTrackOffset = newTrackOffset; @@ -621,12 +615,12 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa function setVttSubtitleOffset(currentTrack, offsetValue) { - if(currentTrack.cues) { + if (currentTrack.cues) { Array.from(currentTrack.cues) - .forEach(function(cue) { - cue.startTime -= offsetValue; - cue.endTime -= offsetValue; - }); + .forEach(function(cue) { + cue.startTime -= offsetValue; + cue.endTime -= offsetValue; + }); } } @@ -652,7 +646,6 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa return profiles.filter(function (p) { - if (p.Type === 'Video') { if (!p.AudioCodec) { @@ -685,7 +678,9 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa } var audioIndex = -1; - var i, length, stream; + var i; + var length; + var stream; for (i = 0, length = streams.length; i < length; i++) { stream = streams[i]; @@ -1031,8 +1026,7 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa if (browser.ps4) { // Text outlines are not rendering very well rendererSettings.enableSvg = false; - } - else if (browser.edge || browser.msie) { + } else if (browser.edge || browser.msie) { // svg not rendering at all rendererSettings.enableSvg = false; } @@ -1192,50 +1186,49 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa } var trackElement = null; - var expectedId = 'manualTrack' + track.Index; + if (videoElement.textTracks && videoElement.textTracks.length > 0) { + trackElement = videoElement.textTracks[0]; - // get list of tracks - var allTracks = videoElement.textTracks; - for (var i = 0; i < allTracks.length; i++) { - - var currentTrack = allTracks[i]; - - if (currentTrack.label === expectedId) { - trackElement = currentTrack; - break; - } else { - currentTrack.mode = 'disabled'; - } - } - - if (!trackElement) { - trackElement = videoElement.addTextTrack('subtitles', 'manualTrack' + track.Index, track.Language || 'und'); - - // download the track json - fetchSubtitles(track, item).then(function (data) { - - // show in ui - console.log('downloaded ' + data.TrackEvents.length + ' track events'); - // add some cues to show the text - // in safari, the cues need to be added before setting the track mode to showing - data.TrackEvents.forEach(function (trackEvent) { - - var trackCueObject = window.VTTCue || window.TextTrackCue; - var cue = new trackCueObject(trackEvent.StartPositionTicks / 10000000, trackEvent.EndPositionTicks / 10000000, normalizeTrackEventText(trackEvent.Text)); - - trackElement.addCue(cue); - }); + // This throws an error in IE, but is fine in chrome + // In IE it's not necessary anyway because changing the src seems to be enough + try { trackElement.mode = 'showing'; - }); + while (trackElement.cues.length) { + trackElement.removeCue(trackElement.cues[0]); + } + } catch (e) { + console.log('Error removing cue from textTrack'); + } + + trackElement.mode = 'disabled'; } else { - trackElement.mode = 'showing'; + // There is a function addTextTrack but no function for removeTextTrack + // Therefore we add ONE element and replace its cue data + trackElement = videoElement.addTextTrack('subtitles', 'manualTrack', 'und'); } + + // download the track json + fetchSubtitles(track, item).then(function (data) { + + // show in ui + console.log('downloaded ' + data.TrackEvents.length + ' track events'); + // add some cues to show the text + // in safari, the cues need to be added before setting the track mode to showing + data.TrackEvents.forEach(function (trackEvent) { + + var trackCueObject = window.VTTCue || window.TextTrackCue; + var cue = new trackCueObject(trackEvent.StartPositionTicks / 10000000, trackEvent.EndPositionTicks / 10000000, normalizeTrackEventText(trackEvent.Text)); + + trackElement.addCue(cue); + }); + trackElement.mode = 'showing'; + }); } function updateSubtitleText(timeMs) { // handle offset for ass tracks - if(currentTrackOffset) { + if (currentTrackOffset) { timeMs += (currentTrackOffset * 1000); } @@ -1564,8 +1557,7 @@ define(['browser', 'require', 'events', 'apphost', 'loading', 'dom', 'playbackMa this.isPip = isEnabled; if (isEnabled) { Windows.UI.ViewManagement.ApplicationView.getForCurrentView().tryEnterViewModeAsync(Windows.UI.ViewManagement.ApplicationViewMode.compactOverlay); - } - else { + } else { Windows.UI.ViewManagement.ApplicationView.getForCurrentView().tryEnterViewModeAsync(Windows.UI.ViewManagement.ApplicationViewMode.default); } } else { diff --git a/src/components/humanedate.js b/src/components/humanedate.js index 9abaa952c2..85d3a6d3bf 100644 --- a/src/components/humanedate.js +++ b/src/components/humanedate.js @@ -1,28 +1,45 @@ -define(["datetime"], function(datetime) { +define(["datetime"], function (datetime) { "use strict"; function humaneDate(date_str) { - var format, time_formats = [ - [90, "a minute"], - [3600, "minutes", 60], - [5400, "an hour"], - [86400, "hours", 3600], - [129600, "a day"], - [604800, "days", 86400], - [907200, "a week"], - [2628e3, "weeks", 604800], - [3942e3, "a month"], - [31536e3, "months", 2628e3], - [47304e3, "a year"], - [31536e5, "years", 31536e3] - ], - dt = new Date, - date = datetime.parseISO8601Date(date_str, !0), - seconds = (dt - date) / 1e3, - i = 0; - for (seconds < 0 && (seconds = Math.abs(seconds)); format = time_formats[i++];) - if (seconds < format[0]) return 2 == format.length ? format[1] + " ago" : Math.round(seconds / format[2]) + " " + format[1] + " ago"; - return seconds > 47304e5 ? Math.round(seconds / 47304e5) + " centuries ago" : date_str + var format; + var time_formats = [ + [90, "a minute"], + [3600, "minutes", 60], + [5400, "an hour"], + [86400, "hours", 3600], + [129600, "a day"], + [604800, "days", 86400], + [907200, "a week"], + [2628e3, "weeks", 604800], + [3942e3, "a month"], + [31536e3, "months", 2628e3], + [47304e3, "a year"], + [31536e5, "years", 31536e3] + ]; + var dt = new Date(); + var date = datetime.parseISO8601Date(date_str, true); + var seconds = (dt - date) / 1000.0; + var i = 0; + + if (seconds < 0) { + seconds = Math.abs(seconds); + } + for (; format = time_formats[i++];) { + if (seconds < format[0]) { + if (2 == format.length) { + return format[1] + " ago"; + } + + return Math.round(seconds / format[2]) + " " + format[1] + " ago"; + } + } + + if (seconds > 47304e5) { + return Math.round(seconds / 47304e5) + " centuries ago"; + } + + return date_str; } function humaneElapsed(firstDateStr, secondDateStr) { @@ -30,12 +47,10 @@ define(["datetime"], function(datetime) { var dateOne = new Date(firstDateStr); var dateTwo = new Date(secondDateStr); var delta = (dateTwo.getTime() - dateOne.getTime()) / 1e3; - var days = Math.floor(delta % 31536e3 / 86400); var hours = Math.floor(delta % 31536e3 % 86400 / 3600); var minutes = Math.floor(delta % 31536e3 % 86400 % 3600 / 60); var seconds = Math.round(delta % 31536e3 % 86400 % 3600 % 60); - var elapsed = ""; elapsed += 1 == days ? days + " day " : ""; elapsed += days > 1 ? days + " days " : ""; @@ -46,15 +61,13 @@ define(["datetime"], function(datetime) { elapsed += elapsed.length > 0 ? "and " : ""; elapsed += 1 == seconds ? seconds + " second" : ""; elapsed += 0 == seconds || seconds > 1 ? seconds + " seconds" : ""; - return elapsed; } window.humaneDate = humaneDate; window.humaneElapsed = humaneElapsed; - return { humaneDate: humaneDate, humaneElapsed: humaneElapsed - } -}); \ No newline at end of file + }; +}); diff --git a/src/components/imagedownloader/imagedownloader.js b/src/components/imagedownloader/imagedownloader.js index 729bce3382..ed0539bdda 100644 --- a/src/components/imagedownloader/imagedownloader.js +++ b/src/components/imagedownloader/imagedownloader.js @@ -1,6 +1,8 @@ define(['loading', 'apphost', 'dialogHelper', 'connectionManager', 'imageLoader', 'browser', 'layoutManager', 'scrollHelper', 'globalize', 'require', 'emby-checkbox', 'paper-icon-button-light', 'emby-button', 'formDialogStyle', 'cardStyle'], function (loading, appHost, dialogHelper, connectionManager, imageLoader, browser, layoutManager, scrollHelper, globalize, require) { 'use strict'; + var enableFocusTransform = !browser.slow && !browser.edge; + var currentItemId; var currentItemType; var currentResolve; @@ -164,6 +166,8 @@ define(['loading', 'apphost', 'dialogHelper', 'connectionManager', 'imageLoader' var tagName = layoutManager.tv ? 'button' : 'div'; var enableFooterButtons = !layoutManager.tv; + // TODO move card creation code to Card component + var html = ''; var cssClass = "card scalableCard imageEditorCard"; @@ -172,22 +176,17 @@ define(['loading', 'apphost', 'dialogHelper', 'connectionManager', 'imageLoader' var shape = 'backdrop'; if (imageType === "Backdrop" || imageType === "Art" || imageType === "Thumb" || imageType === "Logo") { shape = 'backdrop'; - } - else if (imageType === "Banner") { + } else if (imageType === "Banner") { shape = 'banner'; - } - else if (imageType === "Disc") { + } else if (imageType === "Disc") { shape = 'square'; - } - else { + } else { if (currentItemType === "Episode") { shape = 'backdrop'; - } - else if (currentItemType === "MusicAlbum" || currentItemType === "MusicArtist") { + } else if (currentItemType === "MusicAlbum" || currentItemType === "MusicArtist") { shape = 'square'; - } - else { + } else { shape = 'portrait'; } } @@ -196,12 +195,12 @@ define(['loading', 'apphost', 'dialogHelper', 'connectionManager', 'imageLoader' if (tagName === 'button') { cssClass += ' btnImageCard'; - if (layoutManager.tv && !browser.slow) { - cardBoxCssClass += ' cardBox-focustransform'; - } - if (layoutManager.tv) { - cardBoxCssClass += ' card-focuscontent cardBox-withfocuscontent'; + cssClass += ' show-focus'; + + if (enableFocusTransform) { + cssClass += ' show-animation'; + } } html += '
'; - } - else { + } else { html += ''; } @@ -413,4 +411,4 @@ define(['loading', 'apphost', 'dialogHelper', 'connectionManager', 'imageLoader' }); } }; -}); \ No newline at end of file +}); diff --git a/src/components/imageeditor/imageeditor.js b/src/components/imageeditor/imageeditor.js index 15c58ad8d9..fade0dd04c 100644 --- a/src/components/imageeditor/imageeditor.js +++ b/src/components/imageeditor/imageeditor.js @@ -1,6 +1,8 @@ define(['dialogHelper', 'connectionManager', 'loading', 'dom', 'layoutManager', 'focusManager', 'globalize', 'scrollHelper', 'imageLoader', 'require', 'browser', 'apphost', 'cardStyle', 'formDialogStyle', 'emby-button', 'paper-icon-button-light', 'css!./imageeditor'], function (dialogHelper, connectionManager, loading, dom, layoutManager, focusManager, globalize, scrollHelper, imageLoader, require, browser, appHost) { 'use strict'; + var enableFocusTransform = !browser.slow && !browser.edge; + var currentItem; var hasChanges = false; @@ -22,8 +24,7 @@ define(['dialogHelper', 'connectionManager', 'loading', 'dom', 'layoutManager', if (item) { apiClient = connectionManager.getApiClient(item.ServerId); reloadItem(page, item, apiClient, focusContext); - } - else { + } else { apiClient = connectionManager.getApiClient(currentItem.ServerId); apiClient.getItem(apiClient.getCurrentUserId(), currentItem.Id).then(function (item) { @@ -58,7 +59,6 @@ define(['dialogHelper', 'connectionManager', 'loading', 'dom', 'layoutManager', } } - apiClient.getItemImageInfos(currentItem.Id).then(function (imageInfos) { renderStandardImages(page, apiClient, item, imageInfos, providers); @@ -95,6 +95,8 @@ define(['dialogHelper', 'connectionManager', 'loading', 'dom', 'layoutManager', function getCardHtml(image, index, numImages, apiClient, imageProviders, imageSize, tagName, enableFooterButtons) { + // TODO move card creation code to Card component + var html = ''; var cssClass = "card scalableCard imageEditorCard"; @@ -105,12 +107,12 @@ define(['dialogHelper', 'connectionManager', 'loading', 'dom', 'layoutManager', if (tagName === 'button') { cssClass += ' btnImageCard'; - if (layoutManager.tv && !browser.slow) { - cardBoxCssClass += ' cardBox-focustransform'; - } - if (layoutManager.tv) { - cardBoxCssClass += ' card-focuscontent cardBox-withfocuscontent'; + cssClass += ' show-focus'; + + if (enableFocusTransform) { + cssClass += ' show-animation'; + } } html += ''; } - } - else { + } else { if (imageProviders.length) { html += ''; } diff --git a/src/components/imageoptionseditor/imageoptionseditor.js b/src/components/imageoptionseditor/imageoptionseditor.js index 94d37d6f7f..c9dc678099 100644 --- a/src/components/imageoptionseditor/imageoptionseditor.js +++ b/src/components/imageoptionseditor/imageoptionseditor.js @@ -1,4 +1,4 @@ -define(["globalize", "dom", "dialogHelper", "emby-checkbox", "emby-select", "emby-input"], function(globalize, dom, dialogHelper) { +define(["globalize", "dom", "dialogHelper", "emby-checkbox", "emby-select", "emby-input"], function (globalize, dom, dialogHelper) { "use strict"; function getDefaultImageConfig(itemType, type) { @@ -6,72 +6,107 @@ define(["globalize", "dom", "dialogHelper", "emby-checkbox", "emby-select", "emb Type: type, MinWidth: 0, Limit: "Primary" === type ? 1 : 0 - } + }; } function findImageOptions(imageOptions, type) { - return imageOptions.filter(function(i) { - return i.Type == type - })[0] + return imageOptions.filter(function (i) { + return i.Type == type; + })[0]; } function getImageConfig(options, availableOptions, imageType, itemType) { - return findImageOptions(options.ImageOptions || [], imageType) || findImageOptions(availableOptions.DefaultImageOptions || [], imageType) || getDefaultImageConfig(itemType, imageType) + return findImageOptions(options.ImageOptions || [], imageType) || findImageOptions(availableOptions.DefaultImageOptions || [], imageType) || getDefaultImageConfig(itemType, imageType); } function setVisibilityOfBackdrops(elem, visible) { - visible ? (elem.classList.remove("hide"), elem.querySelector("input").setAttribute("required", "required")) : (elem.classList.add("hide"), elem.querySelector("input").setAttribute("required", ""), elem.querySelector("input").removeAttribute("required")) + if (visible) { + elem.classList.remove("hide"); + elem.querySelector("input").setAttribute("required", "required"); + } else { + elem.classList.add("hide"); + elem.querySelector("input").setAttribute("required", ""); + elem.querySelector("input").removeAttribute("required"); + } } function loadValues(context, itemType, options, availableOptions) { var supportedImageTypes = availableOptions.SupportedImageTypes || []; - setVisibilityOfBackdrops(context.querySelector(".backdropFields"), -1 != supportedImageTypes.indexOf("Backdrop")), setVisibilityOfBackdrops(context.querySelector(".screenshotFields"), -1 != supportedImageTypes.indexOf("Screenshot")), Array.prototype.forEach.call(context.querySelectorAll(".imageType"), function(i) { - var imageType = i.getAttribute("data-imagetype"), - container = dom.parentWithTag(i, "LABEL"); - 1 == supportedImageTypes.indexOf(imageType) ? container.classList.add("hide") : container.classList.remove("hide"), getImageConfig(options, availableOptions, imageType, itemType).Limit ? i.checked = !0 : i.checked = !1 + setVisibilityOfBackdrops(context.querySelector(".backdropFields"), -1 != supportedImageTypes.indexOf("Backdrop")); + setVisibilityOfBackdrops(context.querySelector(".screenshotFields"), -1 != supportedImageTypes.indexOf("Screenshot")); + Array.prototype.forEach.call(context.querySelectorAll(".imageType"), function (i) { + var imageType = i.getAttribute("data-imagetype"); + var container = dom.parentWithTag(i, "LABEL"); + + if (-1 == supportedImageTypes.indexOf(imageType)) { + container.classList.add("hide"); + } else { + container.classList.remove("hide"); + } + + if (getImageConfig(options, availableOptions, imageType, itemType).Limit) { + i.checked = true; + } else { + i.checked = false; + } }); var backdropConfig = getImageConfig(options, availableOptions, "Backdrop", itemType); - context.querySelector("#txtMaxBackdrops").value = backdropConfig.Limit, context.querySelector("#txtMinBackdropDownloadWidth").value = backdropConfig.MinWidth; + context.querySelector("#txtMaxBackdrops").value = backdropConfig.Limit; + context.querySelector("#txtMinBackdropDownloadWidth").value = backdropConfig.MinWidth; var screenshotConfig = getImageConfig(options, availableOptions, "Screenshot", itemType); - context.querySelector("#txtMaxScreenshots").value = screenshotConfig.Limit, context.querySelector("#txtMinScreenshotDownloadWidth").value = screenshotConfig.MinWidth + context.querySelector("#txtMaxScreenshots").value = screenshotConfig.Limit; + context.querySelector("#txtMinScreenshotDownloadWidth").value = screenshotConfig.MinWidth; } function saveValues(context, options) { - options.ImageOptions = Array.prototype.map.call(context.querySelectorAll(".imageType:not(.hide)"), function(c) { + options.ImageOptions = Array.prototype.map.call(context.querySelectorAll(".imageType:not(.hide)"), function (c) { return { Type: c.getAttribute("data-imagetype"), Limit: c.checked ? 1 : 0, MinWidth: 0 - } - }), options.ImageOptions.push({ + }; + }); + options.ImageOptions.push({ Type: "Backdrop", Limit: context.querySelector("#txtMaxBackdrops").value, MinWidth: context.querySelector("#txtMinBackdropDownloadWidth").value - }), options.ImageOptions.push({ + }); + options.ImageOptions.push({ Type: "Screenshot", Limit: context.querySelector("#txtMaxScreenshots").value, MinWidth: context.querySelector("#txtMinScreenshotDownloadWidth").value - }) + }); } function editor() { - this.show = function(itemType, options, availableOptions) { - return new Promise(function(resolve, reject) { - var xhr = new XMLHttpRequest; - xhr.open("GET", "components/imageoptionseditor/imageoptionseditor.template.html", !0), xhr.onload = function(e) { - var template = this.response, - dlg = dialogHelper.createDialog({ - size: "medium-tall", - removeOnClose: !0, - scrollY: !1 - }); - dlg.classList.add("formDialog"), dlg.innerHTML = globalize.translateDocument(template), dlg.addEventListener("close", function() { - saveValues(dlg, options) - }), loadValues(dlg, itemType, options, availableOptions), dialogHelper.open(dlg).then(resolve, resolve), dlg.querySelector(".btnCancel").addEventListener("click", function() { - dialogHelper.close(dlg) - }) - }, xhr.send() - }) - } + this.show = function (itemType, options, availableOptions) { + return new Promise(function (resolve, reject) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", "components/imageoptionseditor/imageoptionseditor.template.html", true); + + xhr.onload = function (e) { + var template = this.response; + var dlg = dialogHelper.createDialog({ + size: "medium-tall", + removeOnClose: true, + scrollY: false + }); + dlg.classList.add("formDialog"); + dlg.innerHTML = globalize.translateDocument(template); + dlg.addEventListener("close", function () { + saveValues(dlg, options); + }); + loadValues(dlg, itemType, options, availableOptions); + dialogHelper.open(dlg).then(resolve, resolve); + dlg.querySelector(".btnCancel").addEventListener("click", function () { + dialogHelper.close(dlg); + }); + }; + + xhr.send(); + }); + }; } - return editor -}); \ No newline at end of file + + return editor; +}); diff --git a/src/components/images/imageLoader.js b/src/components/images/imageLoader.js index 2a77daa216..a2906cca85 100644 --- a/src/components/images/imageLoader.js +++ b/src/components/images/imageLoader.js @@ -70,7 +70,9 @@ define(['lazyLoader', 'imageFetcher', 'layoutManager', 'browser', 'appSettings', } // Use the median - values.sort(function (a, b) { return a - b; }); + values.sort(function (a, b) { + return a - b; + }); var half = Math.floor(values.length / 2); @@ -78,8 +80,7 @@ define(['lazyLoader', 'imageFetcher', 'layoutManager', 'browser', 'appSettings', if (values.length % 2) { result = values[half]; - } - else { + } else { result = (values[half - 1] + values[half]) / 2.0; } diff --git a/src/components/imageuploader/imageuploader.js b/src/components/imageuploader/imageuploader.js index 3a52d7110d..98fcf0ebce 100644 --- a/src/components/imageuploader/imageuploader.js +++ b/src/components/imageuploader/imageuploader.js @@ -150,7 +150,7 @@ define(['dialogHelper', 'connectionManager', 'dom', 'loading', 'scrollHelper', ' scrollHelper.centerFocus.on(dlg, false); } - // Has to be assigned a z-index after the call to .open() + // Has to be assigned a z-index after the call to .open() dlg.addEventListener('close', function () { if (layoutManager.tv) { diff --git a/src/components/itemcontextmenu.js b/src/components/itemcontextmenu.js index 46a65cabc3..a3aa8cac4f 100644 --- a/src/components/itemcontextmenu.js +++ b/src/components/itemcontextmenu.js @@ -52,8 +52,6 @@ define(["apphost", "globalize", "connectionManager", "itemHelper", "appRouter", //} } - - if (item.IsFolder || item.Type === "MusicArtist" || item.Type === "MusicGenre") { if (item.CollectionType !== "livetv") { if (options.shuffle !== false) { diff --git a/src/components/itemhelper.js b/src/components/itemhelper.js index 7ea0c2b9eb..88f012a3c4 100644 --- a/src/components/itemhelper.js +++ b/src/components/itemhelper.js @@ -250,9 +250,7 @@ define(['apphost', 'globalize'], function (appHost, globalize) { if (item.Type !== 'TvChannel') { return true; } - } - - else if (item.MediaType === 'Audio') { + } else if (item.MediaType === 'Audio') { if (item.Type === 'AudioPodcast') { return true; } diff --git a/src/components/itemidentifier/itemidentifier.js b/src/components/itemidentifier/itemidentifier.js index 36a337cb7e..6f28de0b3b 100644 --- a/src/components/itemidentifier/itemidentifier.js +++ b/src/components/itemidentifier/itemidentifier.js @@ -1,5 +1,7 @@ -define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', 'scrollHelper', 'layoutManager', 'focusManager', 'browser', 'emby-input', 'emby-checkbox', 'paper-icon-button-light', 'css!./../formdialog', 'material-icons', 'cardStyle'], function (dialogHelper, loading, connectionManager, require, globalize, scrollHelper, layoutManager, focusManager, browser) { - 'use strict'; +define(["dialogHelper", "loading", "connectionManager", "require", "globalize", "scrollHelper", "layoutManager", "focusManager", "browser", "emby-input", "emby-checkbox", "paper-icon-button-light", "css!./../formdialog", "material-icons", "cardStyle"], function (dialogHelper, loading, connectionManager, require, globalize, scrollHelper, layoutManager, focusManager, browser) { + "use strict"; + + var enableFocusTransform = !browser.slow && !browser.edge; var currentItem; var currentItemType; @@ -19,8 +21,9 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', ProviderIds: {} }; - var i, length; - var identifyField = page.querySelectorAll('.identifyField'); + var i; + var length; + var identifyField = page.querySelectorAll(".identifyField"); var value; for (i = 0, length = identifyField.length; i < length; i++) { @@ -28,17 +31,17 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', if (value) { - if (identifyField[i].type === 'number') { + if (identifyField[i].type === "number") { value = parseInt(value); } - lookupInfo[identifyField[i].getAttribute('data-lookup')] = value; + lookupInfo[identifyField[i].getAttribute("data-lookup")] = value; } } var hasId = false; - var txtLookupId = page.querySelectorAll('.txtLookupId'); + var txtLookupId = page.querySelectorAll(".txtLookupId"); for (i = 0, length = txtLookupId.length; i < length; i++) { value = txtLookupId[i].value; @@ -46,12 +49,12 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', if (value) { hasId = true; } - lookupInfo.ProviderIds[txtLookupId[i].getAttribute('data-providerkey')] = value; + lookupInfo.ProviderIds[txtLookupId[i].getAttribute("data-providerkey")] = value; } if (!hasId && !lookupInfo.Name) { - require(['toast'], function (toast) { - toast(globalize.translate('PleaseEnterNameOrId')); + require(["toast"], function (toast) { + toast(globalize.translate("PleaseEnterNameOrId")); }); return; } @@ -62,8 +65,7 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', if (currentItem && currentItem.Id) { lookupInfo.ItemId = currentItem.Id; - } - else { + } else { lookupInfo.IncludeDisabledProviders = true; } @@ -76,7 +78,7 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', url: apiClient.getUrl("Items/RemoteSearch/" + currentItemType), data: JSON.stringify(lookupInfo), contentType: "application/json", - dataType: 'json' + dataType: "json" }).then(function (results) { @@ -87,26 +89,27 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', function showIdentificationSearchResults(page, results) { - var identificationSearchResults = page.querySelector('.identificationSearchResults'); + var identificationSearchResults = page.querySelector(".identificationSearchResults"); - page.querySelector('.popupIdentifyForm').classList.add('hide'); - identificationSearchResults.classList.remove('hide'); - page.querySelector('.identifyOptionsForm').classList.add('hide'); - page.querySelector('.dialogContentInner').classList.remove('dialog-content-centered'); + page.querySelector(".popupIdentifyForm").classList.add("hide"); + identificationSearchResults.classList.remove("hide"); + page.querySelector(".identifyOptionsForm").classList.add("hide"); + page.querySelector(".dialogContentInner").classList.remove("dialog-content-centered"); - var html = ''; - var i, length; + var html = ""; + var i; + var length; for (i = 0, length = results.length; i < length; i++) { var result = results[i]; html += getSearchResultHtml(result, i); } - var elem = page.querySelector('.identificationSearchResultList'); + var elem = page.querySelector(".identificationSearchResultList"); elem.innerHTML = html; function onSearchImageClick() { - var index = parseInt(this.getAttribute('data-index')); + var index = parseInt(this.getAttribute("data-index")); var currentResult = results[index]; @@ -119,10 +122,10 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', } } - var searchImages = elem.querySelectorAll('.card'); + var searchImages = elem.querySelectorAll(".card"); for (i = 0, length = searchImages.length; i < length; i++) { - searchImages[i].addEventListener('click', onSearchImageClick); + searchImages[i].addEventListener("click", onSearchImageClick); } if (layoutManager.tv) { @@ -140,13 +143,13 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', function showIdentifyOptions(page, identifyResult) { - var identifyOptionsForm = page.querySelector('.identifyOptionsForm'); + var identifyOptionsForm = page.querySelector(".identifyOptionsForm"); - page.querySelector('.popupIdentifyForm').classList.add('hide'); - page.querySelector('.identificationSearchResults').classList.add('hide'); - identifyOptionsForm.classList.remove('hide'); - page.querySelector('#chkIdentifyReplaceImages').checked = true; - page.querySelector('.dialogContentInner').classList.add('dialog-content-centered'); + page.querySelector(".popupIdentifyForm").classList.add("hide"); + page.querySelector(".identificationSearchResults").classList.add("hide"); + identifyOptionsForm.classList.remove("hide"); + page.querySelector("#chkIdentifyReplaceImages").checked = true; + page.querySelector(".dialogContentInner").classList.add("dialog-content-centered"); currentSearchResult = identifyResult; @@ -157,49 +160,49 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', lines.push(identifyResult.ProductionYear); } - var resultHtml = lines.join('
'); + var resultHtml = lines.join("
"); if (identifyResult.ImageUrl) { var displayUrl = getSearchImageDisplayUrl(identifyResult.ImageUrl, identifyResult.SearchProviderName); - resultHtml = '
' + resultHtml + '
'; + resultHtml = '
' + resultHtml + "
"; } - page.querySelector('.selectedSearchResult').innerHTML = resultHtml; + page.querySelector(".selectedSearchResult").innerHTML = resultHtml; - focusManager.focus(identifyOptionsForm.querySelector('.btnSubmit')); + focusManager.focus(identifyOptionsForm.querySelector(".btnSubmit")); } function getSearchResultHtml(result, index) { - var html = ''; + // TODO move card creation code to Card component + + var html = ""; var cssClass = "card scalableCard"; - var cardBoxCssClass = 'cardBox'; + var cardBoxCssClass = "cardBox"; var padderClass; if (currentItemType === "Episode") { cssClass += " backdropCard backdropCard-scalable"; - padderClass = 'cardPadder-backdrop'; - } - else if (currentItemType === "MusicAlbum" || currentItemType === "MusicArtist") { + padderClass = "cardPadder-backdrop"; + } else if (currentItemType === "MusicAlbum" || currentItemType === "MusicArtist") { cssClass += " squareCard squareCard-scalable"; - padderClass = 'cardPadder-square'; - } - else { + padderClass = "cardPadder-square"; + } else { cssClass += " portraitCard portraitCard-scalable"; - padderClass = 'cardPadder-portrait'; + padderClass = "cardPadder-portrait"; } - if (layoutManager.tv && !browser.slow) { - cardBoxCssClass += ' cardBox-focustransform'; - } - - cardBoxCssClass += ' cardBox-bottompadded'; - if (layoutManager.tv) { - cardBoxCssClass += ' card-focuscontent cardBox-withfocuscontent'; + cssClass += " show-focus"; + + if (enableFocusTransform) { + cssClass += " show-animation"; + } } + cardBoxCssClass += " cardBox-bottompadded"; + html += '
"; + html += "
"; var numLines = 2; if (currentItemType === "MusicAlbum") { @@ -239,12 +242,12 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', } else { html += '
'; } - html += lines[i] || ' '; - html += '
'; + html += lines[i] || " "; + html += "
"; } - html += '
'; - html += ''; + html += "
"; + html += ""; return html; } @@ -259,7 +262,7 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', loading.show(); var options = { - ReplaceAllImages: page.querySelector('#chkIdentifyReplaceImages').checked + ReplaceAllImages: page.querySelector("#chkIdentifyReplaceImages").checked }; var apiClient = getApiClient(); @@ -291,7 +294,7 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', apiClient.getJSON(apiClient.getUrl("Items/" + item.Id + "/ExternalIdInfos")).then(function (idList) { - var html = ''; + var html = ""; var providerIds = item.ProviderIds || {}; @@ -303,30 +306,30 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', html += '
'; - var idLabel = globalize.translate('LabelDynamicExternalId').replace('{0}', idInfo.Name); + var idLabel = globalize.translate("LabelDynamicExternalId").replace("{0}", idInfo.Name); - var value = providerIds[idInfo.Key] || ''; + var value = providerIds[idInfo.Key] || ""; html += ''; - html += '
'; + html += "
"; } - page.querySelector('#txtLookupName').value = ''; + page.querySelector("#txtLookupName").value = ""; if (item.Type === "Person" || item.Type === "BoxSet") { - page.querySelector('.fldLookupYear').classList.add('hide'); - page.querySelector('#txtLookupYear').value = ''; + page.querySelector(".fldLookupYear").classList.add("hide"); + page.querySelector("#txtLookupYear").value = ""; } else { - page.querySelector('.fldLookupYear').classList.remove('hide'); - page.querySelector('#txtLookupYear').value = ''; + page.querySelector(".fldLookupYear").classList.remove("hide"); + page.querySelector("#txtLookupYear").value = ""; } - page.querySelector('.identifyProviderIds').innerHTML = html; + page.querySelector(".identifyProviderIds").innerHTML = html; - page.querySelector('.formDialogHeaderTitle').innerHTML = globalize.translate('Identify'); + page.querySelector(".formDialogHeaderTitle").innerHTML = globalize.translate("Identify"); }); } @@ -334,7 +337,7 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', loading.show(); - require(['text!./itemidentifier.template.html'], function (template) { + require(["text!./itemidentifier.template.html"], function (template) { var apiClient = getApiClient(); @@ -344,54 +347,62 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', currentItemType = currentItem.Type; var dialogOptions = { - size: 'fullscreen-border', + size: "fullscreen-border", removeOnClose: true, scrollY: false }; if (layoutManager.tv) { - dialogOptions.size = 'fullscreen'; + dialogOptions.size = "fullscreen"; } var dlg = dialogHelper.createDialog(dialogOptions); - dlg.classList.add('formDialog'); - dlg.classList.add('recordingDialog'); + dlg.classList.add("formDialog"); + dlg.classList.add("recordingDialog"); - var html = ''; - html += globalize.translateDocument(template, 'core'); + var html = ""; + html += globalize.translateDocument(template, "core"); dlg.innerHTML = html; // Has to be assigned a z-index after the call to .open() - dlg.addEventListener('close', onDialogClosed); + dlg.addEventListener("close", onDialogClosed); if (layoutManager.tv) { - scrollHelper.centerFocus.on(dlg.querySelector('.formDialogContent'), false); + scrollHelper.centerFocus.on(dlg.querySelector(".formDialogContent"), false); } + if (item.Path) { + dlg.querySelector('.fldPath').classList.remove('hide'); + } else { + dlg.querySelector('.fldPath').classList.add('hide'); + } + + dlg.querySelector('.txtPath').innerHTML = item.Path || ''; + dialogHelper.open(dlg); - dlg.querySelector('.popupIdentifyForm').addEventListener('submit', function (e) { + dlg.querySelector(".popupIdentifyForm").addEventListener("submit", function (e) { e.preventDefault(); searchForIdentificationResults(dlg); return false; }); - dlg.querySelector('.identifyOptionsForm').addEventListener('submit', function (e) { + dlg.querySelector(".identifyOptionsForm").addEventListener("submit", function (e) { e.preventDefault(); submitIdentficationResult(dlg); return false; }); - dlg.querySelector('.btnCancel').addEventListener('click', function (e) { + dlg.querySelector(".btnCancel").addEventListener("click", function (e) { dialogHelper.close(dlg); }); - dlg.classList.add('identifyDialog'); + dlg.classList.add("identifyDialog"); showIdentificationForm(dlg, item); loading.hide(); @@ -414,47 +425,47 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', currentItem = null; currentItemType = itemType; - require(['text!./itemidentifier.template.html'], function (template) { + require(["text!./itemidentifier.template.html"], function (template) { var dialogOptions = { - size: 'fullscreen-border', + size: "fullscreen-border", removeOnClose: true, scrollY: false }; if (layoutManager.tv) { - dialogOptions.size = 'fullscreen'; + dialogOptions.size = "fullscreen"; } var dlg = dialogHelper.createDialog(dialogOptions); - dlg.classList.add('formDialog'); - dlg.classList.add('recordingDialog'); + dlg.classList.add("formDialog"); + dlg.classList.add("recordingDialog"); - var html = ''; - html += globalize.translateDocument(template, 'core'); + var html = ""; + html += globalize.translateDocument(template, "core"); dlg.innerHTML = html; if (layoutManager.tv) { - scrollHelper.centerFocus.on(dlg.querySelector('.formDialogContent'), false); + scrollHelper.centerFocus.on(dlg.querySelector(".formDialogContent"), false); } dialogHelper.open(dlg); - dlg.querySelector('.btnCancel').addEventListener('click', function (e) { + dlg.querySelector(".btnCancel").addEventListener("click", function (e) { dialogHelper.close(dlg); }); - dlg.querySelector('.popupIdentifyForm').addEventListener('submit', function (e) { + dlg.querySelector(".popupIdentifyForm").addEventListener("submit", function (e) { e.preventDefault(); searchForIdentificationResults(dlg); return false; }); - dlg.addEventListener('close', function () { + dlg.addEventListener("close", function () { loading.hide(); var foundItem = hasChanges ? currentSearchResult : null; @@ -462,7 +473,7 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', resolveFunc(foundItem); }); - dlg.classList.add('identifyDialog'); + dlg.classList.add("identifyDialog"); showIdentificationFormFindNew(dlg, itemName, itemYear, itemType); }); @@ -470,20 +481,20 @@ define(['dialogHelper', 'loading', 'connectionManager', 'require', 'globalize', function showIdentificationFormFindNew(dlg, itemName, itemYear, itemType) { - dlg.querySelector('#txtLookupName').value = itemName; + dlg.querySelector("#txtLookupName").value = itemName; if (itemType === "Person" || itemType === "BoxSet") { - dlg.querySelector('.fldLookupYear').classList.add('hide'); - dlg.querySelector('#txtLookupYear').value = ''; + dlg.querySelector(".fldLookupYear").classList.add("hide"); + dlg.querySelector("#txtLookupYear").value = ""; } else { - dlg.querySelector('.fldLookupYear').classList.remove('hide'); - dlg.querySelector('#txtLookupYear').value = itemYear; + dlg.querySelector(".fldLookupYear").classList.remove("hide"); + dlg.querySelector("#txtLookupYear").value = itemYear; } - dlg.querySelector('.formDialogHeaderTitle').innerHTML = globalize.translate('Search'); + dlg.querySelector(".formDialogHeaderTitle").innerHTML = globalize.translate("Search"); } return { diff --git a/src/components/itemidentifier/itemidentifier.template.html b/src/components/itemidentifier/itemidentifier.template.html index e9ba163a02..9750bab57d 100644 --- a/src/components/itemidentifier/itemidentifier.template.html +++ b/src/components/itemidentifier/itemidentifier.template.html @@ -1,5 +1,7 @@
- +

${Identify}

@@ -10,11 +12,17 @@

${HeaderIdentifyItemHelp}

+
+
${LabelPath}
+
+
- +
- +
@@ -43,10 +51,11 @@
-
-
\ No newline at end of file +
diff --git a/src/components/itemsrefresher.js b/src/components/itemsrefresher.js index d9bef95b4b..46956d2df5 100644 --- a/src/components/itemsrefresher.js +++ b/src/components/itemsrefresher.js @@ -11,8 +11,7 @@ define(['playbackManager', 'serverNotifications', 'events'], function (playbackM if (eventsToMonitor.indexOf('markfavorite') !== -1) { instance.notifyRefreshNeeded(); - } - else if (eventsToMonitor.indexOf('markplayed') !== -1) { + } else if (eventsToMonitor.indexOf('markplayed') !== -1) { instance.notifyRefreshNeeded(); } @@ -115,9 +114,7 @@ define(['playbackManager', 'serverNotifications', 'events'], function (playbackM instance.notifyRefreshNeeded(true); return; } - } - - else if (state.NowPlayingItem && state.NowPlayingItem.MediaType === 'Audio') { + } else if (state.NowPlayingItem && state.NowPlayingItem.MediaType === 'Audio') { if (eventsToMonitor.indexOf('audioplayback') !== -1) { diff --git a/src/components/keyboardnavigation.js b/src/components/keyboardnavigation.js index 7ed74f2201..8c0bb1a3ae 100644 --- a/src/components/keyboardnavigation.js +++ b/src/components/keyboardnavigation.js @@ -8,20 +8,20 @@ define(['inputManager', 'focusManager'], function(inputManager, focusManager) { var capture = true; switch (e.keyCode) { - case 37: // ArrowLeft - inputManager.handle('left'); - break; - case 38: // ArrowUp - inputManager.handle('up'); - break; - case 39: // ArrowRight - inputManager.handle('right'); - break; - case 40: // ArrowDown - inputManager.handle('down'); - break; - default: - capture = false; + case 37: // ArrowLeft + inputManager.handle('left'); + break; + case 38: // ArrowUp + inputManager.handle('up'); + break; + case 39: // ArrowRight + inputManager.handle('right'); + break; + case 40: // ArrowDown + inputManager.handle('down'); + break; + default: + capture = false; } if (capture) { console.log("Disabling default event handling"); @@ -31,6 +31,6 @@ define(['inputManager', 'focusManager'], function(inputManager, focusManager) { } return { - enable: enable, + enable: enable }; }); diff --git a/src/components/lazyloader/lazyloader-intersectionobserver.js b/src/components/lazyloader/lazyloader-intersectionobserver.js index 261ca84261..1935f65a30 100644 --- a/src/components/lazyloader/lazyloader-intersectionobserver.js +++ b/src/components/lazyloader/lazyloader-intersectionobserver.js @@ -45,7 +45,7 @@ define(['require', 'browser'], function (require, browser) { } } }, - observerOptions + observerOptions ); this.observer = observer; diff --git a/src/components/listview/listview.js b/src/components/listview/listview.js index 257551abf6..974cb0ab09 100644 --- a/src/components/listview/listview.js +++ b/src/components/listview/listview.js @@ -9,7 +9,8 @@ define(['itemHelper', 'mediaInfo', 'indicators', 'connectionManager', 'layoutMan } var sortBy = (options.sortBy || '').toLowerCase(); - var code, name; + var code; + var name; if (sortBy.indexOf('sortname') === 0) { @@ -85,15 +86,12 @@ define(['itemHelper', 'mediaInfo', 'indicators', 'connectionManager', 'layoutMan options.tag = item.AlbumPrimaryImageTag; return apiClient.getScaledImageUrl(item.AlbumId, options); - } - - else if (item.SeriesId && item.SeriesPrimaryImageTag) { + } else if (item.SeriesId && item.SeriesPrimaryImageTag) { options.tag = item.SeriesPrimaryImageTag; return apiClient.getScaledImageUrl(item.SeriesId, options); - } - else if (item.ParentPrimaryImageTag) { + } else if (item.ParentPrimaryImageTag) { options.tag = item.ParentPrimaryImageTag; return apiClient.getScaledImageUrl(item.ParentPrimaryImageItemId, options); @@ -209,8 +207,7 @@ define(['itemHelper', 'mediaInfo', 'indicators', 'connectionManager', 'layoutMan if (i === 0) { html += '

'; - } - else { + } else { html += '

'; } html += itemGroupTitle; @@ -349,9 +346,7 @@ define(['itemHelper', 'mediaInfo', 'indicators', 'connectionManager', 'layoutMan if (options.showParentTitle) { if (item.Type === 'Episode') { parentTitle = item.SeriesName; - } - - else if (item.IsSeries || (item.EpisodeTitle && item.Name)) { + } else if (item.IsSeries || (item.EpisodeTitle && item.Name)) { parentTitle = item.Name; } } @@ -375,8 +370,7 @@ define(['itemHelper', 'mediaInfo', 'indicators', 'connectionManager', 'layoutMan } textlines.push(parentTitle || ''); - } - else if (options.showParentTitle) { + } else if (options.showParentTitle) { textlines.push(parentTitle || ''); } @@ -400,8 +394,7 @@ define(['itemHelper', 'mediaInfo', 'indicators', 'connectionManager', 'layoutMan if (!artistItems || !artistItems.length) { showArtist = true; - } - else if (artistItems.length > 1 || containerAlbumArtistIds.indexOf(artistItems[0].Id) === -1) { + } else if (artistItems.length > 1 || containerAlbumArtistIds.indexOf(artistItems[0].Id) === -1) { showArtist = true; } } diff --git a/src/components/loading/loading.js b/src/components/loading/loading.js index ad9aea950a..510f311217 100644 --- a/src/components/loading/loading.js +++ b/src/components/loading/loading.js @@ -45,7 +45,8 @@ define(['components/loading/loadingLegacy', 'browser', 'css!./loading'], functio layer3.classList.add('mdl-spinner__layer-3-active'); layer4.classList.add('mdl-spinner__layer-4-active'); - var i, length; + var i; + var length; for (i = 0, length = circleLefts.length; i < length; i++) { circleLefts[i].classList.add('mdl-spinner__circleLeft-active'); @@ -67,7 +68,8 @@ define(['components/loading/loadingLegacy', 'browser', 'css!./loading'], functio elem.classList.remove('mdl-spinner__layer-3-active'); elem.classList.remove('mdl-spinner__layer-4-active'); - var i, length; + var i; + var length; for (i = 0, length = circleLefts.length; i < length; i++) { circleLefts[i].classList.remove('mdl-spinner__circleLeft-active'); diff --git a/src/components/mediainfo/mediainfo.js b/src/components/mediainfo/mediainfo.js index 441adac3dd..0fb4a1e7be 100644 --- a/src/components/mediainfo/mediainfo.js +++ b/src/components/mediainfo/mediainfo.js @@ -7,16 +7,13 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater if (item.Type === 'SeriesTimer') { return ''; - } - else if (item.TimerId || item.SeriesTimerId) { + } else if (item.TimerId || item.SeriesTimerId) { status = item.Status || 'Cancelled'; - } - else if (item.Type === 'Timer') { + } else if (item.Type === 'Timer') { status = item.Status; - } - else { + } else { return ''; } @@ -36,7 +33,8 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater var html = ''; var miscInfo = []; - var text, date; + var text; + var date; if (item.StartDate && options.programTime !== false) { @@ -58,8 +56,7 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater } miscInfo.push(text); - } - catch (e) { + } catch (e) { console.log("Error parsing date: " + item.StartDate); } } @@ -107,7 +104,9 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater var miscInfo = []; options = options || {}; - var text, date, minutes; + var text; + var date; + var minutes; var count; var showFolderRuntime = item.Type === "MusicAlbum" || item.MediaType === 'MusicArtist' || item.MediaType === 'Playlist' || item.MediaType === 'MusicGenre'; @@ -124,9 +123,7 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater if (item.RunTimeTicks) { miscInfo.push(datetime.getDisplayRunningTime(item.RunTimeTicks)); } - } - - else if (item.Type === "PhotoAlbum" || item.Type === "BoxSet") { + } else if (item.Type === "PhotoAlbum" || item.Type === "BoxSet") { count = item.ChildCount; @@ -145,8 +142,7 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater text = datetime.toLocaleDateString(date); miscInfo.push(text); - } - catch (e) { + } catch (e) { console.log("Error parsing date: " + item.PremiereDate); } } @@ -162,8 +158,7 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater if (item.RecordAnyChannel) { miscInfo.push(globalize.translate('AllChannels')); - } - else { + } else { miscInfo.push(item.ChannelName || globalize.translate('OneChannel')); } } @@ -180,8 +175,7 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater text = datetime.getDisplayTime(date); miscInfo.push(text); } - } - catch (e) { + } catch (e) { console.log("Error parsing date: " + item.StartDate); } } @@ -191,8 +185,7 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater if (item.Status === "Continuing") { miscInfo.push(globalize.translate('SeriesYearToPresent', item.ProductionYear)); - } - else if (item.ProductionYear) { + } else if (item.ProductionYear) { text = item.ProductionYear; @@ -206,8 +199,7 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater text += "-" + datetime.parseISO8601Date(item.EndDate).getFullYear(); } - } - catch (e) { + } catch (e) { console.log("Error parsing date: " + item.EndDate); } } @@ -223,18 +215,15 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater miscInfo.push({ html: '
' + globalize.translate('Live') + '
' }); - } - else if (item.IsPremiere) { + } else if (item.IsPremiere) { miscInfo.push({ html: '
' + globalize.translate('Premiere') + '
' }); - } - else if (item.IsSeries && !item.IsRepeat) { + } else if (item.IsSeries && !item.IsRepeat) { miscInfo.push({ html: '
' + globalize.translate('AttributeNew') + '
' }); - } - else if (item.IsSeries && item.IsRepeat) { + } else if (item.IsSeries && item.IsRepeat) { miscInfo.push({ html: '
' + globalize.translate('Repeat') + '
' }); @@ -250,20 +239,15 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater if (text) { miscInfo.push(text); } - } - - else if (item.IsMovie && item.ProductionYear && options.originalAirDate !== false) { + } else if (item.IsMovie && item.ProductionYear && options.originalAirDate !== false) { miscInfo.push(item.ProductionYear); - } - - else if (item.PremiereDate && options.originalAirDate !== false) { + } else if (item.PremiereDate && options.originalAirDate !== false) { try { date = datetime.parseISO8601Date(item.PremiereDate); text = globalize.translate('OriginalAirDateValue', datetime.toLocaleDateString(date)); miscInfo.push(text); - } - catch (e) { + } catch (e) { console.log("Error parsing date: " + item.PremiereDate); } } else if (item.ProductionYear) { @@ -277,14 +261,12 @@ define(['datetime', 'globalize', 'appRouter', 'itemHelper', 'indicators', 'mater if (item.ProductionYear) { miscInfo.push(item.ProductionYear); - } - else if (item.PremiereDate) { + } else if (item.PremiereDate) { try { text = datetime.parseISO8601Date(item.PremiereDate).getFullYear(); miscInfo.push(text); - } - catch (e) { + } catch (e) { console.log("Error parsing date: " + item.PremiereDate); } } diff --git a/src/components/medialibrarycreator/medialibrarycreator.js b/src/components/medialibrarycreator/medialibrarycreator.js index 54c13a4ebe..183e22551f 100644 --- a/src/components/medialibrarycreator/medialibrarycreator.js +++ b/src/components/medialibrarycreator/medialibrarycreator.js @@ -151,13 +151,13 @@ define(["loading", "dialogHelper", "dom", "jQuery", "components/libraryoptionsed var xhr = new XMLHttpRequest; xhr.open("GET", "components/medialibrarycreator/medialibrarycreator.template.html", true); xhr.onload = function(e) { - var template = this.response, - dlg = dialogHelper.createDialog({ - size: "medium-tall", - modal: false, - removeOnClose: true, - scrollY: false - }); + var template = this.response; + var dlg = dialogHelper.createDialog({ + size: "medium-tall", + modal: false, + removeOnClose: true, + scrollY: false + }); dlg.classList.add("ui-body-a"); dlg.classList.add("background-theme-a"); dlg.classList.add("dlg-librarycreator"); diff --git a/src/components/metadataeditor/metadataeditor.js b/src/components/metadataeditor/metadataeditor.js index 552c716c1f..8843dc159c 100644 --- a/src/components/metadataeditor/metadataeditor.js +++ b/src/components/metadataeditor/metadataeditor.js @@ -144,7 +144,9 @@ define(['itemHelper', 'dom', 'layoutManager', 'dialogHelper', 'datetime', 'loadi AirTime: form.querySelector('#txtAirTime').value, Genres: getListValues(form.querySelector("#listGenres")), Tags: getListValues(form.querySelector("#listTags")), - Studios: getListValues(form.querySelector("#listStudios")).map(function (element) { return { Name: element }; }), + Studios: getListValues(form.querySelector("#listStudios")).map(function (element) { + return { Name: element }; + }), PremiereDate: getDateValue(form, '#txtPremiereDate', 'PremiereDate'), DateCreated: getDateValue(form, '#txtDateAdded', 'DateCreated'), @@ -202,7 +204,9 @@ define(['itemHelper', 'dom', 'layoutManager', 'dialogHelper', 'datetime', 'loadi } function getListValues(list) { - return Array.prototype.map.call(list.querySelectorAll('.textValue'), function (el) { return el.textContent; }); + return Array.prototype.map.call(list.querySelectorAll('.textValue'), function (el) { + return el.textContent; + }); } function addElementToList(source, sortCallback) { @@ -439,7 +443,6 @@ define(['itemHelper', 'dom', 'layoutManager', 'dialogHelper', 'datetime', 'loadi var html = metadataInfo.ContentTypeOptions.map(function (i) { - return ''; }).join(''); @@ -744,7 +747,9 @@ define(['itemHelper', 'dom', 'layoutManager', 'dialogHelper', 'datetime', 'loadi populateListView(context.querySelector('#listGenres'), item.Genres); populatePeople(context, item.People || []); - populateListView(context.querySelector('#listStudios'), (item.Studios || []).map(function (element) { return element.Name || ''; })); + populateListView(context.querySelector('#listStudios'), (item.Studios || []).map(function (element) { + return element.Name || ''; + })); populateListView(context.querySelector('#listTags'), item.Tags); @@ -783,8 +788,7 @@ define(['itemHelper', 'dom', 'layoutManager', 'dialogHelper', 'datetime', 'loadi if (item.Type === 'Series') { context.querySelector('#selectDisplayOrder').value = item.DisplayOrder || ''; - } - else { + } else { context.querySelector('#selectDisplayOrder').value = item.DisplayOrder || ''; } @@ -859,7 +863,9 @@ define(['itemHelper', 'dom', 'layoutManager', 'dialogHelper', 'datetime', 'loadi html += ""; var ratings = []; - var i, length, rating; + var i; + var length; + var rating; var currentValueFound = false; @@ -901,7 +907,9 @@ define(['itemHelper', 'dom', 'layoutManager', 'dialogHelper', 'datetime', 'loadi items = items || []; if (typeof (sortCallback) === 'undefined') { - items.sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); + items.sort(function (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()); + }); } else { items = sortCallback(items); } diff --git a/src/components/multiselect/multiselect.js b/src/components/multiselect/multiselect.js index d706b76b99..a6a416d528 100644 --- a/src/components/multiselect/multiselect.js +++ b/src/components/multiselect/multiselect.js @@ -241,8 +241,6 @@ define(['browser', 'appStorage', 'apphost', 'loading', 'connectionManager', 'glo id: 'refresh' }); - - require(['actionsheet'], function (actionsheet) { actionsheet.show({ items: menuItems, diff --git a/src/components/navdrawer/navdrawer.js b/src/components/navdrawer/navdrawer.js index cbf5c1eebc..69adbd1f5a 100644 --- a/src/components/navdrawer/navdrawer.js +++ b/src/components/navdrawer/navdrawer.js @@ -21,13 +21,13 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, } function onMenuTouchMove(e) { - var isOpen = self.visible, - touches = getTouches(e), - touch = touches[0] || {}, - endX = touch.clientX || 0, - endY = touch.clientY || 0, - deltaX = endX - (menuTouchStartX || 0), - deltaY = endY - (menuTouchStartY || 0); + var isOpen = self.visible; + var touches = getTouches(e); + var touch = touches[0] || {}; + var endX = touch.clientX || 0; + var endY = touch.clientY || 0; + var deltaX = endX - (menuTouchStartX || 0); + var deltaY = endY - (menuTouchStartY || 0); setVelocity(deltaX), isOpen && 1 !== dragMode && deltaX > 0 && (dragMode = 2), 0 === dragMode && (!isOpen || Math.abs(deltaX) >= 10) && Math.abs(deltaY) < 5 ? (dragMode = 1, scrollContainer.addEventListener("scroll", disableEvent), self.showMask()) : 0 === dragMode && Math.abs(deltaY) >= 5 && (dragMode = 2), 1 === dragMode && (newPos = currentPos + deltaX, self.changeMenuPos()) } @@ -36,12 +36,12 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, scrollContainer.removeEventListener("scroll", disableEvent); dragMode = 0; - var touches = getTouches(e), - touch = touches[0] || {}, - endX = touch.clientX || 0, - endY = touch.clientY || 0, - deltaX = endX - (menuTouchStartX || 0), - deltaY = endY - (menuTouchStartY || 0); + var touches = getTouches(e); + var touch = touches[0] || {}; + var endX = touch.clientX || 0; + var endY = touch.clientY || 0; + var deltaX = endX - (menuTouchStartX || 0); + var deltaY = endY - (menuTouchStartY || 0); currentPos = deltaX; self.checkMenuState(deltaX, deltaY); @@ -78,15 +78,15 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, } function onBackgroundTouchStart(e) { - var touches = getTouches(e), - touch = touches[0] || {}; + var touches = getTouches(e); + var touch = touches[0] || {}; backgroundTouchStartX = touch.clientX, backgroundTouchStartTime = (new Date).getTime() } function onBackgroundTouchMove(e) { - var touches = getTouches(e), - touch = touches[0] || {}, - endX = touch.clientX || 0; + var touches = getTouches(e); + var touch = touches[0] || {}; + var endX = touch.clientX || 0; if (endX <= options.width && self.isVisible) { countStart++; var deltaX = endX - (backgroundTouchStartX || 0); @@ -100,10 +100,10 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, } function onBackgroundTouchEnd(e) { - var touches = getTouches(e), - touch = touches[0] || {}, - endX = touch.clientX || 0, - deltaX = endX - (backgroundTouchStartX || 0); + var touches = getTouches(e); + var touch = touches[0] || {}; + var endX = touch.clientX || 0; + var deltaX = endX - (backgroundTouchStartX || 0); self.checkMenuState(deltaX), countStart = 0 } @@ -111,21 +111,24 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, var classList = mask.classList; classList.contains("backdrop") || classList.add("hide") } - var self, defaults, mask, newPos = 0, - currentPos = 0, - startPoint = 0, - countStart = 0, - velocity = 0; + var self; + var defaults; + var mask; + var newPos = 0; + var currentPos = 0; + var startPoint = 0; + var countStart = 0; + var velocity = 0; options.target.classList.add("transition"); - var dragMode = 0, - scrollContainer = options.target.querySelector(".mainDrawer-scrollContainer"); + var dragMode = 0; + var scrollContainer = options.target.querySelector(".mainDrawer-scrollContainer"); scrollContainer.classList.add("scrollY"); var TouchMenuLA = function() { self = this, defaults = { width: 260, handleSize: 10, disableMask: !1, - maxMaskOpacity: .5 + maxMaskOpacity: 0.5 }, this.isVisible = !1, this.initialize() }; TouchMenuLA.prototype.initElements = function() { @@ -133,8 +136,11 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, passive: !0 })) }; - var menuTouchStartX, menuTouchStartY, menuTouchStartTime, edgeContainer = document.querySelector(".mainDrawerHandle"), - isPeeking = !1; + var menuTouchStartX; + var menuTouchStartY; + var menuTouchStartTime; + var edgeContainer = document.querySelector(".mainDrawerHandle"); + var isPeeking = false; TouchMenuLA.prototype.animateToPosition = function(pos) { requestAnimationFrame(function() { options.target.style.transform = pos ? "translateX(" + pos + "px)" : "none" @@ -146,7 +152,7 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, self.close() }) }, TouchMenuLA.prototype.checkMenuState = function(deltaX, deltaY) { - velocity >= .4 ? deltaX >= 0 || Math.abs(deltaY || 0) >= 70 ? self.open() : self.close() : newPos >= 100 ? self.open() : newPos && self.close() + velocity >= 0.4 ? deltaX >= 0 || Math.abs(deltaY || 0) >= 70 ? self.open() : self.close() : newPos >= 100 ? self.open() : newPos && self.close() }, TouchMenuLA.prototype.open = function() { this.animateToPosition(options.width), currentPos = options.width, this.isVisible = !0, options.target.classList.add("drawer-open"), self.showMask(), self.invoke(options.onChange) }, TouchMenuLA.prototype.close = function() { @@ -154,7 +160,8 @@ define(["browser", "dom", "css!./navdrawer", "scrollStyles"], function(browser, }, TouchMenuLA.prototype.toggle = function() { self.isVisible ? self.close() : self.open() }; - var backgroundTouchStartX, backgroundTouchStartTime; + var backgroundTouchStartX; + var backgroundTouchStartTime; TouchMenuLA.prototype.showMask = function() { mask.classList.remove("hide"), mask.offsetWidth, mask.classList.add("backdrop") }, TouchMenuLA.prototype.hideMask = function() { diff --git a/src/components/notifications/notifications.js b/src/components/notifications/notifications.js index 304eec7e08..62de365d99 100644 --- a/src/components/notifications/notifications.js +++ b/src/components/notifications/notifications.js @@ -21,8 +21,7 @@ define(['serverNotifications', 'playbackManager', 'events', 'globalize', 'requir if (notification.close) { notification.close(); - } - else if (notification.cancel) { + } else if (notification.cancel) { notification.cancel(); } }, timeoutMs); @@ -180,15 +179,12 @@ define(['serverNotifications', 'playbackManager', 'events', 'globalize', 'requir if (status === 'completed') { notification.title = globalize.translate('PackageInstallCompleted').replace('{0}', installation.Name + ' ' + installation.Version); notification.vibrate = true; - } - else if (status === 'cancelled') { + } else if (status === 'cancelled') { notification.title = globalize.translate('PackageInstallCancelled').replace('{0}', installation.Name + ' ' + installation.Version); - } - else if (status === 'failed') { + } else if (status === 'failed') { notification.title = globalize.translate('PackageInstallFailed').replace('{0}', installation.Name + ' ' + installation.Version); notification.vibrate = true; - } - else if (status === 'progress') { + } else if (status === 'progress') { notification.title = globalize.translate('InstallingPackage').replace('{0}', installation.Name + ' ' + installation.Version); notification.actions = diff --git a/src/components/nowplayingbar/nowplayingbar.js b/src/components/nowplayingbar/nowplayingbar.js index 9fac61ba1f..d7be482c52 100644 --- a/src/components/nowplayingbar/nowplayingbar.js +++ b/src/components/nowplayingbar/nowplayingbar.js @@ -134,7 +134,8 @@ define(['require', 'datetime', 'itemHelper', 'events', 'browser', 'imageLoader', } }); - var i, length; + var i; + var length; playPauseButtons = elem.querySelectorAll('.playPauseButton'); for (i = 0, length = playPauseButtons.length; i < length; i++) { playPauseButtons[i].addEventListener('click', onPlayPauseClick); @@ -195,7 +196,6 @@ define(['require', 'datetime', 'itemHelper', 'events', 'browser', 'imageLoader', volumeSlider.addEventListener('mousemove', setVolume); volumeSlider.addEventListener('touchmove', setVolume); - positionSlider = elem.querySelector('.nowPlayingBarPositionSlider'); positionSlider.addEventListener('change', function () { @@ -282,8 +282,8 @@ define(['require', 'datetime', 'itemHelper', 'events', 'browser', 'imageLoader', } function updatePlayPauseState(isPaused) { - - var i, length; + var i; + var length; if (playPauseButtons) { if (isPaused) { @@ -345,8 +345,7 @@ define(['require', 'datetime', 'itemHelper', 'events', 'browser', 'imageLoader', if (repeatMode === 'RepeatAll') { toggleRepeatButtonIcon.innerHTML = "repeat"; toggleRepeatButton.classList.add('repeatButton-active'); - } - else if (repeatMode === 'RepeatOne') { + } else if (repeatMode === 'RepeatOne') { toggleRepeatButtonIcon.innerHTML = "repeat_one"; toggleRepeatButton.classList.add('repeatButton-active'); } else { diff --git a/src/components/playback/autoplaydetect.js b/src/components/playback/autoplaydetect.js index 7a7a73a538..3610eef2ab 100644 --- a/src/components/playback/autoplaydetect.js +++ b/src/components/playback/autoplaydetect.js @@ -48,9 +48,7 @@ define([], function () { } timeout = setTimeout(testAutoplay, 500); - } - - catch (e) { + } catch (e) { reject(); return; } diff --git a/src/components/playback/brightnessosd.js b/src/components/playback/brightnessosd.js index 1797463f29..c949743bec 100644 --- a/src/components/playback/brightnessosd.js +++ b/src/components/playback/brightnessosd.js @@ -103,8 +103,7 @@ define(['events', 'playbackManager', 'dom', 'browser', 'css!./iconosd', 'materia if (iconElement) { if (brightness >= 80) { iconElement.innerHTML = ''; - } - else if (brightness >= 20) { + } else if (brightness >= 20) { iconElement.innerHTML = ''; } else { iconElement.innerHTML = ''; diff --git a/src/components/playback/mediasession.js b/src/components/playback/mediasession.js index 63e0bde6c1..7f4b9f519e 100644 --- a/src/components/playback/mediasession.js +++ b/src/components/playback/mediasession.js @@ -158,7 +158,7 @@ define(['playbackManager', 'nowPlayingHelper', 'events', 'connectionManager'], f lastUpdateTime = now; - if (navigator.mediaSession){ + if (navigator.mediaSession) { navigator.mediaSession.metadata = new MediaMetadata({ title: title, artist: artist, @@ -278,7 +278,6 @@ define(['playbackManager', 'nowPlayingHelper', 'events', 'connectionManager'], f } if (navigator.mediaSession) { - navigator.mediaSession.setActionHandler('previoustrack', function () { execute('previousTrack'); }); diff --git a/src/components/playback/nowplayinghelper.js b/src/components/playback/nowplayinghelper.js index d5803b426f..b1af977ab0 100644 --- a/src/components/playback/nowplayinghelper.js +++ b/src/components/playback/nowplayinghelper.js @@ -43,8 +43,7 @@ define([], function () { } else if (nowPlayingItem.Artists && nowPlayingItem.Artists.length) { bottomText = nowPlayingItem.Artists.join(', '); - } - else if (nowPlayingItem.SeriesName || nowPlayingItem.Album) { + } else if (nowPlayingItem.SeriesName || nowPlayingItem.Album) { bottomText = topText; topText = nowPlayingItem.SeriesName || nowPlayingItem.Album; @@ -60,8 +59,7 @@ define([], function () { } else { topItem = null; } - } - else if (nowPlayingItem.ProductionYear && includeNonNameInfo !== false) { + } else if (nowPlayingItem.ProductionYear && includeNonNameInfo !== false) { bottomText = nowPlayingItem.ProductionYear; } diff --git a/src/components/playback/playbackmanager.js b/src/components/playback/playbackmanager.js index 04fb89b3d1..23f0d4572e 100644 --- a/src/components/playback/playbackmanager.js +++ b/src/components/playback/playbackmanager.js @@ -107,8 +107,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla TotalRecordCount: 1 }; }); - } - else { + } else { query.Limit = query.Limit || 300; query.Fields = "Chapters"; @@ -182,8 +181,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla if (container === 'm4a') { return 'audio/mp4'; } - } - else if (type === 'video') { + } else if (type === 'video') { if (container === 'mkv') { return 'video/x-matroska'; } @@ -212,8 +210,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla var results = regex.exec(url); if (results == null) { return ""; - } - else { + } else { return decodeURIComponent(results[1].replace(/\+/g, " ")); } } @@ -649,13 +646,10 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla // If this is the only way it can be played, then allow it if (!mediaSource.SupportsDirectStream && !mediaSource.SupportsTranscoding) { return Promise.resolve(true); - } - else { + } else { return isHostReachable(mediaSource, apiClient); } - } - - else if (mediaSource.Protocol === 'File') { + } else if (mediaSource.Protocol === 'File') { return new Promise(function (resolve, reject) { @@ -1272,7 +1266,8 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla var currentMediaSource = self.currentMediaSource(player); var mediaStreams = []; - var i, length; + var i; + var length; for (i = 0, length = currentMediaSource.MediaStreams.length; i < length; i++) { if (currentMediaSource.MediaStreams[i].Type === 'Audio') { mediaStreams.push(currentMediaSource.MediaStreams[i]); @@ -1316,7 +1311,8 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla var currentMediaSource = self.currentMediaSource(player); var mediaStreams = []; - var i, length; + var i; + var length; for (i = 0, length = currentMediaSource.MediaStreams.length; i < length; i++) { if (currentMediaSource.MediaStreams[i].Type === 'Subtitle') { mediaStreams.push(currentMediaSource.MediaStreams[i]); @@ -1360,7 +1356,8 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla function isAudioStreamSupported(mediaSource, index, deviceProfile) { var mediaStream; - var i, length; + var i; + var length; var mediaStreams = mediaSource.MediaStreams; for (i = 0, length = mediaStreams.length; i < length; i++) { @@ -1423,8 +1420,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla if (isAudioStreamSupported(self.currentMediaSource(player), index, profile)) { player.setAudioStreamIndex(index); getPlayerData(player).audioStreamIndex = index; - } - else { + } else { changeStream(player, getCurrentTicks(player), { AudioStreamIndex: index }); getPlayerData(player).audioStreamIndex = index; } @@ -1595,8 +1591,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla // Need to change the transcoded stream to remove subs changeStream(player, getCurrentTicks(player), { SubtitleStreamIndex: -1 }); } - } - else if (!currentStream && newStream) { + } else if (!currentStream && newStream) { if (getDeliveryMethod(newStream) === 'External') { selectedTrackElementIndex = index; @@ -1607,8 +1602,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla // Need to change the transcoded stream to add subs changeStream(player, getCurrentTicks(player), { SubtitleStreamIndex: index }); } - } - else if (currentStream && newStream) { + } else if (currentStream && newStream) { // Switching tracks // We can handle this clientside if the new track is external or the new track is embedded and we're not transcoding @@ -1645,7 +1639,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla player = player || self._currentPlayer; if (player.disableShowingSubtitleOffset) { player.disableShowingSubtitleOffset(); - } + } } self.isShowingSubtitleOffsetEnabled = function(player) { @@ -1667,14 +1661,14 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla self.getPlayerSubtitleOffset = function(player) { player = player || self._currentPlayer; - if (player.getPlayerSubtitleOffset) { + if (player.getSubtitleOffset) { return player.getSubtitleOffset(); } } self.canHandleOffsetOnCurrentSubtitle = function(player) { var index = self.getSubtitleStreamIndex(player); - return index !== -1 && self.isSubtitleStreamExternal(index, player); + return index !== -1 && self.isSubtitleStreamExternal(index, player); } self.seek = function (ticks, player) { @@ -1865,17 +1859,15 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla if (firstItem.Type === "Program") { promise = getItemsForPlayback(serverId, { - Ids: firstItem.ChannelId, + Ids: firstItem.ChannelId }); - } - else if (firstItem.Type === "Playlist") { + } else if (firstItem.Type === "Playlist") { promise = getItemsForPlayback(serverId, { ParentId: firstItem.Id, SortBy: options.shuffle ? 'Random' : null }); - } - else if (firstItem.Type === "MusicArtist") { + } else if (firstItem.Type === "MusicArtist") { promise = getItemsForPlayback(serverId, { ArtistIds: firstItem.Id, @@ -1885,8 +1877,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla MediaTypes: "Audio" }); - } - else if (firstItem.MediaType === "Photo") { + } else if (firstItem.MediaType === "Photo") { promise = getItemsForPlayback(serverId, { ParentId: firstItem.ParentId, @@ -1915,8 +1906,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla return Promise.resolve(result); }); - } - else if (firstItem.Type === "PhotoAlbum") { + } else if (firstItem.Type === "PhotoAlbum") { promise = getItemsForPlayback(serverId, { ParentId: firstItem.Id, @@ -1928,8 +1918,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla Limit: 1000 }); - } - else if (firstItem.Type === "MusicGenre") { + } else if (firstItem.Type === "MusicGenre") { promise = getItemsForPlayback(serverId, { GenreIds: firstItem.Id, @@ -1938,8 +1927,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla SortBy: options.shuffle ? 'Random' : 'SortName', MediaTypes: "Audio" }); - } - else if (firstItem.IsFolder) { + } else if (firstItem.IsFolder) { promise = getItemsForPlayback(serverId, mergePlaybackQueries({ @@ -1951,8 +1939,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla MediaTypes: "Audio,Video" }, queryOptions)); - } - else if (firstItem.Type === "Episode" && items.length === 1 && getPlayer(firstItem, options).supportsProgress !== false) { + } else if (firstItem.Type === "Episode" && items.length === 1 && getPlayer(firstItem, options).supportsProgress !== false) { promise = new Promise(function (resolve, reject) { var apiClient = connectionManager.getApiClient(firstItem.ServerId); @@ -2537,16 +2524,12 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla playMethod = 'DirectPlay'; - } - - else if (mediaSource.StreamUrl) { + } else if (mediaSource.StreamUrl) { // Only used for audio playMethod = 'Transcode'; mediaUrl = mediaSource.StreamUrl; - } - - else if (mediaSource.SupportsDirectStream) { + } else if (mediaSource.SupportsDirectStream) { directOptions = { Static: true, @@ -2706,9 +2689,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla return p.canPlayItem(item, playOptions); } return true; - } - - else if (item.Url && p.canPlayUrl) { + } else if (item.Url && p.canPlayUrl) { return p.canPlayUrl(item.Url); } } @@ -3222,8 +3203,7 @@ define(['events', 'datetime', 'appSettings', 'itemHelper', 'pluginManager', 'pla if (displayErrorCode && typeof (displayErrorCode) === 'string') { showPlaybackInfoErrorMessage(self, displayErrorCode, nextItem); - } - else if (nextItem) { + } else if (nextItem) { self.nextTrack(); } } diff --git a/src/components/playback/playbackorientation.js b/src/components/playback/playbackorientation.js index 731d9c3c42..3253d8acdf 100644 --- a/src/components/playback/playbackorientation.js +++ b/src/components/playback/playbackorientation.js @@ -29,8 +29,7 @@ define(['playbackManager', 'layoutManager', 'events'], function (playbackManager // returns a boolean orientationLocked = promise; } - } - catch (err) { + } catch (err) { onOrientationChangeError(err); } } @@ -46,8 +45,7 @@ define(['playbackManager', 'layoutManager', 'events'], function (playbackManager if (unlockOrientation) { try { unlockOrientation(); - } - catch (err) { + } catch (err) { console.log('error unlocking orientation: ' + err); } orientationLocked = false; diff --git a/src/components/playback/playerSelectionMenu.js b/src/components/playback/playerSelectionMenu.js index 2102720e9a..7e4352bcb7 100644 --- a/src/components/playback/playerSelectionMenu.js +++ b/src/components/playback/playerSelectionMenu.js @@ -153,7 +153,6 @@ define(['appSettings', 'events', 'browser', 'loading', 'playbackManager', 'appRo }); } - function disconnectFromPlayer(currentDeviceName) { if (playbackManager.getSupportedCommands().indexOf('EndSession') !== -1) { @@ -193,7 +192,6 @@ define(['appSettings', 'events', 'browser', 'loading', 'playbackManager', 'appRo }); - } else { playbackManager.setDefaultPlayerActive(); @@ -275,8 +273,7 @@ define(['appSettings', 'events', 'browser', 'loading', 'playbackManager', 'appRo dialogHelper.open(dlg).then(function () { if (destination === 'nowplaying') { appRouter.showNowPlaying(); - } - else if (destination === 'disconnectFromPlayer') { + } else if (destination === 'disconnectFromPlayer') { disconnectFromPlayer(currentDeviceName); } }, emptyCallback); diff --git a/src/components/playback/playmethodhelper.js b/src/components/playback/playmethodhelper.js index 58458aa399..4e85f87093 100644 --- a/src/components/playback/playmethodhelper.js +++ b/src/components/playback/playmethodhelper.js @@ -9,14 +9,11 @@ define([], function () { if (session.TranscodingInfo && session.TranscodingInfo.IsVideoDirect) { return 'DirectStream'; - } - else if (session.PlayState.PlayMethod === 'Transcode') { + } else if (session.PlayState.PlayMethod === 'Transcode') { return 'Transcode'; - } - else if (session.PlayState.PlayMethod === 'DirectStream') { + } else if (session.PlayState.PlayMethod === 'DirectStream') { return 'DirectPlay'; - } - else if (session.PlayState.PlayMethod === 'DirectPlay') { + } else if (session.PlayState.PlayMethod === 'DirectPlay') { return 'DirectPlay'; } } diff --git a/src/components/playback/playqueuemanager.js b/src/components/playback/playqueuemanager.js index 2cbaf1d9f4..ed2076a814 100644 --- a/src/components/playback/playqueuemanager.js +++ b/src/components/playback/playqueuemanager.js @@ -58,15 +58,15 @@ define([], function () { function arrayInsertAt(destArray, pos, arrayToInsert) { var args = []; - args.push(pos); // where to insert - args.push(0); // nothing to remove - args = args.concat(arrayToInsert); // add on array to insert - destArray.splice.apply(destArray, args); // splice it in + args.push(pos); // where to insert + args.push(0); // nothing to remove + args = args.concat(arrayToInsert); // add on array to insert + destArray.splice.apply(destArray, args); // splice it in } PlayQueueManager.prototype.queueNext = function (items) { - - var i, length; + var i; + var length; for (i = 0, length = items.length; i < length; i++) { diff --git a/src/components/playerstats/playerstats.js b/src/components/playerstats/playerstats.js index 5e097f2fe2..4179192dd2 100644 --- a/src/components/playerstats/playerstats.js +++ b/src/components/playerstats/playerstats.js @@ -364,8 +364,7 @@ define(['events', 'globalize', 'playbackManager', 'connectionManager', 'playMeth var category = playerStats[i]; if (category.type === 'audio') { category.name = 'Audio Info'; - } - else if (category.type === 'video') { + } else if (category.type === 'video') { category.name = 'Video Info'; } categories.push(category); diff --git a/src/components/recordingcreator/recordingbutton.js b/src/components/recordingcreator/recordingbutton.js index 0a76d3914c..f51f8f2766 100644 --- a/src/components/recordingcreator/recordingbutton.js +++ b/src/components/recordingcreator/recordingbutton.js @@ -46,16 +46,13 @@ define(['globalize', 'connectionManager', 'require', 'loading', 'apphost', 'dom' if (item.Type === 'SeriesTimer') { return ''; - } - else if (item.TimerId || item.SeriesTimerId) { + } else if (item.TimerId || item.SeriesTimerId) { status = item.Status || 'Cancelled'; - } - else if (item.Type === 'Timer') { + } else if (item.Type === 'Timer') { status = item.Status; - } - else { + } else { return ''; } diff --git a/src/components/recordingcreator/recordingcreator.js b/src/components/recordingcreator/recordingcreator.js index b3d16a0dab..614d483b21 100644 --- a/src/components/recordingcreator/recordingcreator.js +++ b/src/components/recordingcreator/recordingcreator.js @@ -40,8 +40,7 @@ define(['dialogHelper', 'globalize', 'layoutManager', 'mediaInfo', 'apphost', 'c maxHeight: imageHeight, tag: item.ImageTags.Primary }); - } - else if (imageTags.Thumb) { + } else if (imageTags.Thumb) { return apiClient.getScaledImageUrl(item.Id, { type: "Thumb", diff --git a/src/components/recordingcreator/recordingeditor.js b/src/components/recordingcreator/recordingeditor.js index 69b8b1023b..3a1d4ba943 100644 --- a/src/components/recordingcreator/recordingeditor.js +++ b/src/components/recordingcreator/recordingeditor.js @@ -95,7 +95,6 @@ define(['dialogHelper', 'globalize', 'layoutManager', 'mediaInfo', 'apphost', 'c currentResolve = resolve; require(['text!./recordingeditor.template.html'], function (template) { - var dialogOptions = { removeOnClose: true, scrollY: false @@ -103,7 +102,6 @@ define(['dialogHelper', 'globalize', 'layoutManager', 'mediaInfo', 'apphost', 'c if (layoutManager.tv) { dialogOptions.size = 'fullscreen'; - } else { } var dlg = dialogHelper.createDialog(dialogOptions); diff --git a/src/components/recordingcreator/recordinghelper.js b/src/components/recordingcreator/recordinghelper.js index 8c56b578c9..4bfd316c73 100644 --- a/src/components/recordingcreator/recordinghelper.js +++ b/src/components/recordingcreator/recordinghelper.js @@ -166,8 +166,7 @@ define(['globalize', 'loading', 'connectionManager'], function (globalize, loadi loading.show(); cancelTimer(apiClient, timerId, true).then(resolve, reject); - } - else if (result === 'cancelseriestimer') { + } else if (result === 'cancelseriestimer') { loading.show(); diff --git a/src/components/recordingcreator/seriesrecordingeditor.js b/src/components/recordingcreator/seriesrecordingeditor.js index 9878081e67..73a98cf5e7 100644 --- a/src/components/recordingcreator/seriesrecordingeditor.js +++ b/src/components/recordingcreator/seriesrecordingeditor.js @@ -139,7 +139,7 @@ define(['dialogHelper', 'globalize', 'layoutManager', 'mediaInfo', 'apphost', 'c context.querySelector('.selectKeepUpTo').innerHTML = html; } - + function onFieldChange(e) { this.querySelector('.btnSubmit').click(); } diff --git a/src/components/remotecontrol/remotecontrol.js b/src/components/remotecontrol/remotecontrol.js index e586a1e124..562ea7ea35 100644 --- a/src/components/remotecontrol/remotecontrol.js +++ b/src/components/remotecontrol/remotecontrol.js @@ -179,15 +179,15 @@ define(["browser", "datetime", "backdrop", "libraryBrowser", "listView", "imageL if (player) { switch (playbackManager.getRepeatMode(player)) { case "RepeatNone": - playbackManager.setRepeatMode("RepeatAll", player); - break; + playbackManager.setRepeatMode("RepeatAll", player); + break; case "RepeatAll": - playbackManager.setRepeatMode("RepeatOne", player); - break; + playbackManager.setRepeatMode("RepeatOne", player); + break; case "RepeatOne": - playbackManager.setRepeatMode("RepeatNone", player); + playbackManager.setRepeatMode("RepeatNone", player); } } } diff --git a/src/components/sanitizefilename.js b/src/components/sanitizefilename.js index 843ab31f04..d422a95533 100644 --- a/src/components/sanitizefilename.js +++ b/src/components/sanitizefilename.js @@ -34,18 +34,14 @@ define([], function () { // when parsing previous hi-surrogate, 3 is added to byteLength if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) { byteLength += 1; - } - else { + } else { byteLength += 3; } - } - else if (codePoint <= 0x7f) { + } else if (codePoint <= 0x7f) { byteLength += 1; - } - else if (codePoint >= 0x80 && codePoint <= 0x7ff) { + } else if (codePoint >= 0x80 && codePoint <= 0x7ff) { byteLength += 2; - } - else if (codePoint >= 0x800 && codePoint <= 0xffff) { + } else if (codePoint >= 0x800 && codePoint <= 0xffff) { byteLength += 3; } prevCodePoint = codePoint; @@ -77,8 +73,7 @@ define([], function () { if (curByteLength === byteLength) { return string.slice(0, i + 1); - } - else if (curByteLength > byteLength) { + } else if (curByteLength > byteLength) { return string.slice(0, i - segment.length + 1); } } @@ -89,11 +84,11 @@ define([], function () { return { sanitize: function (input, replacement) { var sanitized = input - .replace(illegalRe, replacement) - .replace(controlRe, replacement) - .replace(reservedRe, replacement) - .replace(windowsReservedRe, replacement) - .replace(windowsTrailingRe, replacement); + .replace(illegalRe, replacement) + .replace(controlRe, replacement) + .replace(reservedRe, replacement) + .replace(windowsReservedRe, replacement) + .replace(windowsTrailingRe, replacement); return truncate(sanitized, 255); } }; diff --git a/src/components/scroller.js b/src/components/scroller.js index de0ce6b932..65f33b8e8d 100644 --- a/src/components/scroller.js +++ b/src/components/scroller.js @@ -82,7 +82,7 @@ define(['browser', 'layoutManager', 'dom', 'focusManager', 'ResizeObserver', 'sc intervactive: null, // Selector for special interactive elements. // Mixed options - speed: 0, // Animations speed in milliseconds. 0 to disable animations. + speed: 0 // Animations speed in milliseconds. 0 to disable animations. }, options); @@ -93,17 +93,14 @@ define(['browser', 'layoutManager', 'dom', 'focusManager', 'ResizeObserver', 'sc // in cases with firefox, if the smooth scroll api is supported then use that because their implementation is very good if (options.allowNativeScroll === false) { options.enableNativeScroll = false; - } - else if (isSmoothScrollSupported && ((browser.firefox && !layoutManager.tv) || options.allowNativeSmoothScroll)) { + } else if (isSmoothScrollSupported && ((browser.firefox && !layoutManager.tv) || options.allowNativeSmoothScroll)) { // native smooth scroll options.enableNativeScroll = true; - } - else if (options.requireAnimation && (browser.animate || browser.supportsCssAnimation())) { + } else if (options.requireAnimation && (browser.animate || browser.supportsCssAnimation())) { // transform is the only way to guarantee animation options.enableNativeScroll = false; - } - else if (!layoutManager.tv || !browser.animate) { + } else if (!layoutManager.tv || !browser.animate) { options.enableNativeScroll = true; } @@ -211,7 +208,9 @@ define(['browser', 'layoutManager', 'dom', 'focusManager', 'ResizeObserver', 'sc self.frameResizeObserver.observe(frame); } - self.reload = function () { load(); }; + self.reload = function () { + load(); + }; self.getScrollEventName = function () { return transform ? 'scrollanimate' : 'scroll'; @@ -227,7 +226,6 @@ define(['browser', 'layoutManager', 'dom', 'focusManager', 'ResizeObserver', 'sc function nativeScrollTo(container, pos, immediate) { - if (container.scroll) { if (o.horizontal) { @@ -242,8 +240,7 @@ define(['browser', 'layoutManager', 'dom', 'focusManager', 'ResizeObserver', 'sc behavior: immediate ? 'instant' : 'smooth' }); } - } - else if (!immediate && container.scrollTo) { + } else if (!immediate && container.scrollTo) { if (o.horizontal) { container.scrollTo(Math.round(pos), 0); } else { diff --git a/src/components/search/searchresults.js b/src/components/search/searchresults.js index e42088c066..d979a94693 100644 --- a/src/components/search/searchresults.js +++ b/src/components/search/searchresults.js @@ -56,8 +56,7 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', if (instance.options.collectionType === 'tvshows') { if (query.IncludeArtists) { allowSearch = false; - } - else if (queryIncludeItemTypes === 'Movie' || + } else if (queryIncludeItemTypes === 'Movie' || queryIncludeItemTypes === 'LiveTvProgram' || queryIncludeItemTypes === 'MusicAlbum' || queryIncludeItemTypes === 'Audio' || @@ -69,12 +68,10 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', query.MediaTypes === 'Photo') { allowSearch = false; } - } - else if (instance.options.collectionType === 'movies') { + } else if (instance.options.collectionType === 'movies') { if (query.IncludeArtists) { allowSearch = false; - } - else if (queryIncludeItemTypes === 'Series' || + } else if (queryIncludeItemTypes === 'Series' || queryIncludeItemTypes === 'Episode' || queryIncludeItemTypes === 'LiveTvProgram' || queryIncludeItemTypes === 'MusicAlbum' || @@ -87,23 +84,19 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', query.MediaTypes === 'Photo') { allowSearch = false; } - } - else if (instance.options.collectionType === 'music') { + } else if (instance.options.collectionType === 'music') { if (query.People) { allowSearch = false; - } - else if (queryIncludeItemTypes === 'Series' || + } else if (queryIncludeItemTypes === 'Series' || queryIncludeItemTypes === 'Episode' || queryIncludeItemTypes === 'LiveTvProgram' || queryIncludeItemTypes === 'Movie') { allowSearch = false; } - } - else if (instance.options.collectionType === 'livetv') { + } else if (instance.options.collectionType === 'livetv') { if (query.IncludeArtists || query.IncludePeople) { allowSearch = false; - } - else if (queryIncludeItemTypes === 'Series' || + } else if (queryIncludeItemTypes === 'Series' || queryIncludeItemTypes === 'Episode' || queryIncludeItemTypes === 'MusicAlbum' || queryIncludeItemTypes === 'Audio' || @@ -142,7 +135,7 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', } else if (query.IncludeArtists) { methodName = 'getArtists'; - } + } } return apiClient[methodName](apiClient.getCurrentUserId(), query); @@ -179,19 +172,19 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.movieResults', { - preferThumb: true, - inheritThumb: false, - shape: (enableScrollX() ? 'overflowPortrait' : 'portrait'), - showParentTitleOrTitle: true, - showTitle: false, - centerText: true, - coverImage: true, - overlayText: false, - overlayMoreButton: true, - showAirTime: true, - showAirDateTime: true, - showChannelName: true - }); + preferThumb: true, + inheritThumb: false, + shape: (enableScrollX() ? 'overflowPortrait' : 'portrait'), + showParentTitleOrTitle: true, + showTitle: false, + centerText: true, + coverImage: true, + overlayText: false, + overlayMoreButton: true, + showAirTime: true, + showAirDateTime: true, + showChannelName: true + }); } else { searchType(instance, apiClient, { @@ -205,11 +198,11 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.movieResults', { - showTitle: true, - overlayText: false, - centerText: true, - showYear: true - }); + showTitle: true, + overlayText: false, + centerText: true, + showYear: true + }); } searchType(instance, apiClient, { @@ -223,11 +216,11 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.seriesResults', { - showTitle: true, - overlayText: false, - centerText: true, - showYear: true - }); + showTitle: true, + overlayText: false, + centerText: true, + showYear: true + }); if (instance.options.collectionType === 'livetv') { @@ -246,19 +239,19 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.episodeResults', { - preferThumb: true, - inheritThumb: false, - shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), - showParentTitleOrTitle: true, - showTitle: false, - centerText: true, - coverImage: true, - overlayText: false, - overlayMoreButton: true, - showAirTime: true, - showAirDateTime: true, - showChannelName: true - }); + preferThumb: true, + inheritThumb: false, + shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), + showParentTitleOrTitle: true, + showTitle: false, + centerText: true, + coverImage: true, + overlayText: false, + overlayMoreButton: true, + showAirTime: true, + showAirDateTime: true, + showChannelName: true + }); } else { @@ -273,10 +266,10 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.episodeResults', { - coverImage: true, - showTitle: true, - showParentTitle: true - }); + coverImage: true, + showTitle: true, + showParentTitle: true + }); } searchType(instance, apiClient, { @@ -292,20 +285,20 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.sportsResults', { - preferThumb: true, - inheritThumb: false, - shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), - showParentTitleOrTitle: true, - showTitle: false, - centerText: true, - coverImage: true, - overlayText: false, - overlayMoreButton: true, - showAirTime: true, - showAirDateTime: true, - showChannelName: true + preferThumb: true, + inheritThumb: false, + shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), + showParentTitleOrTitle: true, + showTitle: false, + centerText: true, + coverImage: true, + overlayText: false, + overlayMoreButton: true, + showAirTime: true, + showAirDateTime: true, + showChannelName: true - }); + }); searchType(instance, apiClient, { searchTerm: value, @@ -320,20 +313,20 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.kidsResults', { - preferThumb: true, - inheritThumb: false, - shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), - showParentTitleOrTitle: true, - showTitle: false, - centerText: true, - coverImage: true, - overlayText: false, - overlayMoreButton: true, - showAirTime: true, - showAirDateTime: true, - showChannelName: true + preferThumb: true, + inheritThumb: false, + shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), + showParentTitleOrTitle: true, + showTitle: false, + centerText: true, + coverImage: true, + overlayText: false, + overlayMoreButton: true, + showAirTime: true, + showAirDateTime: true, + showChannelName: true - }); + }); searchType(instance, apiClient, { searchTerm: value, @@ -348,20 +341,20 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.newsResults', { - preferThumb: true, - inheritThumb: false, - shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), - showParentTitleOrTitle: true, - showTitle: false, - centerText: true, - coverImage: true, - overlayText: false, - overlayMoreButton: true, - showAirTime: true, - showAirDateTime: true, - showChannelName: true + preferThumb: true, + inheritThumb: false, + shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), + showParentTitleOrTitle: true, + showTitle: false, + centerText: true, + coverImage: true, + overlayText: false, + overlayMoreButton: true, + showAirTime: true, + showAirDateTime: true, + showChannelName: true - }); + }); searchType(instance, apiClient, { searchTerm: value, @@ -379,20 +372,20 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.programResults', { - preferThumb: true, - inheritThumb: false, - shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), - showParentTitleOrTitle: true, - showTitle: false, - centerText: true, - coverImage: true, - overlayText: false, - overlayMoreButton: true, - showAirTime: true, - showAirDateTime: true, - showChannelName: true + preferThumb: true, + inheritThumb: false, + shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), + showParentTitleOrTitle: true, + showTitle: false, + centerText: true, + coverImage: true, + overlayText: false, + overlayMoreButton: true, + showAirTime: true, + showAirDateTime: true, + showChannelName: true - }); + }); searchType(instance, apiClient, { searchTerm: value, @@ -406,11 +399,11 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.videoResults', { - showParentTitle: true, - showTitle: true, - overlayText: false, - centerText: true - }); + showParentTitle: true, + showTitle: true, + overlayText: false, + centerText: true + }); searchType(instance, apiClient, { searchTerm: value, @@ -422,9 +415,9 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.peopleResults', { - coverImage: true, - showTitle: true - }); + coverImage: true, + showTitle: true + }); searchType(instance, apiClient, { searchTerm: value, @@ -435,9 +428,9 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', IncludeArtists: true }, context, '.artistResults', { - coverImage: true, - showTitle: true - }); + coverImage: true, + showTitle: true + }); searchType(instance, apiClient, { searchTerm: value, @@ -450,11 +443,11 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.albumResults', { - showParentTitle: true, - showTitle: true, - overlayText: false, - centerText: true - }); + showParentTitle: true, + showTitle: true, + overlayText: false, + centerText: true + }); searchType(instance, apiClient, { searchTerm: value, @@ -467,13 +460,13 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.songResults', { - showParentTitle: true, - showTitle: true, - overlayText: false, - centerText: true, - action: 'play' + showParentTitle: true, + showTitle: true, + overlayText: false, + centerText: true, + action: 'play' - }); + }); searchType(instance, apiClient, { searchTerm: value, @@ -486,11 +479,11 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.photoResults', { - showParentTitle: false, - showTitle: true, - overlayText: false, - centerText: true - }); + showParentTitle: false, + showTitle: true, + overlayText: false, + centerText: true + }); searchType(instance, apiClient, { searchTerm: value, @@ -503,10 +496,10 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.photoAlbumResults', { - showTitle: true, - overlayText: false, - centerText: true - }); + showTitle: true, + overlayText: false, + centerText: true + }); searchType(instance, apiClient, { searchTerm: value, @@ -519,11 +512,11 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.bookResults', { - showTitle: true, - overlayText: false, - centerText: true + showTitle: true, + overlayText: false, + centerText: true - }); + }); searchType(instance, apiClient, { searchTerm: value, @@ -536,10 +529,10 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.audioBookResults', { - showTitle: true, - overlayText: false, - centerText: true - }); + showTitle: true, + overlayText: false, + centerText: true + }); searchType(instance, apiClient, { searchTerm: value, @@ -552,10 +545,10 @@ define(['layoutManager', 'globalize', 'require', 'events', 'connectionManager', }, context, '.playlistResults', { - showTitle: true, - overlayText: false, - centerText: true - }); + showTitle: true, + overlayText: false, + centerText: true + }); } function searchType(instance, apiClient, query, context, section, cardOptions) { diff --git a/src/components/serverNotifications/gamepadtokey.js b/src/components/serverNotifications/gamepadtokey.js index 5dafb2828b..abf3ddb38b 100644 --- a/src/components/serverNotifications/gamepadtokey.js +++ b/src/components/serverNotifications/gamepadtokey.js @@ -22,44 +22,44 @@ require(['apphost'], function (appHost) { "use strict"; - var _GAMEPAD_A_BUTTON_INDEX = 0, - _GAMEPAD_B_BUTTON_INDEX = 1, - _GAMEPAD_DPAD_UP_BUTTON_INDEX = 12, - _GAMEPAD_DPAD_DOWN_BUTTON_INDEX = 13, - _GAMEPAD_DPAD_LEFT_BUTTON_INDEX = 14, - _GAMEPAD_DPAD_RIGHT_BUTTON_INDEX = 15, - _GAMEPAD_A_KEY = "GamepadA", - _GAMEPAD_B_KEY = "GamepadB", - _GAMEPAD_DPAD_UP_KEY = "GamepadDPadUp", - _GAMEPAD_DPAD_DOWN_KEY = "GamepadDPadDown", - _GAMEPAD_DPAD_LEFT_KEY = "GamepadDPadLeft", - _GAMEPAD_DPAD_RIGHT_KEY = "GamepadDPadRight", - _GAMEPAD_LEFT_THUMBSTICK_UP_KEY = "GamepadLeftThumbStickUp", - _GAMEPAD_LEFT_THUMBSTICK_DOWN_KEY = "GamepadLeftThumbStickDown", - _GAMEPAD_LEFT_THUMBSTICK_LEFT_KEY = "GamepadLeftThumbStickLeft", - _GAMEPAD_LEFT_THUMBSTICK_RIGHT_KEY = "GamepadLeftThumbStickRight", - _GAMEPAD_A_KEYCODE = 0, - _GAMEPAD_B_KEYCODE = 27, - _GAMEPAD_DPAD_UP_KEYCODE = 38, - _GAMEPAD_DPAD_DOWN_KEYCODE = 40, - _GAMEPAD_DPAD_LEFT_KEYCODE = 37, - _GAMEPAD_DPAD_RIGHT_KEYCODE = 39, - _GAMEPAD_LEFT_THUMBSTICK_UP_KEYCODE = 38, - _GAMEPAD_LEFT_THUMBSTICK_DOWN_KEYCODE = 40, - _GAMEPAD_LEFT_THUMBSTICK_LEFT_KEYCODE = 37, - _GAMEPAD_LEFT_THUMBSTICK_RIGHT_KEYCODE = 39, - _THUMB_STICK_THRESHOLD = 0.75; + var _GAMEPAD_A_BUTTON_INDEX = 0; + var _GAMEPAD_B_BUTTON_INDEX = 1; + var _GAMEPAD_DPAD_UP_BUTTON_INDEX = 12; + var _GAMEPAD_DPAD_DOWN_BUTTON_INDEX = 13; + var _GAMEPAD_DPAD_LEFT_BUTTON_INDEX = 14; + var _GAMEPAD_DPAD_RIGHT_BUTTON_INDEX = 15; + var _GAMEPAD_A_KEY = "GamepadA"; + var _GAMEPAD_B_KEY = "GamepadB"; + var _GAMEPAD_DPAD_UP_KEY = "GamepadDPadUp"; + var _GAMEPAD_DPAD_DOWN_KEY = "GamepadDPadDown"; + var _GAMEPAD_DPAD_LEFT_KEY = "GamepadDPadLeft"; + var _GAMEPAD_DPAD_RIGHT_KEY = "GamepadDPadRight"; + var _GAMEPAD_LEFT_THUMBSTICK_UP_KEY = "GamepadLeftThumbStickUp"; + var _GAMEPAD_LEFT_THUMBSTICK_DOWN_KEY = "GamepadLeftThumbStickDown"; + var _GAMEPAD_LEFT_THUMBSTICK_LEFT_KEY = "GamepadLeftThumbStickLeft"; + var _GAMEPAD_LEFT_THUMBSTICK_RIGHT_KEY = "GamepadLeftThumbStickRight"; + var _GAMEPAD_A_KEYCODE = 0; + var _GAMEPAD_B_KEYCODE = 27; + var _GAMEPAD_DPAD_UP_KEYCODE = 38; + var _GAMEPAD_DPAD_DOWN_KEYCODE = 40; + var _GAMEPAD_DPAD_LEFT_KEYCODE = 37; + var _GAMEPAD_DPAD_RIGHT_KEYCODE = 39; + var _GAMEPAD_LEFT_THUMBSTICK_UP_KEYCODE = 38; + var _GAMEPAD_LEFT_THUMBSTICK_DOWN_KEYCODE = 40; + var _GAMEPAD_LEFT_THUMBSTICK_LEFT_KEYCODE = 37; + var _GAMEPAD_LEFT_THUMBSTICK_RIGHT_KEYCODE = 39; + var _THUMB_STICK_THRESHOLD = 0.75; - var _leftThumbstickUpPressed = false, - _leftThumbstickDownPressed = false, - _leftThumbstickLeftPressed = false, - _leftThumbstickRightPressed = false, - _dPadUpPressed = false, - _dPadDownPressed = false, - _dPadLeftPressed = false, - _dPadRightPressed = false, - _gamepadAPressed = false, - _gamepadBPressed = false; + var _leftThumbstickUpPressed = false; + var _leftThumbstickDownPressed = false; + var _leftThumbstickLeftPressed = false; + var _leftThumbstickRightPressed = false; + var _dPadUpPressed = false; + var _dPadDownPressed = false; + var _dPadLeftPressed = false; + var _dPadRightPressed = false; + var _gamepadAPressed = false; + var _gamepadBPressed = false; // The set of buttons on the gamepad we listen for. var ProcessedButtons = [ @@ -260,7 +260,9 @@ require(['apphost'], function (appHost) { gamepads = navigator.webkitGetGamepads(); } gamepads = gamepads || []; - var i, j, len; + var i; + var j; + var len; for (i = 0, len = gamepads.length; i < len; i++) { var gamepad = gamepads[i]; if (gamepad) { diff --git a/src/components/serverNotifications/serverNotifications.js b/src/components/serverNotifications/serverNotifications.js index 74c65cd473..ff571b1e1a 100644 --- a/src/components/serverNotifications/serverNotifications.js +++ b/src/components/serverNotifications/serverNotifications.js @@ -18,8 +18,7 @@ define(['connectionManager', 'playbackManager', 'events', 'inputManager', 'focus toast({ title: args.Header, text: args.Text }); }); - } - else { + } else { require(['alert'], function (alert) { alert({ title: args.Header, text: args.Text }); }); @@ -157,11 +156,9 @@ define(['connectionManager', 'playbackManager', 'events', 'inputManager', 'focus if (msg.Data.PlayCommand === "PlayNext") { playbackManager.queueNext({ ids: msg.Data.ItemIds, serverId: serverId }); - } - else if (msg.Data.PlayCommand === "PlayLast") { + } else if (msg.Data.PlayCommand === "PlayLast") { playbackManager.queue({ ids: msg.Data.ItemIds, serverId: serverId }); - } - else { + } else { playbackManager.play({ ids: msg.Data.ItemIds, startPositionTicks: msg.Data.StartPositionTicks, @@ -173,38 +170,29 @@ define(['connectionManager', 'playbackManager', 'events', 'inputManager', 'focus }); } - } - else if (msg.MessageType === "Playstate") { + } else if (msg.MessageType === "Playstate") { if (msg.Data.Command === 'Stop') { inputManager.trigger('stop'); - } - else if (msg.Data.Command === 'Pause') { + } else if (msg.Data.Command === 'Pause') { inputManager.trigger('pause'); - } - else if (msg.Data.Command === 'Unpause') { + } else if (msg.Data.Command === 'Unpause') { inputManager.trigger('play'); - } - else if (msg.Data.Command === 'PlayPause') { + } else if (msg.Data.Command === 'PlayPause') { inputManager.trigger('playpause'); - } - else if (msg.Data.Command === 'Seek') { + } else if (msg.Data.Command === 'Seek') { playbackManager.seek(msg.Data.SeekPositionTicks); - } - else if (msg.Data.Command === 'NextTrack') { + } else if (msg.Data.Command === 'NextTrack') { inputManager.trigger('next'); - } - else if (msg.Data.Command === 'PreviousTrack') { + } else if (msg.Data.Command === 'PreviousTrack') { inputManager.trigger('previous'); } else { notifyApp(); } - } - else if (msg.MessageType === "GeneralCommand") { + } else if (msg.MessageType === "GeneralCommand") { var cmd = msg.Data; processGeneralCommand(cmd, apiClient); - } - else if (msg.MessageType === "UserDataChanged") { + } else if (msg.MessageType === "UserDataChanged") { if (msg.Data.UserId === apiClient.getCurrentUserId()) { @@ -212,8 +200,7 @@ define(['connectionManager', 'playbackManager', 'events', 'inputManager', 'focus events.trigger(serverNotifications, 'UserDataChanged', [apiClient, msg.Data.UserDataList[i]]); } } - } - else { + } else { events.trigger(serverNotifications, msg.MessageType, [apiClient, msg.Data]); } diff --git a/src/components/serverRestartDialog.js b/src/components/serverRestartDialog.js index 6c7e5b7386..4c20183b2a 100644 --- a/src/components/serverRestartDialog.js +++ b/src/components/serverRestartDialog.js @@ -6,9 +6,7 @@ define(['loading', 'events', 'dialogHelper', 'dom', 'layoutManager', 'scrollHelp var currentInstance; function reloadPageWhenServerAvailable(retryCount) { - var apiClient = currentApiClient; - if (!apiClient) { return; } @@ -31,7 +29,6 @@ define(['loading', 'events', 'dialogHelper', 'dom', 'layoutManager', 'scrollHelp function retryReload(retryCount) { setTimeout(function () { - retryCount = retryCount || 0; retryCount++; @@ -42,15 +39,12 @@ define(['loading', 'events', 'dialogHelper', 'dom', 'layoutManager', 'scrollHelp } function startRestart(instance, apiClient, dlg) { - currentApiClient = apiClient; currentDlg = dlg; currentInstance = instance; apiClient.restartServer().then(function () { - setTimeout(reloadPageWhenServerAvailable, 250); - }); } @@ -94,7 +88,8 @@ define(['loading', 'events', 'dialogHelper', 'dom', 'layoutManager', 'scrollHelp dlg.querySelector('.text').innerHTML = globalize.translate('RestartPleaseWaitMessage'); - var i, length; + var i; + var length; var html = ''; for (i = 0, length = configuredButtons.length; i < length; i++) { var item = configuredButtons[i]; @@ -138,12 +133,10 @@ define(['loading', 'events', 'dialogHelper', 'dom', 'layoutManager', 'scrollHelp } function ServerRestartDialog(options) { - this.options = options; } ServerRestartDialog.prototype.show = function () { - var instance = this; loading.show(); @@ -155,7 +148,6 @@ define(['loading', 'events', 'dialogHelper', 'dom', 'layoutManager', 'scrollHelp }; ServerRestartDialog.prototype.destroy = function () { - currentApiClient = null; currentDlg = null; currentInstance = null; diff --git a/src/components/shell.js b/src/components/shell.js index 762039ac42..534a57b027 100644 --- a/src/components/shell.js +++ b/src/components/shell.js @@ -8,7 +8,7 @@ define([], function () { } else { window.open(url, target || '_blank'); } - + }, canExec: false, exec: function (options) { diff --git a/src/components/shortcuts.js b/src/components/shortcuts.js index f6c1e97893..9d2b1847e5 100644 --- a/src/components/shortcuts.js +++ b/src/components/shortcuts.js @@ -128,8 +128,7 @@ define(['playbackManager', 'inputManager', 'connectionManager', 'appRouter', 'gl if (result.command === 'playallfromhere' || result.command === 'queueallfromhere') { executeAction(card, options.positionTo, result.command); - } - else if (result.updated || result.deleted) { + } else if (result.updated || result.deleted) { notifyRefreshNeeded(card, options.itemsContainer); } }); @@ -204,21 +203,15 @@ define(['playbackManager', 'inputManager', 'connectionManager', 'appRouter', 'gl context: card.getAttribute('data-context'), parentId: card.getAttribute('data-parentid') }); - } - - else if (action === 'programdialog') { + } else if (action === 'programdialog') { showProgramDialog(item); - } - - else if (action === 'instantmix') { + } else if (action === 'instantmix') { playbackManager.instantMix({ Id: playableItemId, ServerId: serverId }); - } - - else if (action === 'play' || action === 'resume') { + } else if (action === 'play' || action === 'resume') { var startPositionTicks = parseInt(card.getAttribute('data-positionticks') || '0'); @@ -227,9 +220,7 @@ define(['playbackManager', 'inputManager', 'connectionManager', 'appRouter', 'gl startPositionTicks: startPositionTicks, serverId: serverId }); - } - - else if (action === 'queue') { + } else if (action === 'queue') { if (playbackManager.isPlaying()) { playbackManager.queue({ @@ -243,25 +234,15 @@ define(['playbackManager', 'inputManager', 'connectionManager', 'appRouter', 'gl serverId: serverId }); } - } - - else if (action === 'playallfromhere') { + } else if (action === 'playallfromhere') { playAllFromHere(card, serverId); - } - - else if (action === 'queueallfromhere') { + } else if (action === 'queueallfromhere') { playAllFromHere(card, serverId, true); - } - - else if (action === 'setplaylistindex') { + } else if (action === 'setplaylistindex') { playbackManager.setCurrentPlaylistItem(card.getAttribute('data-playlistitemid')); - } - - else if (action === 'record') { + } else if (action === 'record') { onRecordCommand(serverId, id, type, card.getAttribute('data-timerid'), card.getAttribute('data-seriestimerid')); - } - - else if (action === 'menu') { + } else if (action === 'menu') { var options = target.getAttribute('data-playoptions') === 'false' ? { @@ -277,27 +258,17 @@ define(['playbackManager', 'inputManager', 'connectionManager', 'appRouter', 'gl options.positionTo = target; showContextMenu(card, options); - } - - else if (action === 'playmenu') { + } else if (action === 'playmenu') { showPlayMenu(card, target); - } - - else if (action === 'edit') { + } else if (action === 'edit') { getItem(target).then(function (item) { editItem(item, serverId); }); - } - - else if (action === 'playtrailer') { + } else if (action === 'playtrailer') { getItem(target).then(playTrailer); - } - - else if (action === 'addtoplaylist') { + } else if (action === 'addtoplaylist') { getItem(target).then(addToPlaylist); - } - - else if (action === 'custom') { + } else if (action === 'custom') { var customAction = target.getAttribute('data-customaction'); diff --git a/src/components/skinManager.js b/src/components/skinManager.js index 780b8273bb..9f96516422 100644 --- a/src/components/skinManager.js +++ b/src/components/skinManager.js @@ -20,7 +20,7 @@ define(['apphost', 'userSettings', 'browser', 'events', 'pluginManager', 'backdr } else { Emby.Page.goHome(); } - }; + } function getThemes() { return [{ @@ -36,7 +36,7 @@ define(['apphost', 'userSettings', 'browser', 'events', 'pluginManager', 'backdr isDefaultServerDashboard: true }, { name: "Emby", - id: "emby", + id: "emby" }, { name: "Light", id: "light" @@ -47,7 +47,7 @@ define(['apphost', 'userSettings', 'browser', 'events', 'pluginManager', 'backdr name: "Windows Media Center", id: "wmc" }]; - }; + } var skinManager = { getThemes: getThemes, diff --git a/src/components/slideshow/slideshow.js b/src/components/slideshow/slideshow.js index 6bb485a616..a5acd042b3 100644 --- a/src/components/slideshow/slideshow.js +++ b/src/components/slideshow/slideshow.js @@ -77,8 +77,7 @@ define(['dialogHelper', 'inputManager', 'connectionManager', 'layoutManager', 'f try { appHost.setUserScalable(scalable); - } - catch (err) { + } catch (err) { console.log('error in appHost.setUserScalable: ' + err); } } diff --git a/src/components/subtitleeditor/subtitleeditor.js b/src/components/subtitleeditor/subtitleeditor.js index 27055f5976..b79bf4ba1a 100644 --- a/src/components/subtitleeditor/subtitleeditor.js +++ b/src/components/subtitleeditor/subtitleeditor.js @@ -192,8 +192,7 @@ define(['dialogHelper', 'require', 'layoutManager', 'globalize', 'userSettings', var lastLanguage = userSettings.get('subtitleeditor-language'); if (lastLanguage) { selectLanguage.value = lastLanguage; - } - else { + } else { apiClient.getCurrentUser().then(function (user) { @@ -347,8 +346,7 @@ define(['dialogHelper', 'require', 'layoutManager', 'globalize', 'userSettings', if (typeof itemId === 'string') { apiClient.getItem(apiClient.getCurrentUserId(), itemId).then(onGetItem); - } - else { + } else { onGetItem(itemId); } } diff --git a/src/components/subtitlesettings/subtitleappearancehelper.js b/src/components/subtitlesettings/subtitleappearancehelper.js index 588f491a67..8a40bd134b 100644 --- a/src/components/subtitlesettings/subtitleappearancehelper.js +++ b/src/components/subtitlesettings/subtitleappearancehelper.js @@ -33,7 +33,7 @@ define([], function () { case 'smaller': list.push({ name: 'font-size', value: '.8em' }); break; - case 'small': + case 'small': list.push({ name: 'font-size', value: 'inherit' }); break; case 'larger': @@ -132,7 +132,6 @@ define([], function () { function applyStyleList(styles, elem) { - for (var i = 0, length = styles.length; i < length; i++) { var style = styles[i]; diff --git a/src/components/subtitlesync/subtitlesync.js b/src/components/subtitlesync/subtitlesync.js index 3389b7bf89..904c612317 100644 --- a/src/components/subtitlesync/subtitlesync.js +++ b/src/components/subtitlesync/subtitlesync.js @@ -25,10 +25,10 @@ define(['playbackManager', 'text!./subtitlesync.template.html', 'css!./subtitles subtitleSyncTextField.addEventListener("keypress", function(event) { - if(event.key === "Enter"){ + if (event.key === "Enter") { // if input key is enter search for float pattern var inputOffset = /[-+]?\d+\.?\d*/g.exec(this.textContent); - if(inputOffset) { + if (inputOffset) { inputOffset = inputOffset[0]; // replace current text by considered offset @@ -48,7 +48,7 @@ define(['playbackManager', 'text!./subtitlesync.template.html', 'css!./subtitles } else { // keep focus to prevent fade with bottom layout this.hasFocus = true; - if(event.key.match(/[+-\d.s]/) === null) { + if (event.key.match(/[+-\d.s]/) === null) { event.preventDefault(); } } @@ -92,14 +92,13 @@ define(['playbackManager', 'text!./subtitlesync.template.html', 'css!./subtitles instance.element = parent; } - function getOffsetFromPercentage(value) { // convert percent to fraction var offset = (value - 50) / 50; // multiply by offset min/max range value (-x to +x) : offset *= 30; return offset.toFixed(1); - }; + } function getPercentageFromOffset(value) { // divide by offset min/max range value (-x to +x) : @@ -108,16 +107,16 @@ define(['playbackManager', 'text!./subtitlesync.template.html', 'css!./subtitles percentValue *= 50; percentValue += 50; return Math.min(100, Math.max(0, percentValue.toFixed())); - }; + } function SubtitleSync(currentPlayer) { player = currentPlayer; init(this); } - SubtitleSync.prototype.destroy = function(){ + SubtitleSync.prototype.destroy = function() { SubtitleSync.prototype.toggle("forceToHide"); - if(player){ + if (player) { playbackManager.disableShowingSubtitleOffset(player); playbackManager.setSubtitleOffset(0, player); } @@ -130,27 +129,30 @@ define(['playbackManager', 'text!./subtitlesync.template.html', 'css!./subtitles SubtitleSync.prototype.toggle = function(action) { - if(player && playbackManager.supportSubtitleOffset(player)){ + if (player && playbackManager.supportSubtitleOffset(player)) { - switch(action) { + switch (action) { case undefined: // if showing subtitle sync is enabled - if(playbackManager.isShowingSubtitleOffsetEnabled(player) && + if (playbackManager.isShowingSubtitleOffsetEnabled(player) && // if there is an external subtitle stream enabled - playbackManager.canHandleOffsetOnCurrentSubtitle(player)){ - // if no subtitle offset is defined - if(!playbackManager.getPlayerSubtitleOffset(player)) { - // set default offset to '0' = 50% - subtitleSyncSlider.value = "50"; - subtitleSyncTextField.textContent = "0s"; - playbackManager.setSubtitleOffset(0, player); - } - // show subtitle sync - subtitleSyncContainer.classList.remove("hide"); - break; // stop here + playbackManager.canHandleOffsetOnCurrentSubtitle(player)) { + // if no subtitle offset is defined + if (!playbackManager.getPlayerSubtitleOffset(player)) { + // set default offset to '0' = 50% + subtitleSyncSlider.value = "50"; + subtitleSyncTextField.textContent = "0s"; + playbackManager.setSubtitleOffset(0, player); + } + // show subtitle sync + subtitleSyncContainer.classList.remove("hide"); + break; // stop here } // else continue and hide case "hide": - if(subtitleSyncTextField.hasFocus){break;} // else continue and hide + // only break if element has focus + if (subtitleSyncTextField.hasFocus) { + break; + } case "forceToHide": subtitleSyncContainer.classList.add("hide"); break; diff --git a/src/components/tabbedview/itemstab.js b/src/components/tabbedview/itemstab.js index ec874c69e9..7381232fc9 100644 --- a/src/components/tabbedview/itemstab.js +++ b/src/components/tabbedview/itemstab.js @@ -246,7 +246,8 @@ define(['playbackManager', 'userSettings', 'alphaPicker', 'alphaNumericShortcuts this.itemsContainer.setAttribute('data-parentid', params.parentId); } - var i, length; + var i; + var length; var btnViewSettings = view.querySelectorAll('.btnViewSettings'); for (i = 0, length = btnViewSettings.length; i < length; i++) { @@ -559,7 +560,6 @@ define(['playbackManager', 'userSettings', 'alphaPicker', 'alphaNumericShortcuts }; ItemsTab.prototype.onPause = function () { - var scroller = this.scroller; if (scroller && scroller.pause) { scroller.pause(); @@ -573,7 +573,6 @@ define(['playbackManager', 'userSettings', 'alphaPicker', 'alphaNumericShortcuts }; ItemsTab.prototype.destroy = function () { - this.view = null; this.itemsContainer = null; this.params = null; @@ -585,6 +584,7 @@ define(['playbackManager', 'userSettings', 'alphaPicker', 'alphaNumericShortcuts this.alphaPicker.destroy(); this.alphaPicker = null; } + this.sortButtons = null; this.btnSortText = null; this.btnSortIcon = null; diff --git a/src/components/tabbedview/tabbedview.js b/src/components/tabbedview/tabbedview.js index bc656bc3e2..33f1c6e6cc 100644 --- a/src/components/tabbedview/tabbedview.js +++ b/src/components/tabbedview/tabbedview.js @@ -101,8 +101,7 @@ define(['backdrop', 'mainTabsManager', 'layoutManager', 'emby-tabs'], function ( if (!currentTabController) { mainTabsManager.selectedTabIndex(this.initialTabIndex); - } - else if (currentTabController && currentTabController.onResume) { + } else if (currentTabController && currentTabController.onResume) { currentTabController.onResume({}); } }; diff --git a/src/components/thememediaplayer.js b/src/components/thememediaplayer.js index 732cbb1cb0..a8298fad37 100644 --- a/src/components/thememediaplayer.js +++ b/src/components/thememediaplayer.js @@ -94,8 +94,7 @@ define(['playbackManager', 'userSettings', 'connectionManager'], function (playb if (viewOptions.supportsThemeMedia) { // Do nothing here, allow it to keep playing - } - else { + } else { playThemeMedia([], null); } diff --git a/src/components/themes/appletv/theme.css b/src/components/themes/appletv/theme.css index 35b388d1c2..128594bc72 100644 --- a/src/components/themes/appletv/theme.css +++ b/src/components/themes/appletv/theme.css @@ -455,8 +455,9 @@ html { color: #4285F4 } -.card:focus .card-focuscontent { - border-color: #00a4dc +.card:focus .cardBox.visualCardBox, +.card:focus .cardBox:not(.visualCardBox) .cardScalable { + border-color: #00a4dc !important } .metadataSidebarIcon { diff --git a/src/components/themes/blueradiance/theme.css b/src/components/themes/blueradiance/theme.css index 4740fc5ee7..3af56f79b7 100644 --- a/src/components/themes/blueradiance/theme.css +++ b/src/components/themes/blueradiance/theme.css @@ -440,8 +440,9 @@ html { color: #4285F4 } -.card:focus .card-focuscontent { - border-color: #00a4dc +.card:focus .cardBox.visualCardBox, +.card:focus .cardBox:not(.visualCardBox) .cardScalable { + border-color: #00a4dc !important } .layout-desktop ::-webkit-scrollbar { diff --git a/src/components/themes/dark/theme.css b/src/components/themes/dark/theme.css index 161c8d6df3..b4d4bcda4b 100644 --- a/src/components/themes/dark/theme.css +++ b/src/components/themes/dark/theme.css @@ -417,8 +417,9 @@ html { color: #4285F4 } -.card:focus .card-focuscontent { - border-color: #00a4dc +.card:focus .cardBox.visualCardBox, +.card:focus .cardBox:not(.visualCardBox) .cardScalable { + border-color: #00a4dc !important } .layout-desktop ::-webkit-scrollbar { diff --git a/src/components/themes/emby/theme.css b/src/components/themes/emby/theme.css index d018ec715a..7206150235 100644 --- a/src/components/themes/emby/theme.css +++ b/src/components/themes/emby/theme.css @@ -417,8 +417,9 @@ html { color: #4285F4 } -.card:focus .card-focuscontent { - border-color: #52b54b +.card:focus .cardBox.visualCardBox, +.card:focus .cardBox:not(.visualCardBox) .cardScalable { + border-color: #52b54b !important } .layout-desktop ::-webkit-scrollbar { diff --git a/src/components/themes/light/theme.css b/src/components/themes/light/theme.css index f7cc4da9f3..dfac15ec7c 100644 --- a/src/components/themes/light/theme.css +++ b/src/components/themes/light/theme.css @@ -436,8 +436,9 @@ html { color: #4285F4 } -.card:focus .card-focuscontent { - border-color: #00a4dc +.card:focus .cardBox.visualCardBox, +.card:focus .cardBox:not(.visualCardBox) .cardScalable { + border-color: #00a4dc !important } .metadataSidebarIcon { diff --git a/src/components/themes/purple-haze/theme.css b/src/components/themes/purple-haze/theme.css index 684ac96f1f..1bba1e6145 100644 --- a/src/components/themes/purple-haze/theme.css +++ b/src/components/themes/purple-haze/theme.css @@ -533,8 +533,9 @@ a[data-role=button] { color: #4285F4 } -.card:focus .card-focuscontent { - border-color: #ff77f1 +.card:focus .cardBox.visualCardBox, +.card:focus .cardBox:not(.visualCardBox) .cardScalable { + border-color: #ff77f1 !important } .layout-desktop, diff --git a/src/components/themes/wmc/theme.css b/src/components/themes/wmc/theme.css index 239e920a3d..a19eeb93a2 100644 --- a/src/components/themes/wmc/theme.css +++ b/src/components/themes/wmc/theme.css @@ -439,8 +439,9 @@ html { color: #4285F4 } -.card:focus .card-focuscontent { - border-color: #fff +.card:focus .cardBox.visualCardBox, +.card:focus .cardBox:not(.visualCardBox) .cardScalable { + border-color: #fff !important } .layout-desktop ::-webkit-scrollbar { diff --git a/src/components/touchhelper.js b/src/components/touchhelper.js index 66d115046b..0f6d34aace 100644 --- a/src/components/touchhelper.js +++ b/src/components/touchhelper.js @@ -78,11 +78,9 @@ define(['dom', 'events'], function (dom, events) { if (deltaX > swipeXThreshold && Math.abs(deltaY) < swipeXMaxY) { events.trigger(self, 'swiperight', [touchTarget]); - } - else if (deltaX < (0 - swipeXThreshold) && Math.abs(deltaY) < swipeXMaxY) { + } else if (deltaX < (0 - swipeXThreshold) && Math.abs(deltaY) < swipeXMaxY) { events.trigger(self, 'swipeleft', [touchTarget]); - } - else if ((deltaY < (0 - swipeYThreshold) || thresholdYMet) && Math.abs(deltaX) < swipeXMaxY) { + } else if ((deltaY < (0 - swipeYThreshold) || thresholdYMet) && Math.abs(deltaX) < swipeXMaxY) { thresholdYMet = true; @@ -94,8 +92,7 @@ define(['dom', 'events'], function (dom, events) { currentDeltaX: currentDeltaX, currentDeltaY: currentDeltaY }]); - } - else if ((deltaY > swipeYThreshold || thresholdYMet) && Math.abs(deltaX) < swipeXMaxY) { + } else if ((deltaY > swipeYThreshold || thresholdYMet) && Math.abs(deltaX) < swipeXMaxY) { thresholdYMet = true; events.trigger(self, 'swipedown', [touchTarget, { diff --git a/src/components/tunerpicker.js b/src/components/tunerpicker.js index 784f677430..96bfc71dff 100644 --- a/src/components/tunerpicker.js +++ b/src/components/tunerpicker.js @@ -1,78 +1,177 @@ -define(["dialogHelper", "dom", "layoutManager", "connectionManager", "globalize", "loading", "material-icons", "formDialogStyle", "emby-button", "emby-itemscontainer", "cardStyle"], function(dialogHelper, dom, layoutManager, connectionManager, globalize, loading) { +define(["dialogHelper", "dom", "layoutManager", "connectionManager", "globalize", "loading", "browser", "material-icons", "formDialogStyle", "emby-button", "emby-itemscontainer", "cardStyle"], function (dialogHelper, dom, layoutManager, connectionManager, globalize, loading, browser) { "use strict"; + var enableFocusTransform = !browser.slow && !browser.edge; + function getEditorHtml() { var html = ""; - return html += '
', html += '
', html += '
', html += "

" + globalize.translate("DetectingDevices") + "...

", html += "

" + globalize.translate("MessagePleaseWait") + "

", html += "
", html += '

' + globalize.translate("HeaderNewDevices") + "

", html += '
', html += "
", html += "
", html += "
" + html += '
'; + html += '
'; + html += '
'; + html += "

" + globalize.translate("DetectingDevices") + "...

"; + html += "

" + globalize.translate("MessagePleaseWait") + "

"; + html += "
"; + html += '

' + globalize.translate("HeaderNewDevices") + "

"; + html += '
'; + html += "
"; + html += "
"; + return html += "
"; } function getDeviceHtml(device) { - var padderClass, html = "", - cssClass = "card scalableCard", - cardBoxCssClass = "cardBox visualCardBox"; - return cssClass += " backdropCard backdropCard-scalable", padderClass = "cardPadder-backdrop", layoutManager.tv && (cssClass += " card-focusscale", cardBoxCssClass += " cardBox-focustransform"), cardBoxCssClass += " card-focuscontent", html += '" + var padderClass; + var html = ""; + var cssClass = "card scalableCard"; + var cardBoxCssClass = "cardBox visualCardBox"; + cssClass += " backdropCard backdropCard-scalable"; + padderClass = "cardPadder-backdrop"; + + // TODO move card creation code to Card component + + if (layoutManager.tv) { + cssClass += " show-focus"; + + if (enableFocusTransform) { + cssClass += " show-animation"; + } + } + + html += '"; } function getTunerName(providerId) { switch (providerId = providerId.toLowerCase()) { case "m3u": return "M3U"; + case "hdhomerun": return "HDHomerun"; + case "hauppauge": return "Hauppauge"; + case "satip": return "DVB"; + default: - return "Unknown" + return "Unknown"; } } function renderDevices(view, devices) { - var i, length, html = ""; - for (i = 0, length = devices.length; i < length; i++) html += getDeviceHtml(devices[i]); - devices.length ? view.querySelector(".devicesHeader").classList.remove("hide") : (html = "


" + globalize.translate("NoNewDevicesFound") + "

", view.querySelector(".devicesHeader").classList.add("hide")); + var i; + var length; + var html = ""; + + for (i = 0, length = devices.length; i < length; i++) { + html += getDeviceHtml(devices[i]); + } + + if (devices.length) { + view.querySelector(".devicesHeader").classList.remove("hide"); + } else { + html = "


" + globalize.translate("NoNewDevicesFound") + "

"; + view.querySelector(".devicesHeader").classList.add("hide"); + } + var elem = view.querySelector(".results"); - elem.innerHTML = html, layoutManager.tv && focusManager.autoFocus(elem) + elem.innerHTML = html; + + if (layoutManager.tv) { + focusManager.autoFocus(elem); + } } function discoverDevices(view, apiClient) { - return loading.show(), view.querySelector(".loadingContent").classList.remove("hide"), ApiClient.getJSON(ApiClient.getUrl("LiveTv/Tuners/Discvover", { - NewDevicesOnly: !0 - })).then(function(devices) { - currentDevices = devices, renderDevices(view, devices), view.querySelector(".loadingContent").classList.add("hide"), loading.hide() - }) + loading.show(); + view.querySelector(".loadingContent").classList.remove("hide"); + return ApiClient.getJSON(ApiClient.getUrl("LiveTv/Tuners/Discvover", { + NewDevicesOnly: true + })).then(function (devices) { + currentDevices = devices; + renderDevices(view, devices); + view.querySelector(".loadingContent").classList.add("hide"); + loading.hide(); + }); } function tunerPicker() { - this.show = function(options) { + this.show = function (options) { var dialogOptions = { - removeOnClose: !0, - scrollY: !1 + removeOnClose: true, + scrollY: false }; - layoutManager.tv ? dialogOptions.size = "fullscreen" : dialogOptions.size = "small"; + + if (layoutManager.tv) { + dialogOptions.size = "fullscreen"; + } else { + dialogOptions.size = "small"; + } + var dlg = dialogHelper.createDialog(dialogOptions); dlg.classList.add("formDialog"); var html = ""; - html += '
', html += '', html += '

', html += globalize.translate("HeaderLiveTvTunerSetup"), html += "

", html += "
", html += getEditorHtml(), dlg.innerHTML = html, dlg.querySelector(".btnCancel").addEventListener("click", function() { - dialogHelper.close(dlg) + html += '
'; + html += ''; + html += '

'; + html += globalize.translate("HeaderLiveTvTunerSetup"); + html += "

"; + html += "
"; + html += getEditorHtml(); + dlg.innerHTML = html; + dlg.querySelector(".btnCancel").addEventListener("click", function () { + dialogHelper.close(dlg); }); var deviceResult; - dlg.querySelector(".results").addEventListener("click", function(e) { + dlg.querySelector(".results").addEventListener("click", function (e) { var tunerCard = dom.parentWithClass(e.target, "card"); + if (tunerCard) { var deviceId = tunerCard.getAttribute("data-id"); - deviceResult = currentDevices.filter(function(d) { - return d.DeviceId === deviceId - })[0], dialogHelper.close(dlg) + deviceResult = currentDevices.filter(function (d) { + return d.DeviceId === deviceId; + })[0]; + dialogHelper.close(dlg); } - }), layoutManager.tv && centerFocus(dlg.querySelector(".formDialogContent"), !1, !0); + }); + + if (layoutManager.tv) { + centerFocus(dlg.querySelector(".formDialogContent"), false, true); + } + var apiClient = connectionManager.getApiClient(options.serverId); - return discoverDevices(dlg, apiClient), layoutManager.tv && centerFocus(dlg.querySelector(".formDialogContent"), !1, !1), dialogHelper.open(dlg).then(function() { - return deviceResult ? Promise.resolve(deviceResult) : Promise.reject() - }) - } + discoverDevices(dlg, apiClient); + + if (layoutManager.tv) { + centerFocus(dlg.querySelector(".formDialogContent"), false, false); + } + + return dialogHelper.open(dlg).then(function () { + if (deviceResult) { + return Promise.resolve(deviceResult); + } + + return Promise.reject(); + }); + }; } + var currentDevices = []; - return tunerPicker -}); \ No newline at end of file + return tunerPicker; +}); diff --git a/src/components/tvproviders/schedulesdirect.js b/src/components/tvproviders/schedulesdirect.js index 9af7e5be72..a1265e7cc9 100644 --- a/src/components/tvproviders/schedulesdirect.js +++ b/src/components/tvproviders/schedulesdirect.js @@ -1,119 +1,196 @@ -define(["jQuery", "loading", "emby-checkbox", "listViewStyle", "emby-input", "emby-select", "emby-button", "flexStyles"], function($, loading) { +define(["jQuery", "loading", "emby-checkbox", "listViewStyle", "emby-input", "emby-select", "emby-button", "flexStyles"], function ($, loading) { "use strict"; - return function(page, providerId, options) { + + return function (page, providerId, options) { function reload() { - loading.show(), ApiClient.getNamedConfiguration("livetv").then(function(config) { - var info = config.ListingProviders.filter(function(i) { - return i.Id === providerId + loading.show(); + ApiClient.getNamedConfiguration("livetv").then(function (config) { + var info = config.ListingProviders.filter(function (i) { + return i.Id === providerId; })[0] || {}; - listingsId = info.ListingsId, $("#selectListing", page).val(info.ListingsId || ""), page.querySelector(".txtUser").value = info.Username || "", page.querySelector(".txtPass").value = "", page.querySelector(".txtZipCode").value = info.ZipCode || "", info.Username && info.Password ? page.querySelector(".listingsSection").classList.remove("hide") : page.querySelector(".listingsSection").classList.add("hide"), page.querySelector(".chkAllTuners").checked = info.EnableAllTuners, page.querySelector(".chkAllTuners").checked ? page.querySelector(".selectTunersSection").classList.add("hide") : page.querySelector(".selectTunersSection").classList.remove("hide"), setCountry(info), refreshTunerDevices(page, info, config.TunerHosts) - }) + listingsId = info.ListingsId; + $("#selectListing", page).val(info.ListingsId || ""); + page.querySelector(".txtUser").value = info.Username || ""; + page.querySelector(".txtPass").value = ""; + page.querySelector(".txtZipCode").value = info.ZipCode || ""; + + if (info.Username && info.Password) { + page.querySelector(".listingsSection").classList.remove("hide"); + } else { + page.querySelector(".listingsSection").classList.add("hide"); + } + + page.querySelector(".chkAllTuners").checked = info.EnableAllTuners; + + if (info.EnableAllTuners) { + page.querySelector(".selectTunersSection").classList.add("hide"); + } else { + page.querySelector(".selectTunersSection").classList.remove("hide"); + } + + setCountry(info); + refreshTunerDevices(page, info, config.TunerHosts); + }); } function setCountry(info) { - ApiClient.getJSON(ApiClient.getUrl("LiveTv/ListingProviders/SchedulesDirect/Countries")).then(function(result) { - var i, length, countryList = []; + ApiClient.getJSON(ApiClient.getUrl("LiveTv/ListingProviders/SchedulesDirect/Countries")).then(function (result) { + var i; + var length; + var countryList = []; + for (var region in result) { var countries = result[region]; - if (countries.length && "ZZZ" !== region) - for (i = 0, length = countries.length; i < length; i++) countryList.push({ - name: countries[i].fullName, - value: countries[i].shortName - }) + + if (countries.length && "ZZZ" !== region) { + for (i = 0, length = countries.length; i < length; i++) { + countryList.push({ + name: countries[i].fullName, + value: countries[i].shortName + }); + } + } } - countryList.sort(function(a, b) { - return a.name > b.name ? 1 : a.name < b.name ? -1 : 0 - }), $("#selectCountry", page).html(countryList.map(function(c) { - return '" - }).join("")).val(info.Country || ""), $(page.querySelector(".txtZipCode")).trigger("change") - }, function() { + + countryList.sort(function (a, b) { + if (a.name > b.name) { + return 1; + } + + if (a.name < b.name) { + return -1; + } + + return 0; + }); + $("#selectCountry", page).html(countryList.map(function (c) { + return '"; + }).join("")).val(info.Country || ""); + $(page.querySelector(".txtZipCode")).trigger("change"); + }, function () { // ApiClient.getJSON() error handler Dashboard.alert({ message: Globalize.translate("ErrorGettingTvLineups") - }) - }), loading.hide() + }); + }); + loading.hide(); } function sha256(str) { - if (!self.TextEncoder) return Promise.resolve(""); + if (!self.TextEncoder) { + return Promise.resolve(""); + } + var buffer = new TextEncoder("utf-8").encode(str); - return crypto.subtle.digest("SHA-256", buffer).then(function(hash) { - return hex(hash) - }) + return crypto.subtle.digest("SHA-256", buffer).then(function (hash) { + return hex(hash); + }); } function hex(buffer) { - for (var hexCodes = [], view = new DataView(buffer), i = 0; i < view.byteLength; i += 4) { - var value = view.getUint32(i), - stringValue = value.toString(16), - paddedValue = ("00000000" + stringValue).slice(-"00000000".length); - hexCodes.push(paddedValue) + var hexCodes = []; + var view = new DataView(buffer); + + for (var i = 0; i < view.byteLength; i += 4) { + var value = view.getUint32(i); + var stringValue = value.toString(16); + var paddedValue = ("00000000" + stringValue).slice(-"00000000".length); + hexCodes.push(paddedValue); } - return hexCodes.join("") + + return hexCodes.join(""); } function submitLoginForm() { - loading.show(), sha256(page.querySelector(".txtPass").value).then(function(passwordHash) { + loading.show(); + sha256(page.querySelector(".txtPass").value).then(function (passwordHash) { var info = { - Type: "SchedulesDirect", - Username: page.querySelector(".txtUser").value, - EnableAllTuners: !0, - Password: passwordHash, - Pw: page.querySelector(".txtPass").value - }, - id = providerId; - id && (info.Id = id), ApiClient.ajax({ + Type: "SchedulesDirect", + Username: page.querySelector(".txtUser").value, + EnableAllTuners: true, + Password: passwordHash, + Pw: page.querySelector(".txtPass").value + }; + var id = providerId; + + if (id) { + info.Id = id; + } + + ApiClient.ajax({ type: "POST", url: ApiClient.getUrl("LiveTv/ListingProviders", { - ValidateLogin: !0 + ValidateLogin: true }), data: JSON.stringify(info), contentType: "application/json", dataType: "json" - }).then(function(result) { - Dashboard.processServerConfigurationUpdateResult(), providerId = result.Id, reload() - }, function() { - Dashboard.alert({ + }).then(function (result) { + Dashboard.processServerConfigurationUpdateResult(); + providerId = result.Id; + reload(); + }, function () { + Dashboard.alert({ // ApiClient.ajax() error handler message: Globalize.translate("ErrorSavingTvProvider") - }) - }) - }) + }); + }); + }); } function submitListingsForm() { var selectedListingsId = $("#selectListing", page).val(); - if (!selectedListingsId) return void Dashboard.alert({ - message: Globalize.translate("ErrorPleaseSelectLineup") - }); + + if (!selectedListingsId) { + return void Dashboard.alert({ + message: Globalize.translate("ErrorPleaseSelectLineup") + }); + } + loading.show(); var id = providerId; - ApiClient.getNamedConfiguration("livetv").then(function(config) { - var info = config.ListingProviders.filter(function(i) { - return i.Id === id + ApiClient.getNamedConfiguration("livetv").then(function (config) { + var info = config.ListingProviders.filter(function (i) { + return i.Id === id; })[0]; - info.ZipCode = page.querySelector(".txtZipCode").value, info.Country = $("#selectCountry", page).val(), info.ListingsId = selectedListingsId, info.EnableAllTuners = page.querySelector(".chkAllTuners").checked, info.EnabledTuners = info.EnableAllTuners ? [] : $(".chkTuner", page).get().filter(function(i) { - return i.checked - }).map(function(i) { - return i.getAttribute("data-id") - }), ApiClient.ajax({ + info.ZipCode = page.querySelector(".txtZipCode").value; + info.Country = $("#selectCountry", page).val(); + info.ListingsId = selectedListingsId; + info.EnableAllTuners = page.querySelector(".chkAllTuners").checked; + info.EnabledTuners = info.EnableAllTuners ? [] : $(".chkTuner", page).get().filter(function (i) { + return i.checked; + }).map(function (i) { + return i.getAttribute("data-id"); + }); + ApiClient.ajax({ type: "POST", url: ApiClient.getUrl("LiveTv/ListingProviders", { - ValidateListings: !0 + ValidateListings: true }), data: JSON.stringify(info), contentType: "application/json" - }).then(function(result) { - loading.hide(), !1 !== options.showConfirmation && Dashboard.processServerConfigurationUpdateResult(), Events.trigger(self, "submitted") - }, function() { - loading.hide(), Dashboard.alert({ + }).then(function (result) { + loading.hide(); + + if (options.showConfirmation) { + Dashboard.processServerConfigurationUpdateResult(); + } + + Events.trigger(self, "submitted"); + }, function () { + loading.hide(); + Dashboard.alert({ message: Globalize.translate("ErrorAddingListingsToSchedulesDirect") - }) - }) - }) + }); + }); + }); } function refreshListings(value) { - if (!value) return void $("#selectListing", page).html(""); - loading.show(), ApiClient.ajax({ + if (!value) { + return void $("#selectListing", page).html(""); + } + + loading.show(); + ApiClient.ajax({ type: "GET", url: ApiClient.getUrl("LiveTv/ListingProviders/Lineups", { Id: providerId, @@ -121,15 +198,23 @@ define(["jQuery", "loading", "emby-checkbox", "listViewStyle", "emby-input", "em Country: $("#selectCountry", page).val() }), dataType: "json" - }).then(function(result) { - $("#selectListing", page).html(result.map(function(o) { - return '" - })), listingsId && $("#selectListing", page).val(listingsId), loading.hide() - }, function(result) { + }).then(function (result) { + $("#selectListing", page).html(result.map(function (o) { + return '"; + })); + + if (listingsId) { + $("#selectListing", page).val(listingsId); + } + + loading.hide(); + }, function (result) { Dashboard.alert({ message: Globalize.translate("ErrorGettingTvLineups") - }), refreshListings(""), loading.hide() - }) + }); + refreshListings(""); + loading.hide(); + }); } function getTunerName(providerId) { @@ -141,34 +226,76 @@ define(["jQuery", "loading", "emby-checkbox", "listViewStyle", "emby-input", "em case "satip": return "DVB"; default: - return "Unknown" + return "Unknown"; } } function refreshTunerDevices(page, providerInfo, devices) { - for (var html = "", i = 0, length = devices.length; i < length; i++) { + var html = ""; + + for (var i = 0, length = devices.length; i < length; i++) { var device = devices[i]; html += '
'; - var enabledTuners = providerInfo.EnabledTuners || [], - isChecked = providerInfo.EnableAllTuners || -1 !== enabledTuners.indexOf(device.Id), - checkedAttribute = isChecked ? " checked" : ""; - html += '", html += '
', html += '
', html += device.FriendlyName || getTunerName(device.Type), html += "
", html += '
', html += device.Url, html += "
", html += "
", html += "
" + var enabledTuners = providerInfo.EnabledTuners || []; + var isChecked = providerInfo.EnableAllTuners || -1 !== enabledTuners.indexOf(device.Id); + var checkedAttribute = isChecked ? " checked" : ""; + html += '"; + html += '
'; + html += '
'; + html += device.FriendlyName || getTunerName(device.Type); + html += "
"; + html += '
'; + html += device.Url; + html += "
"; + html += "
"; + html += ""; } - page.querySelector(".tunerList").innerHTML = html + + page.querySelector(".tunerList").innerHTML = html; } - var listingsId, self = this; - self.submit = function() { - page.querySelector(".btnSubmitListingsContainer").click() - }, self.init = function() { - options = options || {}, !1 !== options.showCancelButton ? page.querySelector(".btnCancel").classList.remove("hide") : page.querySelector(".btnCancel").classList.add("hide"), !1 !== options.showSubmitButton ? page.querySelector(".btnSubmitListings").classList.remove("hide") : page.querySelector(".btnSubmitListings").classList.add("hide"), $(".formLogin", page).on("submit", function() { - return submitLoginForm(), !1 - }), $(".formListings", page).on("submit", function() { - return submitListingsForm(), !1 - }), $(".txtZipCode", page).on("change", function() { - refreshListings(this.value) - }), page.querySelector(".chkAllTuners").addEventListener("change", function(e) { - e.target.checked ? page.querySelector(".selectTunersSection").classList.add("hide") : page.querySelector(".selectTunersSection").classList.remove("hide") - }), $(".createAccountHelp", page).html(Globalize.translate("MessageCreateAccountAt", 'http://www.schedulesdirect.org')), reload() - } - } -}); \ No newline at end of file + + var listingsId; + var self = this; + + self.submit = function () { + page.querySelector(".btnSubmitListingsContainer").click(); + }; + + self.init = function () { + options = options || {}; + + if (options.showCancelButton) { + page.querySelector(".btnCancel").classList.remove("hide"); + } else { + page.querySelector(".btnCancel").classList.add("hide"); + } + + if (options.showSubmitButton) { + page.querySelector(".btnSubmitListings").classList.remove("hide"); + } else { + page.querySelector(".btnSubmitListings").classList.add("hide"); + } + + $(".formLogin", page).on("submit", function () { + submitLoginForm(); + return false; + }); + $(".formListings", page).on("submit", function () { + submitListingsForm(); + return false; + }); + $(".txtZipCode", page).on("change", function () { + refreshListings(this.value); + }); + page.querySelector(".chkAllTuners").addEventListener("change", function (e) { + if (e.target.checked) { + page.querySelector(".selectTunersSection").classList.add("hide"); + } else { + page.querySelector(".selectTunersSection").classList.remove("hide"); + } + }); + $(".createAccountHelp", page).html(Globalize.translate("MessageCreateAccountAt", 'http://www.schedulesdirect.org')); + reload(); + }; + }; +}); diff --git a/src/components/tvproviders/xmltv.js b/src/components/tvproviders/xmltv.js index 2a9dd88089..a86a1e1099 100644 --- a/src/components/tvproviders/xmltv.js +++ b/src/components/tvproviders/xmltv.js @@ -1,4 +1,4 @@ -define(["jQuery", "loading", "emby-checkbox", "emby-input", "listViewStyle", "paper-icon-button-light"], function ($__q, loading) { +define(["jQuery", "loading", "emby-checkbox", "emby-input", "listViewStyle", "paper-icon-button-light"], function ($, loading) { "use strict"; return function (page, providerId, options) { @@ -69,7 +69,7 @@ define(["jQuery", "loading", "emby-checkbox", "emby-input", "listViewStyle", "pa info.NewsCategories = getCategories(page.querySelector(".txtNews")); info.SportsCategories = getCategories(page.querySelector(".txtSports")); info.EnableAllTuners = page.querySelector(".chkAllTuners").checked; - info.EnabledTuners = info.EnableAllTuners ? [] : $__q(".chkTuner", page).get().filter(function (tuner) { + info.EnabledTuners = info.EnableAllTuners ? [] : $(".chkTuner", page).get().filter(function (tuner) { return tuner.checked; }).map(function (tuner) { return tuner.getAttribute("data-id"); @@ -135,8 +135,8 @@ define(["jQuery", "loading", "emby-checkbox", "emby-input", "listViewStyle", "pa page.querySelector(".tunerList").innerHTML = html; } - function onSelectPathClick(e__u) { - var page = $__q(e__u.target).parents(".xmltvForm")[0]; + function onSelectPathClick(e) { + var page = $(e.target).parents(".xmltvForm")[0]; require(["directorybrowser"], function (directoryBrowser) { var picker = new directoryBrowser(); @@ -175,7 +175,7 @@ define(["jQuery", "loading", "emby-checkbox", "emby-input", "listViewStyle", "pa page.querySelector(".btnSubmitListings").classList.add("hide"); } - $__q("form", page).on("submit", function () { + $("form", page).on("submit", function () { submitListingsForm(); return false; }); diff --git a/src/components/userdatabuttons/emby-ratingbutton.js b/src/components/userdatabuttons/emby-ratingbutton.js index 40cf033cd5..190424d44d 100644 --- a/src/components/userdatabuttons/emby-ratingbutton.js +++ b/src/components/userdatabuttons/emby-ratingbutton.js @@ -33,8 +33,7 @@ define(['connectionManager', 'serverNotifications', 'events', 'globalize', 'emby var isFavorite = this.getAttribute('data-isfavorite') === 'true'; if (likes === 'true') { likes = true; - } - else if (likes === 'false') { + } else if (likes === 'false') { likes = false; } else { likes = null; @@ -64,7 +63,7 @@ define(['connectionManager', 'serverNotifications', 'events', 'globalize', 'emby if (icon) { icon.innerHTML = ''; - icon.classList.add('ratingbutton-icon-withrating'); + icon.classList.add('ratingbutton-icon-withrating'); } button.classList.add('ratingbutton-withrating'); @@ -73,7 +72,7 @@ define(['connectionManager', 'serverNotifications', 'events', 'globalize', 'emby if (icon) { icon.innerHTML = ''; - icon.classList.remove('ratingbutton-icon-withrating'); + icon.classList.remove('ratingbutton-icon-withrating'); //icon.innerHTML = ''; } button.classList.remove('ratingbutton-withrating'); @@ -82,7 +81,7 @@ define(['connectionManager', 'serverNotifications', 'events', 'globalize', 'emby if (icon) { icon.innerHTML = ''; - icon.classList.remove('ratingbutton-icon-withrating'); + icon.classList.remove('ratingbutton-icon-withrating'); //icon.innerHTML = ''; } button.classList.remove('ratingbutton-withrating'); @@ -91,7 +90,7 @@ define(['connectionManager', 'serverNotifications', 'events', 'globalize', 'emby if (icon) { icon.innerHTML = ''; - icon.classList.remove('ratingbutton-icon-withrating'); + icon.classList.remove('ratingbutton-icon-withrating'); //icon.innerHTML = ''; } button.classList.remove('ratingbutton-withrating'); @@ -152,8 +151,7 @@ define(['connectionManager', 'serverNotifications', 'events', 'globalize', 'emby var isFavorite = this.getAttribute('data-isfavorite') === 'true'; if (likes === 'true') { likes = true; - } - else if (likes === 'false') { + } else if (likes === 'false') { likes = false; } else { likes = null; diff --git a/src/components/viewContainer.js b/src/components/viewContainer.js index ece8da1ed6..c2d060162e 100644 --- a/src/components/viewContainer.js +++ b/src/components/viewContainer.js @@ -42,7 +42,6 @@ define(["browser", "dom", "layoutManager", "css!components/viewManager/viewConta var newViewInfo = normalizeNewView(options, isPluginpage); var newView = newViewInfo.elem; - if (isPluginpage) { require(["legacyDashboard"]); } diff --git a/src/components/viewManager/viewManager.js b/src/components/viewManager/viewManager.js index 23612d5a1e..a8e514e06e 100644 --- a/src/components/viewManager/viewManager.js +++ b/src/components/viewManager/viewManager.js @@ -50,8 +50,7 @@ define(['viewContainer', 'focusManager', 'queryString', 'layoutManager'], functi if (options.autoFocus !== false) { focusManager.autoFocus(view); } - } - else if (!layoutManager.mobile) { + } else if (!layoutManager.mobile) { if (view.activeElement && document.body.contains(view.activeElement) && focusManager.isCurrentlyFocusable(view.activeElement)) { focusManager.focus(view.activeElement); } else { diff --git a/src/components/viewsettings/viewsettings.js b/src/components/viewsettings/viewsettings.js index 617e021115..5195598d99 100644 --- a/src/components/viewsettings/viewsettings.js +++ b/src/components/viewsettings/viewsettings.js @@ -29,7 +29,7 @@ define(['require', 'dialogHelper', 'loading', 'apphost', 'layoutManager', 'conne } userSettings.set(settingsKey + '-imageType', context.querySelector('.selectImageType').value); - } + } function centerFocus(elem, horiz, on) { require(['scrollHelper'], function (scrollHelper) { diff --git a/src/components/visibleinviewport.js b/src/components/visibleinviewport.js index 23a2a9d73c..3768740175 100644 --- a/src/components/visibleinviewport.js +++ b/src/components/visibleinviewport.js @@ -22,17 +22,17 @@ define(['dom'], function (dom) { var windowSize = dom.getWindowSize(); - var vpWidth = windowSize.innerWidth, - vpHeight = windowSize.innerHeight; + var vpWidth = windowSize.innerWidth; + var vpHeight = windowSize.innerHeight; // Use this native browser method, if available. - var rec = elem.getBoundingClientRect(), - tViz = rec.top >= 0 && rec.top < vpHeight + thresholdY, - bViz = rec.bottom > 0 && rec.bottom <= vpHeight + thresholdY, - lViz = rec.left >= 0 && rec.left < vpWidth + thresholdX, - rViz = rec.right > 0 && rec.right <= vpWidth + thresholdX, - vVisible = partial ? tViz || bViz : tViz && bViz, - hVisible = partial ? lViz || rViz : lViz && rViz; + var rec = elem.getBoundingClientRect(); + var tViz = rec.top >= 0 && rec.top < vpHeight + thresholdY; + var bViz = rec.bottom > 0 && rec.bottom <= vpHeight + thresholdY; + var lViz = rec.left >= 0 && rec.left < vpWidth + thresholdX; + var rViz = rec.right > 0 && rec.right <= vpWidth + thresholdX; + var vVisible = partial ? tViz || bViz : tViz && bViz; + var hVisible = partial ? lViz || rViz : lViz && rViz; return vVisible && hVisible; } diff --git a/src/components/youtubeplayer/plugin.js b/src/components/youtubeplayer/plugin.js index 1ed95e2110..a2478cd3f4 100644 --- a/src/components/youtubeplayer/plugin.js +++ b/src/components/youtubeplayer/plugin.js @@ -135,7 +135,6 @@ define(['require', 'events', 'browser', 'appRouter', 'loading'], function (requi require(['queryString'], function (queryString) { - instance._currentSrc = options.url; var params = queryString.parse(options.url.split('?')[1]); // 3. This function creates an