text
stringlengths
2
1.05M
var mapAccents={"â":"a","Â":"A","à":"a","À":"A","á":"a","Á":"A","ã":"a","Ã":"A","ê":"e","Ê":"E","è":"e","È":"E","é":"e","É":"E","î":"i","Î":"I","ì":"i","Ì":"I","í":"i","Í":"I","õ":"o","Õ":"O","ô":"o","Ô":"O","ò":"o","Ò":"O","ó":"o","Ó":"O","ö":"o","Ö":"O","ü":"u","Ü":"U","û":"u","Û":"U","ú":"u","Ú":"U","ù":"u","Ù":"U","ç":"c","Ç":"C"}; var removeAccents = function(value){ return value.replace(/[\W\[\] ]/g,function(a){return mapAccents[a]||a}) }; var tagsWithSpace = function(value){ return removeAccents(value).toLowerCase(); }; var tagsWithoutSpace = function(value){ var regex = /[^a-z0-9]+/g; return tagsWithSpace(value).replace(regex, ''); }; var unescapeHtml = function(escaped) { return escaped .replace(/&amp;/g, "&") .replace(/&lt;/g, "<") .replace(/&gt;/g, ">") .replace(/&quot;/g, /"/) .replace(/&#039;/g, "'") .replace(/&apos;/g, "'"); }; var encode = function(str) { return str.replace(/[&\?= ]+/g,'+'); }; var getBytes = function(str) { var bytes = [], char; str = encodeURI(str); while (str.length) { char = str.slice(0, 1); str = str.slice(1); if ('%' !== char) { bytes.push(char.charCodeAt(0)); } else { char = str.slice(0, 2); str = str.slice(2); bytes.push(parseInt(char, 16)); } } return bytes; }; module.exports.removeAccents = removeAccents; module.exports.tagsWithSpace = tagsWithSpace; module.exports.tagsWithoutSpace = tagsWithoutSpace; module.exports.unescapeHtml = unescapeHtml; module.exports.encode = encode; module.exports.getBytes = getBytes;
Component({ externalClasses: ['air-class', 'air-class-mask', 'air-class-header'], options: { multipleSlots: true }, properties: { visible: { type: Boolean, value: false }, maskClosable: { type: Boolean, value: true }, showCancel: { type: Boolean, value: false }, cancelText: { type: String, value: '取消' }, actions: { type: Array, value: [] } }, methods: { handleClickMask() { if (!this.data.maskClosable) return; this.handleClickCancel(); }, handleClickCancel() { this.triggerEvent('cancel'); }, handleClickItem(e) { const dataset = e.currentTarget.dataset || {}; const { index = null } = dataset; if (index) { this.triggerEvent('click', { index }); } } } });
/** vim: et:ts=4:sw=4:sts=4 * @license RequireJS 2.1.14 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ //Not using strict: uneven strict support in browsers, #392, and causes //problems with requirejs.exec()/transpiler plugins that may not be strict. /*jslint regexp: true, nomen: true, sloppy: true */ /*global window, navigator, document, importScripts, setTimeout, opera */ var requirejs, require, define; (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, version = '2.1.14', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\//, op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, ap = Array.prototype, apsp = ap.splice, isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', contexts = {}, cfg = {}, globalDefQueue = [], useInteractive = false; function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } /** * Helper function for iterating over an array backwards. If the func * returns a true value, it will break out of the loop. */ function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function getOwn(obj, prop) { return hasProp(obj, prop) && obj[prop]; } /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; } function scripts() { return document.getElementsByTagName('script'); } function defaultOnError(err) { throw err; } //Allow getting a global that is expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; } if (typeof define !== 'undefined') { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { //Do not overwrite an existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } //Allow for a require config object if (typeof require !== 'undefined' && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } function newContext(contextName) { var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { //Defaults. Do not set a default for map //config to speed up normalize(), which //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, bundles: {}, pkgs: {}, shim: {}, config: {} }, registry = {}, //registry of just enabled modules, to speed //cycle breaking code when lots of modules //are registered, but not activated. enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, bundlesMap = {}, requireCounter = 1, unnormalizedCounter = 1; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; i < ary.length; i++) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { // If at the start, or previous value is still .., // keep them so that when converted to a path it may // still work when converted to a path, even though // as an ID it is less than ideal. In larger point // releases, may be better to just kick out an error. if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') { continue; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, foundMap, foundI, foundStarMap, starI, normalizedBaseParts, baseParts = (baseName && baseName.split('/')), map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name) { name = name.split('/'); lastIndex = name.length - 1; // If wanting node ID compatibility, strip .js from end // of IDs. Have to do this here, and not in nameToUrl // because node allows either .js or non .js to map // to same file. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } // Starts with a '.' so need the baseName if (name[0].charAt(0) === '.' && baseParts) { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); name = normalizedBaseParts.concat(name); } trimDots(name); name = name.join('/'); } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); outerLoop: for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break outerLoop; } } } } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } // If the name points to a package's name, use // the package main instead. pkgMain = getOwn(config.pkgs, name); return pkgMain ? pkgMain : name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); //Custom require that does not do map translation, since //ID is "absolute", already mapped/resolved. context.makeRequire(null, { skipMap: true })([id]); return true; } } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { // If nested plugin references, then do not try to // normalize, as it will not normalize correctly. This // places a restriction on resourceIds, and the longer // term solution is not to normalize until plugins are // loaded and all normalizations to allow for async // loading of a loader plugin. But for now, fixes the // common uses. Details in #1131 normalizedName = name.indexOf('!') === -1 ? normalize(name, parentName, applyMap) : name; } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { 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); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { mod = getModule(depMap); if (mod.error && name === 'error') { fn(mod.error); } else { mod.on(name, fn); } } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length, 0].concat(globalDefQueue)); globalDefQueue = []; } } handlers = { 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { return (defined[mod.map.id] = mod.exports); } else { return (mod.exports = defined[mod.map.id] = {}); } } }, 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return getOwn(config.config, mod.map.id) || {}; }, exports: mod.exports || (mod.exports = {}) }); } } }; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } } function checkLoaded() { var err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { var map = mod.map, modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } 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; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. However, //only do it for define()'d modules. require //errbacks should not be called for failures in //their callbacks (#699). However if a global //onError is set, use that. 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); } // Favor return value over exports. If node/cjs in play, // then will not have a return value anyway. Favor // module.exports assignment over exports object. if (this.map.isDefine && exports === undefined) { cjsModule = this.module; if (cjsModule) { exports = cjsModule.exports; } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = this.map.isDefine ? [this.map.id] : null; err.requireType = this.map.isDefine ? 'define' : 'require'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }, callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. pluginMap = makeModuleMap(map.prefix); //Mark this as a dependency for this plugin, so it //can be traced for cycles. 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: true }); //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap); on(normalizedMap, 'defined', bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(normalizedMap); if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } //If a paths config, then just load that file instead to //resolve the plugin, as it is built into that paths layer. if (bundleId) { this.map.url = context.nameToUrl(bundleId); this.load(); return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), hasInteractive = useInteractive; //As of 2.1.0, support just passing the text, to reinforce //fromText only being called once per resource. Still //support old style of passing moduleName but discard //that moduleName in favor of the internal ref. if (textAlt) { text = textAlt; } //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for //it. getModule(moduleMap); //Transfer any config to this other module. if (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])); } if (hasInteractive) { useInteractive = true; } //Mark this as a dependency for the plugin //resource this.depMaps.push(moduleMap); //Support anonymous modules. context.completeLoad(moduleName); //Bind the value of that module to the value for this //resource ID. localRequire([moduleName], load); }); //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. 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 = true; //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', bind(this, this.errback)); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!hasProp(handlers, id) && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry. delete this.events[name]; } } }; function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } } context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, defQueue: defQueue, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, onError: onError, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } //Save off the paths since they require special processing, //they are additive. var shim = config.shim, objs = { paths: true, bundles: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (!config[prop]) { config[prop] = {}; } mixin(config[prop], value, true, true); } else { config[prop] = value; } }); //Reverse map the bundles if (cfg.bundles) { eachProp(cfg.bundles, function (value, prop) { each(value, function (v) { if (v !== prop) { bundlesMap[v] = prop; } }); }); } //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = context.makeShimExports(value); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location, name; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; name = pkgObj.name; location = pkgObj.location; if (location) { config.paths[name] = pkgObj.location; } //Save pointer to main module ID for pkg name. //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, ''); }); } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; }, makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; } mixin(localRequire, { isBrowser: isBrowser, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; //Have a file extension alias, and it is not the //dots from a relative path. if (index !== -1 && (!isRelative || index > 1)) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true); }, defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } }); //Only allow undef on top level require calls if (!relMap) { localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); removeScript(id); delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; //Clean queued defines too. Go backwards //in array so that the splices do not //mess up the iteration. eachReverse(defQueue, function(args, i) { if(args[0] === id) { defQueue.splice(i, 1); } }); if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } cleanRegistry(id); } }; } return localRequire; }, /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, * is passed in for context, when this method is overridden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, shExports = shim.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = getOwn(registry, moduleName); if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); } } checkLoaded(); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ 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); if (bundleId) { return context.nameToUrl(bundleId, ext, skipExt); } //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callback function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); } } }; context.require = context.makeRequire(); return context; } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = getOwn(contexts, contextName); if (!context) { context = contexts[contextName] = req.s.newContext(contextName); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Execute something after the current tick * of the event loop. Override for other envs * that have a better solution than setTimeout. * @param {Function} fn function to execute later. */ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 4); } : function (fn) { fn(); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; req.isBrowser = isBrowser; s = req.s = { contexts: contexts, newContext: newContext }; //Create default context. req({}); //Exports some context-sensitive methods on global require. each([ 'toUrl', 'undef', 'defined', 'specified' ], function (prop) { //Reference from contexts instead of early binding to default context, //so that during builds, the latest instance of the default context //with its config gets used. req[prop] = function () { var ctx = contexts[defContextName]; return ctx.require[prop].apply(ctx, arguments); }; }); if (isBrowser) { head = s.head = document.getElementsByTagName('head')[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: //http://dev.jquery.com/ticket/2709 baseElement = document.getElementsByTagName('base')[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = defaultOnError; /** * Creates the node for the load command. Only used in browser envs. */ req.createNode = function (config, moduleName, url) { var node = config.xhtml ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; return node; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, node; if (isBrowser) { //In the browser so use a script tag node = req.createNode(config, moduleName, url); node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && //Check if node.attachEvent is artificially added by custom script or //natively supported by browser //read https://github.com/jrburke/requirejs/issues/187 //if we can NOT find [native code] then it must NOT natively supported. //in IE8, node.attachEvent does not have toString() //Note the test for "[native code" with no closing brace, see: //https://github.com/jrburke/requirejs/issues/273 !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in 'interactive' //readyState at the time of the define call. useInteractive = true; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before //the error handler, so that does not help. If addEventListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, //then fire the script load event listener before execute //next script' that other browsers do. //Best hope: IE10 fixes the issues, //and then destroys all installs of IE 6-9. //node.attachEvent('onerror', context.onScriptError); } else { node.addEventListener('load', context.onScriptLoad, false); node.addEventListener('error', context.onScriptError, false); } node.src = url; //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. currentlyAddingScript = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } currentlyAddingScript = null; return node; } else if (isWebWorker) { try { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation that a build has been done so that //only one script needs to be loaded anyway. This may need to be //reevaluated if other use cases become common. importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } catch (e) { context.onError(makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, e, [moduleName])); } } }; function getInteractiveScript() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; } //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser && !cfg.skipDataMain) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { //Preserve dataMain in case it is a path (i.e. contains '?') mainScript = dataMain; //Set final baseUrl if there is not already an explicit one. if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. src = mainScript.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; } //Strip off any trailing .js since mainScript is now //like a module name. mainScript = mainScript.replace(jsSuffixRegExp, ''); //If mainScript is still a path, fall back to dataMain if (req.jsExtRegExp.test(mainScript)) { mainScript = dataMain; } //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; return true; } }); } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous modules if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = null; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps && isFunction(callback)) { deps = []; //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, '') .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = currentlyAddingScript || getInteractiveScript(); if (node) { if (!name) { name = node.getAttribute('data-requiremodule'); } context = contexts[node.getAttribute('data-requirecontext')]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); }; define.amd = { jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a better, environment-specific call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); }(this));
const { ApplicationCommand, ApplicationCommandData, ApplicationCommandOption, ApplicationCommandOptionChoice, Collection, } = require('discord.js'); class SlashCommand { /** * @param command * @param {"USER"|"CHAT_INPUT"|"MESSAGE"} type * @return {ApplicationCommandData} */ constructor(command, type) { this.type = type; this.name = command.names[0]; if (type === 'CHAT_INPUT') { this.description = command.description; this.options = command.getOptions(); } } /** * * @param {ApplicationCommand} command */ matchesDefinition(command) { if (this.name !== command.name || this.type !== this.type) { return false; } return this.type !== 'CHAT_INPUT' || (this.description === command.description && matchingOptions(this.options, command.options)); } /** * @param {[]} commands * @return {Collection<String, SlashCommand>} */ static getFromClasses(commands) { const result = new Collection(); for (const command of commands) { if (command.supportsSlashCommands) { result.set(`CHAT_INPUT:${command.names[0]}`, new SlashCommand(command, 'CHAT_INPUT')); } if (command.supportedContextMenus.USER) { result.set(`USER:${command.names[0]}`, new SlashCommand(command, 'USER')); } if (command.supportedContextMenus.MESSAGE) { result.set(`MESSAGE:${command.names[0]}`, new SlashCommand(command, 'MESSAGE')); } } return result; } } /** * * @param {ApplicationCommandOption[]} a * @param {ApplicationCommandOption[]} b * @return {boolean} */ function matchingOptions(a, b) { if (!Array.isArray(a) && !Array.isArray(b)) return true; if (!Array.isArray(a) || !Array.isArray(b)) return false; return a.every((aElement, index) => { const bElement = b[index]; if (!bElement) { return false; } return aElement.name === bElement.name && aElement.type === bElement.type && aElement.description === bElement.description && aElement.required === bElement.required && matchingChoices(aElement.choices, bElement.choices) && (!aElement.options && !bElement.options || matchingOptions(aElement.options, bElement.options)); }); } /** * @param {ApplicationCommandOptionChoice[]} a * @param {ApplicationCommandOptionChoice[]} b * @return {boolean} */ function matchingChoices(a, b) { if (!Array.isArray(a) && !Array.isArray(b)) return true; if (!Array.isArray(a) || !Array.isArray(b)) return false; if (a.length !== b.length) return false; return a.every((aElement, index) => { const bElement = b[index]; return aElement.value === bElement.value && aElement.name && bElement.name; }); } module.exports = SlashCommand;
/** * @licstart The following is the entire license notice for the * Javascript code in this page * * Copyright 2021 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @licend The above is the entire license notice for the * Javascript code in this page */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("pdfjs-dist/web/pdf_viewer", [], factory); else if(typeof exports === 'object') exports["pdfjs-dist/web/pdf_viewer"] = factory(); else root["pdfjs-dist/web/pdf_viewer"] = root.pdfjsViewer = factory(); })(this, function() { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ /* 0 */, /* 1 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultAnnotationLayerFactory = exports.AnnotationLayerBuilder = void 0; var _pdfjsLib = __w_pdfjs_require__(2); var _l10n_utils = __w_pdfjs_require__(3); var _pdf_link_service = __w_pdfjs_require__(4); class AnnotationLayerBuilder { constructor({ pageDiv, pdfPage, linkService, downloadManager, annotationStorage = null, imageResourcesPath = "", renderForms = true, l10n = _l10n_utils.NullL10n, enableScripting = false, hasJSActionsPromise = null, fieldObjectsPromise = null, mouseState = null }) { this.pageDiv = pageDiv; this.pdfPage = pdfPage; this.linkService = linkService; this.downloadManager = downloadManager; this.imageResourcesPath = imageResourcesPath; this.renderForms = renderForms; this.l10n = l10n; this.annotationStorage = annotationStorage; this.enableScripting = enableScripting; this._hasJSActionsPromise = hasJSActionsPromise; this._fieldObjectsPromise = fieldObjectsPromise; this._mouseState = mouseState; this.div = null; this._cancelled = false; } async render(viewport, intent = "display") { const [annotations, hasJSActions = false, fieldObjects = null] = await Promise.all([this.pdfPage.getAnnotations({ intent }), this._hasJSActionsPromise, this._fieldObjectsPromise]); if (this._cancelled || annotations.length === 0) { return; } const parameters = { viewport: viewport.clone({ dontFlip: true }), div: this.div, annotations, page: this.pdfPage, imageResourcesPath: this.imageResourcesPath, renderForms: this.renderForms, linkService: this.linkService, downloadManager: this.downloadManager, annotationStorage: this.annotationStorage, enableScripting: this.enableScripting, hasJSActions, fieldObjects, mouseState: this._mouseState }; if (this.div) { _pdfjsLib.AnnotationLayer.update(parameters); } else { this.div = document.createElement("div"); this.div.className = "annotationLayer"; this.pageDiv.appendChild(this.div); parameters.div = this.div; _pdfjsLib.AnnotationLayer.render(parameters); this.l10n.translate(this.div); } } cancel() { this._cancelled = true; } hide() { if (!this.div) { return; } this.div.hidden = true; } } exports.AnnotationLayerBuilder = AnnotationLayerBuilder; class DefaultAnnotationLayerFactory { createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderForms = true, l10n = _l10n_utils.NullL10n, enableScripting = false, hasJSActionsPromise = null, mouseState = null, fieldObjectsPromise = null) { return new AnnotationLayerBuilder({ pageDiv, pdfPage, imageResourcesPath, renderForms, linkService: new _pdf_link_service.SimpleLinkService(), l10n, annotationStorage, enableScripting, hasJSActionsPromise, fieldObjectsPromise, mouseState }); } } exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory; /***/ }), /* 2 */ /***/ ((module) => { let pdfjsLib; if (typeof window !== "undefined" && window["pdfjs-dist/build/pdf"]) { pdfjsLib = window["pdfjs-dist/build/pdf"]; } else { pdfjsLib = require("../build/pdf.js"); } module.exports = pdfjsLib; /***/ }), /* 3 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fixupLangCode = fixupLangCode; exports.getL10nFallback = getL10nFallback; exports.NullL10n = void 0; const DEFAULT_L10N_STRINGS = { of_pages: "of {{pagesCount}}", page_of_pages: "({{pageNumber}} of {{pagesCount}})", document_properties_kb: "{{size_kb}} KB ({{size_b}} bytes)", document_properties_mb: "{{size_mb}} MB ({{size_b}} bytes)", document_properties_date_string: "{{date}}, {{time}}", document_properties_page_size_unit_inches: "in", document_properties_page_size_unit_millimeters: "mm", document_properties_page_size_orientation_portrait: "portrait", document_properties_page_size_orientation_landscape: "landscape", document_properties_page_size_name_a3: "A3", document_properties_page_size_name_a4: "A4", document_properties_page_size_name_letter: "Letter", document_properties_page_size_name_legal: "Legal", document_properties_page_size_dimension_string: "{{width}} × {{height}} {{unit}} ({{orientation}})", document_properties_page_size_dimension_name_string: "{{width}} × {{height}} {{unit}} ({{name}}, {{orientation}})", document_properties_linearized_yes: "Yes", document_properties_linearized_no: "No", print_progress_percent: "{{progress}}%", "toggle_sidebar.title": "Toggle Sidebar", "toggle_sidebar_notification2.title": "Toggle Sidebar (document contains outline/attachments/layers)", additional_layers: "Additional Layers", page_landmark: "Page {{page}}", thumb_page_title: "Page {{page}}", thumb_page_canvas: "Thumbnail of Page {{page}}", find_reached_top: "Reached top of document, continued from bottom", find_reached_bottom: "Reached end of document, continued from top", "find_match_count[one]": "{{current}} of {{total}} match", "find_match_count[other]": "{{current}} of {{total}} matches", "find_match_count_limit[one]": "More than {{limit}} match", "find_match_count_limit[other]": "More than {{limit}} matches", find_not_found: "Phrase not found", error_version_info: "PDF.js v{{version}} (build: {{build}})", error_message: "Message: {{message}}", error_stack: "Stack: {{stack}}", error_file: "File: {{file}}", error_line: "Line: {{line}}", rendering_error: "An error occurred while rendering the page.", page_scale_width: "Page Width", page_scale_fit: "Page Fit", page_scale_auto: "Automatic Zoom", page_scale_actual: "Actual Size", page_scale_percent: "{{scale}}%", loading: "Loading…", loading_error: "An error occurred while loading the PDF.", invalid_file_error: "Invalid or corrupted PDF file.", missing_file_error: "Missing PDF file.", unexpected_response_error: "Unexpected server response.", printing_not_supported: "Warning: Printing is not fully supported by this browser.", printing_not_ready: "Warning: The PDF is not fully loaded for printing.", web_fonts_disabled: "Web fonts are disabled: unable to use embedded PDF fonts." }; function getL10nFallback(key, args) { switch (key) { case "find_match_count": key = `find_match_count[${args.total === 1 ? "one" : "other"}]`; break; case "find_match_count_limit": key = `find_match_count_limit[${args.limit === 1 ? "one" : "other"}]`; break; } return DEFAULT_L10N_STRINGS[key] || ""; } const PARTIAL_LANG_CODES = { en: "en-US", es: "es-ES", fy: "fy-NL", ga: "ga-IE", gu: "gu-IN", hi: "hi-IN", hy: "hy-AM", nb: "nb-NO", ne: "ne-NP", nn: "nn-NO", pa: "pa-IN", pt: "pt-PT", sv: "sv-SE", zh: "zh-CN" }; function fixupLangCode(langCode) { return PARTIAL_LANG_CODES[langCode?.toLowerCase()] || langCode; } function formatL10nValue(text, args) { if (!args) { return text; } return text.replace(/\{\{\s*(\w+)\s*\}\}/g, (all, name) => { return name in args ? args[name] : "{{" + name + "}}"; }); } const NullL10n = { async getLanguage() { return "en-us"; }, async getDirection() { return "ltr"; }, async get(key, args = null, fallback = getL10nFallback(key, args)) { return formatL10nValue(fallback, args); }, async translate(element) {} }; exports.NullL10n = NullL10n; /***/ }), /* 4 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SimpleLinkService = exports.PDFLinkService = void 0; var _pdfjsLib = __w_pdfjs_require__(2); var _ui_utils = __w_pdfjs_require__(5); class PDFLinkService { constructor({ eventBus, externalLinkTarget = null, externalLinkRel = null, ignoreDestinationZoom = false } = {}) { this.eventBus = eventBus; this.externalLinkTarget = externalLinkTarget; this.externalLinkRel = externalLinkRel; this.externalLinkEnabled = true; this._ignoreDestinationZoom = ignoreDestinationZoom; this.baseUrl = null; this.pdfDocument = null; this.pdfViewer = null; this.pdfHistory = null; this._pagesRefCache = null; } setDocument(pdfDocument, baseUrl = null) { this.baseUrl = baseUrl; this.pdfDocument = pdfDocument; this._pagesRefCache = Object.create(null); } setViewer(pdfViewer) { this.pdfViewer = pdfViewer; } setHistory(pdfHistory) { this.pdfHistory = pdfHistory; } get pagesCount() { return this.pdfDocument ? this.pdfDocument.numPages : 0; } get page() { return this.pdfViewer.currentPageNumber; } set page(value) { this.pdfViewer.currentPageNumber = value; } get rotation() { return this.pdfViewer.pagesRotation; } set rotation(value) { this.pdfViewer.pagesRotation = value; } _goToDestinationHelper(rawDest, namedDest = null, explicitDest) { const destRef = explicitDest[0]; let pageNumber; if (typeof destRef === "object" && destRef !== null) { pageNumber = this._cachedPageNumber(destRef); if (pageNumber === null) { this.pdfDocument.getPageIndex(destRef).then(pageIndex => { this.cachePageRef(pageIndex + 1, destRef); this._goToDestinationHelper(rawDest, namedDest, explicitDest); }).catch(() => { console.error(`PDFLinkService._goToDestinationHelper: "${destRef}" is not ` + `a valid page reference, for dest="${rawDest}".`); }); return; } } else if (Number.isInteger(destRef)) { pageNumber = destRef + 1; } else { console.error(`PDFLinkService._goToDestinationHelper: "${destRef}" is not ` + `a valid destination reference, for dest="${rawDest}".`); return; } if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { console.error(`PDFLinkService._goToDestinationHelper: "${pageNumber}" is not ` + `a valid page number, for dest="${rawDest}".`); return; } if (this.pdfHistory) { this.pdfHistory.pushCurrentPosition(); this.pdfHistory.push({ namedDest, explicitDest, pageNumber }); } this.pdfViewer.scrollPageIntoView({ pageNumber, destArray: explicitDest, ignoreDestinationZoom: this._ignoreDestinationZoom }); } async goToDestination(dest) { if (!this.pdfDocument) { return; } let namedDest, explicitDest; if (typeof dest === "string") { namedDest = dest; explicitDest = await this.pdfDocument.getDestination(dest); } else { namedDest = null; explicitDest = await dest; } if (!Array.isArray(explicitDest)) { console.error(`PDFLinkService.goToDestination: "${explicitDest}" is not ` + `a valid destination array, for dest="${dest}".`); return; } this._goToDestinationHelper(dest, namedDest, explicitDest); } goToPage(val) { if (!this.pdfDocument) { return; } const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); return; } if (this.pdfHistory) { this.pdfHistory.pushCurrentPosition(); this.pdfHistory.pushPage(pageNumber); } this.pdfViewer.scrollPageIntoView({ pageNumber }); } addLinkAttributes(link, url, newWindow = false) { (0, _pdfjsLib.addLinkAttributes)(link, { url, target: newWindow ? _pdfjsLib.LinkTarget.BLANK : this.externalLinkTarget, rel: this.externalLinkRel, enabled: this.externalLinkEnabled }); } getDestinationHash(dest) { if (typeof dest === "string") { if (dest.length > 0) { return this.getAnchorUrl("#" + escape(dest)); } } else if (Array.isArray(dest)) { const str = JSON.stringify(dest); if (str.length > 0) { return this.getAnchorUrl("#" + escape(str)); } } return this.getAnchorUrl(""); } getAnchorUrl(anchor) { return (this.baseUrl || "") + anchor; } setHash(hash) { if (!this.pdfDocument) { return; } let pageNumber, dest; if (hash.includes("=")) { const params = (0, _ui_utils.parseQueryString)(hash); if (params.has("search")) { this.eventBus.dispatch("findfromurlhash", { source: this, query: params.get("search").replace(/"/g, ""), phraseSearch: params.get("phrase") === "true" }); } if (params.has("page")) { pageNumber = params.get("page") | 0 || 1; } if (params.has("zoom")) { const zoomArgs = params.get("zoom").split(","); const zoomArg = zoomArgs[0]; const zoomArgNumber = parseFloat(zoomArg); if (!zoomArg.includes("Fit")) { dest = [null, { name: "XYZ" }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; } else { if (zoomArg === "Fit" || zoomArg === "FitB") { dest = [null, { name: zoomArg }]; } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { dest = [null, { name: zoomArg }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; } else if (zoomArg === "FitR") { if (zoomArgs.length !== 5) { console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); } else { dest = [null, { name: zoomArg }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; } } else { console.error(`PDFLinkService.setHash: "${zoomArg}" is not ` + "a valid zoom value."); } } } if (dest) { this.pdfViewer.scrollPageIntoView({ pageNumber: pageNumber || this.page, destArray: dest, allowNegativeOffset: true }); } else if (pageNumber) { this.page = pageNumber; } if (params.has("pagemode")) { this.eventBus.dispatch("pagemode", { source: this, mode: params.get("pagemode") }); } if (params.has("nameddest")) { this.goToDestination(params.get("nameddest")); } } else { dest = unescape(hash); try { dest = JSON.parse(dest); if (!Array.isArray(dest)) { dest = dest.toString(); } } catch (ex) {} if (typeof dest === "string" || isValidExplicitDestination(dest)) { this.goToDestination(dest); return; } console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not ` + "a valid destination."); } } executeNamedAction(action) { switch (action) { case "GoBack": this.pdfHistory?.back(); break; case "GoForward": this.pdfHistory?.forward(); break; case "NextPage": this.pdfViewer.nextPage(); break; case "PrevPage": this.pdfViewer.previousPage(); break; case "LastPage": this.page = this.pagesCount; break; case "FirstPage": this.page = 1; break; default: break; } this.eventBus.dispatch("namedaction", { source: this, action }); } cachePageRef(pageNum, pageRef) { if (!pageRef) { return; } const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`; this._pagesRefCache[refStr] = pageNum; } _cachedPageNumber(pageRef) { const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`; return this._pagesRefCache?.[refStr] || null; } isPageVisible(pageNumber) { return this.pdfViewer.isPageVisible(pageNumber); } isPageCached(pageNumber) { return this.pdfViewer.isPageCached(pageNumber); } } exports.PDFLinkService = PDFLinkService; function isValidExplicitDestination(dest) { if (!Array.isArray(dest)) { return false; } const destLength = dest.length; if (destLength < 2) { return false; } const page = dest[0]; if (!(typeof page === "object" && Number.isInteger(page.num) && Number.isInteger(page.gen)) && !(Number.isInteger(page) && page >= 0)) { return false; } const zoom = dest[1]; if (!(typeof zoom === "object" && typeof zoom.name === "string")) { return false; } let allowNull = true; switch (zoom.name) { case "XYZ": if (destLength !== 5) { return false; } break; case "Fit": case "FitB": return destLength === 2; case "FitH": case "FitBH": case "FitV": case "FitBV": if (destLength !== 3) { return false; } break; case "FitR": if (destLength !== 6) { return false; } allowNull = false; break; default: return false; } for (let i = 2; i < destLength; i++) { const param = dest[i]; if (!(typeof param === "number" || allowNull && param === null)) { return false; } } return true; } class SimpleLinkService { constructor() { this.externalLinkEnabled = true; } get pagesCount() { return 0; } get page() { return 0; } set page(value) {} get rotation() { return 0; } set rotation(value) {} async goToDestination(dest) {} goToPage(val) {} addLinkAttributes(link, url, newWindow = false) { (0, _pdfjsLib.addLinkAttributes)(link, { url, enabled: this.externalLinkEnabled }); } getDestinationHash(dest) { return "#"; } getAnchorUrl(hash) { return "#"; } setHash(hash) {} executeNamedAction(action) {} cachePageRef(pageNum, pageRef) {} isPageVisible(pageNumber) { return true; } isPageCached(pageNumber) { return true; } } exports.SimpleLinkService = SimpleLinkService; /***/ }), /* 5 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.apiPageLayoutToSpreadMode = apiPageLayoutToSpreadMode; exports.apiPageModeToSidebarView = apiPageModeToSidebarView; exports.approximateFraction = approximateFraction; exports.backtrackBeforeAllVisibleElements = backtrackBeforeAllVisibleElements; exports.binarySearchFirstItem = binarySearchFirstItem; exports.getActiveOrFocusedElement = getActiveOrFocusedElement; exports.getOutputScale = getOutputScale; exports.getPageSizeInches = getPageSizeInches; exports.getVisibleElements = getVisibleElements; exports.isPortraitOrientation = isPortraitOrientation; exports.isValidRotation = isValidRotation; exports.isValidScrollMode = isValidScrollMode; exports.isValidSpreadMode = isValidSpreadMode; exports.moveToEndOfArray = moveToEndOfArray; exports.noContextMenuHandler = noContextMenuHandler; exports.normalizeWheelEventDelta = normalizeWheelEventDelta; exports.normalizeWheelEventDirection = normalizeWheelEventDirection; exports.parseQueryString = parseQueryString; exports.roundToDivide = roundToDivide; exports.scrollIntoView = scrollIntoView; exports.waitOnEventOrTimeout = waitOnEventOrTimeout; exports.watchScroll = watchScroll; exports.WaitOnType = exports.VERTICAL_PADDING = exports.UNKNOWN_SCALE = exports.TextLayerMode = exports.SpreadMode = exports.SidebarView = exports.ScrollMode = exports.SCROLLBAR_PADDING = exports.RendererType = exports.ProgressBar = exports.PresentationModeState = exports.MIN_SCALE = exports.MAX_SCALE = exports.MAX_AUTO_SCALE = exports.EventBus = exports.DEFAULT_SCALE_VALUE = exports.DEFAULT_SCALE_DELTA = exports.DEFAULT_SCALE = exports.AutoPrintRegExp = exports.AutomationEventBus = exports.animationStarted = void 0; const DEFAULT_SCALE_VALUE = "auto"; exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE; const DEFAULT_SCALE = 1.0; exports.DEFAULT_SCALE = DEFAULT_SCALE; const DEFAULT_SCALE_DELTA = 1.1; exports.DEFAULT_SCALE_DELTA = DEFAULT_SCALE_DELTA; const MIN_SCALE = 0.1; exports.MIN_SCALE = MIN_SCALE; const MAX_SCALE = 10.0; exports.MAX_SCALE = MAX_SCALE; const UNKNOWN_SCALE = 0; exports.UNKNOWN_SCALE = UNKNOWN_SCALE; const MAX_AUTO_SCALE = 1.25; exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE; const SCROLLBAR_PADDING = 40; exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING; const VERTICAL_PADDING = 5; exports.VERTICAL_PADDING = VERTICAL_PADDING; const LOADINGBAR_END_OFFSET_VAR = "--loadingBar-end-offset"; const PresentationModeState = { UNKNOWN: 0, NORMAL: 1, CHANGING: 2, FULLSCREEN: 3 }; exports.PresentationModeState = PresentationModeState; const SidebarView = { UNKNOWN: -1, NONE: 0, THUMBS: 1, OUTLINE: 2, ATTACHMENTS: 3, LAYERS: 4 }; exports.SidebarView = SidebarView; const RendererType = { CANVAS: "canvas", SVG: "svg" }; exports.RendererType = RendererType; const TextLayerMode = { DISABLE: 0, ENABLE: 1, ENABLE_ENHANCE: 2 }; exports.TextLayerMode = TextLayerMode; const ScrollMode = { UNKNOWN: -1, VERTICAL: 0, HORIZONTAL: 1, WRAPPED: 2 }; exports.ScrollMode = ScrollMode; const SpreadMode = { UNKNOWN: -1, NONE: 0, ODD: 1, EVEN: 2 }; exports.SpreadMode = SpreadMode; const AutoPrintRegExp = /\bprint\s*\(/; exports.AutoPrintRegExp = AutoPrintRegExp; function getOutputScale(ctx) { const devicePixelRatio = window.devicePixelRatio || 1; const backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; const pixelRatio = devicePixelRatio / backingStoreRatio; return { sx: pixelRatio, sy: pixelRatio, scaled: pixelRatio !== 1 }; } function scrollIntoView(element, spot, scrollMatches = false) { let parent = element.offsetParent; if (!parent) { console.error("offsetParent is not set -- cannot scroll"); return; } let offsetY = element.offsetTop + element.clientTop; let offsetX = element.offsetLeft + element.clientLeft; while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { offsetY += parent.offsetTop; offsetX += parent.offsetLeft; parent = parent.offsetParent; if (!parent) { return; } } if (spot) { if (spot.top !== undefined) { offsetY += spot.top; } if (spot.left !== undefined) { offsetX += spot.left; parent.scrollLeft = offsetX; } } parent.scrollTop = offsetY; } function watchScroll(viewAreaElement, callback) { const debounceScroll = function (evt) { if (rAF) { return; } rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { rAF = null; const currentX = viewAreaElement.scrollLeft; const lastX = state.lastX; if (currentX !== lastX) { state.right = currentX > lastX; } state.lastX = currentX; const currentY = viewAreaElement.scrollTop; const lastY = state.lastY; if (currentY !== lastY) { state.down = currentY > lastY; } state.lastY = currentY; callback(state); }); }; const state = { right: true, down: true, lastX: viewAreaElement.scrollLeft, lastY: viewAreaElement.scrollTop, _eventHandler: debounceScroll }; let rAF = null; viewAreaElement.addEventListener("scroll", debounceScroll, true); return state; } function parseQueryString(query) { const params = new Map(); for (const part of query.split("&")) { const param = part.split("="), key = param[0].toLowerCase(), value = param.length > 1 ? param[1] : ""; params.set(decodeURIComponent(key), decodeURIComponent(value)); } return params; } function binarySearchFirstItem(items, condition) { let minIndex = 0; let maxIndex = items.length - 1; if (maxIndex < 0 || !condition(items[maxIndex])) { return items.length; } if (condition(items[minIndex])) { return minIndex; } while (minIndex < maxIndex) { const currentIndex = minIndex + maxIndex >> 1; const currentItem = items[currentIndex]; if (condition(currentItem)) { maxIndex = currentIndex; } else { minIndex = currentIndex + 1; } } return minIndex; } function approximateFraction(x) { if (Math.floor(x) === x) { return [x, 1]; } const xinv = 1 / x; const limit = 8; if (xinv > limit) { return [1, limit]; } else if (Math.floor(xinv) === xinv) { return [1, xinv]; } const x_ = x > 1 ? xinv : x; let a = 0, b = 1, c = 1, d = 1; while (true) { const p = a + c, q = b + d; if (q > limit) { break; } if (x_ <= p / q) { c = p; d = q; } else { a = p; b = q; } } let result; if (x_ - a / b < c / d - x_) { result = x_ === x ? [a, b] : [b, a]; } else { result = x_ === x ? [c, d] : [d, c]; } return result; } function roundToDivide(x, div) { const r = x % div; return r === 0 ? x : Math.round(x - r + div); } function getPageSizeInches({ view, userUnit, rotate }) { const [x1, y1, x2, y2] = view; const changeOrientation = rotate % 180 !== 0; const width = (x2 - x1) / 72 * userUnit; const height = (y2 - y1) / 72 * userUnit; return { width: changeOrientation ? height : width, height: changeOrientation ? width : height }; } function backtrackBeforeAllVisibleElements(index, views, top) { if (index < 2) { return index; } let elt = views[index].div; let pageTop = elt.offsetTop + elt.clientTop; if (pageTop >= top) { elt = views[index - 1].div; pageTop = elt.offsetTop + elt.clientTop; } for (let i = index - 2; i >= 0; --i) { elt = views[i].div; if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) { break; } index = i; } return index; } function getVisibleElements({ scrollEl, views, sortByVisibility = false, horizontal = false, rtl = false }) { const top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight; const left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth; function isElementBottomAfterViewTop(view) { const element = view.div; const elementBottom = element.offsetTop + element.clientTop + element.clientHeight; return elementBottom > top; } function isElementNextAfterViewHorizontally(view) { const element = view.div; const elementLeft = element.offsetLeft + element.clientLeft; const elementRight = elementLeft + element.clientWidth; return rtl ? elementLeft < right : elementRight > left; } const visible = [], numViews = views.length; let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); } let lastEdge = horizontal ? right : -1; for (let i = firstVisibleElementInd; i < numViews; i++) { const view = views[i], element = view.div; const currentWidth = element.offsetLeft + element.clientLeft; const currentHeight = element.offsetTop + element.clientTop; const viewWidth = element.clientWidth, viewHeight = element.clientHeight; const viewRight = currentWidth + viewWidth; const viewBottom = currentHeight + viewHeight; if (lastEdge === -1) { if (viewBottom >= bottom) { lastEdge = viewBottom; } } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) { break; } if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) { continue; } const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, fractionWidth = (viewWidth - hiddenWidth) / viewWidth; const percent = fractionHeight * fractionWidth * 100 | 0; visible.push({ id: view.id, x: currentWidth, y: currentHeight, view, percent, widthPercent: fractionWidth * 100 | 0 }); } const first = visible[0], last = visible[visible.length - 1]; if (sortByVisibility) { visible.sort(function (a, b) { const pc = a.percent - b.percent; if (Math.abs(pc) > 0.001) { return -pc; } return a.id - b.id; }); } return { first, last, views: visible }; } function noContextMenuHandler(evt) { evt.preventDefault(); } function normalizeWheelEventDirection(evt) { let delta = Math.hypot(evt.deltaX, evt.deltaY); const angle = Math.atan2(evt.deltaY, evt.deltaX); if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { delta = -delta; } return delta; } function normalizeWheelEventDelta(evt) { let delta = normalizeWheelEventDirection(evt); const MOUSE_DOM_DELTA_PIXEL_MODE = 0; const MOUSE_DOM_DELTA_LINE_MODE = 1; const MOUSE_PIXELS_PER_LINE = 30; const MOUSE_LINES_PER_PAGE = 30; if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) { delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) { delta /= MOUSE_LINES_PER_PAGE; } return delta; } function isValidRotation(angle) { return Number.isInteger(angle) && angle % 90 === 0; } function isValidScrollMode(mode) { return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN; } function isValidSpreadMode(mode) { return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN; } function isPortraitOrientation(size) { return size.width <= size.height; } const WaitOnType = { EVENT: "event", TIMEOUT: "timeout" }; exports.WaitOnType = WaitOnType; function waitOnEventOrTimeout({ target, name, delay = 0 }) { return new Promise(function (resolve, reject) { if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { throw new Error("waitOnEventOrTimeout - invalid parameters."); } function handler(type) { if (target instanceof EventBus) { target._off(name, eventHandler); } else { target.removeEventListener(name, eventHandler); } if (timeout) { clearTimeout(timeout); } resolve(type); } const eventHandler = handler.bind(null, WaitOnType.EVENT); if (target instanceof EventBus) { target._on(name, eventHandler); } else { target.addEventListener(name, eventHandler); } const timeoutHandler = handler.bind(null, WaitOnType.TIMEOUT); const timeout = setTimeout(timeoutHandler, delay); }); } const animationStarted = new Promise(function (resolve) { window.requestAnimationFrame(resolve); }); exports.animationStarted = animationStarted; class EventBus { constructor() { this._listeners = Object.create(null); } on(eventName, listener, options = null) { this._on(eventName, listener, { external: true, once: options?.once }); } off(eventName, listener, options = null) { this._off(eventName, listener, { external: true, once: options?.once }); } dispatch(eventName, data) { const eventListeners = this._listeners[eventName]; if (!eventListeners || eventListeners.length === 0) { return; } let externalListeners; for (const { listener, external, once } of eventListeners.slice(0)) { if (once) { this._off(eventName, listener); } if (external) { (externalListeners ||= []).push(listener); continue; } listener(data); } if (externalListeners) { for (const listener of externalListeners) { listener(data); } externalListeners = null; } } _on(eventName, listener, options = null) { const eventListeners = this._listeners[eventName] ||= []; eventListeners.push({ listener, external: options?.external === true, once: options?.once === true }); } _off(eventName, listener, options = null) { const eventListeners = this._listeners[eventName]; if (!eventListeners) { return; } for (let i = 0, ii = eventListeners.length; i < ii; i++) { if (eventListeners[i].listener === listener) { eventListeners.splice(i, 1); return; } } } } exports.EventBus = EventBus; class AutomationEventBus extends EventBus { dispatch(eventName, data) { throw new Error("Not implemented: AutomationEventBus.dispatch"); } } exports.AutomationEventBus = AutomationEventBus; function clamp(v, min, max) { return Math.min(Math.max(v, min), max); } class ProgressBar { constructor(id, { height, width, units } = {}) { this.visible = true; this.div = document.querySelector(id + " .progress"); this.bar = this.div.parentNode; this.height = height || 100; this.width = width || 100; this.units = units || "%"; this.div.style.height = this.height + this.units; this.percent = 0; } _updateBar() { if (this._indeterminate) { this.div.classList.add("indeterminate"); this.div.style.width = this.width + this.units; return; } this.div.classList.remove("indeterminate"); const progressSize = this.width * this._percent / 100; this.div.style.width = progressSize + this.units; } get percent() { return this._percent; } set percent(val) { this._indeterminate = isNaN(val); this._percent = clamp(val, 0, 100); this._updateBar(); } setWidth(viewer) { if (!viewer) { return; } const container = viewer.parentNode; const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; if (scrollbarWidth > 0) { const doc = document.documentElement; doc.style.setProperty(LOADINGBAR_END_OFFSET_VAR, `${scrollbarWidth}px`); } } hide() { if (!this.visible) { return; } this.visible = false; this.bar.classList.add("hidden"); } show() { if (this.visible) { return; } this.visible = true; this.bar.classList.remove("hidden"); } } exports.ProgressBar = ProgressBar; function moveToEndOfArray(arr, condition) { const moved = [], len = arr.length; let write = 0; for (let read = 0; read < len; ++read) { if (condition(arr[read])) { moved.push(arr[read]); } else { arr[write] = arr[read]; ++write; } } for (let read = 0; write < len; ++read, ++write) { arr[write] = moved[read]; } } function getActiveOrFocusedElement() { let curRoot = document; let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); while (curActiveOrFocused?.shadowRoot) { curRoot = curActiveOrFocused.shadowRoot; curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); } return curActiveOrFocused; } function apiPageLayoutToSpreadMode(layout) { switch (layout) { case "SinglePage": case "OneColumn": return SpreadMode.NONE; case "TwoColumnLeft": case "TwoPageLeft": return SpreadMode.ODD; case "TwoColumnRight": case "TwoPageRight": return SpreadMode.EVEN; } return SpreadMode.NONE; } function apiPageModeToSidebarView(mode) { switch (mode) { case "UseNone": return SidebarView.NONE; case "UseThumbs": return SidebarView.THUMBS; case "UseOutlines": return SidebarView.OUTLINE; case "UseAttachments": return SidebarView.ATTACHMENTS; case "UseOC": return SidebarView.LAYERS; } return SidebarView.NONE; } /***/ }), /* 6 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StructTreeLayerBuilder = exports.DefaultStructTreeLayerFactory = void 0; const PDF_ROLE_TO_HTML_ROLE = { Document: null, DocumentFragment: null, Part: "group", Sect: "group", Div: "group", Aside: "note", NonStruct: "none", P: null, H: "heading", Title: null, FENote: "note", Sub: "group", Lbl: null, Span: null, Em: null, Strong: null, Link: "link", Annot: "note", Form: "form", Ruby: null, RB: null, RT: null, RP: null, Warichu: null, WT: null, WP: null, L: "list", LI: "listitem", LBody: null, Table: "table", TR: "row", TH: "columnheader", TD: "cell", THead: "columnheader", TBody: null, TFoot: null, Caption: null, Figure: "figure", Formula: null, Artifact: null }; const HEADING_PATTERN = /^H(\d+)$/; class StructTreeLayerBuilder { constructor({ pdfPage }) { this.pdfPage = pdfPage; } render(structTree) { return this._walk(structTree); } _setAttributes(structElement, htmlElement) { if (structElement.alt !== undefined) { htmlElement.setAttribute("aria-label", structElement.alt); } if (structElement.id !== undefined) { htmlElement.setAttribute("aria-owns", structElement.id); } } _walk(node) { if (!node) { return null; } const element = document.createElement("span"); if ("role" in node) { const { role } = node; const match = role.match(HEADING_PATTERN); if (match) { element.setAttribute("role", "heading"); element.setAttribute("aria-level", match[1]); } else if (PDF_ROLE_TO_HTML_ROLE[role]) { element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); } } this._setAttributes(node, element); if (node.children) { if (node.children.length === 1 && "id" in node.children[0]) { this._setAttributes(node.children[0], element); } else { for (const kid of node.children) { element.appendChild(this._walk(kid)); } } } return element; } } exports.StructTreeLayerBuilder = StructTreeLayerBuilder; class DefaultStructTreeLayerFactory { createStructTreeLayerBuilder(pdfPage) { return new StructTreeLayerBuilder({ pdfPage }); } } exports.DefaultStructTreeLayerFactory = DefaultStructTreeLayerFactory; /***/ }), /* 7 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TextLayerBuilder = exports.DefaultTextLayerFactory = void 0; var _pdfjsLib = __w_pdfjs_require__(2); const EXPAND_DIVS_TIMEOUT = 300; class TextLayerBuilder { constructor({ textLayerDiv, eventBus, pageIndex, viewport, highlighter = null, enhanceTextSelection = false }) { this.textLayerDiv = textLayerDiv; this.eventBus = eventBus; this.textContent = null; this.textContentItemsStr = []; this.textContentStream = null; this.renderingDone = false; this.pageNumber = pageIndex + 1; this.viewport = viewport; this.textDivs = []; this.textLayerRenderTask = null; this.highlighter = highlighter; this.enhanceTextSelection = enhanceTextSelection; this._bindMouse(); } _finishRendering() { this.renderingDone = true; if (!this.enhanceTextSelection) { const endOfContent = document.createElement("div"); endOfContent.className = "endOfContent"; this.textLayerDiv.appendChild(endOfContent); } this.eventBus.dispatch("textlayerrendered", { source: this, pageNumber: this.pageNumber, numTextDivs: this.textDivs.length }); } render(timeout = 0) { if (!(this.textContent || this.textContentStream) || this.renderingDone) { return; } this.cancel(); this.textDivs.length = 0; this.highlighter?.setTextMapping(this.textDivs, this.textContentItemsStr); const textLayerFrag = document.createDocumentFragment(); this.textLayerRenderTask = (0, _pdfjsLib.renderTextLayer)({ textContent: this.textContent, textContentStream: this.textContentStream, container: textLayerFrag, viewport: this.viewport, textDivs: this.textDivs, textContentItemsStr: this.textContentItemsStr, timeout, enhanceTextSelection: this.enhanceTextSelection }); this.textLayerRenderTask.promise.then(() => { this.textLayerDiv.appendChild(textLayerFrag); this._finishRendering(); this.highlighter?.enable(); }, function (reason) {}); } cancel() { if (this.textLayerRenderTask) { this.textLayerRenderTask.cancel(); this.textLayerRenderTask = null; } this.highlighter?.disable(); } setTextContentStream(readableStream) { this.cancel(); this.textContentStream = readableStream; } setTextContent(textContent) { this.cancel(); this.textContent = textContent; } _bindMouse() { const div = this.textLayerDiv; let expandDivsTimer = null; div.addEventListener("mousedown", evt => { if (this.enhanceTextSelection && this.textLayerRenderTask) { this.textLayerRenderTask.expandTextDivs(true); if (expandDivsTimer) { clearTimeout(expandDivsTimer); expandDivsTimer = null; } return; } const end = div.querySelector(".endOfContent"); if (!end) { return; } let adjustTop = evt.target !== div; adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue("-moz-user-select") !== "none"; if (adjustTop) { const divBounds = div.getBoundingClientRect(); const r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height); end.style.top = (r * 100).toFixed(2) + "%"; } end.classList.add("active"); }); div.addEventListener("mouseup", () => { if (this.enhanceTextSelection && this.textLayerRenderTask) { expandDivsTimer = setTimeout(() => { if (this.textLayerRenderTask) { this.textLayerRenderTask.expandTextDivs(false); } expandDivsTimer = null; }, EXPAND_DIVS_TIMEOUT); return; } const end = div.querySelector(".endOfContent"); if (!end) { return; } end.style.top = ""; end.classList.remove("active"); }); } } exports.TextLayerBuilder = TextLayerBuilder; class DefaultTextLayerFactory { createTextLayerBuilder(textLayerDiv, pageIndex, viewport, enhanceTextSelection = false, eventBus, highlighter) { return new TextLayerBuilder({ textLayerDiv, pageIndex, viewport, enhanceTextSelection, eventBus, highlighter }); } } exports.DefaultTextLayerFactory = DefaultTextLayerFactory; /***/ }), /* 8 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.XfaLayerBuilder = exports.DefaultXfaLayerFactory = void 0; var _pdf_link_service = __w_pdfjs_require__(4); var _pdfjsLib = __w_pdfjs_require__(2); class XfaLayerBuilder { constructor({ pageDiv, pdfPage, annotationStorage, linkService, xfaHtml }) { this.pageDiv = pageDiv; this.pdfPage = pdfPage; this.annotationStorage = annotationStorage; this.linkService = linkService; this.xfaHtml = xfaHtml; this.div = null; this._cancelled = false; } render(viewport, intent = "display") { if (intent === "print") { const parameters = { viewport: viewport.clone({ dontFlip: true }), div: this.div, xfa: this.xfaHtml, page: null, annotationStorage: this.annotationStorage, linkService: this.linkService, intent }; const div = document.createElement("div"); this.pageDiv.appendChild(div); parameters.div = div; const result = _pdfjsLib.XfaLayer.render(parameters); return Promise.resolve(result); } return this.pdfPage.getXfa().then(xfa => { if (this._cancelled || !xfa) { return { textDivs: [] }; } const parameters = { viewport: viewport.clone({ dontFlip: true }), div: this.div, xfa, page: this.pdfPage, annotationStorage: this.annotationStorage, linkService: this.linkService, intent }; if (this.div) { return _pdfjsLib.XfaLayer.update(parameters); } this.div = document.createElement("div"); this.pageDiv.appendChild(this.div); parameters.div = this.div; return _pdfjsLib.XfaLayer.render(parameters); }).catch(error => { console.error(error); }); } cancel() { this._cancelled = true; } hide() { if (!this.div) { return; } this.div.hidden = true; } } exports.XfaLayerBuilder = XfaLayerBuilder; class DefaultXfaLayerFactory { createXfaLayerBuilder(pageDiv, pdfPage, annotationStorage = null, xfaHtml = null) { return new XfaLayerBuilder({ pageDiv, pdfPage, annotationStorage, linkService: new _pdf_link_service.SimpleLinkService(), xfaHtml }); } } exports.DefaultXfaLayerFactory = DefaultXfaLayerFactory; /***/ }), /* 9 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DownloadManager = void 0; var _pdfjsLib = __w_pdfjs_require__(2); var _app_options = __w_pdfjs_require__(10); ; function download(blobUrl, filename) { const a = document.createElement("a"); if (!a.click) { throw new Error('DownloadManager: "a.click()" is not supported.'); } a.href = blobUrl; a.target = "_parent"; if ("download" in a) { a.download = filename; } (document.body || document.documentElement).appendChild(a); a.click(); a.remove(); } class DownloadManager { constructor() { this._openBlobUrls = new WeakMap(); } downloadUrl(url, filename) { if (!(0, _pdfjsLib.createValidAbsoluteUrl)(url, "http://example.com")) { console.error(`downloadUrl - not a valid URL: ${url}`); return; } download(url + "#pdfjs.action=download", filename); } downloadData(data, filename, contentType) { const blobUrl = (0, _pdfjsLib.createObjectURL)(data, contentType, _app_options.compatibilityParams.disableCreateObjectURL); download(blobUrl, filename); } openOrDownloadData(element, data, filename) { const isPdfData = (0, _pdfjsLib.isPdfFile)(filename); const contentType = isPdfData ? "application/pdf" : ""; if (isPdfData && !_app_options.compatibilityParams.disableCreateObjectURL) { let blobUrl = this._openBlobUrls.get(element); if (!blobUrl) { blobUrl = URL.createObjectURL(new Blob([data], { type: contentType })); this._openBlobUrls.set(element, blobUrl); } let viewerUrl; viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename); try { window.open(viewerUrl); return true; } catch (ex) { console.error(`openOrDownloadData: ${ex}`); URL.revokeObjectURL(blobUrl); this._openBlobUrls.delete(element); } } this.downloadData(data, filename, contentType); return false; } download(blob, url, filename, sourceEventType = "download") { if (_app_options.compatibilityParams.disableCreateObjectURL) { this.downloadUrl(url, filename); return; } const blobUrl = URL.createObjectURL(blob); download(blobUrl, filename); } } exports.DownloadManager = DownloadManager; /***/ }), /* 10 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OptionKind = exports.compatibilityParams = exports.AppOptions = void 0; const compatibilityParams = Object.create(null); exports.compatibilityParams = compatibilityParams; { const userAgent = typeof navigator !== "undefined" && navigator.userAgent || ""; const platform = typeof navigator !== "undefined" && navigator.platform || ""; const maxTouchPoints = typeof navigator !== "undefined" && navigator.maxTouchPoints || 1; const isAndroid = /Android/.test(userAgent); const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; const isIOSChrome = /CriOS/.test(userAgent); (function checkOnBlobSupport() { if (isIOSChrome) { compatibilityParams.disableCreateObjectURL = true; } })(); (function checkCanvasSizeLimitation() { if (isIOS || isAndroid) { compatibilityParams.maxCanvasPixels = 5242880; } })(); } const OptionKind = { VIEWER: 0x02, API: 0x04, WORKER: 0x08, PREFERENCE: 0x80 }; exports.OptionKind = OptionKind; const defaultOptions = { annotationMode: { value: 2, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, cursorToolOnLoad: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, defaultUrl: { value: "compressed.tracemonkey-pldi-09.pdf", kind: OptionKind.VIEWER }, defaultZoomValue: { value: "", kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, disableHistory: { value: false, kind: OptionKind.VIEWER }, disablePageLabels: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, enablePermissions: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, enablePrintAutoRotate: { value: true, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, enableScripting: { value: true, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, externalLinkRel: { value: "noopener noreferrer nofollow", kind: OptionKind.VIEWER }, externalLinkTarget: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, historyUpdateUrl: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, ignoreDestinationZoom: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, imageResourcesPath: { value: "./images/", kind: OptionKind.VIEWER }, maxCanvasPixels: { value: 16777216, compatibility: compatibilityParams.maxCanvasPixels, kind: OptionKind.VIEWER }, pdfBugEnabled: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, printResolution: { value: 150, kind: OptionKind.VIEWER }, renderer: { value: "canvas", kind: OptionKind.VIEWER }, sidebarViewOnLoad: { value: -1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, scrollModeOnLoad: { value: -1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, spreadModeOnLoad: { value: -1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, textLayerMode: { value: 1, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, useOnlyCssZoom: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, viewerCssTheme: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, viewOnLoad: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, cMapPacked: { value: true, kind: OptionKind.API }, cMapUrl: { value: "../web/cmaps/", kind: OptionKind.API }, disableAutoFetch: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, disableFontFace: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, disableRange: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, disableStream: { value: false, kind: OptionKind.API + OptionKind.PREFERENCE }, docBaseUrl: { value: "", kind: OptionKind.API }, enableXfa: { value: true, kind: OptionKind.API + OptionKind.PREFERENCE }, fontExtraProperties: { value: false, kind: OptionKind.API }, isEvalSupported: { value: true, kind: OptionKind.API }, maxImageSize: { value: -1, kind: OptionKind.API }, pdfBug: { value: false, kind: OptionKind.API }, standardFontDataUrl: { value: "../web/standard_fonts/", kind: OptionKind.API }, verbosity: { value: 1, kind: OptionKind.API }, workerPort: { value: null, kind: OptionKind.WORKER }, workerSrc: { value: "../build/pdf.worker.js", kind: OptionKind.WORKER } }; { defaultOptions.disablePreferences = { value: false, kind: OptionKind.VIEWER }; defaultOptions.locale = { value: typeof navigator !== "undefined" ? navigator.language : "en-US", kind: OptionKind.VIEWER }; defaultOptions.sandboxBundleSrc = { value: "../build/pdf.sandbox.js", kind: OptionKind.VIEWER }; defaultOptions.renderer.kind += OptionKind.PREFERENCE; } const userOptions = Object.create(null); class AppOptions { constructor() { throw new Error("Cannot initialize AppOptions."); } static get(name) { const userOption = userOptions[name]; if (userOption !== undefined) { return userOption; } const defaultOption = defaultOptions[name]; if (defaultOption !== undefined) { return defaultOption.compatibility ?? defaultOption.value; } return undefined; } static getAll(kind = null) { const options = Object.create(null); for (const name in defaultOptions) { const defaultOption = defaultOptions[name]; if (kind) { if ((kind & defaultOption.kind) === 0) { continue; } if (kind === OptionKind.PREFERENCE) { const value = defaultOption.value, valueType = typeof value; if (valueType === "boolean" || valueType === "string" || valueType === "number" && Number.isInteger(value)) { options[name] = value; continue; } throw new Error(`Invalid type for preference: ${name}`); } } const userOption = userOptions[name]; options[name] = userOption !== undefined ? userOption : defaultOption.compatibility ?? defaultOption.value; } return options; } static set(name, value) { userOptions[name] = value; } static setAll(options) { for (const name in options) { userOptions[name] = options[name]; } } static remove(name) { delete userOptions[name]; } static _hasUserOptions() { return Object.keys(userOptions).length > 0; } } exports.AppOptions = AppOptions; /***/ }), /* 11 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GenericL10n = void 0; __w_pdfjs_require__(12); var _l10n_utils = __w_pdfjs_require__(3); const webL10n = document.webL10n; class GenericL10n { constructor(lang) { this._lang = lang; this._ready = new Promise((resolve, reject) => { webL10n.setLanguage((0, _l10n_utils.fixupLangCode)(lang), () => { resolve(webL10n); }); }); } async getLanguage() { const l10n = await this._ready; return l10n.getLanguage(); } async getDirection() { const l10n = await this._ready; return l10n.getDirection(); } async get(key, args = null, fallback = (0, _l10n_utils.getL10nFallback)(key, args)) { const l10n = await this._ready; return l10n.get(key, args, fallback); } async translate(element) { const l10n = await this._ready; return l10n.translate(element); } } exports.GenericL10n = GenericL10n; /***/ }), /* 12 */ /***/ (() => { document.webL10n = function (window, document, undefined) { var gL10nData = {}; var gTextData = ''; var gTextProp = 'textContent'; var gLanguage = ''; var gMacros = {}; var gReadyState = 'loading'; var gAsyncResourceLoading = true; function getL10nResourceLinks() { return document.querySelectorAll('link[type="application/l10n"]'); } function getL10nDictionary() { var script = document.querySelector('script[type="application/l10n"]'); return script ? JSON.parse(script.innerHTML) : null; } function getTranslatableChildren(element) { return element ? element.querySelectorAll('*[data-l10n-id]') : []; } function getL10nAttributes(element) { if (!element) return {}; var l10nId = element.getAttribute('data-l10n-id'); var l10nArgs = element.getAttribute('data-l10n-args'); var args = {}; if (l10nArgs) { try { args = JSON.parse(l10nArgs); } catch (e) { console.warn('could not parse arguments for #' + l10nId); } } return { id: l10nId, args: args }; } function xhrLoadText(url, onSuccess, onFailure) { onSuccess = onSuccess || function _onSuccess(data) {}; onFailure = onFailure || function _onFailure() {}; var xhr = new XMLHttpRequest(); xhr.open('GET', url, gAsyncResourceLoading); if (xhr.overrideMimeType) { xhr.overrideMimeType('text/plain; charset=utf-8'); } xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200 || xhr.status === 0) { onSuccess(xhr.responseText); } else { onFailure(); } } }; xhr.onerror = onFailure; xhr.ontimeout = onFailure; try { xhr.send(null); } catch (e) { onFailure(); } } function parseResource(href, lang, successCallback, failureCallback) { var baseURL = href.replace(/[^\/]*$/, '') || './'; function evalString(text) { if (text.lastIndexOf('\\') < 0) return text; return text.replace(/\\\\/g, '\\').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\b/g, '\b').replace(/\\f/g, '\f').replace(/\\{/g, '{').replace(/\\}/g, '}').replace(/\\"/g, '"').replace(/\\'/g, "'"); } function parseProperties(text, parsedPropertiesCallback) { var dictionary = {}; var reBlank = /^\s*|\s*$/; var reComment = /^\s*#|^\s*$/; var reSection = /^\s*\[(.*)\]\s*$/; var reImport = /^\s*@import\s+url\((.*)\)\s*$/i; var reSplit = /^([^=\s]*)\s*=\s*(.+)$/; function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) { var entries = rawText.replace(reBlank, '').split(/[\r\n]+/); var currentLang = '*'; var genericLang = lang.split('-', 1)[0]; var skipLang = false; var match = ''; function nextEntry() { while (true) { if (!entries.length) { parsedRawLinesCallback(); return; } var line = entries.shift(); if (reComment.test(line)) continue; if (extendedSyntax) { match = reSection.exec(line); if (match) { currentLang = match[1].toLowerCase(); skipLang = currentLang !== '*' && currentLang !== lang && currentLang !== genericLang; continue; } else if (skipLang) { continue; } match = reImport.exec(line); if (match) { loadImport(baseURL + match[1], nextEntry); return; } } var tmp = line.match(reSplit); if (tmp && tmp.length == 3) { dictionary[tmp[1]] = evalString(tmp[2]); } } } nextEntry(); } function loadImport(url, callback) { xhrLoadText(url, function (content) { parseRawLines(content, false, callback); }, function () { console.warn(url + ' not found.'); callback(); }); } parseRawLines(text, true, function () { parsedPropertiesCallback(dictionary); }); } xhrLoadText(href, function (response) { gTextData += response; parseProperties(response, function (data) { for (var key in data) { var id, prop, index = key.lastIndexOf('.'); if (index > 0) { id = key.substring(0, index); prop = key.substring(index + 1); } else { id = key; prop = gTextProp; } if (!gL10nData[id]) { gL10nData[id] = {}; } gL10nData[id][prop] = data[key]; } if (successCallback) { successCallback(); } }); }, failureCallback); } function loadLocale(lang, callback) { if (lang) { lang = lang.toLowerCase(); } callback = callback || function _callback() {}; clear(); gLanguage = lang; var langLinks = getL10nResourceLinks(); var langCount = langLinks.length; if (langCount === 0) { var dict = getL10nDictionary(); if (dict && dict.locales && dict.default_locale) { console.log('using the embedded JSON directory, early way out'); gL10nData = dict.locales[lang]; if (!gL10nData) { var defaultLocale = dict.default_locale.toLowerCase(); for (var anyCaseLang in dict.locales) { anyCaseLang = anyCaseLang.toLowerCase(); if (anyCaseLang === lang) { gL10nData = dict.locales[lang]; break; } else if (anyCaseLang === defaultLocale) { gL10nData = dict.locales[defaultLocale]; } } } callback(); } else { console.log('no resource to load, early way out'); } gReadyState = 'complete'; return; } var onResourceLoaded = null; var gResourceCount = 0; onResourceLoaded = function () { gResourceCount++; if (gResourceCount >= langCount) { callback(); gReadyState = 'complete'; } }; function L10nResourceLink(link) { var href = link.href; this.load = function (lang, callback) { parseResource(href, lang, callback, function () { console.warn(href + ' not found.'); console.warn('"' + lang + '" resource not found'); gLanguage = ''; callback(); }); }; } for (var i = 0; i < langCount; i++) { var resource = new L10nResourceLink(langLinks[i]); resource.load(lang, onResourceLoaded); } } function clear() { gL10nData = {}; gTextData = ''; gLanguage = ''; } function getPluralRules(lang) { var locales2rules = { 'af': 3, 'ak': 4, 'am': 4, 'ar': 1, 'asa': 3, 'az': 0, 'be': 11, 'bem': 3, 'bez': 3, 'bg': 3, 'bh': 4, 'bm': 0, 'bn': 3, 'bo': 0, 'br': 20, 'brx': 3, 'bs': 11, 'ca': 3, 'cgg': 3, 'chr': 3, 'cs': 12, 'cy': 17, 'da': 3, 'de': 3, 'dv': 3, 'dz': 0, 'ee': 3, 'el': 3, 'en': 3, 'eo': 3, 'es': 3, 'et': 3, 'eu': 3, 'fa': 0, 'ff': 5, 'fi': 3, 'fil': 4, 'fo': 3, 'fr': 5, 'fur': 3, 'fy': 3, 'ga': 8, 'gd': 24, 'gl': 3, 'gsw': 3, 'gu': 3, 'guw': 4, 'gv': 23, 'ha': 3, 'haw': 3, 'he': 2, 'hi': 4, 'hr': 11, 'hu': 0, 'id': 0, 'ig': 0, 'ii': 0, 'is': 3, 'it': 3, 'iu': 7, 'ja': 0, 'jmc': 3, 'jv': 0, 'ka': 0, 'kab': 5, 'kaj': 3, 'kcg': 3, 'kde': 0, 'kea': 0, 'kk': 3, 'kl': 3, 'km': 0, 'kn': 0, 'ko': 0, 'ksb': 3, 'ksh': 21, 'ku': 3, 'kw': 7, 'lag': 18, 'lb': 3, 'lg': 3, 'ln': 4, 'lo': 0, 'lt': 10, 'lv': 6, 'mas': 3, 'mg': 4, 'mk': 16, 'ml': 3, 'mn': 3, 'mo': 9, 'mr': 3, 'ms': 0, 'mt': 15, 'my': 0, 'nah': 3, 'naq': 7, 'nb': 3, 'nd': 3, 'ne': 3, 'nl': 3, 'nn': 3, 'no': 3, 'nr': 3, 'nso': 4, 'ny': 3, 'nyn': 3, 'om': 3, 'or': 3, 'pa': 3, 'pap': 3, 'pl': 13, 'ps': 3, 'pt': 3, 'rm': 3, 'ro': 9, 'rof': 3, 'ru': 11, 'rwk': 3, 'sah': 0, 'saq': 3, 'se': 7, 'seh': 3, 'ses': 0, 'sg': 0, 'sh': 11, 'shi': 19, 'sk': 12, 'sl': 14, 'sma': 7, 'smi': 7, 'smj': 7, 'smn': 7, 'sms': 7, 'sn': 3, 'so': 3, 'sq': 3, 'sr': 11, 'ss': 3, 'ssy': 3, 'st': 3, 'sv': 3, 'sw': 3, 'syr': 3, 'ta': 3, 'te': 3, 'teo': 3, 'th': 0, 'ti': 4, 'tig': 3, 'tk': 3, 'tl': 4, 'tn': 3, 'to': 0, 'tr': 0, 'ts': 3, 'tzm': 22, 'uk': 11, 'ur': 3, 've': 3, 'vi': 0, 'vun': 3, 'wa': 4, 'wae': 3, 'wo': 0, 'xh': 3, 'xog': 3, 'yo': 0, 'zh': 0, 'zu': 3 }; function isIn(n, list) { return list.indexOf(n) !== -1; } function isBetween(n, start, end) { return start <= n && n <= end; } var pluralRules = { '0': function (n) { return 'other'; }, '1': function (n) { if (isBetween(n % 100, 3, 10)) return 'few'; if (n === 0) return 'zero'; if (isBetween(n % 100, 11, 99)) return 'many'; if (n == 2) return 'two'; if (n == 1) return 'one'; return 'other'; }, '2': function (n) { if (n !== 0 && n % 10 === 0) return 'many'; if (n == 2) return 'two'; if (n == 1) return 'one'; return 'other'; }, '3': function (n) { if (n == 1) return 'one'; return 'other'; }, '4': function (n) { if (isBetween(n, 0, 1)) return 'one'; return 'other'; }, '5': function (n) { if (isBetween(n, 0, 2) && n != 2) return 'one'; return 'other'; }, '6': function (n) { if (n === 0) return 'zero'; if (n % 10 == 1 && n % 100 != 11) return 'one'; return 'other'; }, '7': function (n) { if (n == 2) return 'two'; if (n == 1) return 'one'; return 'other'; }, '8': function (n) { if (isBetween(n, 3, 6)) return 'few'; if (isBetween(n, 7, 10)) return 'many'; if (n == 2) return 'two'; if (n == 1) return 'one'; return 'other'; }, '9': function (n) { if (n === 0 || n != 1 && isBetween(n % 100, 1, 19)) return 'few'; if (n == 1) return 'one'; return 'other'; }, '10': function (n) { if (isBetween(n % 10, 2, 9) && !isBetween(n % 100, 11, 19)) return 'few'; if (n % 10 == 1 && !isBetween(n % 100, 11, 19)) return 'one'; return 'other'; }, '11': function (n) { if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few'; if (n % 10 === 0 || isBetween(n % 10, 5, 9) || isBetween(n % 100, 11, 14)) return 'many'; if (n % 10 == 1 && n % 100 != 11) return 'one'; return 'other'; }, '12': function (n) { if (isBetween(n, 2, 4)) return 'few'; if (n == 1) return 'one'; return 'other'; }, '13': function (n) { if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few'; if (n != 1 && isBetween(n % 10, 0, 1) || isBetween(n % 10, 5, 9) || isBetween(n % 100, 12, 14)) return 'many'; if (n == 1) return 'one'; return 'other'; }, '14': function (n) { if (isBetween(n % 100, 3, 4)) return 'few'; if (n % 100 == 2) return 'two'; if (n % 100 == 1) return 'one'; return 'other'; }, '15': function (n) { if (n === 0 || isBetween(n % 100, 2, 10)) return 'few'; if (isBetween(n % 100, 11, 19)) return 'many'; if (n == 1) return 'one'; return 'other'; }, '16': function (n) { if (n % 10 == 1 && n != 11) return 'one'; return 'other'; }, '17': function (n) { if (n == 3) return 'few'; if (n === 0) return 'zero'; if (n == 6) return 'many'; if (n == 2) return 'two'; if (n == 1) return 'one'; return 'other'; }, '18': function (n) { if (n === 0) return 'zero'; if (isBetween(n, 0, 2) && n !== 0 && n != 2) return 'one'; return 'other'; }, '19': function (n) { if (isBetween(n, 2, 10)) return 'few'; if (isBetween(n, 0, 1)) return 'one'; return 'other'; }, '20': function (n) { if ((isBetween(n % 10, 3, 4) || n % 10 == 9) && !(isBetween(n % 100, 10, 19) || isBetween(n % 100, 70, 79) || isBetween(n % 100, 90, 99))) return 'few'; if (n % 1000000 === 0 && n !== 0) return 'many'; if (n % 10 == 2 && !isIn(n % 100, [12, 72, 92])) return 'two'; if (n % 10 == 1 && !isIn(n % 100, [11, 71, 91])) return 'one'; return 'other'; }, '21': function (n) { if (n === 0) return 'zero'; if (n == 1) return 'one'; return 'other'; }, '22': function (n) { if (isBetween(n, 0, 1) || isBetween(n, 11, 99)) return 'one'; return 'other'; }, '23': function (n) { if (isBetween(n % 10, 1, 2) || n % 20 === 0) return 'one'; return 'other'; }, '24': function (n) { if (isBetween(n, 3, 10) || isBetween(n, 13, 19)) return 'few'; if (isIn(n, [2, 12])) return 'two'; if (isIn(n, [1, 11])) return 'one'; return 'other'; } }; var index = locales2rules[lang.replace(/-.*$/, '')]; if (!(index in pluralRules)) { console.warn('plural form unknown for [' + lang + ']'); return function () { return 'other'; }; } return pluralRules[index]; } gMacros.plural = function (str, param, key, prop) { var n = parseFloat(param); if (isNaN(n)) return str; if (prop != gTextProp) return str; if (!gMacros._pluralRules) { gMacros._pluralRules = getPluralRules(gLanguage); } var index = '[' + gMacros._pluralRules(n) + ']'; if (n === 0 && key + '[zero]' in gL10nData) { str = gL10nData[key + '[zero]'][prop]; } else if (n == 1 && key + '[one]' in gL10nData) { str = gL10nData[key + '[one]'][prop]; } else if (n == 2 && key + '[two]' in gL10nData) { str = gL10nData[key + '[two]'][prop]; } else if (key + index in gL10nData) { str = gL10nData[key + index][prop]; } else if (key + '[other]' in gL10nData) { str = gL10nData[key + '[other]'][prop]; } return str; }; function getL10nData(key, args, fallback) { var data = gL10nData[key]; if (!data) { console.warn('#' + key + ' is undefined.'); if (!fallback) { return null; } data = fallback; } var rv = {}; for (var prop in data) { var str = data[prop]; str = substIndexes(str, args, key, prop); str = substArguments(str, args, key); rv[prop] = str; } return rv; } function substIndexes(str, args, key, prop) { var reIndex = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/; var reMatch = reIndex.exec(str); if (!reMatch || !reMatch.length) return str; var macroName = reMatch[1]; var paramName = reMatch[2]; var param; if (args && paramName in args) { param = args[paramName]; } else if (paramName in gL10nData) { param = gL10nData[paramName]; } if (macroName in gMacros) { var macro = gMacros[macroName]; str = macro(str, param, key, prop); } return str; } function substArguments(str, args, key) { var reArgs = /\{\{\s*(.+?)\s*\}\}/g; return str.replace(reArgs, function (matched_text, arg) { if (args && arg in args) { return args[arg]; } if (arg in gL10nData) { return gL10nData[arg]; } console.log('argument {{' + arg + '}} for #' + key + ' is undefined.'); return matched_text; }); } function translateElement(element) { var l10n = getL10nAttributes(element); if (!l10n.id) return; var data = getL10nData(l10n.id, l10n.args); if (!data) { console.warn('#' + l10n.id + ' is undefined.'); return; } if (data[gTextProp]) { if (getChildElementCount(element) === 0) { element[gTextProp] = data[gTextProp]; } else { var children = element.childNodes; var found = false; for (var i = 0, l = children.length; i < l; i++) { if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) { if (found) { children[i].nodeValue = ''; } else { children[i].nodeValue = data[gTextProp]; found = true; } } } if (!found) { var textNode = document.createTextNode(data[gTextProp]); element.insertBefore(textNode, element.firstChild); } } delete data[gTextProp]; } for (var k in data) { element[k] = data[k]; } } function getChildElementCount(element) { if (element.children) { return element.children.length; } if (typeof element.childElementCount !== 'undefined') { return element.childElementCount; } var count = 0; for (var i = 0; i < element.childNodes.length; i++) { count += element.nodeType === 1 ? 1 : 0; } return count; } function translateFragment(element) { element = element || document.documentElement; var children = getTranslatableChildren(element); var elementCount = children.length; for (var i = 0; i < elementCount; i++) { translateElement(children[i]); } translateElement(element); } return { get: function (key, args, fallbackString) { var index = key.lastIndexOf('.'); var prop = gTextProp; if (index > 0) { prop = key.substring(index + 1); key = key.substring(0, index); } var fallback; if (fallbackString) { fallback = {}; fallback[prop] = fallbackString; } var data = getL10nData(key, args, fallback); if (data && prop in data) { return data[prop]; } return '{{' + key + '}}'; }, getData: function () { return gL10nData; }, getText: function () { return gTextData; }, getLanguage: function () { return gLanguage; }, setLanguage: function (lang, callback) { loadLocale(lang, function () { if (callback) callback(); }); }, getDirection: function () { var rtlList = ['ar', 'he', 'fa', 'ps', 'ur']; var shortCode = gLanguage.split('-', 1)[0]; return rtlList.indexOf(shortCode) >= 0 ? 'rtl' : 'ltr'; }, translate: translateFragment, getReadyState: function () { return gReadyState; }, ready: function (callback) { if (!callback) { return; } else if (gReadyState == 'complete' || gReadyState == 'interactive') { window.setTimeout(function () { callback(); }); } else if (document.addEventListener) { document.addEventListener('localized', function once() { document.removeEventListener('localized', once); callback(); }); } } }; }(window, document); /***/ }), /* 13 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFFindController = exports.FindState = void 0; var _pdfjsLib = __w_pdfjs_require__(2); var _pdf_find_utils = __w_pdfjs_require__(14); var _ui_utils = __w_pdfjs_require__(5); const FindState = { FOUND: 0, NOT_FOUND: 1, WRAPPED: 2, PENDING: 3 }; exports.FindState = FindState; const FIND_TIMEOUT = 250; const MATCH_SCROLL_OFFSET_TOP = -50; const MATCH_SCROLL_OFFSET_LEFT = -400; const CHARACTERS_TO_NORMALIZE = { "\u2010": "-", "\u2018": "'", "\u2019": "'", "\u201A": "'", "\u201B": "'", "\u201C": '"', "\u201D": '"', "\u201E": '"', "\u201F": '"', "\u00BC": "1/4", "\u00BD": "1/2", "\u00BE": "3/4" }; let normalizationRegex = null; function normalize(text) { if (!normalizationRegex) { const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); normalizationRegex = new RegExp(`[${replace}]`, "g"); } let diffs = null; const normalizedText = text.replace(normalizationRegex, function (ch, index) { const normalizedCh = CHARACTERS_TO_NORMALIZE[ch], diff = normalizedCh.length - ch.length; if (diff !== 0) { (diffs ||= []).push([index, diff]); } return normalizedCh; }); return [normalizedText, diffs]; } function getOriginalIndex(matchIndex, diffs = null) { if (!diffs) { return matchIndex; } let totalDiff = 0; for (const [index, diff] of diffs) { const currentIndex = index + totalDiff; if (currentIndex >= matchIndex) { break; } if (currentIndex + diff > matchIndex) { totalDiff += matchIndex - currentIndex; break; } totalDiff += diff; } return matchIndex - totalDiff; } class PDFFindController { constructor({ linkService, eventBus }) { this._linkService = linkService; this._eventBus = eventBus; this._reset(); eventBus._on("findbarclose", this._onFindBarClose.bind(this)); } get highlightMatches() { return this._highlightMatches; } get pageMatches() { return this._pageMatches; } get pageMatchesLength() { return this._pageMatchesLength; } get selected() { return this._selected; } get state() { return this._state; } setDocument(pdfDocument) { if (this._pdfDocument) { this._reset(); } if (!pdfDocument) { return; } this._pdfDocument = pdfDocument; this._firstPageCapability.resolve(); } executeCommand(cmd, state) { if (!state) { return; } const pdfDocument = this._pdfDocument; if (this._state === null || this._shouldDirtyMatch(cmd, state)) { this._dirtyMatch = true; } this._state = state; if (cmd !== "findhighlightallchange") { this._updateUIState(FindState.PENDING); } this._firstPageCapability.promise.then(() => { if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { return; } this._extractText(); const findbarClosed = !this._highlightMatches; const pendingTimeout = !!this._findTimeout; if (this._findTimeout) { clearTimeout(this._findTimeout); this._findTimeout = null; } if (cmd === "find") { this._findTimeout = setTimeout(() => { this._nextMatch(); this._findTimeout = null; }, FIND_TIMEOUT); } else if (this._dirtyMatch) { this._nextMatch(); } else if (cmd === "findagain") { this._nextMatch(); if (findbarClosed && this._state.highlightAll) { this._updateAllPages(); } } else if (cmd === "findhighlightallchange") { if (pendingTimeout) { this._nextMatch(); } else { this._highlightMatches = true; } this._updateAllPages(); } else { this._nextMatch(); } }); } scrollMatchIntoView({ element = null, selectedLeft = 0, pageIndex = -1, matchIndex = -1 }) { if (!this._scrollMatches || !element) { return; } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { return; } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { return; } this._scrollMatches = false; const spot = { top: MATCH_SCROLL_OFFSET_TOP, left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT }; (0, _ui_utils.scrollIntoView)(element, spot, true); } _reset() { this._highlightMatches = false; this._scrollMatches = false; this._pdfDocument = null; this._pageMatches = []; this._pageMatchesLength = []; this._state = null; this._selected = { pageIdx: -1, matchIdx: -1 }; this._offset = { pageIdx: null, matchIdx: null, wrapped: false }; this._extractTextPromises = []; this._pageContents = []; this._pageDiffs = []; this._matchesCountTotal = 0; this._pagesToSearch = null; this._pendingFindMatches = new Set(); this._resumePageIdx = null; this._dirtyMatch = false; clearTimeout(this._findTimeout); this._findTimeout = null; this._firstPageCapability = (0, _pdfjsLib.createPromiseCapability)(); } get _query() { if (this._state.query !== this._rawQuery) { this._rawQuery = this._state.query; [this._normalizedQuery] = normalize(this._state.query); } return this._normalizedQuery; } _shouldDirtyMatch(cmd, state) { if (state.query !== this._state.query) { return true; } switch (cmd) { case "findagain": const pageNumber = this._selected.pageIdx + 1; const linkService = this._linkService; if (pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !linkService.isPageVisible(pageNumber)) { return true; } return false; case "findhighlightallchange": return false; } return true; } _prepareMatches(matchesWithLength, matches, matchesLength) { function isSubTerm(currentIndex) { const currentElem = matchesWithLength[currentIndex]; const nextElem = matchesWithLength[currentIndex + 1]; if (currentIndex < matchesWithLength.length - 1 && currentElem.match === nextElem.match) { currentElem.skipped = true; return true; } for (let i = currentIndex - 1; i >= 0; i--) { const prevElem = matchesWithLength[i]; if (prevElem.skipped) { continue; } if (prevElem.match + prevElem.matchLength < currentElem.match) { break; } if (prevElem.match + prevElem.matchLength >= currentElem.match + currentElem.matchLength) { currentElem.skipped = true; return true; } } return false; } matchesWithLength.sort(function (a, b) { return a.match === b.match ? a.matchLength - b.matchLength : a.match - b.match; }); for (let i = 0, len = matchesWithLength.length; i < len; i++) { if (isSubTerm(i)) { continue; } matches.push(matchesWithLength[i].match); matchesLength.push(matchesWithLength[i].matchLength); } } _isEntireWord(content, startIdx, length) { if (startIdx > 0) { const first = content.charCodeAt(startIdx); const limit = content.charCodeAt(startIdx - 1); if ((0, _pdf_find_utils.getCharacterType)(first) === (0, _pdf_find_utils.getCharacterType)(limit)) { return false; } } const endIdx = startIdx + length - 1; if (endIdx < content.length - 1) { const last = content.charCodeAt(endIdx); const limit = content.charCodeAt(endIdx + 1); if ((0, _pdf_find_utils.getCharacterType)(last) === (0, _pdf_find_utils.getCharacterType)(limit)) { return false; } } return true; } _calculatePhraseMatch(query, pageIndex, pageContent, pageDiffs, entireWord) { const matches = [], matchesLength = []; const queryLen = query.length; let matchIdx = -queryLen; while (true) { matchIdx = pageContent.indexOf(query, matchIdx + queryLen); if (matchIdx === -1) { break; } if (entireWord && !this._isEntireWord(pageContent, matchIdx, queryLen)) { continue; } const originalMatchIdx = getOriginalIndex(matchIdx, pageDiffs), matchEnd = matchIdx + queryLen - 1, originalQueryLen = getOriginalIndex(matchEnd, pageDiffs) - originalMatchIdx + 1; matches.push(originalMatchIdx); matchesLength.push(originalQueryLen); } this._pageMatches[pageIndex] = matches; this._pageMatchesLength[pageIndex] = matchesLength; } _calculateWordMatch(query, pageIndex, pageContent, pageDiffs, entireWord) { const matchesWithLength = []; const queryArray = query.match(/\S+/g); for (let i = 0, len = queryArray.length; i < len; i++) { const subquery = queryArray[i]; const subqueryLen = subquery.length; let matchIdx = -subqueryLen; while (true) { matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen); if (matchIdx === -1) { break; } if (entireWord && !this._isEntireWord(pageContent, matchIdx, subqueryLen)) { continue; } const originalMatchIdx = getOriginalIndex(matchIdx, pageDiffs), matchEnd = matchIdx + subqueryLen - 1, originalQueryLen = getOriginalIndex(matchEnd, pageDiffs) - originalMatchIdx + 1; matchesWithLength.push({ match: originalMatchIdx, matchLength: originalQueryLen, skipped: false }); } } this._pageMatchesLength[pageIndex] = []; this._pageMatches[pageIndex] = []; this._prepareMatches(matchesWithLength, this._pageMatches[pageIndex], this._pageMatchesLength[pageIndex]); } _calculateMatch(pageIndex) { let pageContent = this._pageContents[pageIndex]; const pageDiffs = this._pageDiffs[pageIndex]; let query = this._query; const { caseSensitive, entireWord, phraseSearch } = this._state; if (query.length === 0) { return; } if (!caseSensitive) { pageContent = pageContent.toLowerCase(); query = query.toLowerCase(); } if (phraseSearch) { this._calculatePhraseMatch(query, pageIndex, pageContent, pageDiffs, entireWord); } else { this._calculateWordMatch(query, pageIndex, pageContent, pageDiffs, entireWord); } if (this._state.highlightAll) { this._updatePage(pageIndex); } if (this._resumePageIdx === pageIndex) { this._resumePageIdx = null; this._nextPageMatch(); } const pageMatchesCount = this._pageMatches[pageIndex].length; if (pageMatchesCount > 0) { this._matchesCountTotal += pageMatchesCount; this._updateUIResultsCount(); } } _extractText() { if (this._extractTextPromises.length > 0) { return; } let promise = Promise.resolve(); for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { const extractTextCapability = (0, _pdfjsLib.createPromiseCapability)(); this._extractTextPromises[i] = extractTextCapability.promise; promise = promise.then(() => { return this._pdfDocument.getPage(i + 1).then(pdfPage => { return pdfPage.getTextContent({ normalizeWhitespace: true }); }).then(textContent => { const textItems = textContent.items; const strBuf = []; for (let j = 0, jj = textItems.length; j < jj; j++) { strBuf.push(textItems[j].str); } [this._pageContents[i], this._pageDiffs[i]] = normalize(strBuf.join("")); extractTextCapability.resolve(i); }, reason => { console.error(`Unable to get text content for page ${i + 1}`, reason); this._pageContents[i] = ""; this._pageDiffs[i] = null; extractTextCapability.resolve(i); }); }); } } _updatePage(index) { if (this._scrollMatches && this._selected.pageIdx === index) { this._linkService.page = index + 1; } this._eventBus.dispatch("updatetextlayermatches", { source: this, pageIndex: index }); } _updateAllPages() { this._eventBus.dispatch("updatetextlayermatches", { source: this, pageIndex: -1 }); } _nextMatch() { const previous = this._state.findPrevious; const currentPageIndex = this._linkService.page - 1; const numPages = this._linkService.pagesCount; this._highlightMatches = true; if (this._dirtyMatch) { this._dirtyMatch = false; this._selected.pageIdx = this._selected.matchIdx = -1; this._offset.pageIdx = currentPageIndex; this._offset.matchIdx = null; this._offset.wrapped = false; this._resumePageIdx = null; this._pageMatches.length = 0; this._pageMatchesLength.length = 0; this._matchesCountTotal = 0; this._updateAllPages(); for (let i = 0; i < numPages; i++) { if (this._pendingFindMatches.has(i)) { continue; } this._pendingFindMatches.add(i); this._extractTextPromises[i].then(pageIdx => { this._pendingFindMatches.delete(pageIdx); this._calculateMatch(pageIdx); }); } } if (this._query === "") { this._updateUIState(FindState.FOUND); return; } if (this._resumePageIdx) { return; } const offset = this._offset; this._pagesToSearch = numPages; if (offset.matchIdx !== null) { const numPageMatches = this._pageMatches[offset.pageIdx].length; if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; this._updateMatch(true); return; } this._advanceOffsetPage(previous); } this._nextPageMatch(); } _matchesReady(matches) { const offset = this._offset; const numMatches = matches.length; const previous = this._state.findPrevious; if (numMatches) { offset.matchIdx = previous ? numMatches - 1 : 0; this._updateMatch(true); return true; } this._advanceOffsetPage(previous); if (offset.wrapped) { offset.matchIdx = null; if (this._pagesToSearch < 0) { this._updateMatch(false); return true; } } return false; } _nextPageMatch() { if (this._resumePageIdx !== null) { console.error("There can only be one pending page."); } let matches = null; do { const pageIdx = this._offset.pageIdx; matches = this._pageMatches[pageIdx]; if (!matches) { this._resumePageIdx = pageIdx; break; } } while (!this._matchesReady(matches)); } _advanceOffsetPage(previous) { const offset = this._offset; const numPages = this._linkService.pagesCount; offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; offset.matchIdx = null; this._pagesToSearch--; if (offset.pageIdx >= numPages || offset.pageIdx < 0) { offset.pageIdx = previous ? numPages - 1 : 0; offset.wrapped = true; } } _updateMatch(found = false) { let state = FindState.NOT_FOUND; const wrapped = this._offset.wrapped; this._offset.wrapped = false; if (found) { const previousPage = this._selected.pageIdx; this._selected.pageIdx = this._offset.pageIdx; this._selected.matchIdx = this._offset.matchIdx; state = wrapped ? FindState.WRAPPED : FindState.FOUND; if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { this._updatePage(previousPage); } } this._updateUIState(state, this._state.findPrevious); if (this._selected.pageIdx !== -1) { this._scrollMatches = true; this._updatePage(this._selected.pageIdx); } } _onFindBarClose(evt) { const pdfDocument = this._pdfDocument; this._firstPageCapability.promise.then(() => { if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { return; } if (this._findTimeout) { clearTimeout(this._findTimeout); this._findTimeout = null; } if (this._resumePageIdx) { this._resumePageIdx = null; this._dirtyMatch = true; } this._updateUIState(FindState.FOUND); this._highlightMatches = false; this._updateAllPages(); }); } _requestMatchesCount() { const { pageIdx, matchIdx } = this._selected; let current = 0, total = this._matchesCountTotal; if (matchIdx !== -1) { for (let i = 0; i < pageIdx; i++) { current += this._pageMatches[i]?.length || 0; } current += matchIdx + 1; } if (current < 1 || current > total) { current = total = 0; } return { current, total }; } _updateUIResultsCount() { this._eventBus.dispatch("updatefindmatchescount", { source: this, matchesCount: this._requestMatchesCount() }); } _updateUIState(state, previous) { this._eventBus.dispatch("updatefindcontrolstate", { source: this, state, previous, matchesCount: this._requestMatchesCount(), rawQuery: this._state?.query ?? null }); } } exports.PDFFindController = PDFFindController; /***/ }), /* 14 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCharacterType = getCharacterType; exports.CharacterType = void 0; const CharacterType = { SPACE: 0, ALPHA_LETTER: 1, PUNCT: 2, HAN_LETTER: 3, KATAKANA_LETTER: 4, HIRAGANA_LETTER: 5, HALFWIDTH_KATAKANA_LETTER: 6, THAI_LETTER: 7 }; exports.CharacterType = CharacterType; function isAlphabeticalScript(charCode) { return charCode < 0x2e80; } function isAscii(charCode) { return (charCode & 0xff80) === 0; } function isAsciiAlpha(charCode) { return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; } function isAsciiDigit(charCode) { return charCode >= 0x30 && charCode <= 0x39; } function isAsciiSpace(charCode) { return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; } function isHan(charCode) { return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; } function isKatakana(charCode) { return charCode >= 0x30a0 && charCode <= 0x30ff; } function isHiragana(charCode) { return charCode >= 0x3040 && charCode <= 0x309f; } function isHalfwidthKatakana(charCode) { return charCode >= 0xff60 && charCode <= 0xff9f; } function isThai(charCode) { return (charCode & 0xff80) === 0x0e00; } function getCharacterType(charCode) { if (isAlphabeticalScript(charCode)) { if (isAscii(charCode)) { if (isAsciiSpace(charCode)) { return CharacterType.SPACE; } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { return CharacterType.ALPHA_LETTER; } return CharacterType.PUNCT; } else if (isThai(charCode)) { return CharacterType.THAI_LETTER; } else if (charCode === 0xa0) { return CharacterType.SPACE; } return CharacterType.ALPHA_LETTER; } if (isHan(charCode)) { return CharacterType.HAN_LETTER; } else if (isKatakana(charCode)) { return CharacterType.KATAKANA_LETTER; } else if (isHiragana(charCode)) { return CharacterType.HIRAGANA_LETTER; } else if (isHalfwidthKatakana(charCode)) { return CharacterType.HALFWIDTH_KATAKANA_LETTER; } return CharacterType.ALPHA_LETTER; } /***/ }), /* 15 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isDestArraysEqual = isDestArraysEqual; exports.isDestHashesEqual = isDestHashesEqual; exports.PDFHistory = void 0; var _ui_utils = __w_pdfjs_require__(5); const HASH_CHANGE_TIMEOUT = 1000; const POSITION_UPDATED_THRESHOLD = 50; const UPDATE_VIEWAREA_TIMEOUT = 1000; function getCurrentHash() { return document.location.hash; } class PDFHistory { constructor({ linkService, eventBus }) { this.linkService = linkService; this.eventBus = eventBus; this._initialized = false; this._fingerprint = ""; this.reset(); this._boundEvents = null; this._isViewerInPresentationMode = false; this.eventBus._on("presentationmodechanged", evt => { this._isViewerInPresentationMode = evt.state !== _ui_utils.PresentationModeState.NORMAL; }); this.eventBus._on("pagesinit", () => { this._isPagesLoaded = false; this.eventBus._on("pagesloaded", evt => { this._isPagesLoaded = !!evt.pagesCount; }, { once: true }); }); } initialize({ fingerprint, resetHistory = false, updateUrl = false }) { if (!fingerprint || typeof fingerprint !== "string") { console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); return; } if (this._initialized) { this.reset(); } const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; this._fingerprint = fingerprint; this._updateUrl = updateUrl === true; this._initialized = true; this._bindEvents(); const state = window.history.state; this._popStateInProgress = false; this._blockHashChange = 0; this._currentHash = getCurrentHash(); this._numPositionUpdates = 0; this._uid = this._maxUid = 0; this._destination = null; this._position = null; if (!this._isValidState(state, true) || resetHistory) { const { hash, page, rotation } = this._parseCurrentHash(true); if (!hash || reInitialized || resetHistory) { this._pushOrReplaceState(null, true); return; } this._pushOrReplaceState({ hash, page, rotation }, true); return; } const destination = state.destination; this._updateInternalState(destination, state.uid, true); if (destination.rotation !== undefined) { this._initialRotation = destination.rotation; } if (destination.dest) { this._initialBookmark = JSON.stringify(destination.dest); this._destination.page = null; } else if (destination.hash) { this._initialBookmark = destination.hash; } else if (destination.page) { this._initialBookmark = `page=${destination.page}`; } } reset() { if (this._initialized) { this._pageHide(); this._initialized = false; this._unbindEvents(); } if (this._updateViewareaTimeout) { clearTimeout(this._updateViewareaTimeout); this._updateViewareaTimeout = null; } this._initialBookmark = null; this._initialRotation = null; } push({ namedDest = null, explicitDest, pageNumber }) { if (!this._initialized) { return; } if (namedDest && typeof namedDest !== "string") { console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); return; } else if (!Array.isArray(explicitDest)) { console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); return; } else if (!this._isValidPage(pageNumber)) { if (pageNumber !== null || this._destination) { console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); return; } } const hash = namedDest || JSON.stringify(explicitDest); if (!hash) { return; } let forceReplace = false; if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { if (this._destination.page) { return; } forceReplace = true; } if (this._popStateInProgress && !forceReplace) { return; } this._pushOrReplaceState({ dest: explicitDest, hash, page: pageNumber, rotation: this.linkService.rotation }, forceReplace); if (!this._popStateInProgress) { this._popStateInProgress = true; Promise.resolve().then(() => { this._popStateInProgress = false; }); } } pushPage(pageNumber) { if (!this._initialized) { return; } if (!this._isValidPage(pageNumber)) { console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); return; } if (this._destination?.page === pageNumber) { return; } if (this._popStateInProgress) { return; } this._pushOrReplaceState({ dest: null, hash: `page=${pageNumber}`, page: pageNumber, rotation: this.linkService.rotation }); if (!this._popStateInProgress) { this._popStateInProgress = true; Promise.resolve().then(() => { this._popStateInProgress = false; }); } } pushCurrentPosition() { if (!this._initialized || this._popStateInProgress) { return; } this._tryPushCurrentPosition(); } back() { if (!this._initialized || this._popStateInProgress) { return; } const state = window.history.state; if (this._isValidState(state) && state.uid > 0) { window.history.back(); } } forward() { if (!this._initialized || this._popStateInProgress) { return; } const state = window.history.state; if (this._isValidState(state) && state.uid < this._maxUid) { window.history.forward(); } } get popStateInProgress() { return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); } get initialBookmark() { return this._initialized ? this._initialBookmark : null; } get initialRotation() { return this._initialized ? this._initialRotation : null; } _pushOrReplaceState(destination, forceReplace = false) { const shouldReplace = forceReplace || !this._destination; const newState = { fingerprint: this._fingerprint, uid: shouldReplace ? this._uid : this._uid + 1, destination }; this._updateInternalState(destination, newState.uid); let newUrl; if (this._updateUrl && destination?.hash) { const baseUrl = document.location.href.split("#")[0]; if (!baseUrl.startsWith("file://")) { newUrl = `${baseUrl}#${destination.hash}`; } } if (shouldReplace) { window.history.replaceState(newState, "", newUrl); } else { window.history.pushState(newState, "", newUrl); } } _tryPushCurrentPosition(temporary = false) { if (!this._position) { return; } let position = this._position; if (temporary) { position = Object.assign(Object.create(null), this._position); position.temporary = true; } if (!this._destination) { this._pushOrReplaceState(position); return; } if (this._destination.temporary) { this._pushOrReplaceState(position, true); return; } if (this._destination.hash === position.hash) { return; } if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { return; } let forceReplace = false; if (this._destination.page >= position.first && this._destination.page <= position.page) { if (this._destination.dest !== undefined || !this._destination.first) { return; } forceReplace = true; } this._pushOrReplaceState(position, forceReplace); } _isValidPage(val) { return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; } _isValidState(state, checkReload = false) { if (!state) { return false; } if (state.fingerprint !== this._fingerprint) { if (checkReload) { if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { return false; } const [perfEntry] = performance.getEntriesByType("navigation"); if (perfEntry?.type !== "reload") { return false; } } else { return false; } } if (!Number.isInteger(state.uid) || state.uid < 0) { return false; } if (state.destination === null || typeof state.destination !== "object") { return false; } return true; } _updateInternalState(destination, uid, removeTemporary = false) { if (this._updateViewareaTimeout) { clearTimeout(this._updateViewareaTimeout); this._updateViewareaTimeout = null; } if (removeTemporary && destination?.temporary) { delete destination.temporary; } this._destination = destination; this._uid = uid; this._maxUid = Math.max(this._maxUid, uid); this._numPositionUpdates = 0; } _parseCurrentHash(checkNameddest = false) { const hash = unescape(getCurrentHash()).substring(1); const params = (0, _ui_utils.parseQueryString)(hash); const nameddest = params.get("nameddest") || ""; let page = params.get("page") | 0; if (!this._isValidPage(page) || checkNameddest && nameddest.length > 0) { page = null; } return { hash, page, rotation: this.linkService.rotation }; } _updateViewarea({ location }) { if (this._updateViewareaTimeout) { clearTimeout(this._updateViewareaTimeout); this._updateViewareaTimeout = null; } this._position = { hash: this._isViewerInPresentationMode ? `page=${location.pageNumber}` : location.pdfOpenParams.substring(1), page: this.linkService.page, first: location.pageNumber, rotation: location.rotation }; if (this._popStateInProgress) { return; } if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { this._numPositionUpdates++; } if (UPDATE_VIEWAREA_TIMEOUT > 0) { this._updateViewareaTimeout = setTimeout(() => { if (!this._popStateInProgress) { this._tryPushCurrentPosition(true); } this._updateViewareaTimeout = null; }, UPDATE_VIEWAREA_TIMEOUT); } } _popState({ state }) { const newHash = getCurrentHash(), hashChanged = this._currentHash !== newHash; this._currentHash = newHash; if (!state) { this._uid++; const { hash, page, rotation } = this._parseCurrentHash(); this._pushOrReplaceState({ hash, page, rotation }, true); return; } if (!this._isValidState(state)) { return; } this._popStateInProgress = true; if (hashChanged) { this._blockHashChange++; (0, _ui_utils.waitOnEventOrTimeout)({ target: window, name: "hashchange", delay: HASH_CHANGE_TIMEOUT }).then(() => { this._blockHashChange--; }); } const destination = state.destination; this._updateInternalState(destination, state.uid, true); if ((0, _ui_utils.isValidRotation)(destination.rotation)) { this.linkService.rotation = destination.rotation; } if (destination.dest) { this.linkService.goToDestination(destination.dest); } else if (destination.hash) { this.linkService.setHash(destination.hash); } else if (destination.page) { this.linkService.page = destination.page; } Promise.resolve().then(() => { this._popStateInProgress = false; }); } _pageHide() { if (!this._destination || this._destination.temporary) { this._tryPushCurrentPosition(); } } _bindEvents() { if (this._boundEvents) { return; } this._boundEvents = { updateViewarea: this._updateViewarea.bind(this), popState: this._popState.bind(this), pageHide: this._pageHide.bind(this) }; this.eventBus._on("updateviewarea", this._boundEvents.updateViewarea); window.addEventListener("popstate", this._boundEvents.popState); window.addEventListener("pagehide", this._boundEvents.pageHide); } _unbindEvents() { if (!this._boundEvents) { return; } this.eventBus._off("updateviewarea", this._boundEvents.updateViewarea); window.removeEventListener("popstate", this._boundEvents.popState); window.removeEventListener("pagehide", this._boundEvents.pageHide); this._boundEvents = null; } } exports.PDFHistory = PDFHistory; function isDestHashesEqual(destHash, pushHash) { if (typeof destHash !== "string" || typeof pushHash !== "string") { return false; } if (destHash === pushHash) { return true; } const nameddest = (0, _ui_utils.parseQueryString)(destHash).get("nameddest"); if (nameddest === pushHash) { return true; } return false; } function isDestArraysEqual(firstDest, secondDest) { function isEntryEqual(first, second) { if (typeof first !== typeof second) { return false; } if (Array.isArray(first) || Array.isArray(second)) { return false; } if (first !== null && typeof first === "object" && second !== null) { if (Object.keys(first).length !== Object.keys(second).length) { return false; } for (const key in first) { if (!isEntryEqual(first[key], second[key])) { return false; } } return true; } return first === second || Number.isNaN(first) && Number.isNaN(second); } if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { return false; } if (firstDest.length !== secondDest.length) { return false; } for (let i = 0, ii = firstDest.length; i < ii; i++) { if (!isEntryEqual(firstDest[i], secondDest[i])) { return false; } } return true; } /***/ }), /* 16 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFPageView = void 0; var _pdfjsLib = __w_pdfjs_require__(2); var _ui_utils = __w_pdfjs_require__(5); var _app_options = __w_pdfjs_require__(10); var _l10n_utils = __w_pdfjs_require__(3); var _pdf_rendering_queue = __w_pdfjs_require__(17); const MAX_CANVAS_PIXELS = _app_options.compatibilityParams.maxCanvasPixels || 16777216; class PDFPageView { constructor(options) { const container = options.container; const defaultViewport = options.defaultViewport; this.id = options.id; this.renderingId = "page" + this.id; this.pdfPage = null; this.pageLabel = null; this.rotation = 0; this.scale = options.scale || _ui_utils.DEFAULT_SCALE; this.viewport = defaultViewport; this.pdfPageRotate = defaultViewport.rotation; this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; this.hasRestrictedScaling = false; this.textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE; this._annotationMode = options.annotationMode ?? _pdfjsLib.AnnotationMode.ENABLE_FORMS; this.imageResourcesPath = options.imageResourcesPath || ""; this.useOnlyCssZoom = options.useOnlyCssZoom || false; this.maxCanvasPixels = options.maxCanvasPixels || MAX_CANVAS_PIXELS; this.eventBus = options.eventBus; this.renderingQueue = options.renderingQueue; this.textLayerFactory = options.textLayerFactory; this.annotationLayerFactory = options.annotationLayerFactory; this.xfaLayerFactory = options.xfaLayerFactory; this.textHighlighter = options.textHighlighterFactory?.createTextHighlighter(this.id - 1, this.eventBus); this.structTreeLayerFactory = options.structTreeLayerFactory; this.renderer = options.renderer || _ui_utils.RendererType.CANVAS; this.l10n = options.l10n || _l10n_utils.NullL10n; this.paintTask = null; this.paintedViewportMap = new WeakMap(); this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL; this.resume = null; this._renderError = null; this._isStandalone = !this.renderingQueue?.hasViewer(); this.annotationLayer = null; this.textLayer = null; this.zoomLayer = null; this.xfaLayer = null; this.structTreeLayer = null; const div = document.createElement("div"); div.className = "page"; div.style.width = Math.floor(this.viewport.width) + "px"; div.style.height = Math.floor(this.viewport.height) + "px"; div.setAttribute("data-page-number", this.id); div.setAttribute("role", "region"); this.l10n.get("page_landmark", { page: this.id }).then(msg => { div.setAttribute("aria-label", msg); }); this.div = div; container.appendChild(div); } setPdfPage(pdfPage) { this.pdfPage = pdfPage; this.pdfPageRotate = pdfPage.rotate; const totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = pdfPage.getViewport({ scale: this.scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS, rotation: totalRotation }); this.reset(); } destroy() { this.reset(); if (this.pdfPage) { this.pdfPage.cleanup(); } } async _renderAnnotationLayer() { let error = null; try { await this.annotationLayer.render(this.viewport, "display"); } catch (ex) { error = ex; } finally { this.eventBus.dispatch("annotationlayerrendered", { source: this, pageNumber: this.id, error }); } } async _renderXfaLayer() { let error = null; try { const result = await this.xfaLayer.render(this.viewport, "display"); if (this.textHighlighter) { this._buildXfaTextContentItems(result.textDivs); } } catch (ex) { error = ex; } finally { this.eventBus.dispatch("xfalayerrendered", { source: this, pageNumber: this.id, error }); } } async _buildXfaTextContentItems(textDivs) { const text = await this.pdfPage.getTextContent(); const items = []; for (const item of text.items) { items.push(item.str); } this.textHighlighter.setTextMapping(textDivs, items); this.textHighlighter.enable(); } _resetZoomLayer(removeFromDOM = false) { if (!this.zoomLayer) { return; } const zoomLayerCanvas = this.zoomLayer.firstChild; this.paintedViewportMap.delete(zoomLayerCanvas); zoomLayerCanvas.width = 0; zoomLayerCanvas.height = 0; if (removeFromDOM) { this.zoomLayer.remove(); } this.zoomLayer = null; } reset({ keepZoomLayer = false, keepAnnotationLayer = false, keepXfaLayer = false } = {}) { this.cancelRendering({ keepAnnotationLayer, keepXfaLayer }); this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL; const div = this.div; div.style.width = Math.floor(this.viewport.width) + "px"; div.style.height = Math.floor(this.viewport.height) + "px"; const childNodes = div.childNodes, zoomLayerNode = keepZoomLayer && this.zoomLayer || null, annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null; for (let i = childNodes.length - 1; i >= 0; i--) { const node = childNodes[i]; switch (node) { case zoomLayerNode: case annotationLayerNode: case xfaLayerNode: continue; } div.removeChild(node); } div.removeAttribute("data-loaded"); if (annotationLayerNode) { this.annotationLayer.hide(); } if (xfaLayerNode) { this.xfaLayer.hide(); } if (!zoomLayerNode) { if (this.canvas) { this.paintedViewportMap.delete(this.canvas); this.canvas.width = 0; this.canvas.height = 0; delete this.canvas; } this._resetZoomLayer(); } if (this.svg) { this.paintedViewportMap.delete(this.svg); delete this.svg; } this.loadingIconDiv = document.createElement("div"); this.loadingIconDiv.className = "loadingIcon"; this.loadingIconDiv.setAttribute("role", "img"); this.l10n.get("loading").then(msg => { this.loadingIconDiv?.setAttribute("aria-label", msg); }); div.appendChild(this.loadingIconDiv); } update({ scale = 0, rotation = null, optionalContentConfigPromise = null }) { if (typeof arguments[0] !== "object") { console.error("PDFPageView.update called with separate parameters, please use an object instead."); this.update({ scale: arguments[0], rotation: arguments[1], optionalContentConfigPromise: arguments[2] }); return; } this.scale = scale || this.scale; if (typeof rotation === "number") { this.rotation = rotation; } if (optionalContentConfigPromise instanceof Promise) { this._optionalContentConfigPromise = optionalContentConfigPromise; } if (this._isStandalone) { const doc = document.documentElement; doc.style.setProperty("--zoom-factor", this.scale); } const totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = this.viewport.clone({ scale: this.scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS, rotation: totalRotation }); if (this.svg) { this.cssTransform({ target: this.svg, redrawAnnotationLayer: true, redrawXfaLayer: true }); this.eventBus.dispatch("pagerendered", { source: this, pageNumber: this.id, cssTransform: true, timestamp: performance.now(), error: this._renderError }); return; } let isScalingRestricted = false; if (this.canvas && this.maxCanvasPixels > 0) { const outputScale = this.outputScale; if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > this.maxCanvasPixels) { isScalingRestricted = true; } } if (this.canvas) { if (this.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) { this.cssTransform({ target: this.canvas, redrawAnnotationLayer: true, redrawXfaLayer: true }); this.eventBus.dispatch("pagerendered", { source: this, pageNumber: this.id, cssTransform: true, timestamp: performance.now(), error: this._renderError }); return; } if (!this.zoomLayer && !this.canvas.hidden) { this.zoomLayer = this.canvas.parentNode; this.zoomLayer.style.position = "absolute"; } } if (this.zoomLayer) { this.cssTransform({ target: this.zoomLayer.firstChild }); } this.reset({ keepZoomLayer: true, keepAnnotationLayer: true, keepXfaLayer: true }); } cancelRendering({ keepAnnotationLayer = false, keepXfaLayer = false } = {}) { if (this.paintTask) { this.paintTask.cancel(); this.paintTask = null; } this.resume = null; if (this.textLayer) { this.textLayer.cancel(); this.textLayer = null; } if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { this.annotationLayer.cancel(); this.annotationLayer = null; } if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { this.xfaLayer.cancel(); this.xfaLayer = null; this.textHighlighter?.disable(); } if (this._onTextLayerRendered) { this.eventBus._off("textlayerrendered", this._onTextLayerRendered); this._onTextLayerRendered = null; } } cssTransform({ target, redrawAnnotationLayer = false, redrawXfaLayer = false }) { const width = this.viewport.width; const height = this.viewport.height; const div = this.div; target.style.width = target.parentNode.style.width = div.style.width = Math.floor(width) + "px"; target.style.height = target.parentNode.style.height = div.style.height = Math.floor(height) + "px"; const relativeRotation = this.viewport.rotation - this.paintedViewportMap.get(target).rotation; const absRotation = Math.abs(relativeRotation); let scaleX = 1, scaleY = 1; if (absRotation === 90 || absRotation === 270) { scaleX = height / width; scaleY = width / height; } target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`; if (this.textLayer) { const textLayerViewport = this.textLayer.viewport; const textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation; const textAbsRotation = Math.abs(textRelativeRotation); let scale = width / textLayerViewport.width; if (textAbsRotation === 90 || textAbsRotation === 270) { scale = width / textLayerViewport.height; } const textLayerDiv = this.textLayer.textLayerDiv; let transX, transY; switch (textAbsRotation) { case 0: transX = transY = 0; break; case 90: transX = 0; transY = "-" + textLayerDiv.style.height; break; case 180: transX = "-" + textLayerDiv.style.width; transY = "-" + textLayerDiv.style.height; break; case 270: transX = "-" + textLayerDiv.style.width; transY = 0; break; default: console.error("Bad rotation value."); break; } textLayerDiv.style.transform = `rotate(${textAbsRotation}deg) ` + `scale(${scale}) ` + `translate(${transX}, ${transY})`; textLayerDiv.style.transformOrigin = "0% 0%"; } if (redrawAnnotationLayer && this.annotationLayer) { this._renderAnnotationLayer(); } if (redrawXfaLayer && this.xfaLayer) { this._renderXfaLayer(); } } get width() { return this.viewport.width; } get height() { return this.viewport.height; } getPagePoint(x, y) { return this.viewport.convertToPdfPoint(x, y); } draw() { if (this.renderingState !== _pdf_rendering_queue.RenderingStates.INITIAL) { console.error("Must be in new state before drawing"); this.reset(); } const { div, pdfPage } = this; if (!pdfPage) { this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED; if (this.loadingIconDiv) { div.removeChild(this.loadingIconDiv); delete this.loadingIconDiv; } return Promise.reject(new Error("pdfPage is not loaded")); } this.renderingState = _pdf_rendering_queue.RenderingStates.RUNNING; const canvasWrapper = document.createElement("div"); canvasWrapper.style.width = div.style.width; canvasWrapper.style.height = div.style.height; canvasWrapper.classList.add("canvasWrapper"); if (this.annotationLayer?.div) { div.insertBefore(canvasWrapper, this.annotationLayer.div); } else { div.appendChild(canvasWrapper); } let textLayer = null; if (this.textLayerMode !== _ui_utils.TextLayerMode.DISABLE && this.textLayerFactory) { const textLayerDiv = document.createElement("div"); textLayerDiv.className = "textLayer"; textLayerDiv.style.width = canvasWrapper.style.width; textLayerDiv.style.height = canvasWrapper.style.height; if (this.annotationLayer?.div) { div.insertBefore(textLayerDiv, this.annotationLayer.div); } else { div.appendChild(textLayerDiv); } textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.textLayerMode === _ui_utils.TextLayerMode.ENABLE_ENHANCE, this.eventBus, this.textHighlighter); } this.textLayer = textLayer; if (this.xfaLayer?.div) { div.appendChild(this.xfaLayer.div); } let renderContinueCallback = null; if (this.renderingQueue) { renderContinueCallback = cont => { if (!this.renderingQueue.isHighestPriority(this)) { this.renderingState = _pdf_rendering_queue.RenderingStates.PAUSED; this.resume = () => { this.renderingState = _pdf_rendering_queue.RenderingStates.RUNNING; cont(); }; return; } cont(); }; } const finishPaintTask = async (error = null) => { if (paintTask === this.paintTask) { this.paintTask = null; } if (error instanceof _pdfjsLib.RenderingCancelledException) { this._renderError = null; return; } this._renderError = error; this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED; if (this.loadingIconDiv) { div.removeChild(this.loadingIconDiv); delete this.loadingIconDiv; } this._resetZoomLayer(true); this.eventBus.dispatch("pagerendered", { source: this, pageNumber: this.id, cssTransform: false, timestamp: performance.now(), error: this._renderError }); if (error) { throw error; } }; const paintTask = this.renderer === _ui_utils.RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper); paintTask.onRenderContinue = renderContinueCallback; this.paintTask = paintTask; const resultPromise = paintTask.promise.then(() => { return finishPaintTask(null).then(() => { if (textLayer) { const readableStream = pdfPage.streamTextContent({ normalizeWhitespace: true, includeMarkedContent: true }); textLayer.setTextContentStream(readableStream); textLayer.render(); } }); }, function (reason) { return finishPaintTask(reason); }); if (this._annotationMode !== _pdfjsLib.AnnotationMode.DISABLE && this.annotationLayerFactory) { if (!this.annotationLayer) { this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, null, this.imageResourcesPath, this._annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS, this.l10n, null, null, null, null); } this._renderAnnotationLayer(); } if (this.xfaLayerFactory) { if (!this.xfaLayer) { this.xfaLayer = this.xfaLayerFactory.createXfaLayerBuilder(div, pdfPage, null); } this._renderXfaLayer(); } if (this.structTreeLayerFactory && this.textLayer && this.canvas) { this._onTextLayerRendered = event => { if (event.pageNumber !== this.id) { return; } this.eventBus._off("textlayerrendered", this._onTextLayerRendered); this._onTextLayerRendered = null; if (!this.canvas) { return; } this.pdfPage.getStructTree().then(tree => { if (!tree) { return; } if (!this.canvas) { return; } const treeDom = this.structTreeLayer.render(tree); treeDom.classList.add("structTree"); this.canvas.appendChild(treeDom); }); }; this.eventBus._on("textlayerrendered", this._onTextLayerRendered); this.structTreeLayer = this.structTreeLayerFactory.createStructTreeLayerBuilder(pdfPage); } div.setAttribute("data-loaded", true); this.eventBus.dispatch("pagerender", { source: this, pageNumber: this.id }); return resultPromise; } paintOnCanvas(canvasWrapper) { const renderCapability = (0, _pdfjsLib.createPromiseCapability)(); const result = { promise: renderCapability.promise, onRenderContinue(cont) { cont(); }, cancel() { renderTask.cancel(); } }; const viewport = this.viewport; const canvas = document.createElement("canvas"); canvas.hidden = true; let isCanvasHidden = true; const showCanvas = function () { if (isCanvasHidden) { canvas.hidden = false; isCanvasHidden = false; } }; canvasWrapper.appendChild(canvas); this.canvas = canvas; canvas.mozOpaque = true; const ctx = canvas.getContext("2d", { alpha: false }); const outputScale = (0, _ui_utils.getOutputScale)(ctx); this.outputScale = outputScale; if (this.useOnlyCssZoom) { const actualSizeViewport = viewport.clone({ scale: _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS }); outputScale.sx *= actualSizeViewport.width / viewport.width; outputScale.sy *= actualSizeViewport.height / viewport.height; outputScale.scaled = true; } if (this.maxCanvasPixels > 0) { const pixelsInViewport = viewport.width * viewport.height; const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); if (outputScale.sx > maxScale || outputScale.sy > maxScale) { outputScale.sx = maxScale; outputScale.sy = maxScale; outputScale.scaled = true; this.hasRestrictedScaling = true; } else { this.hasRestrictedScaling = false; } } const sfx = (0, _ui_utils.approximateFraction)(outputScale.sx); const sfy = (0, _ui_utils.approximateFraction)(outputScale.sy); canvas.width = (0, _ui_utils.roundToDivide)(viewport.width * outputScale.sx, sfx[0]); canvas.height = (0, _ui_utils.roundToDivide)(viewport.height * outputScale.sy, sfy[0]); canvas.style.width = (0, _ui_utils.roundToDivide)(viewport.width, sfx[1]) + "px"; canvas.style.height = (0, _ui_utils.roundToDivide)(viewport.height, sfy[1]) + "px"; this.paintedViewportMap.set(canvas, viewport); const transform = !outputScale.scaled ? null : [outputScale.sx, 0, 0, outputScale.sy, 0, 0]; const renderContext = { canvasContext: ctx, transform, viewport: this.viewport, annotationMode: this._annotationMode, optionalContentConfigPromise: this._optionalContentConfigPromise }; const renderTask = this.pdfPage.render(renderContext); renderTask.onContinue = function (cont) { showCanvas(); if (result.onRenderContinue) { result.onRenderContinue(cont); } else { cont(); } }; renderTask.promise.then(function () { showCanvas(); renderCapability.resolve(undefined); }, function (error) { showCanvas(); renderCapability.reject(error); }); return result; } paintOnSvg(wrapper) { let cancelled = false; const ensureNotCancelled = () => { if (cancelled) { throw new _pdfjsLib.RenderingCancelledException(`Rendering cancelled, page ${this.id}`, "svg"); } }; const pdfPage = this.pdfPage; const actualSizeViewport = this.viewport.clone({ scale: _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS }); const promise = pdfPage.getOperatorList({ annotationMode: this._annotationMode }).then(opList => { ensureNotCancelled(); const svgGfx = new _pdfjsLib.SVGGraphics(pdfPage.commonObjs, pdfPage.objs, _app_options.compatibilityParams.disableCreateObjectURL); return svgGfx.getSVG(opList, actualSizeViewport).then(svg => { ensureNotCancelled(); this.svg = svg; this.paintedViewportMap.set(svg, actualSizeViewport); svg.style.width = wrapper.style.width; svg.style.height = wrapper.style.height; this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED; wrapper.appendChild(svg); }); }); return { promise, onRenderContinue(cont) { cont(); }, cancel() { cancelled = true; } }; } setPageLabel(label) { this.pageLabel = typeof label === "string" ? label : null; if (this.pageLabel !== null) { this.div.setAttribute("data-page-label", this.pageLabel); } else { this.div.removeAttribute("data-page-label"); } } } exports.PDFPageView = PDFPageView; /***/ }), /* 17 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RenderingStates = exports.PDFRenderingQueue = void 0; var _pdfjsLib = __w_pdfjs_require__(2); const CLEANUP_TIMEOUT = 30000; const RenderingStates = { INITIAL: 0, RUNNING: 1, PAUSED: 2, FINISHED: 3 }; exports.RenderingStates = RenderingStates; class PDFRenderingQueue { constructor() { this.pdfViewer = null; this.pdfThumbnailViewer = null; this.onIdle = null; this.highestPriorityPage = null; this.idleTimeout = null; this.printing = false; this.isThumbnailViewEnabled = false; } setViewer(pdfViewer) { this.pdfViewer = pdfViewer; } setThumbnailViewer(pdfThumbnailViewer) { this.pdfThumbnailViewer = pdfThumbnailViewer; } isHighestPriority(view) { return this.highestPriorityPage === view.renderingId; } hasViewer() { return !!this.pdfViewer; } renderHighestPriority(currentlyVisiblePages) { if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; } if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { return; } if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) { if (this.pdfThumbnailViewer.forceRendering()) { return; } } if (this.printing) { return; } if (this.onIdle) { this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); } } getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { const visibleViews = visible.views; const numVisible = visibleViews.length; if (numVisible === 0) { return null; } for (let i = 0; i < numVisible; ++i) { const view = visibleViews[i].view; if (!this.isViewFinished(view)) { return view; } } let preRenderIndex = scrolledDown ? visible.last.id : visible.first.id - 2; let preRenderView = views[preRenderIndex]; if (preRenderView && !this.isViewFinished(preRenderView)) { return preRenderView; } if (preRenderExtra) { preRenderIndex += scrolledDown ? 1 : -1; preRenderView = views[preRenderIndex]; if (preRenderView && !this.isViewFinished(preRenderView)) { return preRenderView; } } return null; } isViewFinished(view) { return view.renderingState === RenderingStates.FINISHED; } renderView(view) { switch (view.renderingState) { case RenderingStates.FINISHED: return false; case RenderingStates.PAUSED: this.highestPriorityPage = view.renderingId; view.resume(); break; case RenderingStates.RUNNING: this.highestPriorityPage = view.renderingId; break; case RenderingStates.INITIAL: this.highestPriorityPage = view.renderingId; view.draw().finally(() => { this.renderHighestPriority(); }).catch(reason => { if (reason instanceof _pdfjsLib.RenderingCancelledException) { return; } console.error(`renderView: "${reason}"`); }); break; } return true; } } exports.PDFRenderingQueue = PDFRenderingQueue; /***/ }), /* 18 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFScriptingManager = void 0; var _pdfjsLib = __w_pdfjs_require__(2); var _ui_utils = __w_pdfjs_require__(5); var _pdf_rendering_queue = __w_pdfjs_require__(17); class PDFScriptingManager { constructor({ eventBus, sandboxBundleSrc = null, scriptingFactory = null, docPropertiesLookup = null }) { this._pdfDocument = null; this._pdfViewer = null; this._closeCapability = null; this._destroyCapability = null; this._scripting = null; this._mouseState = Object.create(null); this._ready = false; this._eventBus = eventBus; this._sandboxBundleSrc = sandboxBundleSrc; this._scriptingFactory = scriptingFactory; this._docPropertiesLookup = docPropertiesLookup; if (!this._scriptingFactory) { window.addEventListener("updatefromsandbox", event => { this._eventBus.dispatch("updatefromsandbox", { source: window, detail: event.detail }); }); } } setViewer(pdfViewer) { this._pdfViewer = pdfViewer; } async setDocument(pdfDocument) { if (this._pdfDocument) { await this._destroyScripting(); } this._pdfDocument = pdfDocument; if (!pdfDocument) { return; } const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); if (!objects && !docActions) { await this._destroyScripting(); return; } if (pdfDocument !== this._pdfDocument) { return; } try { this._scripting = this._createScripting(); } catch (error) { console.error(`PDFScriptingManager.setDocument: "${error?.message}".`); await this._destroyScripting(); return; } this._internalEvents.set("updatefromsandbox", event => { if (event?.source !== window) { return; } this._updateFromSandbox(event.detail); }); this._internalEvents.set("dispatcheventinsandbox", event => { this._scripting?.dispatchEventInSandbox(event.detail); }); this._internalEvents.set("pagechanging", ({ pageNumber, previous }) => { if (pageNumber === previous) { return; } this._dispatchPageClose(previous); this._dispatchPageOpen(pageNumber); }); this._internalEvents.set("pagerendered", ({ pageNumber }) => { if (!this._pageOpenPending.has(pageNumber)) { return; } if (pageNumber !== this._pdfViewer.currentPageNumber) { return; } this._dispatchPageOpen(pageNumber); }); this._internalEvents.set("pagesdestroy", async event => { await this._dispatchPageClose(this._pdfViewer.currentPageNumber); await this._scripting?.dispatchEventInSandbox({ id: "doc", name: "WillClose" }); this._closeCapability?.resolve(); }); this._domEvents.set("mousedown", event => { this._mouseState.isDown = true; }); this._domEvents.set("mouseup", event => { this._mouseState.isDown = false; }); for (const [name, listener] of this._internalEvents) { this._eventBus._on(name, listener); } for (const [name, listener] of this._domEvents) { window.addEventListener(name, listener); } try { const docProperties = await this._getDocProperties(); if (pdfDocument !== this._pdfDocument) { return; } await this._scripting.createSandbox({ objects, calculationOrder, appInfo: { platform: navigator.platform, language: navigator.language }, docInfo: { ...docProperties, actions: docActions } }); this._eventBus.dispatch("sandboxcreated", { source: this }); } catch (error) { console.error(`PDFScriptingManager.setDocument: "${error?.message}".`); await this._destroyScripting(); return; } await this._scripting?.dispatchEventInSandbox({ id: "doc", name: "Open" }); await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true); Promise.resolve().then(() => { if (pdfDocument === this._pdfDocument) { this._ready = true; } }); } async dispatchWillSave(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "WillSave" }); } async dispatchDidSave(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "DidSave" }); } async dispatchWillPrint(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "WillPrint" }); } async dispatchDidPrint(detail) { return this._scripting?.dispatchEventInSandbox({ id: "doc", name: "DidPrint" }); } get mouseState() { return this._mouseState; } get destroyPromise() { return this._destroyCapability?.promise || null; } get ready() { return this._ready; } get _internalEvents() { return (0, _pdfjsLib.shadow)(this, "_internalEvents", new Map()); } get _domEvents() { return (0, _pdfjsLib.shadow)(this, "_domEvents", new Map()); } get _pageOpenPending() { return (0, _pdfjsLib.shadow)(this, "_pageOpenPending", new Set()); } get _visitedPages() { return (0, _pdfjsLib.shadow)(this, "_visitedPages", new Map()); } async _updateFromSandbox(detail) { const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode; const { id, siblings, command, value } = detail; if (!id) { switch (command) { case "clear": console.clear(); break; case "error": console.error(value); break; case "layout": this._pdfViewer.spreadMode = (0, _ui_utils.apiPageLayoutToSpreadMode)(value); break; case "page-num": this._pdfViewer.currentPageNumber = value + 1; break; case "print": await this._pdfViewer.pagesPromise; this._eventBus.dispatch("print", { source: this }); break; case "println": console.log(value); break; case "zoom": if (isInPresentationMode) { return; } this._pdfViewer.currentScaleValue = value; break; case "SaveAs": this._eventBus.dispatch("save", { source: this }); break; case "FirstPage": this._pdfViewer.currentPageNumber = 1; break; case "LastPage": this._pdfViewer.currentPageNumber = this._pdfViewer.pagesCount; break; case "NextPage": this._pdfViewer.nextPage(); break; case "PrevPage": this._pdfViewer.previousPage(); break; case "ZoomViewIn": if (isInPresentationMode) { return; } this._pdfViewer.increaseScale(); break; case "ZoomViewOut": if (isInPresentationMode) { return; } this._pdfViewer.decreaseScale(); break; } return; } if (isInPresentationMode) { if (detail.focus) { return; } } delete detail.id; delete detail.siblings; const ids = siblings ? [id, ...siblings] : [id]; for (const elementId of ids) { const element = document.getElementById(elementId); if (element) { element.dispatchEvent(new CustomEvent("updatefromsandbox", { detail })); } else { this._pdfDocument?.annotationStorage.setValue(elementId, detail); } } } async _dispatchPageOpen(pageNumber, initialize = false) { const pdfDocument = this._pdfDocument, visitedPages = this._visitedPages; if (initialize) { this._closeCapability = (0, _pdfjsLib.createPromiseCapability)(); } if (!this._closeCapability) { return; } const pageView = this._pdfViewer.getPageView(pageNumber - 1); if (pageView?.renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) { this._pageOpenPending.add(pageNumber); return; } this._pageOpenPending.delete(pageNumber); const actionsPromise = (async () => { const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); if (pdfDocument !== this._pdfDocument) { return; } await this._scripting?.dispatchEventInSandbox({ id: "page", name: "PageOpen", pageNumber, actions }); })(); visitedPages.set(pageNumber, actionsPromise); } async _dispatchPageClose(pageNumber) { const pdfDocument = this._pdfDocument, visitedPages = this._visitedPages; if (!this._closeCapability) { return; } if (this._pageOpenPending.has(pageNumber)) { return; } const actionsPromise = visitedPages.get(pageNumber); if (!actionsPromise) { return; } visitedPages.set(pageNumber, null); await actionsPromise; if (pdfDocument !== this._pdfDocument) { return; } await this._scripting?.dispatchEventInSandbox({ id: "page", name: "PageClose", pageNumber }); } async _getDocProperties() { if (this._docPropertiesLookup) { return this._docPropertiesLookup(this._pdfDocument); } const { docPropertiesLookup } = __w_pdfjs_require__(19); return docPropertiesLookup(this._pdfDocument); } _createScripting() { this._destroyCapability = (0, _pdfjsLib.createPromiseCapability)(); if (this._scripting) { throw new Error("_createScripting: Scripting already exists."); } if (this._scriptingFactory) { return this._scriptingFactory.createScripting({ sandboxBundleSrc: this._sandboxBundleSrc }); } const { GenericScripting } = __w_pdfjs_require__(19); return new GenericScripting(this._sandboxBundleSrc); } async _destroyScripting() { if (!this._scripting) { this._pdfDocument = null; this._destroyCapability?.resolve(); return; } if (this._closeCapability) { await Promise.race([this._closeCapability.promise, new Promise(resolve => { setTimeout(resolve, 1000); })]).catch(reason => {}); this._closeCapability = null; } this._pdfDocument = null; try { await this._scripting.destroySandbox(); } catch (ex) {} for (const [name, listener] of this._internalEvents) { this._eventBus._off(name, listener); } this._internalEvents.clear(); for (const [name, listener] of this._domEvents) { window.removeEventListener(name, listener); } this._domEvents.clear(); this._pageOpenPending.clear(); this._visitedPages.clear(); this._scripting = null; delete this._mouseState.isDown; this._ready = false; this._destroyCapability?.resolve(); } } exports.PDFScriptingManager = PDFScriptingManager; /***/ }), /* 19 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.docPropertiesLookup = docPropertiesLookup; exports.GenericScripting = void 0; var _pdfjsLib = __w_pdfjs_require__(2); async function docPropertiesLookup(pdfDocument) { const url = "", baseUrl = url.split("#")[0]; let { info, metadata, contentDispositionFilename, contentLength } = await pdfDocument.getMetadata(); if (!contentLength) { const { length } = await pdfDocument.getDownloadInfo(); contentLength = length; } return { ...info, baseURL: baseUrl, filesize: contentLength, filename: contentDispositionFilename || (0, _pdfjsLib.getPdfFilenameFromUrl)(url), metadata: metadata?.getRaw(), authors: metadata?.get("dc:creator"), numPages: pdfDocument.numPages, URL: url }; } class GenericScripting { constructor(sandboxBundleSrc) { this._ready = (0, _pdfjsLib.loadScript)(sandboxBundleSrc, true).then(() => { return window.pdfjsSandbox.QuickJSSandbox(); }); } async createSandbox(data) { const sandbox = await this._ready; sandbox.create(data); } async dispatchEventInSandbox(event) { const sandbox = await this._ready; sandbox.dispatchEvent(event); } async destroySandbox() { const sandbox = await this._ready; sandbox.nukeSandbox(); } } exports.GenericScripting = GenericScripting; /***/ }), /* 20 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFSinglePageViewer = void 0; var _base_viewer = __w_pdfjs_require__(21); var _pdfjsLib = __w_pdfjs_require__(2); class PDFSinglePageViewer extends _base_viewer.BaseViewer { constructor(options) { super(options); this.eventBus._on("pagesinit", evt => { this._ensurePageViewVisible(); }); } get _viewerElement() { return (0, _pdfjsLib.shadow)(this, "_viewerElement", this._shadowViewer); } get _pageWidthScaleFactor() { return 1; } _resetView() { super._resetView(); this._previousPageNumber = 1; this._shadowViewer = document.createDocumentFragment(); this._updateScrollDown = null; } _ensurePageViewVisible() { const pageView = this._pages[this._currentPageNumber - 1]; const previousPageView = this._pages[this._previousPageNumber - 1]; const viewerNodes = this.viewer.childNodes; switch (viewerNodes.length) { case 0: this.viewer.appendChild(pageView.div); break; case 1: if (viewerNodes[0] !== previousPageView.div) { throw new Error("_ensurePageViewVisible: Unexpected previously visible page."); } if (pageView === previousPageView) { break; } this._shadowViewer.appendChild(previousPageView.div); this.viewer.appendChild(pageView.div); this.container.scrollTop = 0; break; default: throw new Error("_ensurePageViewVisible: Only one page should be visible at a time."); } this._previousPageNumber = this._currentPageNumber; } _scrollUpdate() { if (this._updateScrollDown) { this._updateScrollDown(); } super._scrollUpdate(); } _scrollIntoView({ pageDiv, pageSpot = null, pageNumber = null }) { if (pageNumber) { this._setCurrentPageNumber(pageNumber); } const scrolledDown = this._currentPageNumber >= this._previousPageNumber; this._ensurePageViewVisible(); this.update(); super._scrollIntoView({ pageDiv, pageSpot, pageNumber }); this._updateScrollDown = () => { this.scroll.down = scrolledDown; this._updateScrollDown = null; }; } _getVisiblePages() { return this._getCurrentVisiblePage(); } _updateHelper(visiblePages) {} get _isScrollModeHorizontal() { return (0, _pdfjsLib.shadow)(this, "_isScrollModeHorizontal", false); } _updateScrollMode() {} _updateSpreadMode() {} _getPageAdvance() { return 1; } } exports.PDFSinglePageViewer = PDFSinglePageViewer; /***/ }), /* 21 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseViewer = void 0; var _pdfjsLib = __w_pdfjs_require__(2); var _ui_utils = __w_pdfjs_require__(5); var _pdf_rendering_queue = __w_pdfjs_require__(17); var _annotation_layer_builder = __w_pdfjs_require__(1); var _l10n_utils = __w_pdfjs_require__(3); var _pdf_page_view = __w_pdfjs_require__(16); var _pdf_link_service = __w_pdfjs_require__(4); var _struct_tree_layer_builder = __w_pdfjs_require__(6); var _text_highlighter = __w_pdfjs_require__(22); var _text_layer_builder = __w_pdfjs_require__(7); var _xfa_layer_builder = __w_pdfjs_require__(8); const DEFAULT_CACHE_SIZE = 10; function PDFPageViewBuffer(size) { const data = []; this.push = function (view) { const i = data.indexOf(view); if (i >= 0) { data.splice(i, 1); } data.push(view); if (data.length > size) { data.shift().destroy(); } }; this.resize = function (newSize, pagesToKeep) { size = newSize; if (pagesToKeep) { const pageIdsToKeep = new Set(); for (let i = 0, iMax = pagesToKeep.length; i < iMax; ++i) { pageIdsToKeep.add(pagesToKeep[i].id); } (0, _ui_utils.moveToEndOfArray)(data, function (page) { return pageIdsToKeep.has(page.id); }); } while (data.length > size) { data.shift().destroy(); } }; this.has = function (view) { return data.includes(view); }; } function isSameScale(oldScale, newScale) { if (newScale === oldScale) { return true; } if (Math.abs(newScale - oldScale) < 1e-15) { return true; } return false; } class BaseViewer { constructor(options) { if (this.constructor === BaseViewer) { throw new Error("Cannot initialize BaseViewer."); } const viewerVersion = '2.11.338'; if (_pdfjsLib.version !== viewerVersion) { throw new Error(`The API version "${_pdfjsLib.version}" does not match the Viewer version "${viewerVersion}".`); } this.container = options.container; this.viewer = options.viewer || options.container.firstElementChild; if (!(this.container?.tagName.toUpperCase() === "DIV" && this.viewer?.tagName.toUpperCase() === "DIV")) { throw new Error("Invalid `container` and/or `viewer` option."); } if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { throw new Error("The `container` must be absolutely positioned."); } this.eventBus = options.eventBus; this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService(); this.downloadManager = options.downloadManager || null; this.findController = options.findController || null; this._scriptingManager = options.scriptingManager || null; this.removePageBorders = options.removePageBorders || false; this.textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE; this._annotationMode = options.annotationMode ?? _pdfjsLib.AnnotationMode.ENABLE_FORMS; this.imageResourcesPath = options.imageResourcesPath || ""; this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; this.renderer = options.renderer || _ui_utils.RendererType.CANVAS; this.useOnlyCssZoom = options.useOnlyCssZoom || false; this.maxCanvasPixels = options.maxCanvasPixels; this.l10n = options.l10n || _l10n_utils.NullL10n; this.defaultRenderingQueue = !options.renderingQueue; if (this.defaultRenderingQueue) { this.renderingQueue = new _pdf_rendering_queue.PDFRenderingQueue(); this.renderingQueue.setViewer(this); } else { this.renderingQueue = options.renderingQueue; } this._doc = document.documentElement; this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this)); this.presentationModeState = _ui_utils.PresentationModeState.UNKNOWN; this._onBeforeDraw = this._onAfterDraw = null; this._resetView(); if (this.removePageBorders) { this.viewer.classList.add("removePageBorders"); } Promise.resolve().then(() => { this.eventBus.dispatch("baseviewerinit", { source: this }); }); } get pagesCount() { return this._pages.length; } getPageView(index) { return this._pages[index]; } get pageViewsReady() { if (!this._pagesCapability.settled) { return false; } return this._pages.every(function (pageView) { return pageView?.pdfPage; }); } get renderForms() { return this._annotationMode === _pdfjsLib.AnnotationMode.ENABLE_FORMS; } get enableScripting() { return !!this._scriptingManager; } get currentPageNumber() { return this._currentPageNumber; } set currentPageNumber(val) { if (!Number.isInteger(val)) { throw new Error("Invalid page number."); } if (!this.pdfDocument) { return; } if (!this._setCurrentPageNumber(val, true)) { console.error(`currentPageNumber: "${val}" is not a valid page.`); } } _setCurrentPageNumber(val, resetCurrentPageView = false) { if (this._currentPageNumber === val) { if (resetCurrentPageView) { this._resetCurrentPageView(); } return true; } if (!(0 < val && val <= this.pagesCount)) { return false; } const previous = this._currentPageNumber; this._currentPageNumber = val; this.eventBus.dispatch("pagechanging", { source: this, pageNumber: val, pageLabel: this._pageLabels?.[val - 1] ?? null, previous }); if (resetCurrentPageView) { this._resetCurrentPageView(); } return true; } get currentPageLabel() { return this._pageLabels?.[this._currentPageNumber - 1] ?? null; } set currentPageLabel(val) { if (!this.pdfDocument) { return; } let page = val | 0; if (this._pageLabels) { const i = this._pageLabels.indexOf(val); if (i >= 0) { page = i + 1; } } if (!this._setCurrentPageNumber(page, true)) { console.error(`currentPageLabel: "${val}" is not a valid page.`); } } get currentScale() { return this._currentScale !== _ui_utils.UNKNOWN_SCALE ? this._currentScale : _ui_utils.DEFAULT_SCALE; } set currentScale(val) { if (isNaN(val)) { throw new Error("Invalid numeric scale."); } if (!this.pdfDocument) { return; } this._setScale(val, false); } get currentScaleValue() { return this._currentScaleValue; } set currentScaleValue(val) { if (!this.pdfDocument) { return; } this._setScale(val, false); } get pagesRotation() { return this._pagesRotation; } set pagesRotation(rotation) { if (!(0, _ui_utils.isValidRotation)(rotation)) { throw new Error("Invalid pages rotation angle."); } if (!this.pdfDocument) { return; } rotation %= 360; if (rotation < 0) { rotation += 360; } if (this._pagesRotation === rotation) { return; } this._pagesRotation = rotation; const pageNumber = this._currentPageNumber; const updateArgs = { rotation }; for (const pageView of this._pages) { pageView.update(updateArgs); } if (this._currentScaleValue) { this._setScale(this._currentScaleValue, true); } this.eventBus.dispatch("rotationchanging", { source: this, pagesRotation: rotation, pageNumber }); if (this.defaultRenderingQueue) { this.update(); } } get firstPagePromise() { return this.pdfDocument ? this._firstPageCapability.promise : null; } get onePageRendered() { return this.pdfDocument ? this._onePageRenderedCapability.promise : null; } get pagesPromise() { return this.pdfDocument ? this._pagesCapability.promise : null; } get _viewerElement() { throw new Error("Not implemented: _viewerElement"); } _onePageRenderedOrForceFetch() { if (!this.container.offsetParent || this._getVisiblePages().views.length === 0) { return Promise.resolve(); } return this._onePageRenderedCapability.promise; } setDocument(pdfDocument) { if (this.pdfDocument) { this.eventBus.dispatch("pagesdestroy", { source: this }); this._cancelRendering(); this._resetView(); if (this.findController) { this.findController.setDocument(null); } if (this._scriptingManager) { this._scriptingManager.setDocument(null); } } this.pdfDocument = pdfDocument; if (!pdfDocument) { return; } const isPureXfa = pdfDocument.isPureXfa; const pagesCount = pdfDocument.numPages; const firstPagePromise = pdfDocument.getPage(1); const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig(); this._pagesCapability.promise.then(() => { this.eventBus.dispatch("pagesloaded", { source: this, pagesCount }); }); this._onBeforeDraw = evt => { const pageView = this._pages[evt.pageNumber - 1]; if (!pageView) { return; } this._buffer.push(pageView); }; this.eventBus._on("pagerender", this._onBeforeDraw); this._onAfterDraw = evt => { if (evt.cssTransform || this._onePageRenderedCapability.settled) { return; } this._onePageRenderedCapability.resolve(); this.eventBus._off("pagerendered", this._onAfterDraw); this._onAfterDraw = null; }; this.eventBus._on("pagerendered", this._onAfterDraw); firstPagePromise.then(firstPdfPage => { this._firstPageCapability.resolve(firstPdfPage); this._optionalContentConfigPromise = optionalContentConfigPromise; const scale = this.currentScale; const viewport = firstPdfPage.getViewport({ scale: scale * _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS }); const textLayerFactory = this.textLayerMode !== _ui_utils.TextLayerMode.DISABLE && !isPureXfa ? this : null; const annotationLayerFactory = this._annotationMode !== _pdfjsLib.AnnotationMode.DISABLE ? this : null; const xfaLayerFactory = isPureXfa ? this : null; for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { const pageView = new _pdf_page_view.PDFPageView({ container: this._viewerElement, eventBus: this.eventBus, id: pageNum, scale, defaultViewport: viewport.clone(), optionalContentConfigPromise, renderingQueue: this.renderingQueue, textLayerFactory, textLayerMode: this.textLayerMode, annotationLayerFactory, annotationMode: this._annotationMode, xfaLayerFactory, textHighlighterFactory: this, structTreeLayerFactory: this, imageResourcesPath: this.imageResourcesPath, renderer: this.renderer, useOnlyCssZoom: this.useOnlyCssZoom, maxCanvasPixels: this.maxCanvasPixels, l10n: this.l10n }); this._pages.push(pageView); } const firstPageView = this._pages[0]; if (firstPageView) { firstPageView.setPdfPage(firstPdfPage); this.linkService.cachePageRef(1, firstPdfPage.ref); } if (this._spreadMode !== _ui_utils.SpreadMode.NONE) { this._updateSpreadMode(); } this._onePageRenderedOrForceFetch().then(() => { if (this.findController) { this.findController.setDocument(pdfDocument); } if (this._scriptingManager) { this._scriptingManager.setDocument(pdfDocument); } if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > 7500) { this._pagesCapability.resolve(); return; } let getPagesLeft = pagesCount - 1; if (getPagesLeft <= 0) { this._pagesCapability.resolve(); return; } for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { pdfDocument.getPage(pageNum).then(pdfPage => { const pageView = this._pages[pageNum - 1]; if (!pageView.pdfPage) { pageView.setPdfPage(pdfPage); } this.linkService.cachePageRef(pageNum, pdfPage.ref); if (--getPagesLeft === 0) { this._pagesCapability.resolve(); } }, reason => { console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); if (--getPagesLeft === 0) { this._pagesCapability.resolve(); } }); } }); this.eventBus.dispatch("pagesinit", { source: this }); if (this.defaultRenderingQueue) { this.update(); } }).catch(reason => { console.error("Unable to initialize viewer", reason); }); } setPageLabels(labels) { if (!this.pdfDocument) { return; } if (!labels) { this._pageLabels = null; } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { this._pageLabels = null; console.error(`setPageLabels: Invalid page labels.`); } else { this._pageLabels = labels; } for (let i = 0, ii = this._pages.length; i < ii; i++) { this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); } } _resetView() { this._pages = []; this._currentPageNumber = 1; this._currentScale = _ui_utils.UNKNOWN_SCALE; this._currentScaleValue = null; this._pageLabels = null; this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); this._location = null; this._pagesRotation = 0; this._optionalContentConfigPromise = null; this._pagesRequests = new WeakMap(); this._firstPageCapability = (0, _pdfjsLib.createPromiseCapability)(); this._onePageRenderedCapability = (0, _pdfjsLib.createPromiseCapability)(); this._pagesCapability = (0, _pdfjsLib.createPromiseCapability)(); this._scrollMode = _ui_utils.ScrollMode.VERTICAL; this._spreadMode = _ui_utils.SpreadMode.NONE; if (this._onBeforeDraw) { this.eventBus._off("pagerender", this._onBeforeDraw); this._onBeforeDraw = null; } if (this._onAfterDraw) { this.eventBus._off("pagerendered", this._onAfterDraw); this._onAfterDraw = null; } this.viewer.textContent = ""; this._updateScrollMode(); } _scrollUpdate() { if (this.pagesCount === 0) { return; } this.update(); } _scrollIntoView({ pageDiv, pageSpot = null, pageNumber = null }) { (0, _ui_utils.scrollIntoView)(pageDiv, pageSpot); } _setScaleUpdatePages(newScale, newValue, noScroll = false, preset = false) { this._currentScaleValue = newValue.toString(); if (isSameScale(this._currentScale, newScale)) { if (preset) { this.eventBus.dispatch("scalechanging", { source: this, scale: newScale, presetValue: newValue }); } return; } this._doc.style.setProperty("--zoom-factor", newScale); const updateArgs = { scale: newScale }; for (const pageView of this._pages) { pageView.update(updateArgs); } this._currentScale = newScale; if (!noScroll) { let page = this._currentPageNumber, dest; if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { page = this._location.pageNumber; dest = [null, { name: "XYZ" }, this._location.left, this._location.top, null]; } this.scrollPageIntoView({ pageNumber: page, destArray: dest, allowNegativeOffset: true }); } this.eventBus.dispatch("scalechanging", { source: this, scale: newScale, presetValue: preset ? newValue : undefined }); if (this.defaultRenderingQueue) { this.update(); } } get _pageWidthScaleFactor() { if (this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL && !this.isInPresentationMode) { return 2; } return 1; } _setScale(value, noScroll = false) { let scale = parseFloat(value); if (scale > 0) { this._setScaleUpdatePages(scale, value, noScroll, false); } else { const currentPage = this._pages[this._currentPageNumber - 1]; if (!currentPage) { return; } const noPadding = this.isInPresentationMode || this.removePageBorders; let hPadding = noPadding ? 0 : _ui_utils.SCROLLBAR_PADDING; let vPadding = noPadding ? 0 : _ui_utils.VERTICAL_PADDING; if (!noPadding && this._isScrollModeHorizontal) { [hPadding, vPadding] = [vPadding, hPadding]; } const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this._pageWidthScaleFactor; const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; switch (value) { case "page-actual": scale = 1; break; case "page-width": scale = pageWidthScale; break; case "page-height": scale = pageHeightScale; break; case "page-fit": scale = Math.min(pageWidthScale, pageHeightScale); break; case "auto": const horizontalScale = (0, _ui_utils.isPortraitOrientation)(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); scale = Math.min(_ui_utils.MAX_AUTO_SCALE, horizontalScale); break; default: console.error(`_setScale: "${value}" is an unknown zoom value.`); return; } this._setScaleUpdatePages(scale, value, noScroll, true); } } _resetCurrentPageView() { if (this.isInPresentationMode) { this._setScale(this._currentScaleValue, true); } const pageView = this._pages[this._currentPageNumber - 1]; this._scrollIntoView({ pageDiv: pageView.div }); } pageLabelToPageNumber(label) { if (!this._pageLabels) { return null; } const i = this._pageLabels.indexOf(label); if (i < 0) { return null; } return i + 1; } scrollPageIntoView({ pageNumber, destArray = null, allowNegativeOffset = false, ignoreDestinationZoom = false }) { if (!this.pdfDocument) { return; } const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; if (!pageView) { console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); return; } if (this.isInPresentationMode || !destArray) { this._setCurrentPageNumber(pageNumber, true); return; } let x = 0, y = 0; let width = 0, height = 0, widthScale, heightScale; const changeOrientation = pageView.rotation % 180 !== 0; const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; let scale = 0; switch (destArray[1].name) { case "XYZ": x = destArray[2]; y = destArray[3]; scale = destArray[4]; x = x !== null ? x : 0; y = y !== null ? y : pageHeight; break; case "Fit": case "FitB": scale = "page-fit"; break; case "FitH": case "FitBH": y = destArray[2]; scale = "page-width"; if (y === null && this._location) { x = this._location.left; y = this._location.top; } else if (typeof y !== "number") { y = pageHeight; } break; case "FitV": case "FitBV": x = destArray[2]; width = pageWidth; height = pageHeight; scale = "page-height"; break; case "FitR": x = destArray[2]; y = destArray[3]; width = destArray[4] - x; height = destArray[5] - y; const hPadding = this.removePageBorders ? 0 : _ui_utils.SCROLLBAR_PADDING; const vPadding = this.removePageBorders ? 0 : _ui_utils.VERTICAL_PADDING; widthScale = (this.container.clientWidth - hPadding) / width / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; heightScale = (this.container.clientHeight - vPadding) / height / _pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS; scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); break; default: console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); return; } if (!ignoreDestinationZoom) { if (scale && scale !== this._currentScale) { this.currentScaleValue = scale; } else if (this._currentScale === _ui_utils.UNKNOWN_SCALE) { this.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE; } } if (scale === "page-fit" && !destArray[4]) { this._scrollIntoView({ pageDiv: pageView.div, pageNumber }); return; } const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; let left = Math.min(boundingRect[0][0], boundingRect[1][0]); let top = Math.min(boundingRect[0][1], boundingRect[1][1]); if (!allowNegativeOffset) { left = Math.max(left, 0); top = Math.max(top, 0); } this._scrollIntoView({ pageDiv: pageView.div, pageSpot: { left, top }, pageNumber }); } _updateLocation(firstPage) { const currentScale = this._currentScale; const currentScaleValue = this._currentScaleValue; const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; const pageNumber = firstPage.id; let pdfOpenParams = "#page=" + pageNumber; pdfOpenParams += "&zoom=" + normalizedScaleValue; const currentPageView = this._pages[pageNumber - 1]; const container = this.container; const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); const intLeft = Math.round(topLeft[0]); const intTop = Math.round(topLeft[1]); pdfOpenParams += "," + intLeft + "," + intTop; this._location = { pageNumber, scale: normalizedScaleValue, top: intTop, left: intLeft, rotation: this._pagesRotation, pdfOpenParams }; } _updateHelper(visiblePages) { throw new Error("Not implemented: _updateHelper"); } update() { const visible = this._getVisiblePages(); const visiblePages = visible.views, numVisiblePages = visiblePages.length; if (numVisiblePages === 0) { return; } const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); this._buffer.resize(newCacheSize, visiblePages); this.renderingQueue.renderHighestPriority(visible); this._updateHelper(visiblePages); this._updateLocation(visible.first); this.eventBus.dispatch("updateviewarea", { source: this, location: this._location }); } containsElement(element) { return this.container.contains(element); } focus() { this.container.focus(); } get _isScrollModeHorizontal() { return this.isInPresentationMode ? false : this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL; } get _isContainerRtl() { return getComputedStyle(this.container).direction === "rtl"; } get isInPresentationMode() { return this.presentationModeState === _ui_utils.PresentationModeState.FULLSCREEN; } get isChangingPresentationMode() { return this.presentationModeState === _ui_utils.PresentationModeState.CHANGING; } get isHorizontalScrollbarEnabled() { return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; } get isVerticalScrollbarEnabled() { return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; } _getCurrentVisiblePage() { if (!this.pagesCount) { return { views: [] }; } const pageView = this._pages[this._currentPageNumber - 1]; const element = pageView.div; const view = { id: pageView.id, x: element.offsetLeft + element.clientLeft, y: element.offsetTop + element.clientTop, view: pageView }; return { first: view, last: view, views: [view] }; } _getVisiblePages() { return (0, _ui_utils.getVisibleElements)({ scrollEl: this.container, views: this._pages, sortByVisibility: true, horizontal: this._isScrollModeHorizontal, rtl: this._isScrollModeHorizontal && this._isContainerRtl }); } isPageVisible(pageNumber) { if (!this.pdfDocument) { return false; } if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { console.error(`isPageVisible: "${pageNumber}" is not a valid page.`); return false; } return this._getVisiblePages().views.some(function (view) { return view.id === pageNumber; }); } isPageCached(pageNumber) { if (!this.pdfDocument || !this._buffer) { return false; } if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { console.error(`isPageCached: "${pageNumber}" is not a valid page.`); return false; } const pageView = this._pages[pageNumber - 1]; if (!pageView) { return false; } return this._buffer.has(pageView); } cleanup() { for (let i = 0, ii = this._pages.length; i < ii; i++) { if (this._pages[i] && this._pages[i].renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) { this._pages[i].reset(); } } } _cancelRendering() { for (let i = 0, ii = this._pages.length; i < ii; i++) { if (this._pages[i]) { this._pages[i].cancelRendering(); } } } _ensurePdfPageLoaded(pageView) { if (pageView.pdfPage) { return Promise.resolve(pageView.pdfPage); } if (this._pagesRequests.has(pageView)) { return this._pagesRequests.get(pageView); } const promise = this.pdfDocument.getPage(pageView.id).then(pdfPage => { if (!pageView.pdfPage) { pageView.setPdfPage(pdfPage); } this._pagesRequests.delete(pageView); return pdfPage; }).catch(reason => { console.error("Unable to get page for page view", reason); this._pagesRequests.delete(pageView); }); this._pagesRequests.set(pageView, promise); return promise; } forceRendering(currentlyVisiblePages) { const visiblePages = currentlyVisiblePages || this._getVisiblePages(); const scrollAhead = this._isScrollModeHorizontal ? this.scroll.right : this.scroll.down; const preRenderExtra = this._scrollMode === _ui_utils.ScrollMode.VERTICAL && this._spreadMode !== _ui_utils.SpreadMode.NONE && !this.isInPresentationMode; const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); if (pageView) { this._ensurePdfPageLoaded(pageView).then(() => { this.renderingQueue.renderView(pageView); }); return true; } return false; } createTextLayerBuilder(textLayerDiv, pageIndex, viewport, enhanceTextSelection = false, eventBus, highlighter) { return new _text_layer_builder.TextLayerBuilder({ textLayerDiv, eventBus, pageIndex, viewport, enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection, highlighter }); } createTextHighlighter(pageIndex, eventBus) { return new _text_highlighter.TextHighlighter({ eventBus, pageIndex, findController: this.isInPresentationMode ? null : this.findController }); } createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderForms = true, l10n = _l10n_utils.NullL10n, enableScripting = null, hasJSActionsPromise = null, mouseState = null, fieldObjectsPromise = null) { return new _annotation_layer_builder.AnnotationLayerBuilder({ pageDiv, pdfPage, annotationStorage: annotationStorage || this.pdfDocument?.annotationStorage, imageResourcesPath, renderForms, linkService: this.linkService, downloadManager: this.downloadManager, l10n, enableScripting: enableScripting ?? this.enableScripting, hasJSActionsPromise: hasJSActionsPromise || this.pdfDocument?.hasJSActions(), fieldObjectsPromise: fieldObjectsPromise || this.pdfDocument?.getFieldObjects(), mouseState: mouseState || this._scriptingManager?.mouseState }); } createXfaLayerBuilder(pageDiv, pdfPage, annotationStorage = null) { return new _xfa_layer_builder.XfaLayerBuilder({ pageDiv, pdfPage, annotationStorage: annotationStorage || this.pdfDocument?.annotationStorage, linkService: this.linkService }); } createStructTreeLayerBuilder(pdfPage) { return new _struct_tree_layer_builder.StructTreeLayerBuilder({ pdfPage }); } get hasEqualPageSizes() { const firstPageView = this._pages[0]; for (let i = 1, ii = this._pages.length; i < ii; ++i) { const pageView = this._pages[i]; if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { return false; } } return true; } getPagesOverview() { return this._pages.map(pageView => { const viewport = pageView.pdfPage.getViewport({ scale: 1 }); if (!this.enablePrintAutoRotate || (0, _ui_utils.isPortraitOrientation)(viewport)) { return { width: viewport.width, height: viewport.height, rotation: viewport.rotation }; } return { width: viewport.height, height: viewport.width, rotation: (viewport.rotation - 90) % 360 }; }); } get optionalContentConfigPromise() { if (!this.pdfDocument) { return Promise.resolve(null); } if (!this._optionalContentConfigPromise) { return this.pdfDocument.getOptionalContentConfig(); } return this._optionalContentConfigPromise; } set optionalContentConfigPromise(promise) { if (!(promise instanceof Promise)) { throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); } if (!this.pdfDocument) { return; } if (!this._optionalContentConfigPromise) { return; } this._optionalContentConfigPromise = promise; const updateArgs = { optionalContentConfigPromise: promise }; for (const pageView of this._pages) { pageView.update(updateArgs); } this.update(); this.eventBus.dispatch("optionalcontentconfigchanged", { source: this, promise }); } get scrollMode() { return this._scrollMode; } set scrollMode(mode) { if (this._scrollMode === mode) { return; } if (!(0, _ui_utils.isValidScrollMode)(mode)) { throw new Error(`Invalid scroll mode: ${mode}`); } this._scrollMode = mode; this.eventBus.dispatch("scrollmodechanged", { source: this, mode }); this._updateScrollMode(this._currentPageNumber); } _updateScrollMode(pageNumber = null) { const scrollMode = this._scrollMode, viewer = this.viewer; viewer.classList.toggle("scrollHorizontal", scrollMode === _ui_utils.ScrollMode.HORIZONTAL); viewer.classList.toggle("scrollWrapped", scrollMode === _ui_utils.ScrollMode.WRAPPED); if (!this.pdfDocument || !pageNumber) { return; } if (this._currentScaleValue && isNaN(this._currentScaleValue)) { this._setScale(this._currentScaleValue, true); } this._setCurrentPageNumber(pageNumber, true); this.update(); } get spreadMode() { return this._spreadMode; } set spreadMode(mode) { if (this._spreadMode === mode) { return; } if (!(0, _ui_utils.isValidSpreadMode)(mode)) { throw new Error(`Invalid spread mode: ${mode}`); } this._spreadMode = mode; this.eventBus.dispatch("spreadmodechanged", { source: this, mode }); this._updateSpreadMode(this._currentPageNumber); } _updateSpreadMode(pageNumber = null) { if (!this.pdfDocument) { return; } const viewer = this.viewer, pages = this._pages; viewer.textContent = ""; if (this._spreadMode === _ui_utils.SpreadMode.NONE) { for (let i = 0, iMax = pages.length; i < iMax; ++i) { viewer.appendChild(pages[i].div); } } else { const parity = this._spreadMode - 1; let spread = null; for (let i = 0, iMax = pages.length; i < iMax; ++i) { if (spread === null) { spread = document.createElement("div"); spread.className = "spread"; viewer.appendChild(spread); } else if (i % 2 === parity) { spread = spread.cloneNode(false); viewer.appendChild(spread); } spread.appendChild(pages[i].div); } } if (!pageNumber) { return; } if (this._currentScaleValue && isNaN(this._currentScaleValue)) { this._setScale(this._currentScaleValue, true); } this._setCurrentPageNumber(pageNumber, true); this.update(); } _getPageAdvance(currentPageNumber, previous = false) { if (this.isInPresentationMode) { return 1; } switch (this._scrollMode) { case _ui_utils.ScrollMode.WRAPPED: { const { views } = this._getVisiblePages(), pageLayout = new Map(); for (const { id, y, percent, widthPercent } of views) { if (percent === 0 || widthPercent < 100) { continue; } let yArray = pageLayout.get(y); if (!yArray) { pageLayout.set(y, yArray ||= []); } yArray.push(id); } for (const yArray of pageLayout.values()) { const currentIndex = yArray.indexOf(currentPageNumber); if (currentIndex === -1) { continue; } const numPages = yArray.length; if (numPages === 1) { break; } if (previous) { for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { const currentId = yArray[i], expectedId = yArray[i + 1] - 1; if (currentId < expectedId) { return currentPageNumber - expectedId; } } } else { for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { const currentId = yArray[i], expectedId = yArray[i - 1] + 1; if (currentId > expectedId) { return expectedId - currentPageNumber; } } } if (previous) { const firstId = yArray[0]; if (firstId < currentPageNumber) { return currentPageNumber - firstId + 1; } } else { const lastId = yArray[numPages - 1]; if (lastId > currentPageNumber) { return lastId - currentPageNumber + 1; } } break; } break; } case _ui_utils.ScrollMode.HORIZONTAL: { break; } case _ui_utils.ScrollMode.VERTICAL: { if (this._spreadMode === _ui_utils.SpreadMode.NONE) { break; } const parity = this._spreadMode - 1; if (previous && currentPageNumber % 2 !== parity) { break; } else if (!previous && currentPageNumber % 2 === parity) { break; } const { views } = this._getVisiblePages(), expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; for (const { id, percent, widthPercent } of views) { if (id !== expectedId) { continue; } if (percent > 0 && widthPercent === 100) { return 2; } break; } break; } } return 1; } nextPage() { const currentPageNumber = this._currentPageNumber, pagesCount = this.pagesCount; if (currentPageNumber >= pagesCount) { return false; } const advance = this._getPageAdvance(currentPageNumber, false) || 1; this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); return true; } previousPage() { const currentPageNumber = this._currentPageNumber; if (currentPageNumber <= 1) { return false; } const advance = this._getPageAdvance(currentPageNumber, true) || 1; this.currentPageNumber = Math.max(currentPageNumber - advance, 1); return true; } increaseScale(steps = 1) { let newScale = this._currentScale; do { newScale = (newScale * _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2); newScale = Math.ceil(newScale * 10) / 10; newScale = Math.min(_ui_utils.MAX_SCALE, newScale); } while (--steps > 0 && newScale < _ui_utils.MAX_SCALE); this.currentScaleValue = newScale; } decreaseScale(steps = 1) { let newScale = this._currentScale; do { newScale = (newScale / _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2); newScale = Math.floor(newScale * 10) / 10; newScale = Math.max(_ui_utils.MIN_SCALE, newScale); } while (--steps > 0 && newScale > _ui_utils.MIN_SCALE); this.currentScaleValue = newScale; } } exports.BaseViewer = BaseViewer; /***/ }), /* 22 */ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TextHighlighter = void 0; class TextHighlighter { constructor({ findController, eventBus, pageIndex }) { this.findController = findController; this.matches = []; this.eventBus = eventBus; this.pageIdx = pageIndex; this._onUpdateTextLayerMatches = null; this.textDivs = null; this.textContentItemsStr = null; this.enabled = false; } setTextMapping(divs, texts) { this.textDivs = divs; this.textContentItemsStr = texts; } enable() { if (!this.textDivs || !this.textContentItemsStr) { throw new Error("Text divs and strings have not been set."); } if (this.enabled) { throw new Error("TextHighlighter is already enabled."); } this.enabled = true; if (!this._onUpdateTextLayerMatches) { this._onUpdateTextLayerMatches = evt => { if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { this._updateMatches(); } }; this.eventBus._on("updatetextlayermatches", this._onUpdateTextLayerMatches); } this._updateMatches(); } disable() { if (!this.enabled) { return; } this.enabled = false; if (this._onUpdateTextLayerMatches) { this.eventBus._off("updatetextlayermatches", this._onUpdateTextLayerMatches); this._onUpdateTextLayerMatches = null; } } _convertMatches(matches, matchesLength) { if (!matches) { return []; } const { textContentItemsStr } = this; let i = 0, iIndex = 0; const end = textContentItemsStr.length - 1; const result = []; for (let m = 0, mm = matches.length; m < mm; m++) { let matchIdx = matches[m]; while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { iIndex += textContentItemsStr[i].length; i++; } if (i === textContentItemsStr.length) { console.error("Could not find a matching mapping"); } const match = { begin: { divIdx: i, offset: matchIdx - iIndex } }; matchIdx += matchesLength[m]; while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { iIndex += textContentItemsStr[i].length; i++; } match.end = { divIdx: i, offset: matchIdx - iIndex }; result.push(match); } return result; } _renderMatches(matches) { if (matches.length === 0) { return; } const { findController, pageIdx } = this; const { textContentItemsStr, textDivs } = this; const isSelectedPage = pageIdx === findController.selected.pageIdx; const selectedMatchIdx = findController.selected.matchIdx; const highlightAll = findController.state.highlightAll; let prevEnd = null; const infinity = { divIdx: -1, offset: undefined }; function beginText(begin, className) { const divIdx = begin.divIdx; textDivs[divIdx].textContent = ""; return appendTextToDiv(divIdx, 0, begin.offset, className); } function appendTextToDiv(divIdx, fromOffset, toOffset, className) { let div = textDivs[divIdx]; if (div.nodeType === Node.TEXT_NODE) { const span = document.createElement("span"); div.parentNode.insertBefore(span, div); span.appendChild(div); textDivs[divIdx] = span; div = span; } const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); const node = document.createTextNode(content); if (className) { const span = document.createElement("span"); span.className = `${className} appended`; span.appendChild(node); div.appendChild(span); return className.includes("selected") ? span.offsetLeft : 0; } div.appendChild(node); return 0; } let i0 = selectedMatchIdx, i1 = i0 + 1; if (highlightAll) { i0 = 0; i1 = matches.length; } else if (!isSelectedPage) { return; } for (let i = i0; i < i1; i++) { const match = matches[i]; const begin = match.begin; const end = match.end; const isSelected = isSelectedPage && i === selectedMatchIdx; const highlightSuffix = isSelected ? " selected" : ""; let selectedLeft = 0; if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { if (prevEnd !== null) { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); } beginText(begin); } else { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); } if (begin.divIdx === end.divIdx) { selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); } else { selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { textDivs[n0].className = "highlight middle" + highlightSuffix; } beginText(end, "highlight end" + highlightSuffix); } prevEnd = end; if (isSelected) { findController.scrollMatchIntoView({ element: textDivs[begin.divIdx], selectedLeft, pageIndex: pageIdx, matchIndex: selectedMatchIdx }); } } if (prevEnd) { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); } } _updateMatches() { if (!this.enabled) { return; } const { findController, matches, pageIdx } = this; const { textContentItemsStr, textDivs } = this; let clearedUntilDivIdx = -1; for (let i = 0, ii = matches.length; i < ii; i++) { const match = matches[i]; const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); for (let n = begin, end = match.end.divIdx; n <= end; n++) { const div = textDivs[n]; div.textContent = textContentItemsStr[n]; div.className = ""; } clearedUntilDivIdx = match.end.divIdx + 1; } if (!findController?.highlightMatches) { return; } const pageMatches = findController.pageMatches[pageIdx] || null; const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; this.matches = this._convertMatches(pageMatches, pageMatchesLength); this._renderMatches(this.matches); } } exports.TextHighlighter = TextHighlighter; /***/ }), /* 23 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFViewer = void 0; var _ui_utils = __w_pdfjs_require__(5); var _base_viewer = __w_pdfjs_require__(21); var _pdfjsLib = __w_pdfjs_require__(2); class PDFViewer extends _base_viewer.BaseViewer { get _viewerElement() { return (0, _pdfjsLib.shadow)(this, "_viewerElement", this.viewer); } _scrollIntoView({ pageDiv, pageSpot = null, pageNumber = null }) { if (!pageSpot && !this.isInPresentationMode) { const left = pageDiv.offsetLeft + pageDiv.clientLeft; const right = left + pageDiv.clientWidth; const { scrollLeft, clientWidth } = this.container; if (this._isScrollModeHorizontal || left < scrollLeft || right > scrollLeft + clientWidth) { pageSpot = { left: 0, top: 0 }; } } super._scrollIntoView({ pageDiv, pageSpot, pageNumber }); } _getVisiblePages() { if (this.isInPresentationMode) { return this._getCurrentVisiblePage(); } return super._getVisiblePages(); } _updateHelper(visiblePages) { if (this.isInPresentationMode) { return; } let currentId = this._currentPageNumber; let stillFullyVisible = false; for (const page of visiblePages) { if (page.percent < 100) { break; } if (page.id === currentId && this._scrollMode === _ui_utils.ScrollMode.VERTICAL && this._spreadMode === _ui_utils.SpreadMode.NONE) { stillFullyVisible = true; break; } } if (!stillFullyVisible) { currentId = visiblePages[0].id; } this._setCurrentPageNumber(currentId); } } exports.PDFViewer = PDFViewer; /***/ }) /******/ ]); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __w_pdfjs_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { var exports = __webpack_exports__; Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "AnnotationLayerBuilder", ({ enumerable: true, get: function () { return _annotation_layer_builder.AnnotationLayerBuilder; } })); Object.defineProperty(exports, "DefaultAnnotationLayerFactory", ({ enumerable: true, get: function () { return _annotation_layer_builder.DefaultAnnotationLayerFactory; } })); Object.defineProperty(exports, "DefaultStructTreeLayerFactory", ({ enumerable: true, get: function () { return _struct_tree_layer_builder.DefaultStructTreeLayerFactory; } })); Object.defineProperty(exports, "StructTreeLayerBuilder", ({ enumerable: true, get: function () { return _struct_tree_layer_builder.StructTreeLayerBuilder; } })); Object.defineProperty(exports, "DefaultTextLayerFactory", ({ enumerable: true, get: function () { return _text_layer_builder.DefaultTextLayerFactory; } })); Object.defineProperty(exports, "TextLayerBuilder", ({ enumerable: true, get: function () { return _text_layer_builder.TextLayerBuilder; } })); Object.defineProperty(exports, "DefaultXfaLayerFactory", ({ enumerable: true, get: function () { return _xfa_layer_builder.DefaultXfaLayerFactory; } })); Object.defineProperty(exports, "XfaLayerBuilder", ({ enumerable: true, get: function () { return _xfa_layer_builder.XfaLayerBuilder; } })); Object.defineProperty(exports, "EventBus", ({ enumerable: true, get: function () { return _ui_utils.EventBus; } })); Object.defineProperty(exports, "ProgressBar", ({ enumerable: true, get: function () { return _ui_utils.ProgressBar; } })); Object.defineProperty(exports, "PDFLinkService", ({ enumerable: true, get: function () { return _pdf_link_service.PDFLinkService; } })); Object.defineProperty(exports, "SimpleLinkService", ({ enumerable: true, get: function () { return _pdf_link_service.SimpleLinkService; } })); Object.defineProperty(exports, "DownloadManager", ({ enumerable: true, get: function () { return _download_manager.DownloadManager; } })); Object.defineProperty(exports, "GenericL10n", ({ enumerable: true, get: function () { return _genericl10n.GenericL10n; } })); Object.defineProperty(exports, "NullL10n", ({ enumerable: true, get: function () { return _l10n_utils.NullL10n; } })); Object.defineProperty(exports, "PDFFindController", ({ enumerable: true, get: function () { return _pdf_find_controller.PDFFindController; } })); Object.defineProperty(exports, "PDFHistory", ({ enumerable: true, get: function () { return _pdf_history.PDFHistory; } })); Object.defineProperty(exports, "PDFPageView", ({ enumerable: true, get: function () { return _pdf_page_view.PDFPageView; } })); Object.defineProperty(exports, "PDFScriptingManager", ({ enumerable: true, get: function () { return _pdf_scripting_manager.PDFScriptingManager; } })); Object.defineProperty(exports, "PDFSinglePageViewer", ({ enumerable: true, get: function () { return _pdf_single_page_viewer.PDFSinglePageViewer; } })); Object.defineProperty(exports, "PDFViewer", ({ enumerable: true, get: function () { return _pdf_viewer.PDFViewer; } })); var _annotation_layer_builder = __w_pdfjs_require__(1); var _struct_tree_layer_builder = __w_pdfjs_require__(6); var _text_layer_builder = __w_pdfjs_require__(7); var _xfa_layer_builder = __w_pdfjs_require__(8); var _ui_utils = __w_pdfjs_require__(5); var _pdf_link_service = __w_pdfjs_require__(4); var _download_manager = __w_pdfjs_require__(9); var _genericl10n = __w_pdfjs_require__(11); var _l10n_utils = __w_pdfjs_require__(3); var _pdf_find_controller = __w_pdfjs_require__(13); var _pdf_history = __w_pdfjs_require__(15); var _pdf_page_view = __w_pdfjs_require__(16); var _pdf_scripting_manager = __w_pdfjs_require__(18); var _pdf_single_page_viewer = __w_pdfjs_require__(20); var _pdf_viewer = __w_pdfjs_require__(23); const pdfjsVersion = '2.11.338'; const pdfjsBuild = 'dedff3c98'; })(); /******/ return __webpack_exports__; /******/ })() ; }); //# sourceMappingURL=pdf_viewer.js.map
"use strict"; //importing dependencies var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = __importDefault(require("express")); const http = __importStar(require("http")); const winston = __importStar(require("winston")); const expressWinston = __importStar(require("express-winston")); const cors_1 = __importDefault(require("cors")); const users_routes_config_1 = require("./users/users.routes.config"); const debug_1 = __importDefault(require("debug")); //variable declaration const app = express_1.default(); const server = http.createServer(app); const port = process.env.PORT || 3000; const routes = []; const debugLog = debug_1.default('app'); //here we are adding middleware to parse all incoming requests as JSON app.use(express_1.default.json()); //here we are adding middleware to allow cross-origin requests app.use(cors_1.default()); //here we are preparing the expressWinston logging middleware //configurationo //which will automatically log all HTTP requests handled by Express.js const loggerOption = { transports: [new winston.transports.Console()], format: winston.format.combine(winston.format.json(), winston.format.prettyPrint(), winston.format.colorize({ all: true })), }; if (!process.env.DEBUG) { loggerOption.meta = false; // when not debugging , log requests as one liners } // initializes the logger with above configuration app.use(expressWinston.logger(loggerOption)); //here we are adding the UserRoutes to our array, //after sending the express.js application object to have the routes // added to our app routes.push(new users_routes_config_1.UserRoutes(app)); //this is a simple route to make sure everything is working properly const runningMessage = 'Serving running at http://localhost: ${port}'; app.get('/', (req, res) => { res.status(200).send(runningMessage); }); server.listen(port, () => { routes.forEach((route) => { debugLog("Route configured for ${route.getName()}"); }); //our only exception to avoiding console.log() , because we // always want to know when server is done starting up console.log(runningMessage); });
/*! * froala_editor v2.8.4 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2018 Froala Labs */ !function(n){"function"==typeof define&&define.amd?define(["jquery"],n):"object"==typeof module&&module.exports?module.exports=function(e,t){return t===undefined&&(t="undefined"!=typeof window?require("jquery"):require("jquery")(e)),n(t)}:n(window.jQuery)}(function(i){i.FE.PLUGINS.quote=function(o){function r(e){for(;e.parentNode&&e.parentNode!=o.el;)e=e.parentNode;return e}return{apply:function(e){o.selection.save(),o.html.wrap(!0,!0,!0,!0),o.selection.restore(),"increase"==e?function(){var e,t=o.selection.blocks();for(e=0;e<t.length;e++)t[e]=r(t[e]);o.selection.save();var n=i("<blockquote>");for(n.insertBefore(t[0]),e=0;e<t.length;e++)n.append(t[e]);o.html.unwrap(),o.selection.restore()}():"decrease"==e&&function(){var e,t=o.selection.blocks();for(e=0;e<t.length;e++)"BLOCKQUOTE"!=t[e].tagName&&(t[e]=i(t[e]).parentsUntil(o.$el,"BLOCKQUOTE").get(0));for(o.selection.save(),e=0;e<t.length;e++)t[e]&&i(t[e]).replaceWith(t[e].innerHTML);o.html.unwrap(),o.selection.restore()}()}}},i.FE.RegisterShortcut(i.FE.KEYCODE.SINGLE_QUOTE,"quote","increase","'"),i.FE.RegisterShortcut(i.FE.KEYCODE.SINGLE_QUOTE,"quote","decrease","'",!0),i.FE.RegisterCommand("quote",{title:"Quote",type:"dropdown",options:{increase:"Increase",decrease:"Decrease"},callback:function(e,t){this.quote.apply(t)},plugin:"quote"}),i.FE.DefineIcon("quote",{NAME:"quote-left"})});
import jQuery from 'jquery'; import angular from 'angular'; import _datePicker from 'jquery-ui/datepicker'; // sets up jQuery with the datepicker plugin export default angular.module('ui.date', []) .constant('uiDateConfig', {}) .constant('uiDateFormatConfig', '') .factory('uiDateConverter', ['uiDateFormatConfig', function(uiDateFormatConfig) { return { stringToDate: stringToDate, dateToString: dateToString, }; //https://github.com/angular/angular.js/blob/622c42169699ec07fc6daaa19fe6d224e5d2f70e/src/Angular.js#L1207 function timezoneToOffset(timezone, fallback) { timezone = timezone.replace(/:/g, ''); var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; } function addDateMinutes(date, minutes) { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + minutes); return date; } function convertTimezoneToLocal(date, timezone, reverse) { reverse = reverse ? -1 : 1; var dateTimezoneOffset = date.getTimezoneOffset(); var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset)); } function doTZ(date,timezone,reverse) { return timezone ? convertTimezoneToLocal(date, timezone, reverse) : date; } function dateToString(uiDateFormat, value) { var dateFormat = uiDateFormat || uiDateFormatConfig; if (value) { if (dateFormat) { try { return jQuery.datepicker.formatDate(dateFormat, value); } catch (formatException) { return undefined; } } if (value.toISOString) { return value.toISOString(); } } return null; } function stringToDate(dateFormat, valueToParse, timezone) { dateFormat = dateFormat || uiDateFormatConfig; if (angular.isDate(valueToParse) && !isNaN(valueToParse)) { return doTZ(valueToParse, timezone); } if (angular.isString(valueToParse)) { if (dateFormat) { return doTZ(jQuery.datepicker.parseDate(dateFormat, valueToParse), timezone); } var isoDate = new Date(valueToParse); return isNaN(isoDate.getTime()) ? null : doTZ(isoDate, timezone); } if (angular.isNumber(valueToParse)) { // presumably timestamp to date object return doTZ(new Date(valueToParse), timezone); } return null; } }]) .directive('uiDate', ['uiDateConfig', 'uiDateConverter', function uiDateDirective(uiDateConfig, uiDateConverter) { return { require: '?ngModel', link: function link(scope, element, attrs, controller) { var $element = jQuery(element); var getOptions = function() { return angular.extend({}, uiDateConfig, scope.$eval(attrs.uiDate)); }; var initDateWidget = function() { var showing = false; var opts = getOptions(); var timezone = controller ? controller.$options.getOption('timezone') : null; function setVal(forcedUpdate) { var keys = ['Hours', 'Minutes', 'Seconds', 'Milliseconds']; var isDate = angular.isDate(controller.$modelValue); var preserve = {}; if (!forcedUpdate && isDate && controller.$modelValue.toDateString() === $element.datepicker('getDate').toDateString()) { return; } if (isDate) { angular.forEach(keys, function(key) { preserve[key] = controller.$modelValue['get' + key](); }); } var newViewValue = $element.datepicker('getDate'); if (isDate) { angular.forEach(keys, (key) => { newViewValue['set' + key](preserve[key]); }); } controller.$setViewValue(newViewValue); } // If we have a controller (i.e. ngModelController) then wire it up if (controller) { // Set the view value in a $apply block when users selects // (calling directive user's function too if provided) var _onSelect = opts.onSelect || angular.noop; opts.onSelect = function(value, picker) { scope.$apply(function() { showing = true; setVal(); $element.blur(); _onSelect(value, picker, $element); }); }; var _beforeShow = opts.beforeShow || angular.noop; opts.beforeShow = function(input, picker) { showing = true; _beforeShow(input, picker, $element); }; var _onClose = opts.onClose || angular.noop; opts.onClose = function(value, picker) { showing = false; _onClose(value, picker, $element); }; element.on('focus', function(focusEvent) { if (attrs.readonly) { focusEvent.stopImmediatePropagation(); } }); $element.off('blur.datepicker').on('blur.datepicker', function() { if (!showing) { scope.$apply(function() { $element.datepicker('setDate', $element.datepicker('getDate')); setVal(); }); } }); controller.$validators.uiDateValidator = function uiDateValidator(modelValue, viewValue) { return viewValue === null || viewValue === '' || angular.isDate(uiDateConverter.stringToDate(attrs.uiDateFormat, viewValue)); }; controller.$parsers.push(function uiDateParser(valueToParse) { return uiDateConverter.stringToDate(attrs.uiDateFormat, valueToParse, timezone); }); // Update the date picker when the model changes controller.$render = function() { // Force a render to override whatever is in the input text box if (angular.isDate(controller.$modelValue) === false && angular.isString(controller.$modelValue)) { controller.$modelValue = uiDateConverter.stringToDate(attrs.uiDateFormat, controller.$modelValue, timezone); } $element.datepicker('setDate', controller.$modelValue); }; } // Check if the $element already has a datepicker. // if ($element.data('datepicker')) { // Updates the datepicker options $element.datepicker('option', opts); $element.datepicker('refresh'); } else { // Creates the new datepicker widget $element.datepicker(opts); // Cleanup on destroy, prevent memory leaking $element.on('$destroy', function() { $element.datepicker('hide'); $element.datepicker('destroy'); }); } if (controller) { controller.$render(); // Update the model with the value from the datepicker after parsed setVal(true); } }; // Watch for changes to the directives options scope.$watch(getOptions, initDateWidget, true); }, }; }]) .directive('uiDateFormat', ['uiDateConverter', function(uiDateConverter) { return { require: 'ngModel', link: function(scope, element, attrs, modelCtrl) { var dateFormat = attrs.uiDateFormat; // Use the datepicker with the attribute value as the dateFormat string to convert to and from a string modelCtrl.$formatters.unshift(function(value) { return uiDateConverter.stringToDate(dateFormat, value); }); modelCtrl.$parsers.push(function(value) { return uiDateConverter.dateToString(dateFormat, value); }); }, }; }]);
// import { take, call, put, select } from 'redux-saga/effects'; // Individual exports for testing export default function* notificationsSaga() { // See example in containers/HomePage/saga.js }
import React, { Component } from 'react'; import Day from './Day'; import uuid from 'uuid/v4'; import s from './Calendar.module.scss'; import moment from 'moment/moment'; class Week extends Component { render() { let days = []; let date = this.props.previousCurrentNextView; const { selectedMonthEvents, selected, currentMonthView } = this.props; for (var i = 0; i < 7; i++) { let dayHasEvents = false, title = '', info = '', itemStyle = '', link = ''; for (var j = 0; j < selectedMonthEvents.length; j++) { if (moment(selectedMonthEvents[j].date).isSame(date, 'day')) { dayHasEvents = true; title = selectedMonthEvents[j].title ? selectedMonthEvents[j].title : ''; info = selectedMonthEvents[j].info ? selectedMonthEvents[j].info : ''; itemStyle = selectedMonthEvents[j].itemStyle ? selectedMonthEvents[j].itemStyle : ''; link = selectedMonthEvents[j].link ? selectedMonthEvents[j].link : ''; } } let day = { name: date.format('dd').substring(0, 1), number: date.date(), isCurrentMonth: date.month() === currentMonthView.month(), isToday: date.isSame(new Date(), 'day'), date: date, hasEvents: dayHasEvents, title: title, info: info, itemStyle: itemStyle, link: link, }; days.push(<Day key={uuid()} day={day} selected={selected} />); date = date.clone(); date.add(1, 'd'); } return <div className={`${s.calendarRow} ${s.week}`}>{days}</div>; } } export default Week;
var CHROME_HELPER_EXTENSION_ID = "fhejmeojlbhfhjndnkkleooeejklmigi"; // Chrome var EDGE_HELPER_EXTENSION_ID = "okkjnfohglnomdbpimkcdkiojbeiedof"; // Edge var extension_available = false; var region = 'us-east-1'; var output_objects = []; var _AWS = AWS; var visited_sections = []; var ping_extension_interval = null; var stack_parameters = []; var MAX_DT_SCANS = 50; var defaultoutput = 'cloudformation'; var iaclangselect = 'typescript'; var check_objects = []; var CLI = false; var CONCURRENT_SDKCALLS = 0; $(document).ready(function(){ /* ========================================================================== */ // Section Templating /* ========================================================================== */ function nav(str) { return str.replace(/\s/g, "").replace(/\,/g, "").replace(/\-/g, "").replace(/\&amp\;/g, "And"); } function navlower(str) { return str.toLowerCase().replace(/\s/g, "").replace(/\,/g, "").replace(/\-/g, "").replace(/\&amp\;/g, "and"); } sections.forEach(section => { var html = ` <div id="section-${navlower(section.category)}-${navlower(section.service)}" class="former2-section" data-section-breadcrumb1-title="${section.category}" data-section-breadcrumb1-link="#section-${navlower(section.category)}-${navlower(section.service)}" data-section-title="${section.service}" style="display: none;"> <section class="tabs-section"> <div class="tabs-section-nav tabs-section-nav-inline"> <ul class="nav" role="tablist"> ${Object.keys(section.resourcetypes).map((resourcetype, i) => ` <li class="nav-item"> <a class="nav-link${i==0 ? " active" : ""}" href="#section-${navlower(section.category)}-${navlower(section.service)}-tab-${i}" role="tab" data-toggle="tab"> ${resourcetype} </a> </li> `).join('\n')} </ul> </div> <div class="tab-content"> ${Object.keys(section.resourcetypes).map((resourcetype, i) => ` <div role="tabpanel" class="tab-pane fade${i==0 ? " in active show" : ""}" id="section-${navlower(section.category)}-${navlower(section.service)}-tab-${i}"> <div id="section-${navlower(section.category)}-${navlower(section.service)}-${navlower(resourcetype)}-toolbar" class="f2toolbar"> <button class="additems btn btn-primary" data-datatable="section-${navlower(section.category)}-${navlower(section.service)}-${navlower(resourcetype)}-datatable" disabled> <i class="font-icon font-icon-plus"></i> Add Selected </button> ${section.resourcetypes[resourcetype].terraformonly ? `<span style="margin-left: 16px; display: inline-block; vertical-align: middle; line-height: 16px; color: #6c7a86; font-weight: 600;"><i class="fa fa-info-circle"></i> Terraform / Pulumi only</span>` : ""} ${section.resourcetypes[resourcetype].limitedresults ? `<span style="margin-left: 16px; display: inline-block; vertical-align: middle; line-height: 16px; color: #6c7a86; font-weight: 600;"><i class="fa fa-info-circle"></i> Limited results</span>` : ""} </div> <div class="table-responsive"> <table id="section-${navlower(section.category)}-${navlower(section.service)}-${navlower(resourcetype)}-datatable" class="table table-striped f2datatable" data-toolbar="#section-${navlower(section.category)}-${navlower(section.service)}-${navlower(resourcetype)}-toolbar" data-search="true" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-show-export="true" data-detail-view="true" data-detail-formatter="detailFormatter" data-minimum-count-columns="2" data-show-pagination-switch="true" data-pagination="true" data-id-field="id" data-page-size="All" data-page-list="[10, 25, 50, 100, ALL]" data-show-footer="false" data-response-handler="responseHandler"> </table> </div> </div> `).join('\n')} </div> </section> </div> `; $('#templated-section-container').append(html); Object.keys(section.resourcetypes).forEach(resourcetype => { $(`#section-${navlower(section.category)}-${navlower(section.service)}-${navlower(resourcetype)}-datatable`).on('refresh.bs.table', window[`updateDatatable${nav(section.category)}${nav(section.service)}`]); }); }); /* ========================================================================== */ // DataTable Pre-Config /* ========================================================================== */ output_objects = []; window.operateEvents = { 'click .like': function (e, value, row, index) { ; } // just an example, use later }; function addAllTableRowsToTemplate(selector) { var ids = $.map($(selector).deferredBootstrapTable('getData'), function (row) { output_objects.push({ 'id': row.f2id, 'type': row.f2type, 'data': row.f2data, 'region': row.f2region }); return row.f2id; }); $('#generate-outputs').text("Generate (" + output_objects.length + ")"); $('#generate-outputs').removeAttr('disabled'); return ids; } function getRelationshipPropertyValues(relation, obj, propertyname) { var propertyvalues = []; if (relation['Arity'] == "Many") { if (Array.isArray(obj.options.cfn[propertyname])) { obj.options.cfn[propertyname].forEach(propertyvalue => { if (relation['EmbeddedPropertyName'] && typeof propertyvalue == "object") { propertyvalue = propertyvalue[relation['EmbeddedPropertyName']]; } if (Array.isArray(propertyvalue)) { propertyvalue.forEach(propertyvalueitem => { propertyvalues.push(propertyvalueitem); }); } else { propertyvalues.push(propertyvalue); } }); } else { var propertyvalue = obj.options.cfn[propertyname]; if (relation['EmbeddedPropertyName'] && typeof propertyvalue == "object") { propertyvalue = propertyvalue[relation['EmbeddedPropertyName']]; } if (Array.isArray(propertyvalue)) { propertyvalue.forEach(propertyvalueitem => { propertyvalues.push(propertyvalueitem); }); } else { propertyvalues.push(propertyvalue); } } } else { var propertyvalue = obj.options.cfn[propertyname]; if (relation['EmbeddedPropertyName'] && typeof propertyvalue == "object") { propertyvalue = propertyvalue[relation['EmbeddedPropertyName']]; } propertyvalues.push(propertyvalue); } return propertyvalues; } function checkRelatedResources(rows) { // TODO: make this function more generic (too much duplication) check_objects = []; var related_resources = {}; var related_resources_post = {}; $('.f2datatable').each(function() { var datatableid = this.id; var ids = $.map($("#" + this.id).deferredBootstrapTable('getData'), function (checkobjectrow) { check_objects.push({ 'id': checkobjectrow.f2id, 'type': checkobjectrow.f2type, 'data': checkobjectrow.f2data, 'region': checkobjectrow.f2region, 'datatableid': datatableid }); return checkobjectrow.f2id; }); }); mapped_check_objects = performF2Mappings(check_objects); check_objects = []; mapped_check_objects.forEach(obj => { rows.forEach(row => { // looks for relationships from the row to the check objects if (obj.obj.id == row.f2id && obj.type && RELATIONSHIP_TYPE_MAP[obj.type] && RELATIONSHIP_TYPE_MAP[obj.type]['Relationships']) { var relationships = RELATIONSHIP_TYPE_MAP[obj.type]['Relationships']; Object.keys(relationships).forEach(relationshiptype => { var readable_relationship_type = relationshiptype; if (relationshiptype == "IsContainedInside") { readable_relationship_type = "Is Contained Inside"; } else if (relationshiptype == "Uses") { readable_relationship_type = "Uses"; } else if (relationshiptype == "IsAssociatedWith") { readable_relationship_type = "Is Associated With"; } else if (relationshiptype == "References") { readable_relationship_type = "References"; } else { f2log("Unknown relationship type"); readable_relationship_type = "Related To"; } Object.keys(relationships[relationshiptype]).forEach(relatedresourcetype => { if (!Array.isArray(relationships[relationshiptype][relatedresourcetype])) { relationships[relationshiptype][relatedresourcetype] = [ relationships[relationshiptype][relatedresourcetype] ]; // always in array } relationships[relationshiptype][relatedresourcetype].forEach(relation => { var propertyname = relation['PropertyName']; if (propertyname && obj.options.cfn[propertyname]) { var propertyvalues = getRelationshipPropertyValues(relation, obj, propertyname); propertyvalues.forEach(propertyvalue => { mapped_check_objects.forEach(child_obj => { if (child_obj.obj.id != obj.obj.id && child_obj.type == relatedresourcetype && JSON.stringify(child_obj.obj.data).includes(propertyvalue)) { var is_duplicate = false; if (!Array.isArray(related_resources[readable_relationship_type])) { related_resources[readable_relationship_type] = []; } for (var related_resource in related_resources[readable_relationship_type]) { // check if already added if (related_resources[readable_relationship_type][related_resource].obj.id == child_obj.obj.id) { is_duplicate = true; } }; if (!is_duplicate) { related_resources[readable_relationship_type].push(child_obj); } } }); }); } }); }); }); } }); // looks for relationships from the check objects to the row if (obj.type && RELATIONSHIP_TYPE_MAP[obj.type] && RELATIONSHIP_TYPE_MAP[obj.type]['Relationships']) { var relationships = RELATIONSHIP_TYPE_MAP[obj.type]['Relationships']; Object.keys(relationships).forEach(relationshiptype => { var readable_relationship_type = relationshiptype; // inverted if (relationshiptype == "IsContainedInside") { readable_relationship_type = "Contains"; } else if (relationshiptype == "Uses") { readable_relationship_type = "Is Used By"; } else if (relationshiptype == "IsAssociatedWith") { readable_relationship_type = "Is Associated With"; } else if (relationshiptype == "References") { readable_relationship_type = "Is Referenced By"; } else { f2log("Unknown relationship type"); readable_relationship_type = "Related To"; } Object.keys(relationships[relationshiptype]).forEach(relatedresourcetype => { if (!Array.isArray(relationships[relationshiptype][relatedresourcetype])) { relationships[relationshiptype][relatedresourcetype] = [ relationships[relationshiptype][relatedresourcetype] ]; // always in array } relationships[relationshiptype][relatedresourcetype].forEach(relation => { var propertyname = relation['PropertyName']; if (propertyname && obj.options.cfn[propertyname]) { var propertyvalues = getRelationshipPropertyValues(relation, obj, propertyname); propertyvalues.forEach(propertyvalue => { rows.forEach(row => { var row_check_object = null; for (var child_obj of mapped_check_objects) { if (child_obj.obj.id == row.f2id) { row_check_object = child_obj; break; } }; if (row.f2id != obj.obj.id && row_check_object.type == relatedresourcetype && JSON.stringify(row_check_object.obj.data).includes(propertyvalue)) { var is_duplicate = false; if (!Array.isArray(related_resources_post[readable_relationship_type])) { related_resources_post[readable_relationship_type] = []; } for (var related_resource in related_resources_post[readable_relationship_type]) { // check if already added if (related_resources_post[readable_relationship_type][related_resource].obj.id == obj.obj.id) { is_duplicate = true; } }; if (!is_duplicate) { related_resources_post[readable_relationship_type].push(obj); } } }); }); } }); }); }); } }); // check for related row overlaps // TODO: include added resources here to rows? rows.forEach(row => { Object.keys(related_resources).forEach(restype => { for (var i=0; i<related_resources[restype].length; i++) { if (related_resources[restype][i].obj.id == row.f2id) { related_resources[restype].splice(i, 1); i--; } }; if (related_resources[restype].length < 1) { delete related_resources[restype]; } }); Object.keys(related_resources_post).forEach(restype => { for (var i=0; i<related_resources_post[restype].length; i++) { if (related_resources_post[restype][i].obj.id == row.f2id) { related_resources_post[restype].splice(i, 1); i--; } }; if (related_resources_post[restype].length < 1) { delete related_resources_post[restype]; } }); }); // create modal if related resources exist if (Object.keys(related_resources).length || Object.keys(related_resources_post).length) { var html = ''; var i = 1; Object.keys(related_resources).forEach(restype => { html += `<h5>${restype}</h5> <p> ${related_resources[restype].map(res => ` <div class="checkbox"> <input type="checkbox" id="related-check-${i}" class="related-check" data-f2id="${res.obj.id}" data-dt="${res.obj.datatableid}" data-splicelocation="${res.splicelocation}" data-post="false" checked=""> <label for="related-check-${i++}">${res.obj.id} (${res.type})</label> </div> `).join('')} </p>`; }); Object.keys(related_resources_post).forEach(restype => { html += `<h5>${restype}</h5> <p> ${related_resources_post[restype].map(res => ` <div class="checkbox"> <input type="checkbox" id="related-check-${i}" class="related-check" data-f2id="${res.obj.id}" data-dt="${res.obj.datatableid}" data-splicelocation="${res.splicelocation}" data-post="true" checked=""> <label for="related-check-${i++}">${res.obj.id} (${res.type})</label> </div> `).join('')} </p>`; }); $('#relatedresources').html(html); $('#add-related-selectall').prop('checked', true); $('#relatedmodal').modal('show'); } $("#add-related-selectall").off('click').on('click', function(){ $(".related-check").prop("checked",$("#add-related-selectall").is(":checked")); }); $('#related-add-selected-button').off('click').on('click', function(){ $('.related-check').each(function(i){ var check_element = $(this); if (check_element.is(':checked')) { $.map($("#" + check_element.attr('data-dt')).deferredBootstrapTable('getData'), function (row) { if (row.f2id == check_element.attr('data-f2id')) { var exists = false; output_objects.forEach(output_object => { // check if already added if (output_object.id == row.f2id && output_object.region == row.f2region && output_object.type == row.f2type) { exists = true; } }); if (exists) return null; if (check_element.attr('data-post') == "true") { output_objects.push({ 'id': row.f2id, 'type': row.f2type, 'data': row.f2data, 'region': row.f2region }); } else { output_objects.unshift({ 'id': row.f2id, 'type': row.f2type, 'data': row.f2data, 'region': row.f2region }); } } }); } }); $('#relatedmodal').modal('hide'); $('#generate-outputs').text("Generate (" + output_objects.length + ")"); $('#generate-outputs').removeAttr('disabled'); }); } function addSelectedRowsToTemplate(selector) { var ids = $.map($(selector).bootstrapTable('getSelections'), function (row) { var exists = false; output_objects.forEach(output_object => { // check if already added if (output_object.id == row.f2id && output_object.region == row.f2region && output_object.type == row.f2type) { exists = true; } }); if (exists) return null; output_objects.push({ 'id': row.f2id, 'type': row.f2type, 'data': row.f2data, 'region': row.f2region }); //$(selector).bootstrapTable('refresh'); return row.f2id; }); $('#generate-outputs').text("Generate (" + output_objects.length + ")"); $('#generate-outputs').removeAttr('disabled'); // Check for associated resources if (window.localStorage.getItem('relatedresourcessetting') == "true") { checkRelatedResources($(selector).bootstrapTable('getSelections')); } return ids; } function initDatatableWithColumns(selector, columndata) { $(selector).bootstrapTable({ iconsPrefix: 'font-icon', icons: { paginationSwitchDown:'font-icon-arrow-square-down', paginationSwitchUp: 'font-icon-arrow-square-down up', refresh: 'font-icon-refresh', toggleOn: 'font-icon-list-square', toggleOff: 'font-icon-list-square', columns: 'font-icon-list-rotate', export: 'font-icon-download', detailOpen: 'font-icon-plus', detailClose: 'font-icon-minus-1' }, paginationPreText: '<i class="font-icon font-icon-arrow-left"></i>', paginationNextText: '<i class="font-icon font-icon-arrow-right"></i>', columns: columndata }); } /* ========================================================================== */ // DataTable Initializations /* ========================================================================== */ sections.forEach(section => { Object.keys(section.resourcetypes).forEach(resourcetype => { var selector = "#section-" + navlower(section.category) + "-" + navlower(section.service) + "-" + navlower(resourcetype) + "-datatable"; initDatatableWithColumns(selector, section.resourcetypes[resourcetype].columns); }); }); initDatatableWithColumns('#section-search-datatable', [ [ { field: 'state', checkbox: true, rowspan: 2, align: 'center', valign: 'middle' }, { title: 'Primary ID', field: 'f2id', rowspan: 2, align: 'center', valign: 'middle', sortable: true, footerFormatter: textFormatter }, { title: 'Type', field: 'f2type', sortable: true, footerFormatter: textFormatter, align: 'center' } ], [] ]); /* ========================================================================== */ // DataTable Post-Config /* ========================================================================== */ $('.f2datatable').on('check.bs.table uncheck.bs.table ' + 'check-all.bs.table uncheck-all.bs.table', function () { $('.additems').each(function(index) { $(this).prop('disabled', !$("#" + $(this).attr('data-datatable')).bootstrapTable('getSelections').length); }); }); // Custom checkboxes $('.f2datatable').on('post-body.bs.table', function () { var dtid = $(this).attr('id'); $('#' + dtid + ' :checkbox').each(function () { if (!$(this).parent().hasClass('checkbox')) { if ($(this).attr('data-index')) { var rowid = dtid + "-row-" + $(this).attr('data-index'); $(this).attr('id', rowid); $(this).wrap('<div class="checkbox checkbox-only"></div>').after('<label for="' + rowid + '"></label>'); } } }); // Select All checkboxes $('input[name="btSelectAll"]').each(function () { if (!$(this).parent().hasClass('checkbox')) { var selectallid = $(this).closest(".f2datatable").attr("id") + "-selectallcheck"; $(this).attr('id', selectallid); $(this).wrap('<div class="checkbox checkbox-only"></div>').after('<label for="' + selectallid + '"></label>'); } }); }); $('.additems').click(function () { var ids = addSelectedRowsToTemplate("#" + $(this).attr('data-datatable')); $(this).closest(".table-responsive").find(".f2datatable").bootstrapTable('uncheckAll'); $(this).closest(".table-responsive").find(".f2datatable tr.selected").removeClass('selected'); $(this).prop('disabled', true); }); $('.f2toolbar').find('select').change(function () { // unused $(this).bootstrapTable('refreshOptions', { exportDataType: $(this).val() }); }); /* ========================================================================== */ // Search /* ========================================================================== */ $('#minisearch-form').on('submit', function () { window.location.href = "#section-search"; $('#search-input').val($('#minisearch-input').val()); $('#search-form').submit(); return false; }); $('#search-form').on('submit', function () { $('#section-search-datatable').deferredBootstrapTable('setActive', true); $('#section-search-datatable').deferredBootstrapTable('removeAll'); $('.f2datatable').each(function(index) { if (this.id != "section-search-datatable") { var rows = $(this).deferredBootstrapTable('getData'); rows.forEach(row => { var searchterm = $('#search-input').val(); var jsonrow = JSON.stringify(row); if (searchterm.includes(",")) { searchterm.split(",").forEach(searchterminst => { if (jsonrow.includes(searchterminst)) { $('#section-search-datatable').deferredBootstrapTable('append', [row]); } }); } else { if (jsonrow.includes(searchterm)) { $('#section-search-datatable').deferredBootstrapTable('append', [row]); } } }); } }); $('#search-results').attr('style', ''); $('#search-form').attr('style', 'background: #1873d2;'); return false; }); /* ========================================================================== */ // Credentials /* ========================================================================== */ var accesskey = window.localStorage.getItem('credentials-accesskey'); if (accesskey) { $('#credentials-accesskey').val(accesskey); } var secretkey = window.localStorage.getItem('credentials-secretkey'); if (secretkey) { $('#credentials-secretkey').val(secretkey); } var sessiontoken = window.localStorage.getItem('credentials-sessiontoken'); if (sessiontoken) { $('#credentials-sessiontoken').val(sessiontoken); } var assumerole = window.localStorage.getItem('credentials-assumerole'); if (assumerole) { $('#credentials-assumerole').val(assumerole); } var sourceidentity = window.localStorage.getItem('credentials-sourceidentity'); if (sourceidentity) { $('#credentials-sourceidentity').val(sourceidentity); } $('#credentials-accesskey').on('change', () => { var val = $('#credentials-accesskey').val().trim(); if (val == "") { window.localStorage.removeItem('credentials-accesskey'); } else { window.localStorage.setItem('credentials-accesskey', val); } updateIdentity(); }); $('#credentials-secretkey').on('change', () => { var val = $('#credentials-secretkey').val().trim(); if (val == "") { window.localStorage.removeItem('credentials-secretkey'); $('.scan-account').attr('disabled', 'disabled'); } else { window.localStorage.setItem('credentials-secretkey', val); $('.scan-account').removeAttr('disabled'); } updateIdentity(); }); $('#credentials-sessiontoken').on('change', () => { var val = $('#credentials-sessiontoken').val().trim(); if (val == "") { window.localStorage.removeItem('credentials-sessiontoken'); } else { window.localStorage.setItem('credentials-sessiontoken', val); } updateIdentity(); }); $('#credentials-assumerole').on('change', () => { var val = $('#credentials-assumerole').val().trim(); if (val == "") { window.localStorage.removeItem('credentials-assumerole'); } else { window.localStorage.setItem('credentials-assumerole', val); } updateIdentity(); }); $('#credentials-sourceidentity').on('change', () => { var val = $('#credentials-sourceidentity').val().trim(); if (val == "") { window.localStorage.removeItem('credentials-sourceidentity'); } else { window.localStorage.setItem('credentials-sourceidentity', val); } updateIdentity(); }); /* ========================================================================== */ // Navigation /* ========================================================================== */ function refreshDatatableFirstVisit(urlpart) { sections.forEach(section => { if (urlpart == navlower(section.category) + "-" + navlower(section.service)) { if (!visited_sections.includes(urlpart)) { visited_sections.push(urlpart); $('.f2datatable').each(function() { if (this.id.startsWith("section-" + urlpart + "-")) { $('#' + this.id).deferredBootstrapTable('setActive', true); } }); if (!visited_sections.includes("all")) { window[`updateDatatable${nav(section.category)}${nav(section.service)}`](); } } } }); } function doNavigation() { $('#header-button-copy-cfn').attr('style', 'display: none;'); $('#header-button-import-cfn').attr('style', 'margin-left: 16px; display: none;'); $('#header-button-download-diagram').attr('style', 'display: none;'); $('#header-button-copy-tf').attr('style', 'display: none;'); $('#header-button-copy-troposphere').attr('style', 'display: none;'); $('#header-button-copy-cdk').attr('style', 'display: none;'); $('#header-button-copy-cdktf').attr('style', 'display: none;'); $('#header-button-copy-pulumi').attr('style', 'display: none;'); $('#header-button-copy-raw').attr('style', 'display: none;'); if ($(location.hash).length) { if (location.hash == "#section-dashboard" || location.hash == "#section-search") { $('.section-header').attr('style', 'display: none;'); } else { $('.section-header').removeAttr('style'); } $('li.opened').removeClass('opened'); $('li[data-category=\'' + location.hash.split("-")[1] + '\']').addClass('opened'); $('.former2-section').attr('style', 'display: none;'); $(location.hash).attr('style', 'display: block;'); $('#header-title').html( $(location.hash).attr('data-section-title') ); if ($(location.hash).attr('data-section-label')) { $('#header-title').append( `&nbsp;<h5 style="display: inline;"><span style="vertical-align: super;" class="label label-info">${$(location.hash).attr('data-section-label')}</span></h5>` ); } $('#header-breadcrumb1').text( $(location.hash).attr('data-section-breadcrumb1-title') ); $('#header-breadcrumb1').attr( 'href', $(location.hash).attr('data-section-breadcrumb1-link') ); $('#header-breadcrumb2').text( $(location.hash).attr('data-section-title') ); $('#header-breadcrumb').attr('style', ''); window.scrollTo({ top: 0 }); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px; display: none;'); if (location.hash == "#section-outputs-cloudformation") { $('#header-button-copy-cfn').attr('style', ''); $('#header-button-import-cfn').attr('style', 'margin-left: 16px;'); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); setTimeout(function(){ cfn_editor.refresh(); tippy('.f2replacementmarker', { content: "Value requires replacement", placement: "right", theme: "material" }); }, 1); } else if (location.hash == "#section-outputs-tf") { $('#header-button-copy-tf').attr('style', ''); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); setTimeout(function(){ tf_editor.refresh(); tippy('.f2replacementmarker', { content: "Value requires replacement", placement: "right", theme: "material" }); }, 1); } else if (location.hash == "#section-outputs-troposphere") { $('#header-button-copy-troposphere').attr('style', ''); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); setTimeout(function(){ troposphere_editor.refresh(); tippy('.f2replacementmarker', { content: "Value requires replacement", placement: "right", theme: "material" }); }, 1); } else if (location.hash == "#section-outputs-cdk") { $('#header-button-copy-cdk').attr('style', ''); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); setTimeout(function(){ cdk_editor.refresh(); tippy('.f2replacementmarker', { content: "Value requires replacement", placement: "right", theme: "material" }); }, 1); } else if (location.hash == "#section-outputs-cdktf") { $('#header-button-copy-cdktf').attr('style', ''); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); setTimeout(function(){ cdktf_editor.refresh(); tippy('.f2replacementmarker', { content: "Value requires replacement", placement: "right", theme: "material" }); }, 1); } else if (location.hash == "#section-outputs-pulumi") { $('#header-button-copy-pulumi').attr('style', ''); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); setTimeout(function(){ pulumi_editor.refresh(); tippy('.f2replacementmarker', { content: "Value requires replacement", placement: "right", theme: "material" }); }, 1); } else if (location.hash == "#section-outputs-diagram") { $('#header-button-download-diagram').attr('style', ''); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); } else if (location.hash == "#section-outputs-raw") { $('#header-button-copy-raw').attr('style', ''); $('#header-button-clear-outputs').attr('style', 'margin-left: 16px;'); setTimeout(function(){ raw_editor.refresh(); }, 1); } else if (location.hash.startsWith("#section-")) { // TODO: unset isactive in deferred refreshDatatableFirstVisit(location.hash.substring(9)); } } else if (location.hash != "" && location.hash != "#") { $.notify({ icon: 'font-icon font-icon-warning', title: '<strong>Not Yet Implemented</strong>', message: 'This action is not available at this time.' },{ type: 'warning' }); } else { $('li.opened').removeClass('opened'); if (window.localStorage.getItem('credentials-accesskey')) { // load dashboard $('li[data-category=\'dashboard\']').addClass('opened'); $('.former2-section').attr('style', 'display: none;'); $('#section-dashboard').attr('style', 'display: block;'); $('.section-header').attr('style', 'display: none;'); } else { // load setup $('li[data-category=\'setup\']').addClass('opened'); $('#section-setup-introduction').attr('style', 'display: block;'); $('#header-title').html( $('#section-setup-introduction').attr('data-section-title') ); $('#header-breadcrumb1').text( $('#section-setup-introduction').attr('data-section-breadcrumb1-title') ); $('#header-breadcrumb1').attr( 'href', $('#section-setup-introduction').attr('data-section-breadcrumb1-link') ); $('#header-breadcrumb2').text( $('#section-setup-introduction').attr('data-section-title') ); $('#header-breadcrumb').attr('style', ''); } window.scrollTo({ top: 0 }); } } window.addEventListener("hashchange", () => { doNavigation(); }, false); /* ========================================================================== */ // Outputs /* ========================================================================== */ $("#generate-outputs").on('click', () => { regenerateOutputs().then(() => { window.location.href = "#section-outputs-" + defaultoutput; }); }); function regenerateOutputs() { return new Promise(function(resolve, reject) { tracked_resources = performF2Mappings(output_objects); var mapped_outputs = compileOutputs(tracked_resources, null); cfn_editor.getDoc().setValue(mapped_outputs['cfn']); tf_editor.getDoc().setValue(mapped_outputs['tf']); troposphere_editor.getDoc().setValue(mapped_outputs['troposphere']); cdk_editor.getDoc().setValue(mapped_outputs['cdk']); cdktf_editor.getDoc().setValue(mapped_outputs['cdktf']); pulumi_editor.getDoc().setValue(mapped_outputs['pulumi']); raw_editor.getDoc().setValue(JSON.stringify(output_objects, null, 4)); // Gutters [ {key: 'cfn', editor: cfn_editor}, {key: 'tf', editor: tf_editor}, {key: 'troposphere', editor: troposphere_editor}, {key: 'cdk', editor: cdk_editor}, {key: 'cdktf', editor: cdktf_editor}, {key: 'pulumi', editor: pulumi_editor} ].forEach(language => { var lines = mapped_outputs[language.key].split("\n"); for (var i=0; i<lines.length; i++) { if (lines[i].includes("REPLACEME")) { language.editor.setGutterMarker(i, "f2gutter", makeReplacementMarker()); } } }); setTimeout(function(){ cfn_editor.refresh(); tf_editor.refresh(); troposphere_editor.refresh(); cdk_editor.refresh(); cdktf_editor.refresh(); pulumi_editor.refresh(); raw_editor.refresh(); tippy('.f2replacementmarker', { content: "Value requires replacement", placement: "right", theme: "material" }); }, 1); resolve(); }); } /* ========================================================================== */ // Region Selector /* ========================================================================== */ var region_map = { "us-east-1": "US East (N. Virginia)", "us-east-2": "US East (Ohio)", "us-west-1": "US West (N. California)", "us-west-2": "US West (Oregon)", "af-south-1": "Africa (Cape Town)", "ap-east-1": "Asia Pacific (Hong Kong)", "ap-south-1": "Asia Pacific (Mumbai)", "ap-northeast-3": "Asia Pacific (Osaka)", "ap-northeast-2": "Asia Pacific (Seoul)", "ap-southeast-1": "Asia Pacific (Singapore)", "ap-southeast-2": "Asia Pacific (Sydney)", "ap-northeast-1": "Asia Pacific (Tokyo)", "ca-central-1": "Canada (Central)", "eu-central-1": "EU (Frankfurt)", "eu-west-1": "EU (Ireland)", "eu-west-2": "EU (London)", "eu-west-3": "EU (Paris)", "eu-north-1": "EU (Stockholm)", "eu-south-1": "EU (Milan)", "me-south-1": "Middle East (Bahrain)", "sa-east-1": "South America (S&#227;o Paulo)", "us-gov-east-1": "AWS GovCloud (US-Gov-East)", "us-gov-west-1": "AWS GovCloud (US-Gov-West)", "cn-north-1": "China (Beijing)", "cn-northwest-1": "China (Ningxia)" }; $('.region-item').on('click', el => { region = $(el.target).attr('data-region'); $('#selected-region').html(region_map[region]); $('.region-item').removeAttr('style'); $('.region-item[data-region=\'' + region + '\']').attr('style', 'font-weight: bold;') window.localStorage.setItem('region', region); for (var sp_index in stack_parameters) { if (stack_parameters[sp_index].name == "AWS::Region") { stack_parameters[sp_index].default_value = region; } } }); var storedregion = window.localStorage.getItem('region'); if (storedregion) { region = storedregion; } else { region = 'us-east-1'; } $('#selected-region').html(region_map[region]); $('.region-item[data-region=\'' + region + '\']').attr('style', 'font-weight: bold;'); stack_parameters.push({ 'name': 'AWS::Region', 'default_value': region, 'type': 'String' }); /* ========================================================================== */ // CodeMirror Init /* ========================================================================== */ function copyStringToClipboard(str) { var el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); document.execCommand('copy'); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } } function setCopyEvent(selector, editor) { $(selector).bind('click', () => { $(selector).attr('disabled', 'disabled'); copyStringToClipboard(editor.getDoc().getValue()); $(selector).html("<i class=\"fa fa-files-o\"></i>&nbsp;&nbsp;Copied"); setTimeout(() => { $(selector).removeAttr('disabled'); $(selector).html("<i class=\"fa fa-files-o\"></i>&nbsp;&nbsp;Copy"); }, 4000); }); } cfn_editor = CodeMirror.fromTextArea(document.getElementById('cfn'), { lineNumbers: true, gutters: ["f2gutter", "CodeMirror-linenumbers"], lineWrapping: true, mode: "yaml", theme: "material", indentUnit: 4, height: "auto", viewportMargin: Infinity, scrollbarStyle: "null" }); setCopyEvent('#header-button-copy-cfn', cfn_editor); tf_editor = CodeMirror.fromTextArea(document.getElementById('tf'), { lineNumbers: true, gutters: ["f2gutter", "CodeMirror-linenumbers"], lineWrapping: true, mode: "ruby", theme: "material", indentUnit: 4, height: "auto", viewportMargin: Infinity, scrollbarStyle: "null" }); setCopyEvent('#header-button-copy-tf', tf_editor); troposphere_editor = CodeMirror.fromTextArea(document.getElementById('troposphere'), { lineNumbers: true, gutters: ["f2gutter", "CodeMirror-linenumbers"], lineWrapping: true, mode: "python", theme: "material", indentUnit: 4, height: "auto", viewportMargin: Infinity, scrollbarStyle: "null" }); setCopyEvent('#header-button-copy-troposphere', troposphere_editor); cdk_editor = CodeMirror.fromTextArea(document.getElementById('cdk'), { lineNumbers: true, gutters: ["f2gutter", "CodeMirror-linenumbers"], lineWrapping: true, mode: "javascript", theme: "material", indentUnit: 4, height: "auto", viewportMargin: Infinity, scrollbarStyle: "null" }); setCopyEvent('#header-button-copy-cdk', cdk_editor); cdktf_editor = CodeMirror.fromTextArea(document.getElementById('cdktf'), { lineNumbers: true, gutters: ["f2gutter", "CodeMirror-linenumbers"], lineWrapping: true, mode: "javascript", theme: "material", indentUnit: 4, height: "auto", viewportMargin: Infinity, scrollbarStyle: "null" }); setCopyEvent('#header-button-copy-cdktf', cdktf_editor); pulumi_editor = CodeMirror.fromTextArea(document.getElementById('pulumi'), { lineNumbers: true, gutters: ["f2gutter", "CodeMirror-linenumbers"], lineWrapping: true, mode: "javascript", theme: "material", indentUnit: 4, height: "auto", viewportMargin: Infinity, scrollbarStyle: "null" }); setCopyEvent('#header-button-copy-pulumi', pulumi_editor); raw_editor = CodeMirror.fromTextArea(document.getElementById('raw'), { lineNumbers: true, gutters: ["f2gutter", "CodeMirror-linenumbers"], lineWrapping: true, mode: "javascript", theme: "material", indentUnit: 4, height: "auto", viewportMargin: Infinity, scrollbarStyle: "null" }); setCopyEvent('#header-button-copy-raw', raw_editor); $('#header-button-clear-outputs').click(function() { output_objects = []; regenerateOutputs(); $('#generate-outputs').text("Generate"); $('#generate-outputs').attr('disabled', 'disabled'); }); regenerateOutputs(); /* ========================================================================== */ // Account Scan /* ========================================================================== */ $('.scan-account').on('click', () => { var completeddatatablecalls = 0; var datatablefuncs = []; $('.scan-account').attr('disabled', 'disabled'); $('#search-no-scan-warning').attr('style', 'display: none;'); Object.getOwnPropertyNames(window).forEach(prop => { if (prop.startsWith("updateDatatable")) { datatablefuncs.push(prop); } }); var totaldatatables = datatablefuncs.length; $('.scan-account').html('Scanning... (0/' + totaldatatables + ')'); function processDatatable(dt) { // var starttime = new Date(); window[dt]().catch(err => {}).finally(() => { completeddatatablecalls += 1; $('.scan-account').html('Scanning... (' + completeddatatablecalls + '/' + totaldatatables + ')'); if (completeddatatablecalls == totaldatatables) { visited_sections.push("all"); $('.scan-account').removeAttr('disabled'); $('.scan-account').html('Scan Again'); } // console.log("Finished " + dt + " - " + Math.ceil((new Date() - starttime)/1000)); // for performance testing var nextdt = datatablefuncs.shift(); if (nextdt) { processDatatable(nextdt); } }); } for (var i=0; i<MAX_DT_SCANS; i++) { processDatatable(datatablefuncs.shift()); } }); $('#add-all-resources').on('click', () => { output_objects = []; $('.f2datatable').each(function() { addAllTableRowsToTemplate("#" + this.id); }); }); /* ========================================================================== */ // AWS SDK Proxy for Extension (must be before Account Scan) /* ========================================================================== */ class AWSConfigClass { static update(obj) { extensionSendMessage({ action: 'configUpdate', obj: obj }, function(){}); } } class AWSCredentialsClass { constructor(...args) { this.credentials = args; return args; } } function pingExtension() { return new Promise(function(resolve, reject) { extensionSendMessage( { action: 'ping' }, function(response) { if (response) { extension_available = true; AWS = new Proxy({}, { get: function(obj, prop) { if (prop == "config") { return AWSConfigClass; } else if (prop == "Credentials") { return AWSCredentialsClass; } return function (service_params) { return new Proxy({ 'name': prop, 'properties': service_params }, { get: function(service, service_action) { return async (params, callback) => { while (CONCURRENT_SDKCALLS > 500) { await new Promise(resolve => setTimeout(resolve, 100)); // sleep 100ms } CONCURRENT_SDKCALLS++; extensionSendMessage( { action: 'serviceAction', args: this.serviceArgs, service: service, service_action: service_action, params: params }, function(response) { CONCURRENT_SDKCALLS--; if (!response) { callback("No response from extension", null); } else if (!response.success) { callback(response.error, response.data); } else { callback(null, response.data); } } ); } } }); }; } }); resolve(); } else { reject(); } } ); }); }; pingExtension().catch(() => { ping_extension_interval = setInterval(function(){ // continuously check for extension being present after pingExtension().then(() => { clearInterval(ping_extension_interval); updateIdentity(); $.notify({ icon: 'font-icon font-icon-success', title: '<strong>Helper Available</strong>', message: 'The Former2 helper is now active for all actions.' },{ type: 'success' }); }).catch(() => {}); }, 3000); }).finally(() => { updateIdentity().finally(doNavigation); }); /* ========================================================================== */ // Import /* ========================================================================== */ $('#header-button-import-cfn').click(function(){ $('#import-warnings').html(""); $('#import-stackname').val(""); var non_importable_resources = getNonImportableResources(); non_importable_resources.forEach(res => { $('#import-warnings').append(`<div class="alert alert-warning" role="alert"> <strong><i class="fa fa-warning"></i> Non-compatible Resource: </strong>${res.obj.id} (${res.type}). This resource will not be imported. </div>`); }); $('#import-button').attr('disabled','disabled'); $('#import-button').text("Create Change Set"); $('#import-button').off('click').on('click', function() { $('#import-button').attr('disabled', 'disabled'); $('#import-button').text("Creating change set..."); importResources($('#import-stackname').val(), $('#import-deletionpolicy').val()); }); $('#importmodal').modal('show'); }); $('#import-stackname').on('input', function() { if ($('#import-stackname').val() == "") { $('#import-button').attr("disabled", "disabled"); } else { $('#import-button').removeAttr("disabled"); } }); $('#import-download-template').off('click').on('click', function() { downloadImportTemplate($('#import-stackname').val(), $('#import-deletionpolicy').val()); }); /* ========================================================================== */ // Diagram /* ========================================================================== */ var sectionHeader = $('.section-header'); var sectionHeaderHeight = 0; if (sectionHeader.length) { sectionHeaderHeight = parseInt(sectionHeader.height()) + parseInt(sectionHeader.css('padding-bottom')); } $('#diagram_container').attr('style', 'min-height: ' + ($(window).height() - parseInt($('.page-content').css('padding-top')) - parseInt($('.page-content').css('padding-bottom')) - sectionHeaderHeight - 40) + 'px;' ); $('#diagramframe').attr('style', 'width: 100%; border: 0; min-height: ' + ($(window).height() - parseInt($('.page-content').css('padding-top')) - parseInt($('.page-content').css('padding-bottom')) - sectionHeaderHeight - 40) + 'px;' ); $('#diagramframe').attr('src', '/lib/drawio/src/main/webapp/index.html?embed=1&libraries=1&proto=json&local=1&sync=none&browser=0&gapi=0&db=0&od=0&tr=0&gh=0&gl=0&stealth=1&math=0&picker=0&libs=aws4&spin=1&p=page&saveAndExit=0&noSaveBtn=1&noExitBtn=1'); // &configure=1 $('#header-button-download-diagram').click(function(){ var message = JSON.stringify({ action: 'export', format: 'png' }); var iframe = document.getElementById('diagramframe'); iframe.contentWindow.postMessage(message, '*'); }); window.addEventListener('message', (message) => { var evt = JSON.parse(message.data); if (evt['event'] == "init") { clearDiagram(); } else if (evt['event'] == "export") { var element = document.createElement('a'); element.setAttribute('href', evt.data); element.setAttribute('download', "graph.png"); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } else if (evt['event'] == "toggleFullscreen") { $('#diagramframe').toggleClass('fullscreen'); } }); /* ========================================================================== */ // Misc /* ========================================================================== */ tippy('[data-tippy-content]', { theme: 'material' }); $("#credentials-secretkey").focus(function() { $(this).attr('type', 'text'); }); $("#credentials-secretkey").blur(function() { $(this).attr('type', 'password'); }); $("#credentials-sessiontoken").focus(function() { $(this).attr('type', 'text'); }); $("#credentials-sessiontoken").blur(function() { $(this).attr('type', 'password'); }); $('.select2-no-search-arrow').select2({ // Selectors for settings minimumResultsForSearch: "Infinity", theme: "arrow" }); $('.tags-field').tagEditor(); $('#load-settings').click(function(){$('#load-settings-picker').click();}); $('#save-settings').click(function(){saveSettings()}); $('#load-settings-picker').change(loadSettings); $('#add-parameter-expand-link').click(function(){ if ($("#add-parameter-expand-section").is(":hidden")) { $('#add-parameter-expand-link').html("[&ndash;] Advanced Settings"); } else { $('#add-parameter-expand-link').html("[+] Advanced Settings"); } $('#add-parameter-expand-section').slideToggle('fast'); }); $('#add-parameter-name').mask("B", {translation: {'B': {pattern: /[a-zA-Z0-9]/, recursive: true}}}); $('#add-parameter-form').submit(function(e){ e.preventDefault(); if (!$('#add-parameter-name').val() || $('#add-parameter-name').val().length < 1) return; var allowed_values = $('#add-parameter-allowed-values').val(); if (allowed_values && allowed_values.length) { allowed_values = allowed_values.split(","); } stack_parameters.unshift({ 'name': $('#add-parameter-name').val(), 'description': $('#add-parameter-description').val(), 'constraint_description': $('#add-parameter-constraint-description').val(), 'default_value': $('#add-parameter-default-value').val(), 'allowed_pattern': $('#add-parameter-allowed-pattern').val(), 'allowed_values': allowed_values, 'minimum_length': $('#add-parameter-minimum-length').val(), 'maximum_length': $('#add-parameter-maximum-length').val(), 'minimum_value': $('#add-parameter-minimum-value').val(), 'maximum_value': $('#add-parameter-maximum-value').val(), 'no_echo': $('#add-parameter-noecho').prop('checked'), 'type': $('#add-parameter-type').val() }); $('#add-parameter-name').val(""); $('#add-parameter-default-value').val(""); $('#add-parameter-description').val(""); $('#add-parameter-constraint-description').val(""); $('#add-parameter-allowed-pattern').val(""); $('#add-parameter-allowed-values').val(""); $('#add-parameter-minimum-length').val(""); $('#add-parameter-maximum-length').val(""); $('#add-parameter-minimum-value').val(""); $('#add-parameter-maximum-value').val(""); $('#add-parameter-noecho').prop('checked', false); $('#add-parameter-type').val("String"); $('#add-parameter-name').focus(); generateParameterTable(); }); var spacingamount = window.localStorage.getItem('cfnspacing'); if (spacingamount && spacingamount == 2) { cfnspacing = " "; $('#cfnspacing').val("2").trigger('change'); } else { cfnspacing = " "; } $('#cfnspacing').change(function() { window.localStorage.setItem('cfnspacing', $(this).val()); if ($(this).val() == "2") { cfnspacing = " "; } else if ($(this).val() == "4") { cfnspacing = " "; } }); logicalidstrategy = window.localStorage.getItem('logicalidstrategy') || 'longtypeprefixoptionalindexsuffix'; $('#logicalidstrategy').val(logicalidstrategy).trigger('change'); $('#logicalidstrategy').change(function() { window.localStorage.setItem('logicalidstrategy', $(this).val()); logicalidstrategy = $(this).val(); // Clear resource state output_objects = []; regenerateOutputs(); $('#generate-outputs').text("Generate"); $('#generate-outputs').attr('disabled', 'disabled'); }); defaultoutput = window.localStorage.getItem('defaultoutput') || 'cloudformation'; if (defaultoutput == "cdkts") { defaultoutput = "cdk"; } // breaking change if (defaultoutput == "pulumits") { defaultoutput = "pulumi"; } // breaking change $('#defaultoutput').val(defaultoutput).trigger('change'); $('#defaultoutput').change(function() { window.localStorage.setItem('defaultoutput', $(this).val()); defaultoutput = $(this).val(); }); iaclangselect = window.localStorage.getItem('iaclangselect') || 'typescript'; $('#iaclangselect').change(function() { window.localStorage.setItem('iaclangselect', $(this).val()); iaclangselect = $(this).val(); if ($(this).val() == "typescript") { cdk_editor.setOption("mode", "javascript"); cdktf_editor.setOption("mode", "javascript"); } else if ($(this).val() == "java") { cdk_editor.setOption("mode", "text/x-java"); cdktf_editor.setOption("mode", "text/x-java"); } else if ($(this).val() == "dotnet") { cdk_editor.setOption("mode", "text/x-csrc"); cdktf_editor.setOption("mode", "text/x-csrc"); } else { cdk_editor.setOption("mode", $(this).val()); cdktf_editor.setOption("mode", $(this).val()); } }); $('#iaclangselect').val(iaclangselect).trigger('change'); if (window.localStorage.getItem('relatedresourcessetting') == "true") { $('#relatedresourcessetting').prop('checked', true); } $('#relatedresourcessetting').change(function() { window.localStorage.setItem('relatedresourcessetting', $(this).is(':checked').toString()); }); if (window.localStorage.getItem('skipirrelevantresources') == "true") { $('#skipirrelevantresources').prop('checked', true); } $('#skipirrelevantresources').change(function() { window.localStorage.setItem('skipirrelevantresources', $(this).is(':checked').toString()); }); if (window.localStorage.getItem('includedefaultresources') == "true") { $('#includedefaultresources').prop('checked', true); include_default_resources = true; } $('#includedefaultresources').change(function() { window.localStorage.setItem('includedefaultresources', $(this).is(':checked').toString()); if ($(this).is(':checked')) { include_default_resources = true; } else { include_default_resources = false; } }); if (window.localStorage.getItem('credentials-secretkey')) { $('.scan-account').removeAttr('disabled'); } }); // <-- End of documentReady /* ========================================================================== */ // Extension Request/Response /* ========================================================================== */ var active_firefoxaddon_requests = {}; document.addEventListener('f2response', msg => { var detail = JSON.parse(msg.detail); if (active_firefoxaddon_requests[detail.id]) { active_firefoxaddon_requests[detail.id](detail.data); delete active_firefoxaddon_requests[msg.id]; } else { f2log("No callback found for request: " + detail.id); } }); function extensionSendMessage(data, callback) { if (navigator.userAgent.search("Firefox") > -1) { // Firefox var uid = Math.random().toString(36); var event = new CustomEvent('f2request', { detail: JSON.stringify({ id: uid, data: data }) }); active_firefoxaddon_requests[uid] = callback; document.dispatchEvent(event); if (data.action == "ping") { // quick timeout for ping setTimeout(function(callback){ callback(null); }, 200, callback); } } else if (navigator.userAgent.search("Edg/") > -1) { // Edge (Chromium) if (window.chrome && window.chrome.runtime) { chrome.runtime.sendMessage(EDGE_HELPER_EXTENSION_ID, data, callback); } else { callback(null); } } else { // Chrome if (window.chrome && window.chrome.runtime) { chrome.runtime.sendMessage(CHROME_HELPER_EXTENSION_ID, data, callback); } else { callback(null); } } } /* ========================================================================== */ // BlockUI /* ========================================================================== */ function blockUI(selector) { if (selector.startsWith(window.location.hash)) { $(selector).block({ message: '<div class="blockui-default-message"><i class="fa fa-circle-o-notch fa-spin"></i><h6>Loading...</h6></div>', overlayCSS: { background: 'rgba(142, 159, 167, 0.8)', opacity: 1, cursor: 'wait' }, css: { width: '50%' }, blockMsgClass: 'block-msg-default' }); } } function unblockUI(selector) { setTimeout(function(selector){ $(selector).unblock(); }, 200, selector); } /* ========================================================================== */ var resource_tag_cache = {}; async function getResourceTags(arn) { if (!arn) { return null; } if (arn.split(":").length < 7 && !arn.split(":")[5].includes("/")) { return null; } var service = arn.split(":")[2]; var type = arn.split(":")[5].split("/")[0]; if (!resource_tag_cache[ service/*+ "." + type*/ ]) { resource_tag_cache[service] = []; await sdkcall("ResourceGroupsTaggingAPI", "getResources", { ResourceTypeFilters: [ service/* + "." + type*/ ] }, false).then((data) => { resource_tag_cache[ service/* + "." + type*/ ] = data.ResourceTagMappingList; }).catch(() => { }); setTimeout((k) => { delete resource_tag_cache[k]; }, 20000, service/* + "." + type*/); // 20s cache } for (var res of resource_tag_cache[ service/* + "." + type*/ ]) { var resarnparts = res['ResourceARN'].split(":"); resarnparts[3] = ""; resarnparts[4] = ""; var arnparts = arn.split(":"); arnparts[3] = ""; arnparts[4] = ""; if (resarnparts.join(":") == arnparts.join(":")) { return res['Tags'].filter(tag => !tag['Key'].startsWith("aws:")); } } return null; } function stripAWSTags(tags) { if (tags) { if (Array.isArray(tags)) { tags = tags.filter(function (value, index, array) { return (!value['Key'].startsWith("aws:")); }); } else { var i = Object.keys(tags).length; while (i--) { var k = Object.keys(tags)[i]; if (k.startsWith("aws:")) { delete tags[k]; } } } } return tags; } function saveSettings() { var jsondoc = { 'parameters': stack_parameters.filter(function(p){ return !p.name.startsWith("AWS::"); }), 'settings': { 'cfnspacing': window.localStorage.getItem('cfnspacing'), 'logicalidstrategy': window.localStorage.getItem('logicalidstrategy') || 'longtypeprefixoptionalindexsuffix', 'defaultoutput': window.localStorage.getItem('defaultoutput') || 'cloudformation', 'iaclangselect': window.localStorage.getItem('iaclangselect') || 'typescript', 'relatedresourcessetting': window.localStorage.getItem('relatedresourcessetting'), 'skipirrelevantresources': window.localStorage.getItem('skipirrelevantresources'), 'includedefaultresources': window.localStorage.getItem('includedefaultresources') } }; var element = document.createElement('a'); element.setAttribute('href', 'data:application/json,' + encodeURIComponent(JSON.stringify(jsondoc, null, 2))); element.setAttribute('download', "Former2Settings.json"); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } function loadSettings() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function(e){ loaded_settings = JSON.parse(e.target.result); stack_parameters = loaded_settings.parameters.concat(stack_parameters.filter(function(p){ return p.name.startsWith("AWS::"); })); generateParameterTable(); if ('cfnspacing' in loaded_settings.settings) { $('#cfnspacing').val(loaded_settings.settings.cfnspacing).trigger('change'); } if ('logicalidstrategy' in loaded_settings.settings) { $('#logicalidstrategy').val(loaded_settings.settings.logicalidstrategy).trigger('change'); } if ('defaultoutput' in loaded_settings.settings) { $('#defaultoutput').val(loaded_settings.settings.defaultoutput).trigger('change'); } if ('iaclangselect' in loaded_settings.settings) { $('#iaclangselect').val(loaded_settings.settings.iaclangselect).trigger('change'); } if ('relatedresourcessetting' in loaded_settings.settings) { if (loaded_settings.settings.relatedresourcessetting == "true") { $('#relatedresourcessetting').prop('checked', true); } else { $('#relatedresourcessetting').prop('checked', false); } } if ('skipirrelevantresources' in loaded_settings.settings) { if (loaded_settings.settings.skipirrelevantresources == "true") { $('#skipirrelevantresources').prop('checked', true); } else { $('#skipirrelevantresources').prop('checked', false); } } if ('includedefaultresources' in loaded_settings.settings) { if (loaded_settings.settings.includedefaultresources == "true") { $('#includedefaultresources').prop('checked', true); include_default_resources = true; } else { $('#includedefaultresources').prop('checked', false); include_default_resources = false; } } } reader.readAsText(this.files[0]); } } function makeReplacementMarker() { var marker = document.createElement("div"); marker.classList.add("f2replacementmarker"); marker.innerHTML = "<i style=\"color: #ffd301; font-size: .8em; padding-left: 6px;\" class=\"fa fa-warning\"></i>"; return marker; } function generateParameterTable() { if (stack_parameters.length > 2) { var parameter_html = ""; var p_index = 0; stack_parameters.forEach(stack_parameter => { if (!stack_parameter.name.startsWith("AWS::")) { parameter_html += "<tr><td>" + stack_parameter.name + "</td><td>" + stack_parameter.type + "</td><td>" + (stack_parameter.default_value ? stack_parameter.default_value : "") + "</td><td>&nbsp;&nbsp;&nbsp;&nbsp;<button onclick='removeParameter(" + p_index + ")' type='button' class='param-del'><i class='font-icon font-icon-trash'></i></button></td></tr>"; } p_index += 1; }); $('#parameter-list').html(parameter_html); $('#parameter-table').attr('style', ''); } else { $('#parameter-table').attr('style', 'display: none;'); } } function removeParameter(index) { stack_parameters.splice(index, 1); generateParameterTable(); } function updateIdentity() { return new Promise(function(resolve, reject) { $('#user-id').html("..."); AWS.config.update({ credentials: new AWS.Credentials( window.localStorage.getItem('credentials-accesskey'), window.localStorage.getItem('credentials-secretkey'), window.localStorage.getItem('credentials-sessiontoken') ), region: region, httpOptions: { timeout: 60000 } }); if (window.localStorage.getItem('credentials-assumerole')) { sdkcall("STS", "assumeRole", { RoleArn: window.localStorage.getItem('credentials-assumerole'), RoleSessionName: "former2-session-" + window.localStorage.getItem('credentials-assumerole').split("/").pop(), SourceIdentity: window.localStorage.getItem('credentials-sourceidentity') }, false).then((data) => { AWS.config.update({ credentials: new AWS.Credentials( data.Credentials.AccessKeyId, data.Credentials.SecretAccessKey, data.Credentials.SessionToken ), region: region, httpOptions: { timeout: 60000 } }); account = data.AssumedRoleUser.Arn.split(":")[4]; var account_param_exists = false; for (var sp_index in stack_parameters) { if (stack_parameters[sp_index].name == "AWS::AccountId") { stack_parameters[sp_index].default_value = account; account_param_exists = true; } } if (!account_param_exists) { stack_parameters.push({ 'name': 'AWS::AccountId', 'default_value': account, 'type': 'String' }); } user = data.AssumedRoleUser.Arn.split("/").pop(); sdkcall("IAM", "listAccountAliases", { // no params }, false).then((accountAliases) => { if (accountAliases.AccountAliases && accountAliases.AccountAliases.length) { account = accountAliases.AccountAliases[0]; } $('#user-id').html(user + " @ " + account); }).catch(err => { $('#user-id').html(user + " @ " + account); }); resolve(); }).catch(err => { $('#user-id').html(""); reject(); }); } else if (window.localStorage.getItem('credentials-accesskey')) { var account = "unknown-account"; var user = "unknown-user"; sdkcall("STS", "getCallerIdentity", { // no params }, false).then((callerid) => { account = callerid.Account; var account_param_exists = false; for (var sp_index in stack_parameters) { if (stack_parameters[sp_index].name == "AWS::AccountId") { stack_parameters[sp_index].default_value = account; account_param_exists = true; } } if (!account_param_exists) { stack_parameters.push({ 'name': 'AWS::AccountId', 'default_value': account, 'type': 'String' }); } user = callerid.Arn.split("/").pop(); sdkcall("IAM", "listAccountAliases", { // no params }, false).then((accountAliases) => { if (accountAliases.AccountAliases && accountAliases.AccountAliases.length) { account = accountAliases.AccountAliases[0]; } $('#user-id').html(user + " @ " + account); }).catch(err => { $('#user-id').html(user + " @ " + account); }); }).catch(err => { $('#user-id').html(""); }); resolve(); } else { $('#user-id').html(""); reject(); } }); } /* Detect resource stack association */ async function getResourceStackAssociation() { templates = {}; await sdkcall("CloudFormation", "listStacks", { StackStatusFilter: ["CREATE_COMPLETE", "ROLLBACK_IN_PROGRESS", "ROLLBACK_FAILED", "ROLLBACK_COMPLETE", "DELETE_FAILED", "UPDATE_IN_PROGRESS", "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_COMPLETE", "UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_FAILED", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"] }, true).then(async (data) => { await Promise.all(data.StackSummaries.map(async (stack) => { await sdkcall("CloudFormation", "getTemplate", { StackName: stack.StackId, TemplateStage: "Processed" }, true).then((data) => { template = null; try { template = JSON.parse(data.TemplateBody); templates[stack.StackName] = template; } catch(err) { console.log("Couldn't parse"); // TODO: yaml 2 json } }); })); }); console.log(templates); } // Import (util/findImportAttributes.py) eligibleImportResources = { "AWS::ACMPCA::Certificate": { "importProperties": [ "Arn", "CertificateAuthorityArn" ] }, "AWS::ACMPCA::CertificateAuthority": { "importProperties": [ "Arn" ] }, "AWS::ACMPCA::CertificateAuthorityActivation": { "importProperties": [ "CertificateAuthorityArn" ] }, "AWS::AccessAnalyzer::Analyzer": { "importProperties": [ "Arn" ] }, "AWS::ApiGateway::ApiKey": { "importProperties": [ "APIKeyId" ] }, "AWS::ApiGateway::Authorizer": { "importProperties": [ "RestApiId", "AuthorizerId" ] }, "AWS::ApiGateway::ClientCertificate": { "importProperties": [ "ClientCertificateId" ] }, "AWS::ApiGateway::Deployment": { "importProperties": [ "RestApiId", "DeploymentId" ] }, "AWS::ApiGateway::DocumentationVersion": { "importProperties": [ "DocumentationVersion", "RestApiId" ] }, "AWS::ApiGateway::DomainName": { "importProperties": [ "DomainName" ] }, "AWS::ApiGateway::Method": { "importProperties": [ "RestApiId", "ResourceId", "HttpMethod" ] }, "AWS::ApiGateway::Model": { "importProperties": [ "RestApiId", "Name" ] }, "AWS::ApiGateway::RequestValidator": { "importProperties": [ "RestApiId", "RequestValidatorId" ] }, "AWS::ApiGateway::Resource": { "importProperties": [ "RestApiId", "ResourceId" ] }, "AWS::ApiGateway::RestApi": { "importProperties": [ "RestApiId" ] }, "AWS::ApiGateway::Stage": { "importProperties": [ "RestApiId", "StageName" ] }, "AWS::AppFlow::ConnectorProfile": { "importProperties": [ "ConnectorProfileName" ] }, "AWS::AppFlow::Flow": { "importProperties": [ "FlowName" ] }, "AWS::ApplicationInsights::Application": { "importProperties": [ "ApplicationARN" ] }, "AWS::Athena::DataCatalog": { "importProperties": [ "Name" ] }, "AWS::Athena::NamedQuery": { "importProperties": [ "NamedQueryId" ] }, "AWS::Athena::WorkGroup": { "importProperties": [ "Name" ] }, "AWS::AuditManager::Assessment": { "importProperties": [ "AssessmentId" ] }, "AWS::AutoScaling::AutoScalingGroup": { "importProperties": [ "AutoScalingGroupName" ] }, "AWS::AutoScaling::LaunchConfiguration": { "importProperties": [ "LaunchConfigurationName" ] }, "AWS::AutoScaling::LifecycleHook": { "importProperties": [ "AutoScalingGroupName", "LifecycleHookName" ] }, "AWS::AutoScaling::ScalingPolicy": { "importProperties": [ "PolicyName" ] }, "AWS::AutoScaling::ScheduledAction": { "importProperties": [ "ScheduledActionName" ] }, "AWS::CE::CostCategory": { "importProperties": [ "Arn" ] }, "AWS::Cassandra::Keyspace": { "importProperties": [ "KeyspaceName" ] }, "AWS::Cassandra::Table": { "importProperties": [ "KeyspaceName", "TableName" ] }, "AWS::Chatbot::SlackChannelConfiguration": { "importProperties": [ "Arn" ] }, "AWS::CloudFormation::ModuleDefaultVersion": { "importProperties": [ "Arn" ] }, "AWS::CloudFormation::ModuleVersion": { "importProperties": [ "Arn" ] }, "AWS::CloudFormation::ResourceDefaultVersion": { "importProperties": [ "Arn" ] }, "AWS::CloudFormation::ResourceVersion": { "importProperties": [ "Arn" ] }, "AWS::CloudFormation::StackSet": { "importProperties": [ "StackSetId" ] }, "AWS::CloudFront::CachePolicy": { "importProperties": [ "Id" ] }, "AWS::CloudFront::KeyGroup": { "importProperties": [ "Id" ] }, "AWS::CloudFront::OriginRequestPolicy": { "importProperties": [ "Id" ] }, "AWS::CloudFront::PublicKey": { "importProperties": [ "Id" ] }, "AWS::CloudFront::RealtimeLogConfig": { "importProperties": [ "Arn" ] }, "AWS::CloudTrail::Trail": { "importProperties": [ "TrailName" ] }, "AWS::CloudWatch::Alarm": { "importProperties": [ "AlarmName" ] }, "AWS::CloudWatch::CompositeAlarm": { "importProperties": [ "AlarmName" ] }, "AWS::CloudWatch::MetricStream": { "importProperties": [ "Name" ] }, "AWS::CodeArtifact::Domain": { "importProperties": [ "Arn" ] }, "AWS::CodeArtifact::Repository": { "importProperties": [ "Arn" ] }, "AWS::CodeGuruProfiler::ProfilingGroup": { "importProperties": [ "ProfilingGroupName" ] }, "AWS::CodeGuruReviewer::RepositoryAssociation": { "importProperties": [ "AssociationArn" ] }, "AWS::CodeStarConnections::Connection": { "importProperties": [ "ConnectionArn" ] }, "AWS::Config::ConformancePack": { "importProperties": [ "ConformancePackName" ] }, "AWS::Config::OrganizationConformancePack": { "importProperties": [ "OrganizationConformancePackName" ] }, "AWS::Config::StoredQuery": { "importProperties": [ "QueryName" ] }, "AWS::DataBrew::Dataset": { "importProperties": [ "Name" ] }, "AWS::DataBrew::Job": { "importProperties": [ "Name" ] }, "AWS::DataBrew::Project": { "importProperties": [ "Name" ] }, "AWS::DataBrew::Recipe": { "importProperties": [ "Name" ] }, "AWS::DataBrew::Schedule": { "importProperties": [ "Name" ] }, "AWS::DataSync::Agent": { "importProperties": [ "AgentArn" ] }, "AWS::DataSync::LocationEFS": { "importProperties": [ "LocationArn" ] }, "AWS::DataSync::LocationFSxWindows": { "importProperties": [ "LocationArn" ] }, "AWS::DataSync::LocationNFS": { "importProperties": [ "LocationArn" ] }, "AWS::DataSync::LocationObjectStorage": { "importProperties": [ "LocationArn" ] }, "AWS::DataSync::LocationS3": { "importProperties": [ "LocationArn" ] }, "AWS::DataSync::LocationSMB": { "importProperties": [ "LocationArn" ] }, "AWS::DataSync::Task": { "importProperties": [ "TaskArn" ] }, "AWS::Detective::Graph": { "importProperties": [ "Arn" ] }, "AWS::Detective::MemberInvitation": { "importProperties": [ "GraphArn", "MemberId" ] }, "AWS::DevOpsGuru::NotificationChannel": { "importProperties": [ "Id" ] }, "AWS::DevOpsGuru::ResourceCollection": { "importProperties": [ "ResourceCollectionType" ] }, "AWS::DynamoDB::Table": { "importProperties": [ "TableName" ] }, "AWS::EC2::CarrierGateway": { "importProperties": [ "CarrierGatewayId" ] }, "AWS::EC2::EIP": { "importProperties": [ "PublicIp" ] }, "AWS::EC2::FlowLog": { "importProperties": [ "Id" ] }, "AWS::EC2::GatewayRouteTableAssociation": { "importProperties": [ "GatewayId" ] }, "AWS::EC2::Instance": { "importProperties": [ "InstanceId" ] }, "AWS::EC2::InternetGateway": { "importProperties": [ "InternetGatewayId" ] }, "AWS::EC2::LocalGatewayRoute": { "importProperties": [ "DestinationCidrBlock", "LocalGatewayRouteTableId" ] }, "AWS::EC2::LocalGatewayRouteTableVPCAssociation": { "importProperties": [ "LocalGatewayRouteTableVpcAssociationId" ] }, "AWS::EC2::NatGateway": { "importProperties": [ "NatGatewayId" ] }, "AWS::EC2::NetworkAcl": { "importProperties": [ "NetworkAclId" ] }, "AWS::EC2::NetworkInsightsAnalysis": { "importProperties": [ "NetworkInsightsAnalysisId" ] }, "AWS::EC2::NetworkInsightsPath": { "importProperties": [ "NetworkInsightsPathId" ] }, "AWS::EC2::NetworkInterface": { "importProperties": [ "NetworkInterfaceId" ] }, "AWS::EC2::PrefixList": { "importProperties": [ "PrefixListId" ] }, "AWS::EC2::RouteTable": { "importProperties": [ "RouteTableId" ] }, "AWS::EC2::SecurityGroup": { "importProperties": [ "GroupId" ] }, "AWS::EC2::Subnet": { "importProperties": [ "SubnetId" ] }, "AWS::EC2::TransitGatewayMulticastDomain": { "importProperties": [ "TransitGatewayMulticastDomainId" ] }, "AWS::EC2::TransitGatewayMulticastDomainAssociation": { "importProperties": [ "TransitGatewayMulticastDomainId", "TransitGatewayAttachmentId", "SubnetId" ] }, "AWS::EC2::TransitGatewayMulticastGroupMember": { "importProperties": [ "TransitGatewayMulticastDomainId", "GroupIpAddress", "NetworkInterfaceId" ] }, "AWS::EC2::TransitGatewayMulticastGroupSource": { "importProperties": [ "TransitGatewayMulticastDomainId", "GroupIpAddress", "NetworkInterfaceId" ] }, "AWS::EC2::VPC": { "importProperties": [ "VpcId" ] }, "AWS::EC2::Volume": { "importProperties": [ "VolumeId" ] }, "AWS::ECR::PublicRepository": { "importProperties": [ "RepositoryName" ] }, "AWS::ECR::RegistryPolicy": { "importProperties": [ "RegistryId" ] }, "AWS::ECR::ReplicationConfiguration": { "importProperties": [ "RegistryId" ] }, "AWS::ECR::Repository": { "importProperties": [ "RepositoryName" ] }, "AWS::ECS::CapacityProvider": { "importProperties": [ "Name" ] }, "AWS::ECS::Cluster": { "importProperties": [ "ClusterName" ] }, "AWS::ECS::PrimaryTaskSet": { "importProperties": [ "Cluster", "Service" ] }, "AWS::ECS::Service": { "importProperties": [ "ServiceArn", "Cluster" ] }, "AWS::ECS::TaskDefinition": { "importProperties": [ "TaskDefinitionArn" ] }, "AWS::ECS::TaskSet": { "importProperties": [ "Cluster", "Service", "Id" ] }, "AWS::EFS::AccessPoint": { "importProperties": [ "AccessPointId" ] }, "AWS::EFS::FileSystem": { "importProperties": [ "FileSystemId" ] }, "AWS::EKS::FargateProfile": { "importProperties": [ "ClusterName", "FargateProfileName" ] }, "AWS::EMRContainers::VirtualCluster": { "importProperties": [ "Id" ] }, "AWS::ElastiCache::GlobalReplicationGroup": { "importProperties": [ "GlobalReplicationGroupId" ] }, "AWS::ElastiCache::User": { "importProperties": [ "UserId" ] }, "AWS::ElastiCache::UserGroup": { "importProperties": [ "UserGroupId" ] }, "AWS::ElasticLoadBalancing::LoadBalancer": { "importProperties": [ "LoadBalancerName" ] }, "AWS::ElasticLoadBalancingV2::Listener": { "importProperties": [ "ListenerArn" ] }, "AWS::ElasticLoadBalancingV2::ListenerRule": { "importProperties": [ "RuleArn" ] }, "AWS::ElasticLoadBalancingV2::LoadBalancer": { "importProperties": [ "LoadBalancerArn" ] }, "AWS::EventSchemas::RegistryPolicy": { "importProperties": [ "Id" ] }, "AWS::Events::Archive": { "importProperties": [ "ArchiveName" ] }, "AWS::Events::Rule": { "importProperties": [ "Name" ] }, "AWS::FMS::NotificationChannel": { "importProperties": [ "SnsTopicArn" ] }, "AWS::FMS::Policy": { "importProperties": [ "Id" ] }, "AWS::GameLift::Alias": { "importProperties": [ "AliasId" ] }, "AWS::GameLift::GameServerGroup": { "importProperties": [ "GameServerGroupArn" ] }, "AWS::GlobalAccelerator::Accelerator": { "importProperties": [ "AcceleratorArn" ] }, "AWS::GlobalAccelerator::EndpointGroup": { "importProperties": [ "EndpointGroupArn" ] }, "AWS::GlobalAccelerator::Listener": { "importProperties": [ "ListenerArn" ] }, "AWS::Glue::Registry": { "importProperties": [ "Arn" ] }, "AWS::Glue::Schema": { "importProperties": [ "Arn" ] }, "AWS::Glue::SchemaVersion": { "importProperties": [ "VersionId" ] }, "AWS::Glue::SchemaVersionMetadata": { "importProperties": [ "SchemaVersionId", "Key", "Value" ] }, "AWS::GreengrassV2::ComponentVersion": { "importProperties": [ "Arn" ] }, "AWS::IVS::Channel": { "importProperties": [ "Arn" ] }, "AWS::IVS::PlaybackKeyPair": { "importProperties": [ "Arn" ] }, "AWS::IVS::StreamKey": { "importProperties": [ "Arn" ] }, "AWS::ImageBuilder::Component": { "importProperties": [ "Arn" ] }, "AWS::ImageBuilder::ContainerRecipe": { "importProperties": [ "Arn" ] }, "AWS::ImageBuilder::DistributionConfiguration": { "importProperties": [ "Arn" ] }, "AWS::ImageBuilder::Image": { "importProperties": [ "Arn" ] }, "AWS::ImageBuilder::ImagePipeline": { "importProperties": [ "Arn" ] }, "AWS::ImageBuilder::ImageRecipe": { "importProperties": [ "Arn" ] }, "AWS::ImageBuilder::InfrastructureConfiguration": { "importProperties": [ "Arn" ] }, "AWS::IoT::Authorizer": { "importProperties": [ "AuthorizerName" ] }, "AWS::IoT::Certificate": { "importProperties": [ "Id" ] }, "AWS::IoT::DomainConfiguration": { "importProperties": [ "DomainConfigurationName" ] }, "AWS::IoT::ProvisioningTemplate": { "importProperties": [ "TemplateName" ] }, "AWS::IoT::Thing": { "importProperties": [ "ThingName" ] }, "AWS::IoT::TopicRuleDestination": { "importProperties": [ "Arn" ] }, "AWS::IoTSiteWise::AccessPolicy": { "importProperties": [ "AccessPolicyId" ] }, "AWS::IoTSiteWise::Asset": { "importProperties": [ "AssetId" ] }, "AWS::IoTSiteWise::AssetModel": { "importProperties": [ "AssetModelId" ] }, "AWS::IoTSiteWise::Dashboard": { "importProperties": [ "DashboardId" ] }, "AWS::IoTSiteWise::Gateway": { "importProperties": [ "GatewayId" ] }, "AWS::IoTSiteWise::Portal": { "importProperties": [ "PortalId" ] }, "AWS::IoTSiteWise::Project": { "importProperties": [ "ProjectId" ] }, "AWS::IoTWireless::Destination": { "importProperties": [ "Name" ] }, "AWS::IoTWireless::DeviceProfile": { "importProperties": [ "Id" ] }, "AWS::IoTWireless::ServiceProfile": { "importProperties": [ "Id" ] }, "AWS::IoTWireless::WirelessDevice": { "importProperties": [ "Id" ] }, "AWS::IoTWireless::WirelessGateway": { "importProperties": [ "Id" ] }, "AWS::KMS::Alias": { "importProperties": [ "AliasName" ] }, "AWS::KMS::Key": { "importProperties": [ "KeyId" ] }, "AWS::Kendra::DataSource": { "importProperties": [ "Id", "IndexId" ] }, "AWS::Kendra::Faq": { "importProperties": [ "Id", "IndexId" ] }, "AWS::Kendra::Index": { "importProperties": [ "Id" ] }, "AWS::Kinesis::Stream": { "importProperties": [ "Name" ] }, "AWS::KinesisFirehose::DeliveryStream": { "importProperties": [ "DeliveryStreamName" ] }, "AWS::Lambda::Alias": { "importProperties": [ "AliasArn" ] }, "AWS::Lambda::CodeSigningConfig": { "importProperties": [ "CodeSigningConfigArn" ] }, "AWS::Lambda::EventSourceMapping": { "importProperties": [ "Id" ] }, "AWS::Lambda::Function": { "importProperties": [ "FunctionName" ] }, "AWS::Lambda::Version": { "importProperties": [ "FunctionArn" ] }, "AWS::LicenseManager::Grant": { "importProperties": [ "GrantArn" ] }, "AWS::LicenseManager::License": { "importProperties": [ "LicenseArn" ] }, "AWS::Logs::LogGroup": { "importProperties": [ "LogGroupName" ] }, "AWS::Logs::MetricFilter": { "importProperties": [ "FilterName" ] }, "AWS::Logs::SubscriptionFilter": { "importProperties": [ "LogGroupName", "FilterName" ] }, "AWS::LookoutVision::Project": { "importProperties": [ "ProjectName" ] }, "AWS::MWAA::Environment": { "importProperties": [ "Name" ] }, "AWS::Macie::CustomDataIdentifier": { "importProperties": [ "Id" ] }, "AWS::Macie::FindingsFilter": { "importProperties": [ "Id" ] }, "AWS::Macie::Session": { "importProperties": [ "AwsAccountId" ] }, "AWS::MediaConnect::Flow": { "importProperties": [ "FlowArn" ] }, "AWS::MediaConnect::FlowEntitlement": { "importProperties": [ "EntitlementArn" ] }, "AWS::MediaConnect::FlowOutput": { "importProperties": [ "OutputArn" ] }, "AWS::MediaConnect::FlowSource": { "importProperties": [ "SourceArn" ] }, "AWS::MediaConnect::FlowVpcInterface": { "importProperties": [ "FlowArn", "Name" ] }, "AWS::MediaPackage::Asset": { "importProperties": [ "Id" ] }, "AWS::MediaPackage::Channel": { "importProperties": [ "Id" ] }, "AWS::MediaPackage::OriginEndpoint": { "importProperties": [ "Id" ] }, "AWS::MediaPackage::PackagingConfiguration": { "importProperties": [ "Id" ] }, "AWS::MediaPackage::PackagingGroup": { "importProperties": [ "Id" ] }, "AWS::NetworkFirewall::Firewall": { "importProperties": [ "FirewallArn" ] }, "AWS::NetworkFirewall::FirewallPolicy": { "importProperties": [ "FirewallPolicyArn" ] }, "AWS::NetworkFirewall::LoggingConfiguration": { "importProperties": [ "FirewallArn" ] }, "AWS::NetworkFirewall::RuleGroup": { "importProperties": [ "RuleGroupArn" ] }, "AWS::NetworkManager::CustomerGatewayAssociation": { "importProperties": [ "GlobalNetworkId", "CustomerGatewayArn" ] }, "AWS::NetworkManager::Device": { "importProperties": [ "GlobalNetworkId", "DeviceId" ] }, "AWS::NetworkManager::GlobalNetwork": { "importProperties": [ "Id" ] }, "AWS::NetworkManager::Link": { "importProperties": [ "GlobalNetworkId", "LinkId" ] }, "AWS::NetworkManager::LinkAssociation": { "importProperties": [ "GlobalNetworkId", "DeviceId", "LinkId" ] }, "AWS::NetworkManager::Site": { "importProperties": [ "GlobalNetworkId", "SiteId" ] }, "AWS::NetworkManager::TransitGatewayRegistration": { "importProperties": [ "GlobalNetworkId", "TransitGatewayArn" ] }, "AWS::OpsWorksCM::Server": { "importProperties": [ "ServerName" ] }, "AWS::QLDB::Stream": { "importProperties": [ "LedgerName", "Id" ] }, "AWS::QuickSight::Analysis": { "importProperties": [ "AnalysisId", "AwsAccountId" ] }, "AWS::QuickSight::Dashboard": { "importProperties": [ "AwsAccountId", "DashboardId" ] }, "AWS::QuickSight::Template": { "importProperties": [ "AwsAccountId", "TemplateId" ] }, "AWS::QuickSight::Theme": { "importProperties": [ "ThemeId", "AwsAccountId" ] }, "AWS::RDS::DBCluster": { "importProperties": [ "DBClusterIdentifier" ] }, "AWS::RDS::DBInstance": { "importProperties": [ "DBInstanceIdentifier" ] }, "AWS::RDS::DBProxy": { "importProperties": [ "DBProxyName" ] }, "AWS::RDS::DBProxyTargetGroup": { "importProperties": [ "TargetGroupArn" ] }, "AWS::RDS::GlobalCluster": { "importProperties": [ "GlobalClusterIdentifier" ] }, "AWS::ResourceGroups::Group": { "importProperties": [ "Name" ] }, "AWS::Route53::DNSSEC": { "importProperties": [ "HostedZoneId" ] }, "AWS::Route53::HealthCheck": { "importProperties": [ "HealthCheckId" ] }, "AWS::Route53::HostedZone": { "importProperties": [ "Id" ] }, "AWS::Route53::KeySigningKey": { "importProperties": [ "HostedZoneId", "Name" ] }, "AWS::Route53Resolver::ResolverDNSSECConfig": { "importProperties": [ "Id" ] }, "AWS::Route53Resolver::ResolverQueryLoggingConfig": { "importProperties": [ "Id" ] }, "AWS::Route53Resolver::ResolverQueryLoggingConfigAssociation": { "importProperties": [ "Id" ] }, "AWS::S3::AccessPoint": { "importProperties": [ "Name" ] }, "AWS::S3::Bucket": { "importProperties": [ "BucketName" ] }, "AWS::SES::ConfigurationSet": { "importProperties": [ "Name" ] }, "AWS::SNS::Topic": { "importProperties": [ "TopicArn" ] }, "AWS::SQS::Queue": { "importProperties": [ "QueueUrl" ] }, "AWS::SSM::Association": { "importProperties": [ "AssociationId" ] }, "AWS::SSO::InstanceAccessControlAttributeConfiguration": { "importProperties": [ "InstanceArn" ] }, "AWS::SSO::PermissionSet": { "importProperties": [ "InstanceArn", "PermissionSetArn" ] }, "AWS::SageMaker::App": { "importProperties": [ "AppName", "AppType", "DomainId", "UserProfileName" ] }, "AWS::SageMaker::AppImageConfig": { "importProperties": [ "AppImageConfigName" ] }, "AWS::SageMaker::DataQualityJobDefinition": { "importProperties": [ "JobDefinitionArn" ] }, "AWS::SageMaker::Device": { "importProperties": [ "DeviceFleetName" ] }, "AWS::SageMaker::DeviceFleet": { "importProperties": [ "DeviceFleetName" ] }, "AWS::SageMaker::Domain": { "importProperties": [ "DomainId" ] }, "AWS::SageMaker::FeatureGroup": { "importProperties": [ "FeatureGroupName" ] }, "AWS::SageMaker::ModelBiasJobDefinition": { "importProperties": [ "JobDefinitionArn" ] }, "AWS::SageMaker::ModelExplainabilityJobDefinition": { "importProperties": [ "JobDefinitionArn" ] }, "AWS::SageMaker::ModelPackageGroup": { "importProperties": [ "ModelPackageGroupArn" ] }, "AWS::SageMaker::ModelQualityJobDefinition": { "importProperties": [ "JobDefinitionArn" ] }, "AWS::SageMaker::MonitoringSchedule": { "importProperties": [ "MonitoringScheduleArn" ] }, "AWS::SageMaker::Pipeline": { "importProperties": [ "PipelineName" ] }, "AWS::SageMaker::Project": { "importProperties": [ "ProjectArn" ] }, "AWS::SageMaker::UserProfile": { "importProperties": [ "UserProfileName", "DomainId" ] }, "AWS::ServiceCatalog::CloudFormationProvisionedProduct": { "importProperties": [ "ProvisionedProductId" ] }, "AWS::ServiceCatalog::ServiceAction": { "importProperties": [ "Id" ] }, "AWS::ServiceCatalog::ServiceActionAssociation": { "importProperties": [ "ProductId", "ProvisioningArtifactId", "ServiceActionId" ] }, "AWS::ServiceCatalogAppRegistry::Application": { "importProperties": [ "Id" ] }, "AWS::ServiceCatalogAppRegistry::AttributeGroup": { "importProperties": [ "Id" ] }, "AWS::ServiceCatalogAppRegistry::AttributeGroupAssociation": { "importProperties": [ "Id" ] }, "AWS::ServiceCatalogAppRegistry::ResourceAssociation": { "importProperties": [ "Id" ] }, "AWS::Signer::ProfilePermission": { "importProperties": [ "StatementId", "ProfileName" ] }, "AWS::Signer::SigningProfile": { "importProperties": [ "Arn" ] }, "AWS::StepFunctions::StateMachine": { "importProperties": [ "Arn" ] }, "AWS::Synthetics::Canary": { "importProperties": [ "Name" ] }, "AWS::Timestream::Database": { "importProperties": [ "DatabaseName" ] }, "AWS::Timestream::Table": { "importProperties": [ "DatabaseName", "TableName" ] }, "AWS::WAFv2::IPSet": { "importProperties": [ "Name", "Id", "Scope" ] }, "AWS::WAFv2::RegexPatternSet": { "importProperties": [ "Name", "Id", "Scope" ] }, "AWS::WAFv2::RuleGroup": { "importProperties": [ "Name", "Id", "Scope" ] }, "AWS::WAFv2::WebACL": { "importProperties": [ "Name", "Id", "Scope" ] }, "AWS::WAFv2::WebACLAssociation": { "importProperties": [ "ResourceArn", "WebACLArn" ] }, "AWS::WorkSpaces::ConnectionAlias": { "importProperties": [ "AliasId" ] }, /*****/ "AWS::CloudFormation::Stack": { "importProperties": [ "StackId" ], "capabilities": [ "CAPABILITY_NAMED_IAM" ] }, "AWS::IAM::Group": { "importProperties": [ "GroupName" ], "capabilities": [ "CAPABILITY_NAMED_IAM" ] }, "AWS::IAM::InstanceProfile": { "importProperties": [ "InstanceProfileName" ], "capabilities": [ "CAPABILITY_NAMED_IAM" ] }, "AWS::IAM::Role": { "importProperties": [ "RoleName" ], "capabilities": [ "CAPABILITY_NAMED_IAM" ] }, "AWS::IAM::User": { "importProperties": [ "UserName" ], "capabilities": [ "CAPABILITY_NAMED_IAM" ] }, "AWS::IAM::ManagedPolicy": { "importProperties": [ "PolicyArn" ], "capabilities": [ "CAPABILITY_NAMED_IAM" ] } }; async function downloadImportTemplate(stack_name, deletion_policy) { var importable_resources = []; var resources_to_import = []; tracked_resources.forEach(res => { if ('type' in res && res['type'] in eligibleImportResources && res.returnValues && res.returnValues.Import) { importable_resources.push(res); var resource_identifier = {}; eligibleImportResources[res.type].importProperties.forEach(prop => { resource_identifier[prop] = res.returnValues.Import[prop]; }); resources_to_import.push({ 'LogicalResourceId': res.logicalId, 'ResourceIdentifier': resource_identifier, 'ResourceType': res.type }); } }); if (stack_name == "") { stack_name = "template"; } var mapped_cfn_output = ""; resources_to_import.forEach(res => { mapped_cfn_output += "# Import properties for " + res['LogicalResourceId'] + " (" + res['ResourceType'] + ")\n# \n"; Object.keys(res['ResourceIdentifier']).forEach(k => { mapped_cfn_output += "# " + k + ": " + res['ResourceIdentifier'][k] + "\n"; }); mapped_cfn_output += "# \n"; }); mapped_cfn_output += compileOutputs(importable_resources, deletion_policy)['cfn']; var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(mapped_cfn_output)); element.setAttribute('download', stack_name + ".yaml"); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } async function importResources(stack_name, deletion_policy) { var importable_resources = []; var resources_to_import = []; var capabilities = []; tracked_resources.forEach(res => { if ('type' in res && res['type'] in eligibleImportResources && res.returnValues && res.returnValues.Import) { importable_resources.push(res); var resource_identifier = {}; eligibleImportResources[res.type].importProperties.forEach(prop => { resource_identifier[prop] = res.returnValues.Import[prop]; }); resources_to_import.push({ 'LogicalResourceId': res.logicalId, 'ResourceIdentifier': resource_identifier, 'ResourceType': res.type }); if ('capabilities' in eligibleImportResources[res.type]) { capabilities = eligibleImportResources[res.type].capabilities; // TODO: Make aggregate } } }); var mapped_cfn_output = compileOutputs(importable_resources, deletion_policy)['cfn']; if (mapped_cfn_output.length > 51200) { $('#import-button').removeAttr('disabled'); $('#import-button').text("Create Change Set"); $('#import-warnings').append(`<div class="alert alert-danger" role="alert"> <strong><i class="fa fa-exclamation-circle"></i></strong> Cannot create a change set as the total length of the template would exceed 50kb </div>`); return; } var changeSetName = 'Import' + Math.round((new Date()).getTime() / 1000); await sdkcall("CloudFormation", "createChangeSet", { ChangeSetName: changeSetName, StackName: stack_name, ChangeSetType: "IMPORT", ResourcesToImport: resources_to_import, TemplateBody: mapped_cfn_output, Capabilities: capabilities }, true).then(async (data) => { status = "CREATE_PENDING"; while (['CREATE_PENDING', 'CREATE_IN_PROGRESS'].includes(status)) { await new Promise(resolve => setTimeout(resolve, 2000)); await sdkcall("CloudFormation", "describeChangeSet", { ChangeSetName: changeSetName, StackName: stack_name }, false).then(async (data) => { status = data.Status; }).catch(() => { status = "ERROR"; }); } var stack_url = "https://console.aws.amazon.com/cloudformation/home?region=" + region + "#/stacks/stackinfo?stackId=" + encodeURIComponent(data.StackId); var change_set_url = "https://console.aws.amazon.com/cloudformation/home?region=" + region + "#/stacks/changesets/changes?stackId=" + encodeURIComponent(data.StackId) + "&changeSetId=" + encodeURIComponent(data.Id); $('#import-warnings').append(`<div class="alert alert-info" role="alert"> <strong><i class="fa fa-info-circle"></i></strong> Created change set <a target="_blank" href="${change_set_url}">${changeSetName}</a> in stack <a target="_blank" href="${stack_url}">${stack_name}</i> </div>`); if (status != "CREATE_COMPLETE") { throw "Bad change set status: " + status; } $('#import-button').removeAttr('disabled'); $('#import-button').text("Execute Change Set"); $('#import-button').off('click').on('click', function() { $('#import-button').attr('disabled', 'disabled'); $('#import-button').text("Executing change set..."); var crt = (new Date()).getTime().toString(); sdkcall("CloudFormation", "executeChangeSet", { ChangeSetName: changeSetName, StackName: stack_name, ClientRequestToken: crt }, true).then(async (data) => { await new Promise(resolve => setTimeout(resolve, 4000)); // eventual consistency weirdness await sdkcallwaiter("CloudFormation", "waitFor", "stackImportComplete", { StackName: stack_name }); $('#import-button').removeAttr('disabled'); $('#import-button').text("Close"); $('#import-warnings').append(`<div class="alert alert-info" role="alert"> <strong><i class="fa fa-info-circle"></i></strong> Successfully deployed stack <a target="_blank" href="${stack_url}">${stack_name}</i> </div>`); $('#import-button').off('click').on('click', function() { $('#importmodal').modal('hide'); }); }).catch(e => { console.log(e); $('#import-button').removeAttr('disabled'); $('#import-button').text("Execute Change Set"); $('#import-warnings').append(`<div class="alert alert-danger" role="alert"> <strong><i class="fa fa-exclamation-circle"></i></strong> An error occurred executing the change set. </div>`); }); }); }).catch(e => { console.log(e); $('#import-button').removeAttr('disabled'); $('#import-button').text("Create Change Set"); $('#import-warnings').append(`<div class="alert alert-danger" role="alert"> <strong><i class="fa fa-exclamation-circle"></i></strong> An error occurred creating the change set. </div>`); console.log(mapped_cfn_output); }); } function getNonImportableResources() { var non_importable_resources = []; tracked_resources.forEach(res => { if ('type' in res && !(res['type'] in eligibleImportResources)) { non_importable_resources.push(res); } }); return non_importable_resources; }
/*! ========================================================= * Argon Dashboard React - v1.2.1 ========================================================= * Product Page: https://www.creative-tim.com/product/argon-dashboard-react * Copyright 2021 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/argon-dashboard-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom"; import "assets/plugins/nucleo/css/nucleo.css"; import "@fortawesome/fontawesome-free/css/all.min.css"; import "assets/scss/argon-dashboard-react.scss"; import AdminLayout from "layouts/Admin.js"; import AuthLayout from "layouts/Auth.js"; import Main from "AdminNavbar.js" ReactDOM.render( <BrowserRouter> <Switch> <Route path="/admin" render={(props) => <AdminLayout {...props} />} /> <Route path="/auth" render={(props) => <AuthLayout {...props} />} /> {/* <Redirect from="/" to="/admin/index" /> */} <Route path="/" render = {() => <Main/>} /> </Switch> </BrowserRouter>, document.getElementById("root") );
console.log("hello...") require('./utils.js') console.log('======= yoo ========') var DebugSession = require('./session.js').DebugSession // var util = require('util') // var thrift = require('thrift') // var droidStalker = require('./thrift/DroidStalkerKernelService.js') // var AndroidAppStruct = require('./thrift/AndroidAppStruct_types.js').AndroidAppStruct // var DeviceStruct = require('./thrift/DeviceStruct_types.js').DeviceStruct // // var connection = thrift.createConnection('192.168.3.137', 10000) // // connection.on('error', function(err) { // console.log('== Error on connection -') // console.log(err) // }) // // var client = thrift.createClient(droidStalker, connection) // client.getDevices(function(errs, list){ // if(errs){ // console.log('== Error getting devices: ') // console.log(errs) // }else{ // console.log(list) // if(list.length != 0){ // console.log('got device, starting debug session - ') // var device = list[0] // startDebugSession(device) // }else{ // console.log('== No connected devices found.') // } // } // }) var ds = new DebugSession() // init it to start connections - ds.init() // get devices - ds.getDevices(function(device){ // once device is here, start debug session by sending app - app_params = { packageName: 'com.obeat.advertdisplay', activityName: 'com.obeat.advertdisplay.activities.Boot', applicationName: '', applicationIcon: '' } // start debug session - ds.start(device, app_params, function(session){ console.log('session is here.') console.log(session) // first get cpu stat - session.stats.cpu(device, ds.currentApp, function(info){ console.log('from cpu stat: ' + info) }) }) })
define([ "../core", "../selector" ], function (jQuery) { jQuery.expr.filters.hidden = function (elem) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function (elem) { return !jQuery.expr.filters.hidden(elem); }; });
// @flow /* globals test expect */ import { scenes as scenesReducer } from './reducer.js' import { request } from './Request/reducer.js' import { initialState as SendConfirmationInitialState } from './SendConfirmation/selectors.js' const dummyAction = { type: 'DUMMY_ACTION_PLEASE_IGNORE' } test('initialState', () => { const expected = { ABAlert: { syntax: { buttons: [], message: '', title: '' }, view: false }, controlPanel: { selectedUser: null, usersView: false }, createWallet: { isCreatingWallet: false }, dimensions: { keyboardHeight: 0 }, editToken: { deleteCustomTokenProcessing: false, deleteTokenModalVisible: false, editCustomTokenProcessing: false }, exchangeRate: { exchangeRates: {} }, helpModal: false, request: request(undefined, dummyAction), requestType: { useLegacyAddress: false, uniqueLegacyAddress: false }, scan: { addressModalVisible: false, scanEnabled: false, torchEnabled: false, legacyAddressModal: { isActive: false }, privateKeyModal: { error: null, isSweeping: false, primaryModal: { isActive: false }, secondaryModal: { isActive: false } }, parsedUri: null }, sendConfirmation: SendConfirmationInitialState, changeMiningFee: { isCustomFeeVisible: false }, transactionAlert: { edgeTransaction: null, displayAlert: false }, transactionDetails: { subcategories: [] }, transactionList: { searchVisible: false, transactions: [], updatingBalance: true, loadingTransactions: false, currentCurrencyCode: '', currentEndIndex: 0, numTransactions: 0, currentWalletId: '' }, walletList: { deleteWalletModalVisible: false, getSeedWalletModalVisible: false, privateSeedUnlocked: false, renameWalletInput: '', viewXPubWalletModalVisible: false, xPubSyntax: '', renameWalletModalVisible: false, resyncWalletModalVisible: false, splitWalletModalVisible: false, walletArchivesVisible: false, walletId: '', walletName: '' }, walletListModal: { walletListModalVisible: false }, walletTransferList: { walletListModalVisible: false, walletTransferList: [] }, currentScene: '', passwordReminderModal: { status: null }, passwordRecoveryReminderModal: { isVisible: false }, uniqueIdentifierModal: { isActive: false, uniqueIdentifier: '' } } const actual = scenesReducer(undefined, dummyAction) expect(actual).toEqual(expected) })
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: "/", }, resolve: { extensions: ['.js', '.jsx'], alias: { '@components': path.resolve(__dirname, 'src/components/'), '@styles': path.resolve(__dirname, 'src/styles/') } }, mode: 'production', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', } }, { test: /\.html$/, use: [ { loader: 'html-loader' } ] }, { test: /\.s[ac]ss$/, use: [ 'style-loader', 'css-loader', 'sass-loader' ] } ] }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', filename: './index.html' }), new MiniCssExtractPlugin({ filename: '[name].css' }), new CleanWebpackPlugin(), ], optimization: { minimize: true, minimizer: [ new CssMinimizerPlugin(), new TerserPlugin(), ] } }
// const proxy = require('http-proxy-middleware'); // module.exports = function(app){ // app.use( // proxy('/developers',{ // target:'https://gh-trending-api.herokuapp.com', // changeOrigin: true, // }) // ); // } const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/developers', createProxyMiddleware({ target: 'https://gh-trending-api.herokuapp.com', changeOrigin: true, }) ); app.use( '/repositories', createProxyMiddleware({ target: 'https://gh-trending-api.herokuapp.com', changeOrigin: true, }) ); // app.use( // '{**}', // createProxyMiddleware({ // target: 'https://avatars.githubusercontent.com', // changeOrigin: true, // }) // ); };
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../..' export const input = ( <editor> <block>one</block> <block>two</block> <block>three</block> </editor> ) export const run = editor => { return Array.from( Editor.positions(editor, { reverse: true, at: { anchor: { path: [0, 0], offset: 1 }, focus: { path: [2, 0], offset: 2 }, }, }) ) } export const output = [ { path: [2, 0], offset: 2 }, { path: [2, 0], offset: 1 }, { path: [2, 0], offset: 0 }, { path: [1, 0], offset: 3 }, { path: [1, 0], offset: 2 }, { path: [1, 0], offset: 1 }, { path: [1, 0], offset: 0 }, { path: [0, 0], offset: 3 }, { path: [0, 0], offset: 2 }, { path: [0, 0], offset: 1 }, ]
/*! * reveal.js * http://lab.hakim.se/reveal-js * MIT licensed * * Copyright (C) 2017 Hakim El Hattab, http://hakim.se */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(function() { root.Reveal = factory(); return root.Reveal; }); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS. module.exports = factory(); } else { // Browser globals. root.Reveal = factory(); } })(this, function() { 'use strict'; var Reveal; // The reveal.js version var VERSION = '3.5.0'; var SLIDES_SELECTOR = '.slides section', HORIZONTAL_SLIDES_SELECTOR = '.slides>section', VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section', HOME_SLIDE_SELECTOR = '.slides>section:first-of-type', UA = navigator.userAgent, // Configuration defaults, can be overridden at initialization time config = { // The "normal" size of the presentation, aspect ratio will be preserved // when the presentation is scaled to fit different resolutions width: 960, height: 720, // Factor of the display size that should remain empty around the content margin: 0.04, // Bounds for smallest/largest possible scale to apply to content minScale: 0.2, maxScale: 2.0, // Display controls in the bottom right corner controls: true, // Display a presentation progress bar progress: true, // Display the page number of the current slide slideNumber: false, // Determine which displays to show the slide number on showSlideNumber: 'all', // Push each slide change to the browser history history: false, // Enable keyboard shortcuts for navigation keyboard: true, // Optional function that blocks keyboard events when retuning false keyboardCondition: null, // Enable the slide overview mode overview: true, // Vertical centering of slides center: true, // Enables touch navigation on devices with touch input touch: true, // Loop the presentation loop: false, // Change the presentation direction to be RTL rtl: false, // Randomizes the order of slides each time the presentation loads shuffle: false, // Turns fragments on and off globally fragments: true, // Flags if the presentation is running in an embedded mode, // i.e. contained within a limited portion of the screen embedded: false, // Flags if we should show a help overlay when the question-mark // key is pressed help: true, // Flags if it should be possible to pause the presentation (blackout) pause: true, // Flags if speaker notes should be visible to all viewers showNotes: false, // Global override for autolaying embedded media (video/audio/iframe) // - null: Media will only autoplay if data-autoplay is present // - true: All media will autoplay, regardless of individual setting // - false: No media will autoplay, regardless of individual setting autoPlayMedia: null, // Number of milliseconds between automatically proceeding to the // next slide, disabled when set to 0, this value can be overwritten // by using a data-autoslide attribute on your slides autoSlide: 0, // Stop auto-sliding after user input autoSlideStoppable: true, // Use this method for navigation when auto-sliding (defaults to navigateNext) autoSlideMethod: null, // Enable slide navigation via mouse wheel mouseWheel: false, // Apply a 3D roll to links on hover rollingLinks: false, // Hides the address bar on mobile devices hideAddressBar: true, // Opens links in an iframe preview overlay previewLinks: false, // Exposes the reveal.js API through window.postMessage postMessage: true, // Dispatches all reveal.js events to the parent window through postMessage postMessageEvents: false, // Focuses body when page changes visibility to ensure keyboard shortcuts work focusBodyOnPageVisibilityChange: true, // Transition style transition: 'slide', // none/fade/slide/convex/concave/zoom // Transition speed transitionSpeed: 'default', // default/fast/slow // Transition style for full page slide backgrounds backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom // Parallax background image parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg" // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px" // Amount of pixels to move the parallax background per slide step parallaxBackgroundHorizontal: null, parallaxBackgroundVertical: null, // The maximum number of pages a single slide can expand onto when printing // to PDF, unlimited by default pdfMaxPagesPerSlide: Number.POSITIVE_INFINITY, // Offset used to reduce the height of content within exported PDF pages. // This exists to account for environment differences based on how you // print to PDF. CLI printing options, like phantomjs and wkpdf, can end // on precisely the total height of the document whereas in-browser // printing has to end one pixel before. pdfPageHeightOffset: -1, // Number of slides away from the current that are visible viewDistance: 3, // The display mode that will be used to show slides display: 'block', // Script dependencies to load dependencies: [] }, // Flags if Reveal.initialize() has been called initialized = false, // Flags if reveal.js is loaded (has dispatched the 'ready' event) loaded = false, // Flags if the overview mode is currently active overview = false, // Holds the dimensions of our overview slides, including margins overviewSlideWidth = null, overviewSlideHeight = null, // The horizontal and vertical index of the currently active slide indexh, indexv, // The previous and current slide HTML elements previousSlide, currentSlide, previousBackground, // Slides may hold a data-state attribute which we pick up and apply // as a class to the body. This list contains the combined state of // all current slides. state = [], // The current scale of the presentation (see width/height config) scale = 1, // CSS transform that is currently applied to the slides container, // split into two groups slidesTransform = { layout: '', overview: '' }, // Cached references to DOM elements dom = {}, // Features supported by the browser, see #checkCapabilities() features = {}, // Client is a mobile device, see #checkCapabilities() isMobileDevice, // Client is a desktop Chrome, see #checkCapabilities() isChrome, // Throttles mouse wheel navigation lastMouseWheelStep = 0, // Delays updates to the URL due to a Chrome thumbnailer bug writeURLTimeout = 0, // Flags if the interaction event listeners are bound eventsAreBound = false, // The current auto-slide duration autoSlide = 0, // Auto slide properties autoSlidePlayer, autoSlideTimeout = 0, autoSlideStartTime = -1, autoSlidePaused = false, // Holds information about the currently ongoing touch input touch = { startX: 0, startY: 0, startSpan: 0, startCount: 0, captured: false, threshold: 40 }, // Holds information about the keyboard shortcuts keyboardShortcuts = { 'N , SPACE': 'Next slide', P: 'Previous slide', '&#8592; , H': 'Navigate left', '&#8594; , L': 'Navigate right', '&#8593; , K': 'Navigate up', '&#8595; , J': 'Navigate down', Home: 'First slide', End: 'Last slide', 'B , .': 'Pause', F: 'Fullscreen', 'ESC, O': 'Slide overview' }; /** * Starts up the presentation if the client is capable. */ function initialize(options) { // Make sure we only initialize once if (initialized === true) return; initialized = true; checkCapabilities(); if (!features.transforms2d && !features.transforms3d) { document.body.setAttribute('class', 'no-transforms'); // Since JS won't be running any further, we load all lazy // loading elements upfront var images = toArray(document.getElementsByTagName('img')), iframes = toArray(document.getElementsByTagName('iframe')); var lazyLoadable = images.concat(iframes); for (var i = 0, len = lazyLoadable.length; i < len; i++) { var element = lazyLoadable[i]; if (element.getAttribute('data-src')) { element.setAttribute('src', element.getAttribute('data-src')); element.removeAttribute('data-src'); } } // If the browser doesn't support core features we won't be // using JavaScript to control the presentation return; } // Cache references to key DOM elements dom.wrapper = document.querySelector('.reveal'); dom.slides = document.querySelector('.reveal .slides'); // Force a layout when the whole page, incl fonts, has loaded window.addEventListener('load', layout, false); var query = Reveal.getQueryHash(); // Do not accept new dependencies via query config to avoid // the potential of malicious script injection if (typeof query['dependencies'] !== 'undefined') delete query['dependencies']; // Copy options over to our config object extend(config, options); extend(config, query); // Hide the address bar in mobile browsers hideAddressBar(); // Loads the dependencies and continues to #start() once done load(); } /** * Inspect the client to see what it's capable of, this * should only happens once per runtime. */ function checkCapabilities() { isMobileDevice = /(iphone|ipod|ipad|android)/gi.test(UA); isChrome = /chrome/i.test(UA) && !/edge/i.test(UA); var testElement = document.createElement('div'); features.transforms3d = 'WebkitPerspective' in testElement.style || 'MozPerspective' in testElement.style || 'msPerspective' in testElement.style || 'OPerspective' in testElement.style || 'perspective' in testElement.style; features.transforms2d = 'WebkitTransform' in testElement.style || 'MozTransform' in testElement.style || 'msTransform' in testElement.style || 'OTransform' in testElement.style || 'transform' in testElement.style; features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function'; features.canvas = !!document.createElement('canvas').getContext; // Transitions in the overview are disabled in desktop and // Safari due to lag features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test(UA); // Flags if we should use zoom instead of transform to scale // up slides. Zoom produces crisper results but has a lot of // xbrowser quirks so we only use it in whitelsited browsers. features.zoom = 'zoom' in testElement.style && !isMobileDevice && (isChrome || /Version\/[\d\.]+.*Safari/.test(UA)); } /** * Loads the dependencies of reveal.js. Dependencies are * defined via the configuration option 'dependencies' * and will be loaded prior to starting/binding reveal.js. * Some dependencies may have an 'async' flag, if so they * will load after reveal.js has been started up. */ function load() { var scripts = [], scriptsAsync = [], scriptsToPreload = 0; // Called once synchronous scripts finish loading function proceed() { if (scriptsAsync.length) { // Load asynchronous scripts head.js.apply(null, scriptsAsync); } start(); } function loadScript(s) { head.ready(s.src.match(/([\w\d_\-]*)\.?js$|[^\\\/]*$/i)[0], function() { // Extension may contain callback functions if (typeof s.callback === 'function') { s.callback.apply(this); } if (--scriptsToPreload === 0) { proceed(); } }); } for (var i = 0, len = config.dependencies.length; i < len; i++) { var s = config.dependencies[i]; // Load if there's no condition or the condition is truthy if (!s.condition || s.condition()) { if (s.async) { scriptsAsync.push(s.src); } else { scripts.push(s.src); } loadScript(s); } } if (scripts.length) { scriptsToPreload = scripts.length; // Load synchronous scripts head.js.apply(null, scripts); } else { proceed(); } } /** * Starts up reveal.js by binding input events and navigating * to the current URL deeplink if there is one. */ function start() { // Make sure we've got all the DOM elements we need setupDOM(); // Listen to messages posted to this window setupPostMessage(); // Prevent the slides from being scrolled out of view setupScrollPrevention(); // Resets all vertical slides so that only the first is visible resetVerticalSlides(); // Updates the presentation to match the current configuration values configure(); // Read the initial hash readURL(); // Update all backgrounds updateBackground(true); // Notify listeners that the presentation is ready but use a 1ms // timeout to ensure it's not fired synchronously after #initialize() setTimeout(function() { // Enable transitions now that we're loaded dom.slides.classList.remove('no-transition'); loaded = true; dom.wrapper.classList.add('ready'); dispatchEvent('ready', { indexh: indexh, indexv: indexv, currentSlide: currentSlide }); }, 1); // Special setup and config is required when printing to PDF if (isPrintingPDF()) { removeEventListeners(); // The document needs to have loaded for the PDF layout // measurements to be accurate if (document.readyState === 'complete') { setupPDF(); } else { window.addEventListener('load', setupPDF); } } } /** * Finds and stores references to DOM elements which are * required by the presentation. If a required element is * not found, it is created. */ function setupDOM() { // Prevent transitions while we're loading dom.slides.classList.add('no-transition'); // Background element dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null ); // Progress bar dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' ); dom.progressbar = dom.progress.querySelector('span'); // Arrow controls createSingletonNode( dom.wrapper, 'aside', 'controls', '<button class="navigate-left" aria-label="previous slide"></button>' + '<button class="navigate-right" aria-label="next slide"></button>' + '<button class="navigate-up" aria-label="above slide"></button>' + '<button class="navigate-down" aria-label="below slide"></button>' ); // Slide number dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' ); // Element containing notes that are visible to the audience dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null ); dom.speakerNotes.setAttribute('data-prevent-swipe', ''); dom.speakerNotes.setAttribute('tabindex', '0'); // Overlay graphic which is displayed during the paused mode createSingletonNode(dom.wrapper, 'div', 'pause-overlay', null); // Cache references to elements dom.controls = document.querySelector('.reveal .controls'); dom.wrapper.setAttribute('role', 'application'); // There can be multiple instances of controls throughout the page dom.controlsLeft = toArray(document.querySelectorAll('.navigate-left')); dom.controlsRight = toArray(document.querySelectorAll('.navigate-right')); dom.controlsUp = toArray(document.querySelectorAll('.navigate-up')); dom.controlsDown = toArray(document.querySelectorAll('.navigate-down')); dom.controlsPrev = toArray(document.querySelectorAll('.navigate-prev')); dom.controlsNext = toArray(document.querySelectorAll('.navigate-next')); dom.statusDiv = createStatusDiv(); } /** * Creates a hidden div with role aria-live to announce the * current slide content. Hide the div off-screen to make it * available only to Assistive Technologies. * * @return {HTMLElement} */ function createStatusDiv() { var statusDiv = document.getElementById('aria-status-div'); if (!statusDiv) { statusDiv = document.createElement('div'); statusDiv.style.position = 'absolute'; statusDiv.style.height = '1px'; statusDiv.style.width = '1px'; statusDiv.style.overflow = 'hidden'; statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )'; statusDiv.setAttribute('id', 'aria-status-div'); statusDiv.setAttribute('aria-live', 'polite'); statusDiv.setAttribute('aria-atomic', 'true'); dom.wrapper.appendChild(statusDiv); } return statusDiv; } /** * Converts the given HTML element into a string of text * that can be announced to a screen reader. Hidden * elements are excluded. */ function getStatusText(node) { var text = ''; // Text node if (node.nodeType === 3) { text += node.textContent; } else if (node.nodeType === 1) { // Element node var isAriaHidden = node.getAttribute('aria-hidden'); var isDisplayHidden = window.getComputedStyle(node)['display'] === 'none'; if (isAriaHidden !== 'true' && !isDisplayHidden) { toArray(node.childNodes).forEach(function(child) { text += getStatusText(child); }); } } return text; } /** * Configures the presentation for printing to a static * PDF. */ function setupPDF() { var slideSize = getComputedSlideSize(window.innerWidth, window.innerHeight); // Dimensions of the PDF pages var pageWidth = Math.floor(slideSize.width * (1 + config.margin)), pageHeight = Math.floor(slideSize.height * (1 + config.margin)); // Dimensions of slides within the pages var slideWidth = slideSize.width, slideHeight = slideSize.height; // Let the browser know what page size we want to print injectStyleSheet( '@page{size:' + pageWidth + 'px ' + pageHeight + 'px; margin: 0px;}' ); // Limit the size of certain elements to the dimensions of the slide injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: ' + slideWidth + 'px; max-height:' + slideHeight + 'px}' ); document.body.classList.add('print-pdf'); document.body.style.width = pageWidth + 'px'; document.body.style.height = pageHeight + 'px'; // Make sure stretch elements fit on slide layoutSlideContents(slideWidth, slideHeight); // Add each slide's index as attributes on itself, we need these // indices to generate slide numbers below toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)).forEach( function(hslide, h) { hslide.setAttribute('data-index-h', h); if (hslide.classList.contains('stack')) { toArray(hslide.querySelectorAll('section')).forEach(function( vslide, v ) { vslide.setAttribute('data-index-h', h); vslide.setAttribute('data-index-v', v); }); } } ); // Slide and slide background layout toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR)).forEach(function( slide ) { // Vertical stacks are not centred since their section // children will be if (slide.classList.contains('stack') === false) { // Center the slide inside of the page, giving the slide some margin var left = (pageWidth - slideWidth) / 2, top = (pageHeight - slideHeight) / 2; var contentHeight = slide.scrollHeight; var numberOfPages = Math.max(Math.ceil(contentHeight / pageHeight), 1); // Adhere to configured pages per slide limit numberOfPages = Math.min(numberOfPages, config.pdfMaxPagesPerSlide); // Center slides vertically if ( (numberOfPages === 1 && config.center) || slide.classList.contains('center') ) { top = Math.max((pageHeight - contentHeight) / 2, 0); } // Wrap the slide in a page element and hide its overflow // so that no page ever flows onto another var page = document.createElement('div'); page.className = 'pdf-page'; page.style.height = (pageHeight + config.pdfPageHeightOffset) * numberOfPages + 'px'; slide.parentNode.insertBefore(page, slide); page.appendChild(slide); // Position the slide inside of the page slide.style.left = left + 'px'; slide.style.top = top + 'px'; slide.style.width = slideWidth + 'px'; if (slide.slideBackgroundElement) { page.insertBefore(slide.slideBackgroundElement, slide); } // Inject notes if `showNotes` is enabled if (config.showNotes) { // Are there notes for this slide? var notes = getSlideNotes(slide); if (notes) { var notesSpacing = 8; var notesLayout = typeof config.showNotes === 'string' ? config.showNotes : 'inline'; var notesElement = document.createElement('div'); notesElement.classList.add('speaker-notes'); notesElement.classList.add('speaker-notes-pdf'); notesElement.setAttribute('data-layout', notesLayout); notesElement.innerHTML = notes; if (notesLayout === 'separate-page') { page.parentNode.insertBefore(notesElement, page.nextSibling); } else { notesElement.style.left = notesSpacing + 'px'; notesElement.style.bottom = notesSpacing + 'px'; notesElement.style.width = pageWidth - notesSpacing * 2 + 'px'; page.appendChild(notesElement); } } } // Inject slide numbers if `slideNumbers` are enabled if (config.slideNumber && /all|print/i.test(config.showSlideNumber)) { var slideNumberH = parseInt(slide.getAttribute('data-index-h'), 10) + 1, slideNumberV = parseInt(slide.getAttribute('data-index-v'), 10) + 1; var numberElement = document.createElement('div'); numberElement.classList.add('slide-number'); numberElement.classList.add('slide-number-pdf'); numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV ); page.appendChild(numberElement); } } }); // Show all fragments toArray( dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ' .fragment') ).forEach(function(fragment) { fragment.classList.add('visible'); }); // Notify subscribers that the PDF layout is good to go dispatchEvent('pdf-ready'); } /** * This is an unfortunate necessity. Some actions – such as * an input field being focused in an iframe or using the * keyboard to expand text selection beyond the bounds of * a slide – can trigger our content to be pushed out of view. * This scrolling can not be prevented by hiding overflow in * CSS (we already do) so we have to resort to repeatedly * checking if the slides have been offset :( */ function setupScrollPrevention() { setInterval(function() { if (dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0) { dom.wrapper.scrollTop = 0; dom.wrapper.scrollLeft = 0; } }, 1000); } /** * Creates an HTML element and returns a reference to it. * If the element already exists the existing instance will * be returned. * * @param {HTMLElement} container * @param {string} tagname * @param {string} classname * @param {string} innerHTML * * @return {HTMLElement} */ function createSingletonNode(container, tagname, classname, innerHTML) { // Find all nodes matching the description var nodes = container.querySelectorAll('.' + classname); // Check all matches to find one which is a direct child of // the specified container for (var i = 0; i < nodes.length; i++) { var testNode = nodes[i]; if (testNode.parentNode === container) { return testNode; } } // If no node was found, create it now var node = document.createElement(tagname); node.classList.add(classname); if (typeof innerHTML === 'string') { node.innerHTML = innerHTML; } container.appendChild(node); return node; } /** * Creates the slide background elements and appends them * to the background container. One element is created per * slide no matter if the given slide has visible background. */ function createBackgrounds() { var printMode = isPrintingPDF(); // Clear prior backgrounds dom.background.innerHTML = ''; dom.background.classList.add('no-transition'); // Iterate over all horizontal slides toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)).forEach( function(slideh) { var backgroundStack = createBackground(slideh, dom.background); // Iterate over all vertical slides toArray(slideh.querySelectorAll('section')).forEach(function(slidev) { createBackground(slidev, backgroundStack); backgroundStack.classList.add('stack'); }); } ); // Add parallax background if specified if (config.parallaxBackgroundImage) { dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")'; dom.background.style.backgroundSize = config.parallaxBackgroundSize; // Make sure the below properties are set on the element - these properties are // needed for proper transitions to be set on the element via CSS. To remove // annoying background slide-in effect when the presentation starts, apply // these properties after short time delay setTimeout(function() { dom.wrapper.classList.add('has-parallax-background'); }, 1); } else { dom.background.style.backgroundImage = ''; dom.wrapper.classList.remove('has-parallax-background'); } } /** * Creates a background for the given slide. * * @param {HTMLElement} slide * @param {HTMLElement} container The element that the background * should be appended to * @return {HTMLElement} New background div */ function createBackground(slide, container) { var data = { background: slide.getAttribute('data-background'), backgroundSize: slide.getAttribute('data-background-size'), backgroundImage: slide.getAttribute('data-background-image'), backgroundVideo: slide.getAttribute('data-background-video'), backgroundIframe: slide.getAttribute('data-background-iframe'), backgroundColor: slide.getAttribute('data-background-color'), backgroundRepeat: slide.getAttribute('data-background-repeat'), backgroundPosition: slide.getAttribute('data-background-position'), backgroundTransition: slide.getAttribute('data-background-transition') }; var element = document.createElement('div'); // Carry over custom classes from the slide to the background element.className = 'slide-background ' + slide.className.replace(/present|past|future/, ''); if (data.background) { // Auto-wrap image urls in url(...) if ( /^(http|file|\/\/)/gi.test(data.background) || /\.(svg|png|jpg|jpeg|gif|bmp)([?#]|$)/gi.test(data.background) ) { slide.setAttribute('data-background-image', data.background); } else { element.style.background = data.background; } } // Create a hash for this combination of background settings. // This is used to determine when two slide backgrounds are // the same. if ( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) { element.setAttribute( 'data-background-hash', data.background + data.backgroundSize + data.backgroundImage + data.backgroundVideo + data.backgroundIframe + data.backgroundColor + data.backgroundRepeat + data.backgroundPosition + data.backgroundTransition ); } // Additional and optional background properties if (data.backgroundSize) element.style.backgroundSize = data.backgroundSize; if (data.backgroundSize) element.setAttribute('data-background-size', data.backgroundSize); if (data.backgroundColor) element.style.backgroundColor = data.backgroundColor; if (data.backgroundRepeat) element.style.backgroundRepeat = data.backgroundRepeat; if (data.backgroundPosition) element.style.backgroundPosition = data.backgroundPosition; if (data.backgroundTransition) element.setAttribute( 'data-background-transition', data.backgroundTransition ); container.appendChild(element); // If backgrounds are being recreated, clear old classes slide.classList.remove('has-dark-background'); slide.classList.remove('has-light-background'); slide.slideBackgroundElement = element; // If this slide has a background color, add a class that // signals if it is light or dark. If the slide has no background // color, no class will be set var computedBackgroundStyle = window.getComputedStyle(element); if (computedBackgroundStyle && computedBackgroundStyle.backgroundColor) { var rgb = colorToRgb(computedBackgroundStyle.backgroundColor); // Ignore fully transparent backgrounds. Some browsers return // rgba(0,0,0,0) when reading the computed background color of // an element with no background if (rgb && rgb.a !== 0) { if (colorBrightness(computedBackgroundStyle.backgroundColor) < 128) { slide.classList.add('has-dark-background'); } else { slide.classList.add('has-light-background'); } } } return element; } /** * Registers a listener to postMessage events, this makes it * possible to call all reveal.js API methods from another * window. For example: * * revealWindow.postMessage( JSON.stringify({ * method: 'slide', * args: [ 2 ] * }), '*' ); */ function setupPostMessage() { if (config.postMessage) { window.addEventListener( 'message', function(event) { var data = event.data; // Make sure we're dealing with JSON if ( typeof data === 'string' && data.charAt(0) === '{' && data.charAt(data.length - 1) === '}' ) { data = JSON.parse(data); // Check if the requested method can be found if (data.method && typeof Reveal[data.method] === 'function') { Reveal[data.method].apply(Reveal, data.args); } } }, false ); } } /** * Applies the configuration settings from the config * object. May be called multiple times. * * @param {object} options */ function configure(options) { var numberOfSlides = dom.wrapper.querySelectorAll(SLIDES_SELECTOR).length; dom.wrapper.classList.remove(config.transition); // New config options may be passed when this method // is invoked through the API after initialization if (typeof options === 'object') extend(config, options); // Force linear transition based on browser capabilities if (features.transforms3d === false) config.transition = 'linear'; dom.wrapper.classList.add(config.transition); dom.wrapper.setAttribute('data-transition-speed', config.transitionSpeed); dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition ); dom.controls.style.display = config.controls ? 'block' : 'none'; dom.progress.style.display = config.progress ? 'block' : 'none'; if (config.shuffle) { shuffle(); } if (config.rtl) { dom.wrapper.classList.add('rtl'); } else { dom.wrapper.classList.remove('rtl'); } if (config.center) { dom.wrapper.classList.add('center'); } else { dom.wrapper.classList.remove('center'); } // Exit the paused mode if it was configured off if (config.pause === false) { resume(); } if (config.showNotes) { dom.speakerNotes.classList.add('visible'); dom.speakerNotes.setAttribute( 'data-layout', typeof config.showNotes === 'string' ? config.showNotes : 'inline' ); } else { dom.speakerNotes.classList.remove('visible'); } if (config.mouseWheel) { document.addEventListener('DOMMouseScroll', onDocumentMouseScroll, false); // FF document.addEventListener('mousewheel', onDocumentMouseScroll, false); } else { document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF document.removeEventListener('mousewheel', onDocumentMouseScroll, false); } // Rolling 3D links if (config.rollingLinks) { enableRollingLinks(); } else { disableRollingLinks(); } // Iframe link previews if (config.previewLinks) { enablePreviewLinks(); disablePreviewLinks('[data-preview-link=false]'); } else { disablePreviewLinks(); enablePreviewLinks('[data-preview-link]:not([data-preview-link=false])'); } // Remove existing auto-slide controls if (autoSlidePlayer) { autoSlidePlayer.destroy(); autoSlidePlayer = null; } // Generate auto-slide controls if needed if ( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) { autoSlidePlayer = new Playback(dom.wrapper, function() { return Math.min( Math.max((Date.now() - autoSlideStartTime) / autoSlide, 0), 1 ); }); autoSlidePlayer.on('click', onAutoSlidePlayerClick); autoSlidePaused = false; } // When fragments are turned off they should be visible if (config.fragments === false) { toArray(dom.slides.querySelectorAll('.fragment')).forEach(function( element ) { element.classList.add('visible'); element.classList.remove('current-fragment'); }); } // Slide numbers var slideNumberDisplay = 'none'; if (config.slideNumber && !isPrintingPDF()) { if (config.showSlideNumber === 'all') { slideNumberDisplay = 'block'; } else if (config.showSlideNumber === 'speaker' && isSpeakerNotes()) { slideNumberDisplay = 'block'; } } dom.slideNumber.style.display = slideNumberDisplay; sync(); } /** * Binds all event listeners. */ function addEventListeners() { eventsAreBound = true; window.addEventListener('hashchange', onWindowHashChange, false); window.addEventListener('resize', onWindowResize, false); if (config.touch) { dom.wrapper.addEventListener('touchstart', onTouchStart, false); dom.wrapper.addEventListener('touchmove', onTouchMove, false); dom.wrapper.addEventListener('touchend', onTouchEnd, false); // Support pointer-style touch interaction as well if (window.navigator.pointerEnabled) { // IE 11 uses un-prefixed version of pointer events dom.wrapper.addEventListener('pointerdown', onPointerDown, false); dom.wrapper.addEventListener('pointermove', onPointerMove, false); dom.wrapper.addEventListener('pointerup', onPointerUp, false); } else if (window.navigator.msPointerEnabled) { // IE 10 uses prefixed version of pointer events dom.wrapper.addEventListener('MSPointerDown', onPointerDown, false); dom.wrapper.addEventListener('MSPointerMove', onPointerMove, false); dom.wrapper.addEventListener('MSPointerUp', onPointerUp, false); } } if (config.keyboard) { document.addEventListener('keydown', onDocumentKeyDown, false); document.addEventListener('keypress', onDocumentKeyPress, false); } if (config.progress && dom.progress) { dom.progress.addEventListener('click', onProgressClicked, false); } if (config.focusBodyOnPageVisibilityChange) { var visibilityChange; if ('hidden' in document) { visibilityChange = 'visibilitychange'; } else if ('msHidden' in document) { visibilityChange = 'msvisibilitychange'; } else if ('webkitHidden' in document) { visibilityChange = 'webkitvisibilitychange'; } if (visibilityChange) { document.addEventListener( visibilityChange, onPageVisibilityChange, false ); } } // Listen to both touch and click events, in case the device // supports both var pointerEvents = ['touchstart', 'click']; // Only support touch for Android, fixes double navigations in // stock browser if (UA.match(/android/gi)) { pointerEvents = ['touchstart']; } pointerEvents.forEach(function(eventName) { dom.controlsLeft.forEach(function(el) { el.addEventListener(eventName, onNavigateLeftClicked, false); }); dom.controlsRight.forEach(function(el) { el.addEventListener(eventName, onNavigateRightClicked, false); }); dom.controlsUp.forEach(function(el) { el.addEventListener(eventName, onNavigateUpClicked, false); }); dom.controlsDown.forEach(function(el) { el.addEventListener(eventName, onNavigateDownClicked, false); }); dom.controlsPrev.forEach(function(el) { el.addEventListener(eventName, onNavigatePrevClicked, false); }); dom.controlsNext.forEach(function(el) { el.addEventListener(eventName, onNavigateNextClicked, false); }); }); } /** * Unbinds all event listeners. */ function removeEventListeners() { eventsAreBound = false; document.removeEventListener('keydown', onDocumentKeyDown, false); document.removeEventListener('keypress', onDocumentKeyPress, false); window.removeEventListener('hashchange', onWindowHashChange, false); window.removeEventListener('resize', onWindowResize, false); dom.wrapper.removeEventListener('touchstart', onTouchStart, false); dom.wrapper.removeEventListener('touchmove', onTouchMove, false); dom.wrapper.removeEventListener('touchend', onTouchEnd, false); // IE11 if (window.navigator.pointerEnabled) { dom.wrapper.removeEventListener('pointerdown', onPointerDown, false); dom.wrapper.removeEventListener('pointermove', onPointerMove, false); dom.wrapper.removeEventListener('pointerup', onPointerUp, false); } else if (window.navigator.msPointerEnabled) { // IE10 dom.wrapper.removeEventListener('MSPointerDown', onPointerDown, false); dom.wrapper.removeEventListener('MSPointerMove', onPointerMove, false); dom.wrapper.removeEventListener('MSPointerUp', onPointerUp, false); } if (config.progress && dom.progress) { dom.progress.removeEventListener('click', onProgressClicked, false); } ['touchstart', 'click'].forEach(function(eventName) { dom.controlsLeft.forEach(function(el) { el.removeEventListener(eventName, onNavigateLeftClicked, false); }); dom.controlsRight.forEach(function(el) { el.removeEventListener(eventName, onNavigateRightClicked, false); }); dom.controlsUp.forEach(function(el) { el.removeEventListener(eventName, onNavigateUpClicked, false); }); dom.controlsDown.forEach(function(el) { el.removeEventListener(eventName, onNavigateDownClicked, false); }); dom.controlsPrev.forEach(function(el) { el.removeEventListener(eventName, onNavigatePrevClicked, false); }); dom.controlsNext.forEach(function(el) { el.removeEventListener(eventName, onNavigateNextClicked, false); }); }); } /** * Extend object a with the properties of object b. * If there's a conflict, object b takes precedence. * * @param {object} a * @param {object} b */ function extend(a, b) { for (var i in b) { a[i] = b[i]; } } /** * Converts the target object to an array. * * @param {object} o * @return {object[]} */ function toArray(o) { return Array.prototype.slice.call(o); } /** * Utility for deserializing a value. * * @param {*} value * @return {*} */ function deserialize(value) { if (typeof value === 'string') { if (value === 'null') return null; else if (value === 'true') return true; else if (value === 'false') return false; else if (value.match(/^[\d\.]+$/)) return parseFloat(value); } return value; } /** * Measures the distance in pixels between point a * and point b. * * @param {object} a point with x/y properties * @param {object} b point with x/y properties * * @return {number} */ function distanceBetween(a, b) { var dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt(dx * dx + dy * dy); } /** * Applies a CSS transform to the target element. * * @param {HTMLElement} element * @param {string} transform */ function transformElement(element, transform) { element.style.WebkitTransform = transform; element.style.MozTransform = transform; element.style.msTransform = transform; element.style.transform = transform; } /** * Applies CSS transforms to the slides container. The container * is transformed from two separate sources: layout and the overview * mode. * * @param {object} transforms */ function transformSlides(transforms) { // Pick up new transforms from arguments if (typeof transforms.layout === 'string') slidesTransform.layout = transforms.layout; if (typeof transforms.overview === 'string') slidesTransform.overview = transforms.overview; // Apply the transforms to the slides container if (slidesTransform.layout) { transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview ); } else { transformElement(dom.slides, slidesTransform.overview); } } /** * Injects the given CSS styles into the DOM. * * @param {string} value */ function injectStyleSheet(value) { var tag = document.createElement('style'); tag.type = 'text/css'; if (tag.styleSheet) { tag.styleSheet.cssText = value; } else { tag.appendChild(document.createTextNode(value)); } document.getElementsByTagName('head')[0].appendChild(tag); } /** * Find the closest parent that matches the given * selector. * * @param {HTMLElement} target The child element * @param {String} selector The CSS selector to match * the parents against * * @return {HTMLElement} The matched parent or null * if no matching parent was found */ function closestParent(target, selector) { var parent = target.parentNode; while (parent) { // There's some overhead doing this each time, we don't // want to rewrite the element prototype but should still // be enough to feature detect once at startup... var matchesMethod = parent.matches || parent.matchesSelector || parent.msMatchesSelector; // If we find a match, we're all set if (matchesMethod && matchesMethod.call(parent, selector)) { return parent; } // Keep searching parent = parent.parentNode; } return null; } /** * Converts various color input formats to an {r:0,g:0,b:0} object. * * @param {string} color The string representation of a color * @example * colorToRgb('#000'); * @example * colorToRgb('#000000'); * @example * colorToRgb('rgb(0,0,0)'); * @example * colorToRgb('rgba(0,0,0)'); * * @return {{r: number, g: number, b: number, [a]: number}|null} */ function colorToRgb(color) { var hex3 = color.match(/^#([0-9a-f]{3})$/i); if (hex3 && hex3[1]) { hex3 = hex3[1]; return { r: parseInt(hex3.charAt(0), 16) * 0x11, g: parseInt(hex3.charAt(1), 16) * 0x11, b: parseInt(hex3.charAt(2), 16) * 0x11 }; } var hex6 = color.match(/^#([0-9a-f]{6})$/i); if (hex6 && hex6[1]) { hex6 = hex6[1]; return { r: parseInt(hex6.substr(0, 2), 16), g: parseInt(hex6.substr(2, 2), 16), b: parseInt(hex6.substr(4, 2), 16) }; } var rgb = color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i); if (rgb) { return { r: parseInt(rgb[1], 10), g: parseInt(rgb[2], 10), b: parseInt(rgb[3], 10) }; } var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i ); if (rgba) { return { r: parseInt(rgba[1], 10), g: parseInt(rgba[2], 10), b: parseInt(rgba[3], 10), a: parseFloat(rgba[4]) }; } return null; } /** * Calculates brightness on a scale of 0-255. * * @param {string} color See colorToRgb for supported formats. * @see {@link colorToRgb} */ function colorBrightness(color) { if (typeof color === 'string') color = colorToRgb(color); if (color) { return (color.r * 299 + color.g * 587 + color.b * 114) / 1000; } return null; } /** * Returns the remaining height within the parent of the * target element. * * remaining height = [ configured parent height ] - [ current parent height ] * * @param {HTMLElement} element * @param {number} [height] */ function getRemainingHeight(element, height) { height = height || 0; if (element) { var newHeight, oldHeight = element.style.height; // Change the .stretch element height to 0 in order find the height of all // the other elements element.style.height = '0px'; newHeight = height - element.parentNode.offsetHeight; // Restore the old height, just in case element.style.height = oldHeight + 'px'; return newHeight; } return height; } /** * Checks if this instance is being used to print a PDF. */ function isPrintingPDF() { return /print-pdf/gi.test(window.location.search); } /** * Hides the address bar if we're on a mobile device. */ function hideAddressBar() { if (config.hideAddressBar && isMobileDevice) { // Events that should trigger the address bar to hide window.addEventListener('load', removeAddressBar, false); window.addEventListener('orientationchange', removeAddressBar, false); } } /** * Causes the address bar to hide on mobile devices, * more vertical space ftw. */ function removeAddressBar() { setTimeout(function() { window.scrollTo(0, 1); }, 10); } /** * Dispatches an event of the specified type from the * reveal DOM element. */ function dispatchEvent(type, args) { var event = document.createEvent('HTMLEvents', 1, 2); event.initEvent(type, true, true); extend(event, args); dom.wrapper.dispatchEvent(event); // If we're in an iframe, post each reveal.js event to the // parent window. Used by the notes plugin if (config.postMessageEvents && window.parent !== window.self) { window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' ); } } /** * Wrap all links in 3D goodness. */ function enableRollingLinks() { if (features.transforms3d && !('msPerspective' in document.body.style)) { var anchors = dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ' a'); for (var i = 0, len = anchors.length; i < len; i++) { var anchor = anchors[i]; if ( anchor.textContent && !anchor.querySelector('*') && (!anchor.className || !anchor.classList.contains(anchor, 'roll')) ) { var span = document.createElement('span'); span.setAttribute('data-title', anchor.text); span.innerHTML = anchor.innerHTML; anchor.classList.add('roll'); anchor.innerHTML = ''; anchor.appendChild(span); } } } } /** * Unwrap all 3D links. */ function disableRollingLinks() { var anchors = dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ' a.roll'); for (var i = 0, len = anchors.length; i < len; i++) { var anchor = anchors[i]; var span = anchor.querySelector('span'); if (span) { anchor.classList.remove('roll'); anchor.innerHTML = span.innerHTML; } } } /** * Bind preview frame links. * * @param {string} [selector=a] - selector for anchors */ function enablePreviewLinks(selector) { var anchors = toArray(document.querySelectorAll(selector ? selector : 'a')); anchors.forEach(function(element) { if (/^(http|www)/gi.test(element.getAttribute('href'))) { element.addEventListener('click', onPreviewLinkClicked, false); } }); } /** * Unbind preview frame links. */ function disablePreviewLinks(selector) { var anchors = toArray(document.querySelectorAll(selector ? selector : 'a')); anchors.forEach(function(element) { if (/^(http|www)/gi.test(element.getAttribute('href'))) { element.removeEventListener('click', onPreviewLinkClicked, false); } }); } /** * Opens a preview window for the target URL. * * @param {string} url - url for preview iframe src */ function showPreview(url) { closeOverlay(); dom.overlay = document.createElement('div'); dom.overlay.classList.add('overlay'); dom.overlay.classList.add('overlay-preview'); dom.wrapper.appendChild(dom.overlay); dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '<a class="external" href="' + url + '" target="_blank"><span class="icon"></span></a>', '</header>', '<div class="spinner"></div>', '<div class="viewport">', '<iframe src="' + url + '"></iframe>', '<small class="viewport-inner">', '<span class="x-frame-error">Unable to load iframe. This is likely due to the site\'s policy (x-frame-options).</span>', '</small>', '</div>' ].join(''); dom.overlay.querySelector('iframe').addEventListener( 'load', function(event) { dom.overlay.classList.add('loaded'); }, false ); dom.overlay.querySelector('.close').addEventListener( 'click', function(event) { closeOverlay(); event.preventDefault(); }, false ); dom.overlay.querySelector('.external').addEventListener( 'click', function(event) { closeOverlay(); }, false ); setTimeout(function() { dom.overlay.classList.add('visible'); }, 1); } /** * Open or close help overlay window. * * @param {Boolean} [override] Flag which overrides the * toggle logic and forcibly sets the desired state. True means * help is open, false means it's closed. */ function toggleHelp(override) { if (typeof override === 'boolean') { override ? showHelp() : closeOverlay(); } else { if (dom.overlay) { closeOverlay(); } else { showHelp(); } } } /** * Opens an overlay window with help material. */ function showHelp() { if (config.help) { closeOverlay(); dom.overlay = document.createElement('div'); dom.overlay.classList.add('overlay'); dom.overlay.classList.add('overlay-help'); dom.wrapper.appendChild(dom.overlay); var html = '<p class="title">Keyboard Shortcuts</p><br/>'; html += '<table><th>KEY</th><th>ACTION</th>'; for (var key in keyboardShortcuts) { html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[key] + '</td></tr>'; } html += '</table>'; dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '</header>', '<div class="viewport">', '<div class="viewport-inner">' + html + '</div>', '</div>' ].join(''); dom.overlay.querySelector('.close').addEventListener( 'click', function(event) { closeOverlay(); event.preventDefault(); }, false ); setTimeout(function() { dom.overlay.classList.add('visible'); }, 1); } } /** * Closes any currently open overlay. */ function closeOverlay() { if (dom.overlay) { dom.overlay.parentNode.removeChild(dom.overlay); dom.overlay = null; } } /** * Applies JavaScript-controlled layout rules to the * presentation. */ function layout() { if (dom.wrapper && !isPrintingPDF()) { var size = getComputedSlideSize(); // Layout the contents of the slides layoutSlideContents(config.width, config.height); dom.slides.style.width = size.width + 'px'; dom.slides.style.height = size.height + 'px'; // Determine scale of content to fit within available space scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height ); // Respect max/min scale settings scale = Math.max(scale, config.minScale); scale = Math.min(scale, config.maxScale); // Don't apply any scaling styles if scale is 1 if (scale === 1) { dom.slides.style.zoom = ''; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides({ layout: '' }); } else { // Prefer zoom for scaling up so that content remains crisp. // Don't use zoom to scale down since that can lead to shifts // in text layout/line breaks. if (scale > 1 && features.zoom) { dom.slides.style.zoom = scale; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides({ layout: '' }); } else { // Apply scale transform as a fallback dom.slides.style.zoom = ''; dom.slides.style.left = '50%'; dom.slides.style.top = '50%'; dom.slides.style.bottom = 'auto'; dom.slides.style.right = 'auto'; transformSlides({ layout: 'translate(-50%, -50%) scale(' + scale + ')' }); } } // Select all slides, vertical and horizontal var slides = toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR)); for (var i = 0, len = slides.length; i < len; i++) { var slide = slides[i]; // Don't bother updating invisible slides if (slide.style.display === 'none') { continue; } if (config.center || slide.classList.contains('center')) { // Vertical stacks are not centred since their section // children will be if (slide.classList.contains('stack')) { slide.style.top = 0; } else { slide.style.top = Math.max((size.height - slide.scrollHeight) / 2, 0) + 'px'; } } else { slide.style.top = ''; } } updateProgress(); updateParallax(); if (isOverview()) { updateOverview(); } } } /** * Applies layout logic to the contents of all slides in * the presentation. * * @param {string|number} width * @param {string|number} height */ function layoutSlideContents(width, height) { // Handle sizing of elements with the 'stretch' class toArray(dom.slides.querySelectorAll('section > .stretch')).forEach(function( element ) { // Determine how much vertical space we can use var remainingHeight = getRemainingHeight(element, height); // Consider the aspect ratio of media elements if (/(img|video)/gi.test(element.nodeName)) { var nw = element.naturalWidth || element.videoWidth, nh = element.naturalHeight || element.videoHeight; var es = Math.min(width / nw, remainingHeight / nh); element.style.width = nw * es + 'px'; element.style.height = nh * es + 'px'; } else { element.style.width = width + 'px'; element.style.height = remainingHeight + 'px'; } }); } /** * Calculates the computed pixel size of our slides. These * values are based on the width and height configuration * options. * * @param {number} [presentationWidth=dom.wrapper.offsetWidth] * @param {number} [presentationHeight=dom.wrapper.offsetHeight] */ function getComputedSlideSize(presentationWidth, presentationHeight) { var size = { // Slide size width: config.width, height: config.height, // Presentation size presentationWidth: presentationWidth || dom.wrapper.offsetWidth, presentationHeight: presentationHeight || dom.wrapper.offsetHeight }; // Reduce available space by margin size.presentationWidth -= size.presentationWidth * config.margin; size.presentationHeight -= size.presentationHeight * config.margin; // Slide width may be a percentage of available width if (typeof size.width === 'string' && /%$/.test(size.width)) { size.width = (parseInt(size.width, 10) / 100) * size.presentationWidth; } // Slide height may be a percentage of available height if (typeof size.height === 'string' && /%$/.test(size.height)) { size.height = (parseInt(size.height, 10) / 100) * size.presentationHeight; } return size; } /** * Stores the vertical index of a stack so that the same * vertical slide can be selected when navigating to and * from the stack. * * @param {HTMLElement} stack The vertical stack element * @param {string|number} [v=0] Index to memorize */ function setPreviousVerticalIndex(stack, v) { if (typeof stack === 'object' && typeof stack.setAttribute === 'function') { stack.setAttribute('data-previous-indexv', v || 0); } } /** * Retrieves the vertical index which was stored using * #setPreviousVerticalIndex() or 0 if no previous index * exists. * * @param {HTMLElement} stack The vertical stack element */ function getPreviousVerticalIndex(stack) { if ( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains('stack') ) { // Prefer manually defined start-indexv var attributeName = stack.hasAttribute('data-start-indexv') ? 'data-start-indexv' : 'data-previous-indexv'; return parseInt(stack.getAttribute(attributeName) || 0, 10); } return 0; } /** * Displays the overview of slides (quick nav) by scaling * down and arranging all slide elements. */ function activateOverview() { // Only proceed if enabled in config if (config.overview && !isOverview()) { overview = true; dom.wrapper.classList.add('overview'); dom.wrapper.classList.remove('overview-deactivating'); if (features.overviewTransitions) { setTimeout(function() { dom.wrapper.classList.add('overview-animated'); }, 1); } // Don't auto-slide while in overview mode cancelAutoSlide(); // Move the backgrounds element into the slide container to // that the same scaling is applied dom.slides.appendChild(dom.background); // Clicking on an overview slide navigates to it toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR)).forEach(function( slide ) { if (!slide.classList.contains('stack')) { slide.addEventListener('click', onOverviewSlideClicked, true); } }); // Calculate slide sizes var margin = 70; var slideSize = getComputedSlideSize(); overviewSlideWidth = slideSize.width + margin; overviewSlideHeight = slideSize.height + margin; // Reverse in RTL mode if (config.rtl) { overviewSlideWidth = -overviewSlideWidth; } updateSlidesVisibility(); layoutOverview(); updateOverview(); layout(); // Notify observers of the overview showing dispatchEvent('overviewshown', { indexh: indexh, indexv: indexv, currentSlide: currentSlide }); } } /** * Uses CSS transforms to position all slides in a grid for * display inside of the overview mode. */ function layoutOverview() { // Layout slides toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)).forEach( function(hslide, h) { hslide.setAttribute('data-index-h', h); transformElement( hslide, 'translate3d(' + h * overviewSlideWidth + 'px, 0, 0)' ); if (hslide.classList.contains('stack')) { toArray(hslide.querySelectorAll('section')).forEach(function( vslide, v ) { vslide.setAttribute('data-index-h', h); vslide.setAttribute('data-index-v', v); transformElement( vslide, 'translate3d(0, ' + v * overviewSlideHeight + 'px, 0)' ); }); } } ); // Layout slide backgrounds toArray(dom.background.childNodes).forEach(function(hbackground, h) { transformElement( hbackground, 'translate3d(' + h * overviewSlideWidth + 'px, 0, 0)' ); toArray(hbackground.querySelectorAll('.slide-background')).forEach( function(vbackground, v) { transformElement( vbackground, 'translate3d(0, ' + v * overviewSlideHeight + 'px, 0)' ); } ); }); } /** * Moves the overview viewport to the current slides. * Called each time the current slide changes. */ function updateOverview() { var vmin = Math.min(window.innerWidth, window.innerHeight); var scale = Math.max(vmin / 5, 150) / vmin; transformSlides({ overview: [ 'scale(' + scale + ')', 'translateX(' + -indexh * overviewSlideWidth + 'px)', 'translateY(' + -indexv * overviewSlideHeight + 'px)' ].join(' ') }); } /** * Exits the slide overview and enters the currently * active slide. */ function deactivateOverview() { // Only proceed if enabled in config if (config.overview) { overview = false; dom.wrapper.classList.remove('overview'); dom.wrapper.classList.remove('overview-animated'); // Temporarily add a class so that transitions can do different things // depending on whether they are exiting/entering overview, or just // moving from slide to slide dom.wrapper.classList.add('overview-deactivating'); setTimeout(function() { dom.wrapper.classList.remove('overview-deactivating'); }, 1); // Move the background element back out dom.wrapper.appendChild(dom.background); // Clean up changes made to slides toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR)).forEach(function( slide ) { transformElement(slide, ''); slide.removeEventListener('click', onOverviewSlideClicked, true); }); // Clean up changes made to backgrounds toArray(dom.background.querySelectorAll('.slide-background')).forEach( function(background) { transformElement(background, ''); } ); transformSlides({ overview: '' }); slide(indexh, indexv); layout(); cueAutoSlide(); // Notify observers of the overview hiding dispatchEvent('overviewhidden', { indexh: indexh, indexv: indexv, currentSlide: currentSlide }); } } /** * Toggles the slide overview mode on and off. * * @param {Boolean} [override] Flag which overrides the * toggle logic and forcibly sets the desired state. True means * overview is open, false means it's closed. */ function toggleOverview(override) { if (typeof override === 'boolean') { override ? activateOverview() : deactivateOverview(); } else { isOverview() ? deactivateOverview() : activateOverview(); } } /** * Checks if the overview is currently active. * * @return {Boolean} true if the overview is active, * false otherwise */ function isOverview() { return overview; } /** * Checks if the current or specified slide is vertical * (nested within another slide). * * @param {HTMLElement} [slide=currentSlide] The slide to check * orientation of * @return {Boolean} */ function isVerticalSlide(slide) { // Prefer slide argument, otherwise use current slide slide = slide ? slide : currentSlide; return ( slide && slide.parentNode && !!slide.parentNode.nodeName.match(/section/i) ); } /** * Handling the fullscreen functionality via the fullscreen API * * @see http://fullscreen.spec.whatwg.org/ * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode */ function enterFullscreen() { var element = document.documentElement; // Check which implementation is available var requestMethod = element.requestFullscreen || element.webkitRequestFullscreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullscreen; if (requestMethod) { requestMethod.apply(element); } } /** * Enters the paused mode which fades everything on screen to * black. */ function pause() { if (config.pause) { var wasPaused = dom.wrapper.classList.contains('paused'); cancelAutoSlide(); dom.wrapper.classList.add('paused'); if (wasPaused === false) { dispatchEvent('paused'); } } } /** * Exits from the paused mode. */ function resume() { var wasPaused = dom.wrapper.classList.contains('paused'); dom.wrapper.classList.remove('paused'); cueAutoSlide(); if (wasPaused) { dispatchEvent('resumed'); } } /** * Toggles the paused mode on and off. */ function togglePause(override) { if (typeof override === 'boolean') { override ? pause() : resume(); } else { isPaused() ? resume() : pause(); } } /** * Checks if we are currently in the paused mode. * * @return {Boolean} */ function isPaused() { return dom.wrapper.classList.contains('paused'); } /** * Toggles the auto slide mode on and off. * * @param {Boolean} [override] Flag which sets the desired state. * True means autoplay starts, false means it stops. */ function toggleAutoSlide(override) { if (typeof override === 'boolean') { override ? resumeAutoSlide() : pauseAutoSlide(); } else { autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide(); } } /** * Checks if the auto slide mode is currently on. * * @return {Boolean} */ function isAutoSliding() { return !!(autoSlide && !autoSlidePaused); } /** * Steps from the current point in the presentation to the * slide which matches the specified horizontal and vertical * indices. * * @param {number} [h=indexh] Horizontal index of the target slide * @param {number} [v=indexv] Vertical index of the target slide * @param {number} [f] Index of a fragment within the * target slide to activate * @param {number} [o] Origin for use in multimaster environments */ function slide(h, v, f, o) { // Remember where we were at before previousSlide = currentSlide; // Query all horizontal slides in the deck var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); // Abort if there are no slides if (horizontalSlides.length === 0) return; // If no vertical index is specified and the upcoming slide is a // stack, resume at its previous vertical index if (v === undefined && !isOverview()) { v = getPreviousVerticalIndex(horizontalSlides[h]); } // If we were on a vertical stack, remember what vertical index // it was on so we can resume at the same position when returning if ( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains('stack') ) { setPreviousVerticalIndex(previousSlide.parentNode, indexv); } // Remember the state before this slide var stateBefore = state.concat(); // Reset the state array state.length = 0; var indexhBefore = indexh || 0, indexvBefore = indexv || 0; // Activate and transition to the new slide indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h ); indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v ); // Update the visibility of slides now that the indices have changed updateSlidesVisibility(); layout(); // Apply the new state stateLoop: for (var i = 0, len = state.length; i < len; i++) { // Check if this state existed on the previous slide. If it // did, we will avoid adding it repeatedly for (var j = 0; j < stateBefore.length; j++) { if (stateBefore[j] === state[i]) { stateBefore.splice(j, 1); continue stateLoop; } } document.documentElement.classList.add(state[i]); // Dispatch custom event matching the state's name dispatchEvent(state[i]); } // Clean up the remains of the previous state while (stateBefore.length) { document.documentElement.classList.remove(stateBefore.pop()); } // Update the overview if it's currently active if (isOverview()) { updateOverview(); } // Find the current horizontal slide and any possible vertical slides // within it var currentHorizontalSlide = horizontalSlides[indexh], currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' ); // Store references to the previous and current slides currentSlide = currentVerticalSlides[indexv] || currentHorizontalSlide; // Show fragment, if specified if (typeof f !== 'undefined') { navigateFragment(f); } // Dispatch an event if the slide changed var slideChanged = indexh !== indexhBefore || indexv !== indexvBefore; if (slideChanged) { dispatchEvent('slidechanged', { indexh: indexh, indexv: indexv, previousSlide: previousSlide, currentSlide: currentSlide, origin: o }); } else { // Ensure that the previous slide is never the same as the current previousSlide = null; } // Solves an edge case where the previous slide maintains the // 'present' class when navigating between adjacent vertical // stacks if (previousSlide) { previousSlide.classList.remove('present'); previousSlide.setAttribute('aria-hidden', 'true'); // Reset all slides upon navigate to home // Issue: #285 if ( dom.wrapper .querySelector(HOME_SLIDE_SELECTOR) .classList.contains('present') ) { // Launch async task setTimeout(function() { var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack' ) ), i; for (i in slides) { if (slides[i]) { // Reset stack setPreviousVerticalIndex(slides[i], 0); } } }, 0); } } // Handle embedded content if (slideChanged || !previousSlide) { stopEmbeddedContent(previousSlide); startEmbeddedContent(currentSlide); } // Announce the current slide contents, for screen readers dom.statusDiv.textContent = getStatusText(currentSlide); updateControls(); updateProgress(); updateBackground(); updateParallax(); updateSlideNumber(); updateNotes(); // Update the URL hash writeURL(); cueAutoSlide(); } /** * Syncs the presentation with the current DOM. Useful * when new slides or control elements are added or when * the configuration has changed. */ function sync() { // Subscribe to input removeEventListeners(); addEventListeners(); // Force a layout to make sure the current config is accounted for layout(); // Reflect the current autoSlide value autoSlide = config.autoSlide; // Start auto-sliding if it's enabled cueAutoSlide(); // Re-create the slide backgrounds createBackgrounds(); // Write the current hash to the URL writeURL(); sortAllFragments(); updateControls(); updateProgress(); updateSlideNumber(); updateSlidesVisibility(); updateBackground(true); updateNotes(); formatEmbeddedContent(); // Start or stop embedded content depending on global config if (config.autoPlayMedia === false) { stopEmbeddedContent(currentSlide); } else { startEmbeddedContent(currentSlide); } if (isOverview()) { layoutOverview(); } } /** * Resets all vertical slides so that only the first * is visible. */ function resetVerticalSlides() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR) ); horizontalSlides.forEach(function(horizontalSlide) { var verticalSlides = toArray(horizontalSlide.querySelectorAll('section')); verticalSlides.forEach(function(verticalSlide, y) { if (y > 0) { verticalSlide.classList.remove('present'); verticalSlide.classList.remove('past'); verticalSlide.classList.add('future'); verticalSlide.setAttribute('aria-hidden', 'true'); } }); }); } /** * Sorts and formats all of fragments in the * presentation. */ function sortAllFragments() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR) ); horizontalSlides.forEach(function(horizontalSlide) { var verticalSlides = toArray(horizontalSlide.querySelectorAll('section')); verticalSlides.forEach(function(verticalSlide, y) { sortFragments(verticalSlide.querySelectorAll('.fragment')); }); if (verticalSlides.length === 0) sortFragments(horizontalSlide.querySelectorAll('.fragment')); }); } /** * Randomly shuffles all slides in the deck. */ function shuffle() { var slides = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR) ); slides.forEach(function(slide) { // Insert this slide next to another random slide. This may // cause the slide to insert before itself but that's fine. dom.slides.insertBefore( slide, slides[Math.floor(Math.random() * slides.length)] ); }); } /** * Updates one dimension of slides by showing the slide * with the specified index. * * @param {string} selector A CSS selector that will fetch * the group of slides we are working with * @param {number} index The index of the slide that should be * shown * * @return {number} The index of the slide that is now shown, * might differ from the passed in index if it was out of * bounds. */ function updateSlides(selector, index) { // Select all slides and convert the NodeList result to // an array var slides = toArray(dom.wrapper.querySelectorAll(selector)), slidesLength = slides.length; var printMode = isPrintingPDF(); if (slidesLength) { // Should the index loop? if (config.loop) { index %= slidesLength; if (index < 0) { index = slidesLength + index; } } // Enforce max and minimum index bounds index = Math.max(Math.min(index, slidesLength - 1), 0); for (var i = 0; i < slidesLength; i++) { var element = slides[i]; var reverse = config.rtl && !isVerticalSlide(element); element.classList.remove('past'); element.classList.remove('present'); element.classList.remove('future'); // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute element.setAttribute('hidden', ''); element.setAttribute('aria-hidden', 'true'); // If this element contains vertical slides if (element.querySelector('section')) { element.classList.add('stack'); } // If we're printing static slides, all slides are "present" if (printMode) { element.classList.add('present'); continue; } if (i < index) { // Any element previous to index is given the 'past' class element.classList.add(reverse ? 'future' : 'past'); if (config.fragments) { var pastFragments = toArray(element.querySelectorAll('.fragment')); // Show all fragments on prior slides while (pastFragments.length) { var pastFragment = pastFragments.pop(); pastFragment.classList.add('visible'); pastFragment.classList.remove('current-fragment'); } } } else if (i > index) { // Any element subsequent to index is given the 'future' class element.classList.add(reverse ? 'past' : 'future'); if (config.fragments) { var futureFragments = toArray( element.querySelectorAll('.fragment.visible') ); // No fragments in future slides should be visible ahead of time while (futureFragments.length) { var futureFragment = futureFragments.pop(); futureFragment.classList.remove('visible'); futureFragment.classList.remove('current-fragment'); } } } } // Mark the current slide as present slides[index].classList.add('present'); slides[index].removeAttribute('hidden'); slides[index].removeAttribute('aria-hidden'); // If this slide has a state associated with it, add it // onto the current state of the deck var slideState = slides[index].getAttribute('data-state'); if (slideState) { state = state.concat(slideState.split(' ')); } } else { // Since there are no slides we can't be anywhere beyond the // zeroth index index = 0; } return index; } /** * Optimization method; hide all slides that are far away * from the present slide. */ function updateSlidesVisibility() { // Select all slides and convert the NodeList result to // an array var horizontalSlides = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR) ), horizontalSlidesLength = horizontalSlides.length, distanceX, distanceY; if (horizontalSlidesLength && typeof indexh !== 'undefined') { // The number of steps away from the present slide that will // be visible var viewDistance = isOverview() ? 10 : config.viewDistance; // Limit view distance on weaker devices if (isMobileDevice) { viewDistance = isOverview() ? 6 : 2; } // All slides need to be visible when exporting to PDF if (isPrintingPDF()) { viewDistance = Number.MAX_VALUE; } for (var x = 0; x < horizontalSlidesLength; x++) { var horizontalSlide = horizontalSlides[x]; var verticalSlides = toArray( horizontalSlide.querySelectorAll('section') ), verticalSlidesLength = verticalSlides.length; // Determine how far away this slide is from the present distanceX = Math.abs((indexh || 0) - x) || 0; // If the presentation is looped, distance should measure // 1 between the first and last slides if (config.loop) { distanceX = Math.abs( ((indexh || 0) - x) % (horizontalSlidesLength - viewDistance) ) || 0; } // Show the horizontal slide if it's within the view distance if (distanceX < viewDistance) { showSlide(horizontalSlide); } else { hideSlide(horizontalSlide); } if (verticalSlidesLength) { var oy = getPreviousVerticalIndex(horizontalSlide); for (var y = 0; y < verticalSlidesLength; y++) { var verticalSlide = verticalSlides[y]; distanceY = x === (indexh || 0) ? Math.abs((indexv || 0) - y) : Math.abs(y - oy); if (distanceX + distanceY < viewDistance) { showSlide(verticalSlide); } else { hideSlide(verticalSlide); } } } } } } /** * Pick up notes from the current slide and display them * to the viewer. * * @see {@link config.showNotes} */ function updateNotes() { if ( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) { dom.speakerNotes.innerHTML = getSlideNotes() || ''; } } /** * Updates the progress bar to reflect the current slide. */ function updateProgress() { // Update progress if enabled if (config.progress && dom.progressbar) { dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px'; } } /** * Updates the slide number div to reflect the current slide. * * The following slide number formats are available: * "h.v": horizontal . vertical slide number (default) * "h/v": horizontal / vertical slide number * "c": flattened slide number * "c/t": flattened slide number / total slides */ function updateSlideNumber() { // Update slide number if enabled if (config.slideNumber && dom.slideNumber) { var value = []; var format = 'h.v'; // Check if a custom number format is available if (typeof config.slideNumber === 'string') { format = config.slideNumber; } switch (format) { case 'c': value.push(getSlidePastCount() + 1); break; case 'c/t': value.push(getSlidePastCount() + 1, '/', getTotalSlides()); break; case 'h/v': value.push(indexh + 1); if (isVerticalSlide()) value.push('/', indexv + 1); break; default: value.push(indexh + 1); if (isVerticalSlide()) value.push('.', indexv + 1); } dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] ); } } /** * Applies HTML formatting to a slide number before it's * written to the DOM. * * @param {number} a Current slide * @param {string} delimiter Character to separate slide numbers * @param {(number|*)} b Total slides * @return {string} HTML string fragment */ function formatSlideNumber(a, delimiter, b) { if (typeof b === 'number' && !isNaN(b)) { return ( '<span class="slide-number-a">' + a + '</span>' + '<span class="slide-number-delimiter">' + delimiter + '</span>' + '<span class="slide-number-b">' + b + '</span>' ); } else { return '<span class="slide-number-a">' + a + '</span>'; } } /** * Updates the state of all control/navigation arrows. */ function updateControls() { var routes = availableRoutes(); var fragments = availableFragments(); // Remove the 'enabled' class from all directions dom.controlsLeft .concat(dom.controlsRight) .concat(dom.controlsUp) .concat(dom.controlsDown) .concat(dom.controlsPrev) .concat(dom.controlsNext) .forEach(function(node) { node.classList.remove('enabled'); node.classList.remove('fragmented'); // Set 'disabled' attribute on all directions node.setAttribute('disabled', 'disabled'); }); // Add the 'enabled' class to the available routes; remove 'disabled' attribute to enable buttons if (routes.left) dom.controlsLeft.forEach(function(el) { el.classList.add('enabled'); el.removeAttribute('disabled'); }); if (routes.right) dom.controlsRight.forEach(function(el) { el.classList.add('enabled'); el.removeAttribute('disabled'); }); if (routes.up) dom.controlsUp.forEach(function(el) { el.classList.add('enabled'); el.removeAttribute('disabled'); }); if (routes.down) dom.controlsDown.forEach(function(el) { el.classList.add('enabled'); el.removeAttribute('disabled'); }); // Prev/next buttons if (routes.left || routes.up) dom.controlsPrev.forEach(function(el) { el.classList.add('enabled'); el.removeAttribute('disabled'); }); if (routes.right || routes.down) dom.controlsNext.forEach(function(el) { el.classList.add('enabled'); el.removeAttribute('disabled'); }); // Highlight fragment directions if (currentSlide) { // Always apply fragment decorator to prev/next buttons if (fragments.prev) dom.controlsPrev.forEach(function(el) { el.classList.add('fragmented', 'enabled'); el.removeAttribute('disabled'); }); if (fragments.next) dom.controlsNext.forEach(function(el) { el.classList.add('fragmented', 'enabled'); el.removeAttribute('disabled'); }); // Apply fragment decorators to directional buttons based on // what slide axis they are in if (isVerticalSlide(currentSlide)) { if (fragments.prev) dom.controlsUp.forEach(function(el) { el.classList.add('fragmented', 'enabled'); el.removeAttribute('disabled'); }); if (fragments.next) dom.controlsDown.forEach(function(el) { el.classList.add('fragmented', 'enabled'); el.removeAttribute('disabled'); }); } else { if (fragments.prev) dom.controlsLeft.forEach(function(el) { el.classList.add('fragmented', 'enabled'); el.removeAttribute('disabled'); }); if (fragments.next) dom.controlsRight.forEach(function(el) { el.classList.add('fragmented', 'enabled'); el.removeAttribute('disabled'); }); } } } /** * Updates the background elements to reflect the current * slide. * * @param {boolean} includeAll If true, the backgrounds of * all vertical slides (not just the present) will be updated. */ function updateBackground(includeAll) { var currentBackground = null; // Reverse past/future classes when in RTL mode var horizontalPast = config.rtl ? 'future' : 'past', horizontalFuture = config.rtl ? 'past' : 'future'; // Update the classes of all backgrounds to match the // states of their slides (past/present/future) toArray(dom.background.childNodes).forEach(function(backgroundh, h) { backgroundh.classList.remove('past'); backgroundh.classList.remove('present'); backgroundh.classList.remove('future'); if (h < indexh) { backgroundh.classList.add(horizontalPast); } else if (h > indexh) { backgroundh.classList.add(horizontalFuture); } else { backgroundh.classList.add('present'); // Store a reference to the current background element currentBackground = backgroundh; } if (includeAll || h === indexh) { toArray(backgroundh.querySelectorAll('.slide-background')).forEach( function(backgroundv, v) { backgroundv.classList.remove('past'); backgroundv.classList.remove('present'); backgroundv.classList.remove('future'); if (v < indexv) { backgroundv.classList.add('past'); } else if (v > indexv) { backgroundv.classList.add('future'); } else { backgroundv.classList.add('present'); // Only if this is the present horizontal and vertical slide if (h === indexh) currentBackground = backgroundv; } } ); } }); // Stop content inside of previous backgrounds if (previousBackground) { stopEmbeddedContent(previousBackground); } // Start content in the current background if (currentBackground) { startEmbeddedContent(currentBackground); var backgroundImageURL = currentBackground.style.backgroundImage || ''; // Restart GIFs (doesn't work in Firefox) if (/\.gif/i.test(backgroundImageURL)) { currentBackground.style.backgroundImage = ''; window.getComputedStyle(currentBackground).opacity; currentBackground.style.backgroundImage = backgroundImageURL; } // Don't transition between identical backgrounds. This // prevents unwanted flicker. var previousBackgroundHash = previousBackground ? previousBackground.getAttribute('data-background-hash') : null; var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' ); if ( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) { dom.background.classList.add('no-transition'); } previousBackground = currentBackground; } // If there's a background brightness flag for this slide, // bubble it to the .reveal container if (currentSlide) { ['has-light-background', 'has-dark-background'].forEach(function( classToBubble ) { if (currentSlide.classList.contains(classToBubble)) { dom.wrapper.classList.add(classToBubble); } else { dom.wrapper.classList.remove(classToBubble); } }); } // Allow the first background to apply without transition setTimeout(function() { dom.background.classList.remove('no-transition'); }, 1); } /** * Updates the position of the parallax background based * on the current slide index. */ function updateParallax() { if (config.parallaxBackgroundImage) { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll(VERTICAL_SLIDES_SELECTOR); var backgroundSize = dom.background.style.backgroundSize.split(' '), backgroundWidth, backgroundHeight; if (backgroundSize.length === 1) { backgroundWidth = backgroundHeight = parseInt(backgroundSize[0], 10); } else { backgroundWidth = parseInt(backgroundSize[0], 10); backgroundHeight = parseInt(backgroundSize[1], 10); } var slideWidth = dom.background.offsetWidth, horizontalSlideCount = horizontalSlides.length, horizontalOffsetMultiplier, horizontalOffset; if (typeof config.parallaxBackgroundHorizontal === 'number') { horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal; } else { horizontalOffsetMultiplier = horizontalSlideCount > 1 ? (backgroundWidth - slideWidth) / (horizontalSlideCount - 1) : 0; } horizontalOffset = horizontalOffsetMultiplier * indexh * -1; var slideHeight = dom.background.offsetHeight, verticalSlideCount = verticalSlides.length, verticalOffsetMultiplier, verticalOffset; if (typeof config.parallaxBackgroundVertical === 'number') { verticalOffsetMultiplier = config.parallaxBackgroundVertical; } else { verticalOffsetMultiplier = (backgroundHeight - slideHeight) / (verticalSlideCount - 1); } verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv : 0; dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px'; } } /** * Called when the given slide is within the configured view * distance. Shows the slide element and loads any content * that is set to load lazily (data-src). * * @param {HTMLElement} slide Slide to show */ /** * Called when the given slide is within the configured view * distance. Shows the slide element and loads any content * that is set to load lazily (data-src). * * @param {HTMLElement} slide Slide to show */ function showSlide(slide) { // Show the slide element slide.style.display = config.display; // Media elements with data-src attributes toArray( slide.querySelectorAll('img[data-src], video[data-src], audio[data-src]') ).forEach(function(element) { element.setAttribute('src', element.getAttribute('data-src')); element.removeAttribute('data-src'); }); // Media elements with <source> children toArray(slide.querySelectorAll('video, audio')).forEach(function(media) { var sources = 0; toArray(media.querySelectorAll('source[data-src]')).forEach(function( source ) { source.setAttribute('src', source.getAttribute('data-src')); source.removeAttribute('data-src'); sources += 1; }); // If we rewrote sources for this video/audio element, we need // to manually tell it to load from its new origin if (sources > 0) { media.load(); } }); // Show the corresponding background element var indices = getIndices(slide); var background = getSlideBackground(indices.h, indices.v); if (background) { background.style.display = 'block'; // If the background contains media, load it if (background.hasAttribute('data-loaded') === false) { background.setAttribute('data-loaded', 'true'); var backgroundImage = slide.getAttribute('data-background-image'), backgroundVideo = slide.getAttribute('data-background-video'), backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ), backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ), backgroundIframe = slide.getAttribute('data-background-iframe'); // Images if (backgroundImage) { background.style.backgroundImage = 'url(' + backgroundImage + ')'; } else if (backgroundVideo && !isSpeakerNotes()) { // Videos var video = document.createElement('video'); if (backgroundVideoLoop) { video.setAttribute('loop', ''); } if (backgroundVideoMuted) { video.muted = true; } // Inline video playback works (at least in Mobile Safari) as // long as the video is muted and the `playsinline` attribute is // present if (isMobileDevice) { video.muted = true; video.autoplay = true; video.setAttribute('playsinline', ''); } // Support comma separated lists of video sources backgroundVideo.split(',').forEach(function(source) { video.innerHTML += '<source src="' + source + '">'; }); background.appendChild(video); } else if (backgroundIframe) { // Iframes var iframe = document.createElement('iframe'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('mozallowfullscreen', ''); iframe.setAttribute('webkitallowfullscreen', ''); // Only load autoplaying content when the slide is shown to // avoid having it play in the background if (/autoplay=(1|true|yes)/gi.test(backgroundIframe)) { iframe.setAttribute('data-src', backgroundIframe); } else { iframe.setAttribute('src', backgroundIframe); } iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.maxHeight = '100%'; iframe.style.maxWidth = '100%'; background.appendChild(iframe); } } } } /** * Called when the given slide is moved outside of the * configured view distance. * * @param {HTMLElement} slide */ function hideSlide(slide) { // Hide the slide element slide.style.display = 'none'; // Hide the corresponding background element var indices = getIndices(slide); var background = getSlideBackground(indices.h, indices.v); if (background) { background.style.display = 'none'; } } /** * Determine what available routes there are for navigation. * * @return {{left: boolean, right: boolean, up: boolean, down: boolean}} */ function availableRoutes() { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll(VERTICAL_SLIDES_SELECTOR); var routes = { left: indexh > 0 || config.loop, right: indexh < horizontalSlides.length - 1 || config.loop, up: indexv > 0, down: indexv < verticalSlides.length - 1 }; // reverse horizontal controls for rtl if (config.rtl) { var left = routes.left; routes.left = routes.right; routes.right = left; } return routes; } /** * Returns an object describing the available fragment * directions. * * @return {{prev: boolean, next: boolean}} */ function availableFragments() { if (currentSlide && config.fragments) { var fragments = currentSlide.querySelectorAll('.fragment'); var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' ); return { prev: fragments.length - hiddenFragments.length > 0, next: !!hiddenFragments.length }; } else { return { prev: false, next: false }; } } /** * Enforces origin-specific format rules for embedded media. */ function formatEmbeddedContent() { var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) { toArray( dom.slides.querySelectorAll( 'iframe[' + sourceAttribute + '*="' + sourceURL + '"]' ) ).forEach(function(el) { var src = el.getAttribute(sourceAttribute); if (src && src.indexOf(param) === -1) { el.setAttribute( sourceAttribute, src + (!/\?/.test(src) ? '?' : '&') + param ); } }); }; // YouTube frames must include "?enablejsapi=1" _appendParamToIframeSource('src', 'youtube.com/embed/', 'enablejsapi=1'); _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' ); // Vimeo frames must include "?api=1" _appendParamToIframeSource('src', 'player.vimeo.com/', 'api=1'); _appendParamToIframeSource('data-src', 'player.vimeo.com/', 'api=1'); } /** * Start playback of any embedded content inside of * the given element. * * @param {HTMLElement} element */ function startEmbeddedContent(element) { if (element && !isSpeakerNotes()) { // Restart GIFs toArray(element.querySelectorAll('img[src$=".gif"]')).forEach(function( el ) { // Setting the same unchanged source like this was confirmed // to work in Chrome, FF & Safari el.setAttribute('src', el.getAttribute('src')); }); // HTML5 media elements toArray(element.querySelectorAll('video, audio')).forEach(function(el) { if ( closestParent(el, '.fragment') && !closestParent(el, '.fragment.visible') ) { return; } // Prefer an explicit global autoplay setting var autoplay = config.autoPlayMedia; // If no global setting is available, fall back on the element's // own autoplay setting if (typeof autoplay !== 'boolean') { autoplay = el.hasAttribute('data-autoplay') || !!closestParent(el, '.slide-background'); } if (autoplay && typeof el.play === 'function') { if (el.readyState > 1) { startEmbeddedMedia({ target: el }); } else { el.removeEventListener('loadeddata', startEmbeddedMedia); // remove first to avoid dupes el.addEventListener('loadeddata', startEmbeddedMedia); } } }); // Normal iframes toArray(element.querySelectorAll('iframe[src]')).forEach(function(el) { if ( closestParent(el, '.fragment') && !closestParent(el, '.fragment.visible') ) { return; } startEmbeddedIframe({ target: el }); }); // Lazy loading iframes toArray(element.querySelectorAll('iframe[data-src]')).forEach(function( el ) { if ( closestParent(el, '.fragment') && !closestParent(el, '.fragment.visible') ) { return; } if (el.getAttribute('src') !== el.getAttribute('data-src')) { el.removeEventListener('load', startEmbeddedIframe); // remove first to avoid dupes el.addEventListener('load', startEmbeddedIframe); el.setAttribute('src', el.getAttribute('data-src')); } }); } } /** * Starts playing an embedded video/audio element after * it has finished loading. * * @param {object} event */ function startEmbeddedMedia(event) { var isAttachedToDOM = !!closestParent(event.target, 'html'), isVisible = !!closestParent(event.target, '.present'); if (isAttachedToDOM && isVisible) { event.target.currentTime = 0; event.target.play(); } event.target.removeEventListener('loadeddata', startEmbeddedMedia); } /** * "Starts" the content of an embedded iframe using the * postMessage API. * * @param {object} event */ function startEmbeddedIframe(event) { var iframe = event.target; if (iframe && iframe.contentWindow) { var isAttachedToDOM = !!closestParent(event.target, 'html'), isVisible = !!closestParent(event.target, '.present'); if (isAttachedToDOM && isVisible) { // Prefer an explicit global autoplay setting var autoplay = config.autoPlayMedia; // If no global setting is available, fall back on the element's // own autoplay setting if (typeof autoplay !== 'boolean') { autoplay = iframe.hasAttribute('data-autoplay') || !!closestParent(iframe, '.slide-background'); } // YouTube postMessage API if ( /youtube\.com\/embed\//.test(iframe.getAttribute('src')) && autoplay ) { iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ); } else if ( /player\.vimeo\.com\//.test(iframe.getAttribute('src')) && autoplay ) { // Vimeo postMessage API iframe.contentWindow.postMessage('{"method":"play"}', '*'); } else { // Generic postMessage API iframe.contentWindow.postMessage('slide:start', '*'); } } } } /** * Stop playback of any embedded content inside of * the targeted slide. * * @param {HTMLElement} element */ function stopEmbeddedContent(element) { if (element && element.parentNode) { // HTML5 media elements toArray(element.querySelectorAll('video, audio')).forEach(function(el) { if (!el.hasAttribute('data-ignore') && typeof el.pause === 'function') { el.setAttribute('data-paused-by-reveal', ''); el.pause(); } }); // Generic postMessage API for non-lazy loaded iframes toArray(element.querySelectorAll('iframe')).forEach(function(el) { if (el.contentWindow) el.contentWindow.postMessage('slide:stop', '*'); el.removeEventListener('load', startEmbeddedIframe); }); // YouTube postMessage API toArray( element.querySelectorAll('iframe[src*="youtube.com/embed/"]') ).forEach(function(el) { if ( !el.hasAttribute('data-ignore') && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ); } }); // Vimeo postMessage API toArray( element.querySelectorAll('iframe[src*="player.vimeo.com/"]') ).forEach(function(el) { if ( !el.hasAttribute('data-ignore') && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage('{"method":"pause"}', '*'); } }); // Lazy loading iframes toArray(element.querySelectorAll('iframe[data-src]')).forEach(function( el ) { // Only removing the src doesn't actually unload the frame // in all browsers (Firefox) so we set it to blank first el.setAttribute('src', 'about:blank'); el.removeAttribute('src'); }); } } /** * Returns the number of past slides. This can be used as a global * flattened index for slides. * * @return {number} Past slide count */ function getSlidePastCount() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR) ); // The number of past slides var pastCount = 0; // Step through all slides and count the past ones mainLoop: for (var i = 0; i < horizontalSlides.length; i++) { var horizontalSlide = horizontalSlides[i]; var verticalSlides = toArray(horizontalSlide.querySelectorAll('section')); for (var j = 0; j < verticalSlides.length; j++) { // Stop as soon as we arrive at the present if (verticalSlides[j].classList.contains('present')) { break mainLoop; } pastCount++; } // Stop as soon as we arrive at the present if (horizontalSlide.classList.contains('present')) { break; } // Don't count the wrapping section for vertical slides if (horizontalSlide.classList.contains('stack') === false) { pastCount++; } } return pastCount; } /** * Returns a value ranging from 0-1 that represents * how far into the presentation we have navigated. * * @return {number} */ function getProgress() { // The number of past and total slides var totalCount = getTotalSlides(); var pastCount = getSlidePastCount(); if (currentSlide) { var allFragments = currentSlide.querySelectorAll('.fragment'); // If there are fragments in the current slide those should be // accounted for in the progress. if (allFragments.length > 0) { var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' ); // This value represents how big a portion of the slide progress // that is made up by its fragments (0-1) var fragmentWeight = 0.9; // Add fragment progress to the past slide count pastCount += (visibleFragments.length / allFragments.length) * fragmentWeight; } } return pastCount / (totalCount - 1); } /** * Checks if this presentation is running inside of the * speaker notes window. * * @return {boolean} */ function isSpeakerNotes() { return !!window.location.search.match(/receiver/gi); } /** * Reads the current URL (hash) and navigates accordingly. */ function readURL() { var hash = window.location.hash; // Attempt to parse the hash as either an index or name var bits = hash.slice(2).split('/'), name = hash.replace(/#|\//gi, ''); // If the first bit is invalid and there is a name we can // assume that this is a named link if (isNaN(parseInt(bits[0], 10)) && name.length) { var element; // Ensure the named link is a valid HTML ID attribute if (/^[a-zA-Z][\w:.-]*$/.test(name)) { // Find the slide with the specified ID element = document.getElementById(name); } if (element) { // Find the position of the named slide and navigate to it var indices = Reveal.getIndices(element); slide(indices.h, indices.v); } else { // If the slide doesn't exist, navigate to the current slide slide(indexh || 0, indexv || 0); } } else { // Read the index components of the hash var h = parseInt(bits[0], 10) || 0, v = parseInt(bits[1], 10) || 0; if (h !== indexh || v !== indexv) { slide(h, v); } } } /** * Updates the page URL (hash) to reflect the current * state. * * @param {number} delay The time in ms to wait before * writing the hash */ function writeURL(delay) { if (config.history) { // Make sure there's never more than one timeout running clearTimeout(writeURLTimeout); // If a delay is specified, timeout this call if (typeof delay === 'number') { writeURLTimeout = setTimeout(writeURL, delay); } else if (currentSlide) { var url = '/'; // Attempt to create a named link based on the slide's ID var id = currentSlide.getAttribute('id'); if (id) { id = id.replace(/[^a-zA-Z0-9\-\_\:\.]/g, ''); } // If the current slide has an ID, use that as a named link if (typeof id === 'string' && id.length) { url = '/' + id; } else { // Otherwise use the /h/v index if (indexh > 0 || indexv > 0) url += indexh; if (indexv > 0) url += '/' + indexv; } window.location.hash = url; } } } /** * Retrieves the h/v location and fragment of the current, * or specified, slide. * * @param {HTMLElement} [slide] If specified, the returned * index will be for this slide rather than the currently * active one * * @return {{h: number, v: number, f: number}} */ function getIndices(slide) { // By default, return the current indices var h = indexh, v = indexv, f; // If a slide is specified, return the indices of that slide if (slide) { var isVertical = isVerticalSlide(slide); var slideh = isVertical ? slide.parentNode : slide; // Select all horizontal slides var horizontalSlides = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR) ); // Now that we know which the horizontal slide is, get its index h = Math.max(horizontalSlides.indexOf(slideh), 0); // Assume we're not vertical v = undefined; // If this is a vertical slide, grab the vertical index if (isVertical) { v = Math.max( toArray(slide.parentNode.querySelectorAll('section')).indexOf(slide), 0 ); } } if (!slide && currentSlide) { var hasFragments = currentSlide.querySelectorAll('.fragment').length > 0; if (hasFragments) { var currentFragment = currentSlide.querySelector('.current-fragment'); if ( currentFragment && currentFragment.hasAttribute('data-fragment-index') ) { f = parseInt(currentFragment.getAttribute('data-fragment-index'), 10); } else { f = currentSlide.querySelectorAll('.fragment.visible').length - 1; } } } return { h: h, v: v, f: f }; } /** * Retrieves all slides in this presentation. */ function getSlides() { return toArray( dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ':not(.stack)') ); } /** * Retrieves the total number of slides in this presentation. * * @return {number} */ function getTotalSlides() { return getSlides().length; } /** * Returns the slide element matching the specified index. * * @return {HTMLElement} */ function getSlide(x, y) { var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[x]; var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll('section'); if (verticalSlides && verticalSlides.length && typeof y === 'number') { return verticalSlides ? verticalSlides[y] : undefined; } return horizontalSlide; } /** * Returns the background element for the given slide. * All slides, even the ones with no background properties * defined, have a background element so as long as the * index is valid an element will be returned. * * @param {number} x Horizontal background index * @param {number} y Vertical background index * @return {(HTMLElement[]|*)} */ function getSlideBackground(x, y) { // When printing to PDF the slide backgrounds are nested // inside of the slides if (isPrintingPDF()) { var slide = getSlide(x, y); if (slide) { return slide.slideBackgroundElement; } return undefined; } var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[x]; var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll('.slide-background'); if ( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) { return verticalBackgrounds ? verticalBackgrounds[y] : undefined; } return horizontalBackground; } /** * Retrieves the speaker notes from a slide. Notes can be * defined in two ways: * 1. As a data-notes attribute on the slide <section> * 2. As an <aside class="notes"> inside of the slide * * @param {HTMLElement} [slide=currentSlide] * @return {(string|null)} */ function getSlideNotes(slide) { // Default to the current slide slide = slide || currentSlide; // Notes can be specified via the data-notes attribute... if (slide.hasAttribute('data-notes')) { return slide.getAttribute('data-notes'); } // ... or using an <aside class="notes"> element var notesElement = slide.querySelector('aside.notes'); if (notesElement) { return notesElement.innerHTML; } return null; } /** * Retrieves the current state of the presentation as * an object. This state can then be restored at any * time. * * @return {{indexh: number, indexv: number, indexf: number, paused: boolean, overview: boolean}} */ function getState() { var indices = getIndices(); return { indexh: indices.h, indexv: indices.v, indexf: indices.f, paused: isPaused(), overview: isOverview() }; } /** * Restores the presentation to the given state. * * @param {object} state As generated by getState() * @see {@link getState} generates the parameter `state` */ function setState(state) { if (typeof state === 'object') { slide( deserialize(state.indexh), deserialize(state.indexv), deserialize(state.indexf) ); var pausedFlag = deserialize(state.paused), overviewFlag = deserialize(state.overview); if (typeof pausedFlag === 'boolean' && pausedFlag !== isPaused()) { togglePause(pausedFlag); } if (typeof overviewFlag === 'boolean' && overviewFlag !== isOverview()) { toggleOverview(overviewFlag); } } } /** * Return a sorted fragments list, ordered by an increasing * "data-fragment-index" attribute. * * Fragments will be revealed in the order that they are returned by * this function, so you can use the index attributes to control the * order of fragment appearance. * * To maintain a sensible default fragment order, fragments are presumed * to be passed in document order. This function adds a "fragment-index" * attribute to each node if such an attribute is not already present, * and sets that attribute to an integer value which is the position of * the fragment within the fragments list. * * @param {object[]|*} fragments * @return {object[]} sorted Sorted array of fragments */ function sortFragments(fragments) { fragments = toArray(fragments); var ordered = [], unordered = [], sorted = []; // Group ordered and unordered elements fragments.forEach(function(fragment, i) { if (fragment.hasAttribute('data-fragment-index')) { var index = parseInt(fragment.getAttribute('data-fragment-index'), 10); if (!ordered[index]) { ordered[index] = []; } ordered[index].push(fragment); } else { unordered.push([fragment]); } }); // Append fragments without explicit indices in their // DOM order ordered = ordered.concat(unordered); // Manually count the index up per group to ensure there // are no gaps var index = 0; // Push all fragments in their sorted order to an array, // this flattens the groups ordered.forEach(function(group) { group.forEach(function(fragment) { sorted.push(fragment); fragment.setAttribute('data-fragment-index', index); }); index++; }); return sorted; } /** * Navigate to the specified slide fragment. * * @param {?number} index The index of the fragment that * should be shown, -1 means all are invisible * @param {number} offset Integer offset to apply to the * fragment index * * @return {boolean} true if a change was made in any * fragments visibility as part of this call */ function navigateFragment(index, offset) { if (currentSlide && config.fragments) { var fragments = sortFragments(currentSlide.querySelectorAll('.fragment')); if (fragments.length) { // If no index is specified, find the current if (typeof index !== 'number') { var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll('.fragment.visible') ).pop(); if (lastVisibleFragment) { index = parseInt( lastVisibleFragment.getAttribute('data-fragment-index') || 0, 10 ); } else { index = -1; } } // If an offset is specified, apply it to the index if (typeof offset === 'number') { index += offset; } var fragmentsShown = [], fragmentsHidden = []; toArray(fragments).forEach(function(element, i) { if (element.hasAttribute('data-fragment-index')) { i = parseInt(element.getAttribute('data-fragment-index'), 10); } // Visible fragments if (i <= index) { if (!element.classList.contains('visible')) fragmentsShown.push(element); element.classList.add('visible'); element.classList.remove('current-fragment'); // Announce the fragments one by one to the Screen Reader dom.statusDiv.textContent = getStatusText(element); if (i === index) { element.classList.add('current-fragment'); startEmbeddedContent(element); } } else { // Hidden fragments if (element.classList.contains('visible')) fragmentsHidden.push(element); element.classList.remove('visible'); element.classList.remove('current-fragment'); } }); if (fragmentsHidden.length) { dispatchEvent('fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden }); } if (fragmentsShown.length) { dispatchEvent('fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown }); } updateControls(); updateProgress(); return !!(fragmentsShown.length || fragmentsHidden.length); } } return false; } /** * Navigate to the next slide fragment. * * @return {boolean} true if there was a next fragment, * false otherwise */ function nextFragment() { return navigateFragment(null, 1); } /** * Navigate to the previous slide fragment. * * @return {boolean} true if there was a previous fragment, * false otherwise */ function previousFragment() { return navigateFragment(null, -1); } /** * Cues a new automated slide if enabled in the config. */ function cueAutoSlide() { cancelAutoSlide(); if (currentSlide) { var fragment = currentSlide.querySelector('.current-fragment'); // When the slide first appears there is no "current" fragment so // we look for a data-autoslide timing on the first fragment if (!fragment) fragment = currentSlide.querySelector('.fragment'); var fragmentAutoSlide = fragment ? fragment.getAttribute('data-autoslide') : null; var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute('data-autoslide') : null; var slideAutoSlide = currentSlide.getAttribute('data-autoslide'); // Pick value in the following priority order: // 1. Current fragment's data-autoslide // 2. Current slide's data-autoslide // 3. Parent slide's data-autoslide // 4. Global autoSlide setting if (fragmentAutoSlide) { autoSlide = parseInt(fragmentAutoSlide, 10); } else if (slideAutoSlide) { autoSlide = parseInt(slideAutoSlide, 10); } else if (parentAutoSlide) { autoSlide = parseInt(parentAutoSlide, 10); } else { autoSlide = config.autoSlide; } // If there are media elements with data-autoplay, // automatically set the autoSlide duration to the // length of that media. Not applicable if the slide // is divided up into fragments. // playbackRate is accounted for in the duration. if (currentSlide.querySelectorAll('.fragment').length === 0) { toArray(currentSlide.querySelectorAll('video, audio')).forEach(function( el ) { if (el.hasAttribute('data-autoplay')) { if ( autoSlide && (el.duration * 1000) / el.playbackRate > autoSlide ) { autoSlide = (el.duration * 1000) / el.playbackRate + 1000; } } }); } // Cue the next auto-slide if: // - There is an autoSlide value // - Auto-sliding isn't paused by the user // - The presentation isn't paused // - The overview isn't active // - The presentation isn't over if ( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && (!Reveal.isLastSlide() || availableFragments().next || config.loop === true) ) { autoSlideTimeout = setTimeout(function() { typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext(); cueAutoSlide(); }, autoSlide); autoSlideStartTime = Date.now(); } if (autoSlidePlayer) { autoSlidePlayer.setPlaying(autoSlideTimeout !== -1); } } } /** * Cancels any ongoing request to auto-slide. */ function cancelAutoSlide() { clearTimeout(autoSlideTimeout); autoSlideTimeout = -1; } function pauseAutoSlide() { if (autoSlide && !autoSlidePaused) { autoSlidePaused = true; dispatchEvent('autoslidepaused'); clearTimeout(autoSlideTimeout); if (autoSlidePlayer) { autoSlidePlayer.setPlaying(false); } } } function resumeAutoSlide() { if (autoSlide && autoSlidePaused) { autoSlidePaused = false; dispatchEvent('autoslideresumed'); cueAutoSlide(); } } function navigateLeft() { // Reverse for RTL if (config.rtl) { if ( (isOverview() || nextFragment() === false) && availableRoutes().left ) { slide(indexh + 1); } } else if ( (isOverview() || previousFragment() === false) && availableRoutes().left ) { // Normal navigation slide(indexh - 1); } } function navigateRight() { // Reverse for RTL if (config.rtl) { if ( (isOverview() || previousFragment() === false) && availableRoutes().right ) { slide(indexh - 1); } } else if ( (isOverview() || nextFragment() === false) && availableRoutes().right ) { // Normal navigation slide(indexh + 1); } } function navigateUp() { // Prioritize hiding fragments if ( (isOverview() || previousFragment() === false) && availableRoutes().up ) { slide(indexh, indexv - 1); } } function navigateDown() { // Prioritize revealing fragments if ((isOverview() || nextFragment() === false) && availableRoutes().down) { slide(indexh, indexv + 1); } } /** * Navigates backwards, prioritized in the following order: * 1) Previous fragment * 2) Previous vertical slide * 3) Previous horizontal slide */ function navigatePrev() { // Prioritize revealing fragments if (previousFragment() === false) { if (availableRoutes().up) { navigateUp(); } else { // Fetch the previous horizontal slide, if there is one var previousSlide; if (config.rtl) { previousSlide = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR + '.future') ).pop(); } else { previousSlide = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR + '.past') ).pop(); } if (previousSlide) { var v = previousSlide.querySelectorAll('section').length - 1 || undefined; var h = indexh - 1; slide(h, v); } } } } /** * The reverse of #navigatePrev(). */ function navigateNext() { // Prioritize revealing fragments if (nextFragment() === false) { if (availableRoutes().down) { navigateDown(); } else if (config.rtl) { navigateLeft(); } else { navigateRight(); } } } /** * Checks if the target element prevents the triggering of * swipe navigation. */ function isSwipePrevented(target) { while (target && typeof target.hasAttribute === 'function') { if (target.hasAttribute('data-prevent-swipe')) return true; target = target.parentNode; } return false; } // --------------------------------------------------------------------// // ----------------------------- EVENTS -------------------------------// // --------------------------------------------------------------------// /** * Called by all event handlers that are based on user * input. * * @param {object} [event] */ function onUserInput(event) { if (config.autoSlideStoppable) { pauseAutoSlide(); } } /** * Handler for the document level 'keypress' event. * * @param {object} event */ function onDocumentKeyPress(event) { // Check if the pressed key is question mark if (event.shiftKey && event.charCode === 63) { toggleHelp(); } } /** * Handler for the document level 'keydown' event. * * @param {object} event */ function onDocumentKeyDown(event) { // If there's a condition specified and it returns false, // ignore this event if ( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) { return true; } // Remember if auto-sliding was paused so we can toggle it var autoSlideWasPaused = autoSlidePaused; onUserInput(event); // Check if there's a focused element that could be using // the keyboard var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit'; var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test(document.activeElement.tagName); var activeElementIsNotes = document.activeElement && document.activeElement.className && /speaker-notes/i.test(document.activeElement.className); // Disregard the event if there's a focused element or a // keyboard modifier key is present if ( activeElementIsCE || activeElementIsInput || activeElementIsNotes || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return; // While paused only allow resume keyboard events; 'b', 'v', '.' var resumeKeyCodes = [66, 86, 190, 191]; var key; // Custom key bindings for togglePause should be able to resume if (typeof config.keyboard === 'object') { for (key in config.keyboard) { if (config.keyboard[key] === 'togglePause') { resumeKeyCodes.push(parseInt(key, 10)); } } } if (isPaused() && resumeKeyCodes.indexOf(event.keyCode) === -1) { return false; } var triggered = false; // 1. User defined key bindings if (typeof config.keyboard === 'object') { for (key in config.keyboard) { // Check if this binding matches the pressed key if (parseInt(key, 10) === event.keyCode) { var value = config.keyboard[key]; // Callback function if (typeof value === 'function') { value.apply(null, [event]); } else if ( typeof value === 'string' && typeof Reveal[value] === 'function' ) { // String shortcuts to reveal.js API Reveal[value].call(); } triggered = true; } } } // 2. System defined key bindings if (triggered === false) { // Assume true and try to prove false triggered = true; switch (event.keyCode) { // p, page up, arrow up case 80: case 33: case 38: navigatePrev(); break; // n, page down, arrow down case 78: case 34: case 40: navigateNext(); break; // h, left case 72: case 37: navigateLeft(); break; // l, right case 76: case 39: navigateRight(); break; // k, up case 75: navigateUp(); break; // j, down case 74: navigateDown(); break; // home case 36: slide(0); break; // end case 35: slide(Number.MAX_VALUE); break; // space case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break; // return case 13: isOverview() ? deactivateOverview() : (triggered = false); break; // two-spot, semicolon, b, v, period, Logitech presenter tools "black screen" button case 58: case 59: case 66: case 86: case 190: case 191: togglePause(); break; // f case 70: enterFullscreen(); break; // a case 65: if (config.autoSlideStoppable) toggleAutoSlide(autoSlideWasPaused); break; default: triggered = false; } } // If the input resulted in a triggered action we should prevent // the browsers default behavior if (triggered) { event.preventDefault && event.preventDefault(); } else if ( (event.keyCode === 27 || event.keyCode === 79) && features.transforms3d ) { // ESC or O key if (dom.overlay) { closeOverlay(); } else { toggleOverview(); } event.preventDefault && event.preventDefault(); } // If auto-sliding is enabled we need to cue up // another timeout cueAutoSlide(); } /** * Handler for the 'touchstart' event, enables support for * swipe and pinch gestures. * * @param {object} event */ function onTouchStart(event) { if (isSwipePrevented(event.target)) return true; touch.startX = event.touches[0].clientX; touch.startY = event.touches[0].clientY; touch.startCount = event.touches.length; // If there's two touches we need to memorize the distance // between those two points to detect pinching if (event.touches.length === 2 && config.overview) { touch.startSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); } } function applyTouch(type) { let triggered = false; if (typeof config.touches === 'object') { for (let key in config.touches) { // Check if this binding matches the pressed key if (type === key) { var value = config.touches[key]; // Callback function if (typeof value === 'function') { value.apply(null, [type]); } else if ( typeof value === 'string' && typeof Reveal[value] === 'function' ) { // String shortcuts to reveal.js API Reveal[value].call(); } triggered = true; } } } if (!triggered) { switch (type) { case 'pinchOut': activateOverview(); break; case 'pinchIn': deactiveOverview(); break; case 'swipeLeft': navigateLeft(); break; case 'swipeRight': navigateRight(); break; case 'swipeUp': navigateUp(); break; case 'swipeDown': navigateDown(); break; default: break; } } } /** * Handler for the 'touchmove' event. * * @param {object} event */ function onTouchMove(event) { if (isSwipePrevented(event.target)) return true; // Each touch should only trigger one action if (!touch.captured) { onUserInput(event); var currentX = event.touches[0].clientX; var currentY = event.touches[0].clientY; // If the touch started with two points and still has // two active touches; test for the pinch gesture if ( event.touches.length === 2 && touch.startCount === 2 && config.overview ) { // The current distance in pixels between the two touch points var currentSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); // If the span is larger than the desire amount we've got // ourselves a pinch if (Math.abs(touch.startSpan - currentSpan) > touch.threshold) { touch.captured = true; if (currentSpan < touch.startSpan) { applyTouch('pinchOut'); // activateOverview(); } else { applyTouch('pinchIn'); //deactivateOverview(); } } event.preventDefault(); } else if (event.touches.length === 1 && touch.startCount !== 2) { // There was only one touch point, look for a swipe var deltaX = currentX - touch.startX, deltaY = currentY - touch.startY; if (deltaX > touch.threshold && Math.abs(deltaX) > Math.abs(deltaY)) { touch.captured = true; applyTouch('swipeLeft'); //navigateLeft(); } else if ( deltaX < -touch.threshold && Math.abs(deltaX) > Math.abs(deltaY) ) { touch.captured = true; applyTouch('swipeRight'); //navigateRight(); } else if (deltaY > touch.threshold) { touch.captured = true; applyTouch('swipeUp'); //navigateUp(); } else if (deltaY < -touch.threshold) { touch.captured = true; applyTouch('swipeDown'); //navigateDown(); } // If we're embedded, only block touch events if they have // triggered an action if (config.embedded) { if (touch.captured || isVerticalSlide(currentSlide)) { event.preventDefault(); } } else { // Not embedded? Block them all to avoid needless tossing // around of the viewport in iOS event.preventDefault(); } } } else if (UA.match(/android/gi)) { // There's a bug with swiping on some Android devices unless // the default action is always prevented event.preventDefault(); } } /** * Handler for the 'touchend' event. * * @param {object} event */ function onTouchEnd(event) { touch.captured = false; } /** * Convert pointer down to touch start. * * @param {object} event */ function onPointerDown(event) { if ( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === 'touch' ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchStart(event); } } /** * Convert pointer move to touch move. * * @param {object} event */ function onPointerMove(event) { if ( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === 'touch' ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchMove(event); } } /** * Convert pointer up to touch end. * * @param {object} event */ function onPointerUp(event) { if ( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === 'touch' ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchEnd(event); } } /** * Handles mouse wheel scrolling, throttled to avoid skipping * multiple slides. * * @param {object} event */ function onDocumentMouseScroll(event) { if (Date.now() - lastMouseWheelStep > 600) { lastMouseWheelStep = Date.now(); var delta = event.detail || -event.wheelDelta; if (delta > 0) { navigateNext(); } else if (delta < 0) { navigatePrev(); } } } /** * Clicking on the progress bar results in a navigation to the * closest approximate horizontal slide using this equation: * * ( clickX / presentationWidth ) * numberOfSlides * * @param {object} event */ function onProgressClicked(event) { onUserInput(event); event.preventDefault(); var slidesTotal = toArray( dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR) ).length; var slideIndex = Math.floor( (event.clientX / dom.wrapper.offsetWidth) * slidesTotal ); if (config.rtl) { slideIndex = slidesTotal - slideIndex; } slide(slideIndex); } /** * Event handler for navigation control buttons. */ function onNavigateLeftClicked(event) { event.preventDefault(); onUserInput(); navigateLeft(); } function onNavigateRightClicked(event) { event.preventDefault(); onUserInput(); navigateRight(); } function onNavigateUpClicked(event) { event.preventDefault(); onUserInput(); navigateUp(); } function onNavigateDownClicked(event) { event.preventDefault(); onUserInput(); navigateDown(); } function onNavigatePrevClicked(event) { event.preventDefault(); onUserInput(); navigatePrev(); } function onNavigateNextClicked(event) { event.preventDefault(); onUserInput(); navigateNext(); } /** * Handler for the window level 'hashchange' event. * * @param {object} [event] */ function onWindowHashChange(event) { readURL(); } /** * Handler for the window level 'resize' event. * * @param {object} [event] */ function onWindowResize(event) { layout(); } /** * Handle for the window level 'visibilitychange' event. * * @param {object} [event] */ function onPageVisibilityChange(event) { var isHidden = document.webkitHidden || document.msHidden || document.hidden; // If, after clicking a link or similar and we're coming back, // focus the document.body to ensure we can use keyboard shortcuts if (isHidden === false && document.activeElement !== document.body) { // Not all elements support .blur() - SVGs among them. if (typeof document.activeElement.blur === 'function') { document.activeElement.blur(); } document.body.focus(); } } /** * Invoked when a slide is and we're in the overview. * * @param {object} event */ function onOverviewSlideClicked(event) { // TODO There's a bug here where the event listeners are not // removed after deactivating the overview. if (eventsAreBound && isOverview()) { event.preventDefault(); var element = event.target; while (element && !element.nodeName.match(/section/gi)) { element = element.parentNode; } if (element && !element.classList.contains('disabled')) { deactivateOverview(); if (element.nodeName.match(/section/gi)) { var h = parseInt(element.getAttribute('data-index-h'), 10), v = parseInt(element.getAttribute('data-index-v'), 10); slide(h, v); } } } } /** * Handles clicks on links that are set to preview in the * iframe overlay. * * @param {object} event */ function onPreviewLinkClicked(event) { if (event.currentTarget && event.currentTarget.hasAttribute('href')) { var url = event.currentTarget.getAttribute('href'); if (url) { showPreview(url); event.preventDefault(); } } } /** * Handles click on the auto-sliding controls element. * * @param {object} [event] */ function onAutoSlidePlayerClick(event) { // Replay if (Reveal.isLastSlide() && config.loop === false) { slide(0, 0); resumeAutoSlide(); } else if (autoSlidePaused) { // Resume resumeAutoSlide(); } else { // Pause pauseAutoSlide(); } } // --------------------------------------------------------------------// // ------------------------ PLAYBACK COMPONENT ------------------------// // --------------------------------------------------------------------// /** * Constructor for the playback component, which displays * play/pause/progress controls. * * @param {HTMLElement} container The component will append * itself to this * @param {function} progressCheck A method which will be * called frequently to get the current progress on a range * of 0-1 */ function Playback(container, progressCheck) { // Cosmetics this.diameter = 100; this.diameter2 = this.diameter / 2; this.thickness = 6; // Flags if we are currently playing this.playing = false; // Current progress on a 0-1 range this.progress = 0; // Used to loop the animation smoothly this.progressOffset = 1; this.container = container; this.progressCheck = progressCheck; this.canvas = document.createElement('canvas'); this.canvas.className = 'playback'; this.canvas.width = this.diameter; this.canvas.height = this.diameter; this.canvas.style.width = this.diameter2 + 'px'; this.canvas.style.height = this.diameter2 + 'px'; this.context = this.canvas.getContext('2d'); this.container.appendChild(this.canvas); this.render(); } /** * @param value */ Playback.prototype.setPlaying = function(value) { var wasPlaying = this.playing; this.playing = value; // Start repainting if we weren't already if (!wasPlaying && this.playing) { this.animate(); } else { this.render(); } }; Playback.prototype.animate = function() { var progressBefore = this.progress; this.progress = this.progressCheck(); // When we loop, offset the progress so that it eases // smoothly rather than immediately resetting if (progressBefore > 0.8 && this.progress < 0.2) { this.progressOffset = this.progress; } this.render(); if (this.playing) { features.requestAnimationFrameMethod.call( window, this.animate.bind(this) ); } }; /** * Renders the current progress and playback state. */ Playback.prototype.render = function() { var progress = this.playing ? this.progress : 0, radius = this.diameter2 - this.thickness, x = this.diameter2, y = this.diameter2, iconSize = 28; // Ease towards 1 this.progressOffset += (1 - this.progressOffset) * 0.1; var endAngle = -Math.PI / 2 + progress * (Math.PI * 2); var startAngle = -Math.PI / 2 + this.progressOffset * (Math.PI * 2); this.context.save(); this.context.clearRect(0, 0, this.diameter, this.diameter); // Solid background color this.context.beginPath(); this.context.arc(x, y, radius + 4, 0, Math.PI * 2, false); this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )'; this.context.fill(); // Draw progress track this.context.beginPath(); this.context.arc(x, y, radius, 0, Math.PI * 2, false); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#666'; this.context.stroke(); if (this.playing) { // Draw progress on top of track this.context.beginPath(); this.context.arc(x, y, radius, startAngle, endAngle, false); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#fff'; this.context.stroke(); } this.context.translate(x - iconSize / 2, y - iconSize / 2); // Draw play/pause icons if (this.playing) { this.context.fillStyle = '#fff'; this.context.fillRect(0, 0, iconSize / 2 - 4, iconSize); this.context.fillRect(iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize); } else { this.context.beginPath(); this.context.translate(4, 0); this.context.moveTo(0, 0); this.context.lineTo(iconSize - 4, iconSize / 2); this.context.lineTo(0, iconSize); this.context.fillStyle = '#fff'; this.context.fill(); } this.context.restore(); }; Playback.prototype.on = function(type, listener) { this.canvas.addEventListener(type, listener, false); }; Playback.prototype.off = function(type, listener) { this.canvas.removeEventListener(type, listener, false); }; Playback.prototype.destroy = function() { this.playing = false; if (this.canvas.parentNode) { this.container.removeChild(this.canvas); } }; // --------------------------------------------------------------------// // ------------------------------- API --------------------------------// // --------------------------------------------------------------------// Reveal = { VERSION: VERSION, initialize: initialize, configure: configure, sync: sync, // Navigation methods slide: slide, left: navigateLeft, right: navigateRight, up: navigateUp, down: navigateDown, prev: navigatePrev, next: navigateNext, // Fragment methods navigateFragment: navigateFragment, prevFragment: previousFragment, nextFragment: nextFragment, // Deprecated aliases navigateTo: slide, navigateLeft: navigateLeft, navigateRight: navigateRight, navigateUp: navigateUp, navigateDown: navigateDown, navigatePrev: navigatePrev, navigateNext: navigateNext, // Forces an update in slide layout layout: layout, // Randomizes the order of slides shuffle: shuffle, // Returns an object with the available routes as booleans (left/right/top/bottom) availableRoutes: availableRoutes, // Returns an object with the available fragments as booleans (prev/next) availableFragments: availableFragments, // Toggles a help overlay with keyboard shortcuts toggleHelp: toggleHelp, // Toggles the overview mode on/off toggleOverview: toggleOverview, // Toggles the "black screen" mode on/off togglePause: togglePause, // Toggles the auto slide mode on/off toggleAutoSlide: toggleAutoSlide, // State checks isOverview: isOverview, isPaused: isPaused, isAutoSliding: isAutoSliding, // Adds or removes all internal event listeners (such as keyboard) addEventListeners: addEventListeners, removeEventListeners: removeEventListeners, // Facility for persisting and restoring the presentation state getState: getState, setState: setState, // Presentation progress getSlidePastCount: getSlidePastCount, // Presentation progress on range of 0-1 getProgress: getProgress, // Returns the indices of the current, or specified, slide getIndices: getIndices, // Returns an Array of all slides getSlides: getSlides, // Returns the total number of slides getTotalSlides: getTotalSlides, // Returns the slide element at the specified index getSlide: getSlide, // Returns the slide background element at the specified index getSlideBackground: getSlideBackground, // Returns the speaker notes string for a slide, or null getSlideNotes: getSlideNotes, // Returns the previous slide element, may be null getPreviousSlide: function() { return previousSlide; }, // Returns the current slide element getCurrentSlide: function() { return currentSlide; }, // Returns the current scale of the presentation content getScale: function() { return scale; }, // Returns the current configuration object getConfig: function() { return config; }, // Helper method, retrieves query string as a key/value hash getQueryHash: function() { var query = {}; location.search.replace(/[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) { query[a.split('=').shift()] = a.split('=').pop(); }); // Basic deserialization for (var i in query) { var value = query[i]; query[i] = deserialize(unescape(value)); } return query; }, // Returns true if we're currently on the first slide isFirstSlide: function() { return indexh === 0 && indexv === 0; }, // Returns true if we're currently on the last slide isLastSlide: function() { if (currentSlide) { // Does this slide has next a sibling? if (currentSlide.nextElementSibling) return false; // If it's vertical, does its parent have a next sibling? if ( isVerticalSlide(currentSlide) && currentSlide.parentNode.nextElementSibling ) return false; return true; } return false; }, // Checks if reveal.js has been loaded and is ready for use isReady: function() { return loaded; }, // Forward event binding to the reveal DOM element addEventListener: function(type, listener, useCapture) { if ('addEventListener' in window) { (dom.wrapper || document.querySelector('.reveal')).addEventListener( type, listener, useCapture ); } }, removeEventListener: function(type, listener, useCapture) { if ('addEventListener' in window) { (dom.wrapper || document.querySelector('.reveal')).removeEventListener( type, listener, useCapture ); } }, // Programatically triggers a keyboard event triggerKey: function(keyCode) { onDocumentKeyDown({ keyCode: keyCode }); }, // Registers a new shortcut to include in the help overlay registerKeyboardShortcut: function(key, value) { keyboardShortcuts[key] = value; } }; return Reveal; });
module.exports = { preset: "ts-jest", moduleNameMapper: { "^images/(.+)$": "<rootDir>/images/$1", "^src/(.+)$": "<rootDir>/src/$1", }, testEnvironment: "node", };
import { getAttributes } from '@carbon/icon-helpers'; import PropTypes from 'prop-types'; import React from 'react'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var defaultStyle = { "willChange": "transform" }; var NumberSmall_632 = React.forwardRef(function (_ref, ref) { var className = _ref.className, children = _ref.children, style = _ref.style, tabIndex = _ref.tabIndex, rest = _objectWithoutProperties(_ref, ["className", "children", "style", "tabIndex"]); var _getAttributes = getAttributes(_objectSpread({}, rest, { tabindex: tabIndex })), tabindex = _getAttributes.tabindex, props = _objectWithoutProperties(_getAttributes, ["tabindex"]); if (className) { props.className = className; } if (tabindex !== undefined && tabindex !== null) { props.tabIndex = tabindex; } if (_typeof(style) === 'object') { props.style = _objectSpread({}, defaultStyle, style); } else { props.style = defaultStyle; } if (ref) { props.ref = ref; } return React.createElement('svg', props, children, React.createElement('path', { d: 'M17 21h-2a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h3v2h-3v2h2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2zm-2-4v2h2v-2z' })); }); NumberSmall_632.displayName = 'NumberSmall_632'; NumberSmall_632.propTypes = { 'aria-hidden': PropTypes.bool, 'aria-label': PropTypes.string, 'aria-labelledby': PropTypes.string, className: PropTypes.string, children: PropTypes.node, height: PropTypes.number, preserveAspectRatio: PropTypes.string, tabIndex: PropTypes.string, viewBox: PropTypes.string, width: PropTypes.number, xmlns: PropTypes.string }; NumberSmall_632.defaultProps = { width: 32, height: 32, viewBox: '0 0 32 32', xmlns: 'http://www.w3.org/2000/svg', preserveAspectRatio: 'xMidYMid meet' }; export default NumberSmall_632;
import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter, Link, Route, Switch} from 'react-router-dom'; import Home from './pages/home'; import Diagnosis from './pages/diagnosa'; import DeskripsiPenyakit from './pages/deskrpsiPenyakit'; import listPenyakit from './pages/listPenyakit'; const Index = () => { return ( <BrowserRouter> <Switch> <Route exact path="/" component={Diagnosis} /> <Route exact path="/list_penyakit" component={listPenyakit} /> <Route exact path="/deskripsi_penyakit/:id" component={DeskripsiPenyakit} /> </Switch> </BrowserRouter> ) } ReactDOM.render(<Index />, document.getElementById('index'));
import {ADD_PERSON, SWITCH_ACTIVITY} from '../actions/people'; import {combineReducers} from "redux"; const createActivity = (type = "idle") => ({type}); const createPerson = (id, name, activity = createActivity()) => ({id, name, activity}); const personReducer = (state, action) => { const {type, payload} = action; switch (type) { case ADD_PERSON: { const {id, name} = payload; return createPerson(id, name); } case SWITCH_ACTIVITY: { const {activityType} = payload; return {...state, activity: createActivity(activityType)} } default: return state; } }; const byId = (state = {}, action) => { const {type, payload} = action; switch (type) { case ADD_PERSON: { const {id} = payload; return {...state, [id]: personReducer({}, action)}; } case SWITCH_ACTIVITY: { const {personId} = payload; return {...state, [personId]: personReducer(state[personId], action) }; } default: return state; } }; const allIds = (state = [], action) => { const {type, payload} = action; switch (type) { case ADD_PERSON: const {id} = payload; return [...state, id]; default: return state; } }; export default combineReducers({byId, allIds});
Arquivo 1 linha
var MOVES_RBY = { '(No Move)': { bp: 0, type: 'Normal', category: 'Physical' }, 'Acid': { bp: 40, type: 'Poison' }, 'Agility': { bp: 0, type: 'Psychic' }, 'Amnesia': { bp: 0, type: 'Psychic' }, 'Aurora Beam': { bp: 65, type: 'Ice', category: 'Special', hasSecondaryEffect: true }, 'Barrier': { bp: 0, type: 'Psychic' }, 'Bind': { bp: 15, type: 'Normal' }, 'Blizzard': { bp: 120, type: 'Ice', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Body Slam': { bp: 85, type: 'Normal', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Bone Club': { bp: 65, type: 'Ground', category: 'Physical', hasSecondaryEffect: true }, 'Bubble Beam': { bp: 65, type: 'Water' }, 'Clamp': { bp: 35, type: 'Water' }, 'Crabhammer': { bp: 90, type: 'Water', category: 'Physical', makesContact: true, alwaysCrit: true }, 'Confuse Ray': { bp: 0, type: 'Ghost' }, 'Defense Curl': { bp: 0, type: 'Normal' }, 'Dig': { bp: 100, type: 'Ground', makesContact: true }, 'Disable': { bp: 0, type: 'Normal' }, 'Double Kick': { bp: 30, type: 'Fighting', category: 'Physical', makesContact: true, isTwoHit: true }, 'Double-Edge': { bp: 100, type: 'Normal', category: 'Physical', makesContact: true, hasRecoil: true }, 'Double Team': { bp: 0, type: 'Normal' }, 'Dream Eater': { bp: 100, type: 'Psychic', category: 'Special', givesHealth: true }, 'Drill Peck': { bp: 80, type: 'Flying', category: 'Physical', makesContact: true }, 'Earthquake': { bp: 100, type: 'Ground', category: 'Physical', isSpread: true }, 'Explosion': { bp: 170, type: 'Normal', category: 'Physical', isSpread: true }, 'Fire Blast': { bp: 120, type: 'Fire', category: 'Special', hasSecondaryEffect: true }, 'Fire Punch': { bp: 75, type: 'Fire', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isPunch: true }, 'Fire Spin': { bp: 15, type: 'Fire' }, 'Flamethrower': { bp: 95, type: 'Fire', category: 'Special', hasSecondaryEffect: true }, 'Fly': { bp: 70, type: 'Flying', category: 'Physical', makesContact: true }, 'Fury Swipes': { bp: 18, type: 'Normal', category: 'Physical', makesContact: true, isMultiHit: true }, 'Glare': { bp: 0, type: 'Normal' }, 'Gust': { bp: 40, type: 'Normal', category: 'Special' }, 'Haze': { bp: 0, type: 'Ice' }, 'High Jump Kick': { bp: 85, type: 'Fighting', category: 'Physical', makesContact: true, hasRecoil: true }, 'Hydro Pump': { bp: 120, type: 'Water', category: 'Special' }, 'Hyper Beam': { bp: 150, type: 'Normal', category: 'Special' }, 'Ice Beam': { bp: 95, type: 'Ice', category: 'Special', hasSecondaryEffect: true }, 'Ice Punch': { bp: 75, type: 'Ice', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isPunch: true }, 'Jump Kick': { bp: 70, type: 'Fighting', category: 'Physical', makesContact: true, hasRecoil: true }, 'Leech Life': { bp: 20, type: 'Bug', category: 'Physical', makesContact: true, givesHealth: true }, 'Leech Seed': { bp: 0, type: 'Grass' }, 'Light Screen': { bp: 0, type: 'Psychic' }, 'Lovely Kiss': { bp: 0, type: 'Normal' }, 'Mega Drain': { bp: 40, type: 'Grass', givesHealth: true }, 'Mirror Move': { bp: 0, type: 'Flying' }, 'Night Shade': { bp: 100, type: 'Ghost', category: 'Special' }, 'Pin Missile': { bp: 14, type: 'Bug', category: 'Physical', isMultiHit: true }, 'Psychic': { bp: 90, type: 'Psychic', category: 'Special', hasSecondaryEffect: true }, 'Quick Attack': { bp: 40, type: 'Normal', category: 'Physical', makesContact: true, hasPriority: true }, 'Razor Leaf': { bp: 55, type: 'Grass', category: 'Special', alwaysCrit: true }, 'Recover': { bp: 0, type: 'Normal' }, 'Reflect': { bp: 0, type: 'Psychic' }, 'Rest': { bp: 0, type: 'Psychic' }, 'Roar': { bp: 0, type: 'Normal' }, 'Rock Slide': { bp: 75, type: 'Rock', category: 'Physical', hasSecondaryEffect: true, isSpread: true }, 'Rock Throw': { bp: 50, type: 'Rock', category: 'Physical' }, 'Seismic Toss': { bp: 100, type: 'Fighting', category: 'Physical', makesContact: true }, 'Self-Destruct': { bp: 130, type: 'Normal', category: 'Physical', isSpread: true }, 'Sing': { bp: 0, type: 'Normal' }, 'Sky Attack': { bp: 140, type: 'Flying', category: 'Physical', hasSecondaryEffect: true }, 'Skull Bash': { bp: 100, type: 'Normal', category: 'Physical', makesContact: true }, 'Slash': { bp: 70, type: 'Normal', alwaysCrit: true, makesContact: true }, 'Sludge': { bp: 65, type: 'Poison' }, 'Soft-Boiled': { bp: 0, type: 'Normal' }, 'Spore': { bp: 0, type: 'Grass' }, 'Submission': { bp: 80, type: 'Fighting', makesContact: true }, 'Substitute': { bp: 0, type: 'Normal' }, 'Super Fang': { bp: 0, type: 'Normal', makesContact: true }, 'Surf': { bp: 95, type: 'Water', category: 'Special', isSpread: true }, 'Swift': { bp: 60, type: 'Normal', category: 'Special', isSpread: true }, 'Swords Dance': { bp: 0, type: 'Normal' }, 'Tackle': { bp: 35, type: 'Normal', category: 'Physical', makesContact: true }, 'Thrash': { bp: 90, type: 'Normal', category: 'Physical', makesContact: true }, 'Thunder': { bp: 120, type: 'Electric', category: 'Special', hasSecondaryEffect: true }, 'Thunderbolt': { bp: 95, type: 'Electric', category: 'Special', hasSecondaryEffect: true }, 'Thunder Punch': { bp: 75, type: 'Electric', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isPunch: true }, 'Thunder Wave': { bp: 0, type: 'Electric' }, 'Toxic': { bp: 0, type: 'Poison' }, 'Tri Attack': { bp: 80, type: 'Normal', category: 'Special' }, 'Twineedle': { bp: 25, type: 'Bug', isTwoHit: true }, 'Waterfall': { bp: 80, type: 'Water', category: 'Physical', makesContact: true }, 'Wrap': { bp: 15, type: 'Normal' }, 'Whirlwind': { bp: 0, type: 'Normal' } }; var MOVES_GSC = $.extend(true, {}, MOVES_RBY, { 'Aeroblast': { bp: 100, type: 'Flying', category: 'Special' }, 'Ancient Power': { bp: 60, type: 'Rock', category: 'Special', hasSecondaryEffect: true }, 'Baton Pass': { bp: 0, type: 'Normal' }, 'Belly Drum': { bp: 0, type: 'Normal' }, 'Bite': { bp: 60, type: 'Dark', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isBite: true }, 'Bone Rush': { bp: 25, type: 'Ground', category: 'Physical', isMultiHit: true }, 'Crabhammer': { alwaysCrit: false }, 'Cross Chop': { bp: 100, type: 'Fighting', category: 'Physical', makesContact: true }, 'Crunch': { bp: 80, type: 'Dark', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isBite: true }, 'Curse': { bp: 0, type: 'Ghost' }, 'Destiny Bond': { bp: 0, type: 'Ghost' }, 'Dig': { bp: 60 }, 'Double-Edge': { bp: 120 }, 'Dynamic Punch': { bp: 100, type: 'Fighting', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isPunch: true }, 'Encore': { bp: 0, type: 'Normal' }, 'Endure': { bp: 0, type: 'Normal' }, 'Explosion': { bp: 250 }, 'Extreme Speed': { bp: 80, type: 'Normal', category: 'Physical', makesContact: true, hasPriority: true }, 'Feint Attack': { bp: 60, type: 'Dark', category: 'Physical', makesContact: true }, 'Flail': { bp: 1, type: 'Normal', category: 'Physical', makesContact: true }, 'Flame Wheel': { bp: 60, type: 'Fire', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Frustration': { bp: 102, type: 'Normal', category: 'Physical', makesContact: true }, 'Future Sight': { bp: 80, type: 'Psychic', category: 'Special' }, 'Giga Drain': { bp: 60, type: 'Grass', category: 'Special', givesHealth: true }, 'Gust': { type: 'Flying' }, 'Headbutt': { bp: 70, type: 'Normal', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Heal Bell': { bp: 0, type: 'Normal' }, 'Hidden Power Bug': { bp: 70, type: 'Bug', category: 'Special' }, 'Hidden Power Dark': { bp: 70, type: 'Dark', category: 'Special' }, 'Hidden Power Dragon': { bp: 70, type: 'Dragon', category: 'Special' }, 'Hidden Power Electric': { bp: 70, type: 'Electric', category: 'Special' }, 'Hidden Power Fighting': { bp: 70, type: 'Fighting', category: 'Special' }, 'Hidden Power Fire': { bp: 70, type: 'Fire', category: 'Special' }, 'Hidden Power Flying': { bp: 70, type: 'Flying', category: 'Special' }, 'Hidden Power Ghost': { bp: 70, type: 'Ghost', category: 'Special' }, 'Hidden Power Grass': { bp: 70, type: 'Grass', category: 'Special' }, 'Hidden Power Ground': { bp: 70, type: 'Ground', category: 'Special' }, 'Hidden Power Ice': { bp: 70, type: 'Ice', category: 'Special' }, 'Hidden Power Poison': { bp: 70, type: 'Poison', category: 'Special' }, 'Hidden Power Psychic': { bp: 70, type: 'Psychic', category: 'Special' }, 'Hidden Power Rock': { bp: 70, type: 'Rock', category: 'Special' }, 'Hidden Power Steel': { bp: 70, type: 'Steel', category: 'Special' }, 'Hidden Power Water': { bp: 70, type: 'Water', category: 'Special' }, 'Icy Wind': { bp: 55, type: 'Ice', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Iron Tail': { bp: 100, type: 'Steel', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Mach Punch': { bp: 40, type: 'Fighting', category: 'Physical', makesContact: true, isPunch: true, hasPriority: true }, 'Megahorn': { bp: 120, type: 'Bug', category: 'Physical', makesContact: true }, 'Milk Drink': { bp: 0, type: 'Normal' }, 'Moonlight': { bp: 0, type: 'Normal' }, 'Protect': { bp: 0, type: 'Normal' }, 'Pursuit': { bp: 40, type: 'Dark', category: 'Physical', makesContact: true }, 'Rapid Spin': { bp: 20, type: 'Normal', category: 'Physical', makesContact: true }, 'Razor Leaf': { alwaysCrit: false }, 'Return': { bp: 102, type: 'Normal', category: 'Physical', makesContact: true }, 'Reversal': { bp: 1, type: 'Fighting', category: 'Physical', makesContact: true }, 'Rock Smash': { bp: 20, type: 'Fighting', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Sacred Fire': { bp: 100, type: 'Fire', category: 'Physical', hasSecondaryEffect: true }, 'Self-Destruct': { bp: 200 }, 'Shadow Ball': { bp: 80, type: 'Ghost', category: 'Special', hasSecondaryEffect: true, isBullet: true }, 'Slash': { alwaysCrit: false }, 'Sleep Talk': { bp: 0, type: 'Normal' }, 'Sludge Bomb': { bp: 90, type: 'Poison', category: 'Special', hasSecondaryEffect: true, isBullet: true }, 'Solar Beam': { bp: 120, type: 'Grass', category: 'Special' }, 'Spark': { bp: 65, type: 'Electric', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Spikes': { bp: 0, type: 'Ground' }, 'Steel Wing': { bp: 70, type: 'Steel', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Sunny Day': { bp: 0, type: 'Fire' }, 'Swagger': { bp: 0, type: 'Normal' }, 'Synthesis': { bp: 0, type: 'Grass' }, 'Thief': { bp: 40, type: 'Dark', category: 'Physical', makesContact: true }, 'Tri Attack': { hasSecondaryEffect: true }, 'Zap Cannon': { bp: 100, type: 'Electric', category: 'Special', hasSecondaryEffect: true } }); delete MOVES_GSC['Acid']; delete MOVES_GSC['Bind']; delete MOVES_GSC['Clamp']; delete MOVES_GSC['Fire Spin']; delete MOVES_GSC['Mega Drain']; delete MOVES_GSC['Wrap']; var MOVES_ADV = $.extend(true, {}, MOVES_GSC, { 'Aerial Ace': { bp: 60, type: 'Flying', category: 'Physical', makesContact: true }, 'Air Cutter': { bp: 55, type: 'Flying', category: 'Special', isSpread: true }, 'Astonish': { bp: 30, type: 'Ghost', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Aromatherapy': { bp: 0, type: 'Grass' }, 'Blast Burn': { bp: 150, type: 'Fire', category: 'Special' }, 'Blaze Kick': { bp: 85, type: 'Fire', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Bonemerang': { bp: 50, type: 'Ground', category: 'Physical', isTwoHit: true }, 'Bounce': { bp: 85, type: 'Flying', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Brick Break': { bp: 75, type: 'Fighting', category: 'Physical', makesContact: true }, 'Bulk Up': { bp: 0, type: 'Fighting' }, 'Bullet Seed': { bp: 10, type: 'Grass', category: 'Physical', isMultiHit: true, isBullet: true }, 'Calm Mind': { bp: 0, type: 'Psychic' }, 'Covet': { bp: 40, type: 'Normal', category: 'Physical', makesContact: true }, 'Crush Claw': { bp: 75, type: 'Normal', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Dive': { bp: 60, type: 'Water', category: 'Physical', makesContact: true }, 'Doom Desire': { bp: 120, type: 'Steel', category: 'Special' }, 'Dragon Claw': { bp: 80, type: 'Dragon', category: 'Physical', makesContact: true }, 'Endeavor': { bp: 1, type: 'Normal', category: 'Physical', makesContact: true }, 'Eruption': { bp: 150, type: 'Fire', category: 'Special', isSpread: true }, 'Extrasensory': { bp: 80, type: 'Psychic', category: 'Special', hasSecondaryEffect: true }, 'Facade': { bp: 70, type: 'Normal', category: 'Physical', makesContact: true }, 'Fake Out': { bp: 40, type: 'Normal', category: 'Physical', makesContact: true, hasSecondaryEffect: true, hasPriority: true }, 'Focus Punch': { bp: 150, type: 'Fighting', category: 'Physical', makesContact: true, isPunch: true }, 'Frenzy Plant': { bp: 150, type: 'Grass', category: 'Special' }, 'Heat Wave': { bp: 100, type: 'Fire', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Helping Hand': { bp: 0, type: 'Normal' }, 'Hydro Cannon': { bp: 150, type: 'Water', category: 'Special' }, 'Hyper Voice': { bp: 90, type: 'Normal', category: 'Special', isSound: true, isSpread: true }, 'Icicle Spear': { bp: 10, type: 'Ice', category: 'Physical', isMultiHit: true }, 'Ingrain': { bp: 0, type: 'Grass' }, 'Iron Defense': { bp: 0, type: 'Steel' }, 'Knock Off': { bp: 20, type: 'Dark', category: 'Physical', makesContact: true }, 'Leaf Blade': { bp: 70, type: 'Grass', category: 'Physical', makesContact: true }, 'Luster Purge': { bp: 70, type: 'Psychic', category: 'Special', hasSecondaryEffect: true }, 'Low Kick': { bp: 1, type: 'Fighting', category: 'Physical', makesContact: true }, 'Magical Leaf': { bp: 60, type: 'Grass', category: 'Special' }, 'Magic Coat': { bp: 0, type: 'Psychic' }, 'Meteor Mash': { bp: 100, type: 'Steel', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isPunch: true }, 'Mist Ball': { bp: 70, type: 'Psychic', category: 'Special', hasSecondaryEffect: true, isBullet: true }, 'Mud Shot': { bp: 55, type: 'Ground', category: 'Special', hasSecondaryEffect: true }, 'Muddy Water': { bp: 95, type: 'Water', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Needle Arm': { bp: 60, type: 'Grass', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Overheat': { bp: 140, type: 'Fire', category: 'Special' }, 'Poison Fang': { bp: 50, type: 'Poison', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isBite: true }, 'Poison Tail': { bp: 50, type: 'Poison', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Psycho Boost': { bp: 140, type: 'Psychic', category: 'Special' }, 'Recycle': { bp: 0, type: 'Normal' }, 'Refresh': { bp: 0, type: 'Normal' }, 'Revenge': { bp: 120, type: 'Fighting', category: 'Physical', makesContact: true }, 'Rock Blast': { bp: 25, type: 'Rock', category: 'Physical', isMultiHit: true }, 'Rock Tomb': { bp: 50, type: 'Rock', category: 'Physical', hasSecondaryEffect: true }, 'Secret Power': { bp: 70, type: 'Normal', category: 'Physical', hasSecondaryEffect: true }, 'Shadow Punch': { bp: 60, type: 'Ghost', category: 'Physical', makesContact: true, isPunch: true }, 'Shock Wave': { bp: 60, type: 'Electric', category: 'Special' }, 'Signal Beam': { bp: 75, type: 'Bug', category: 'Special', hasSecondaryEffect: true }, 'Silver Wind': { bp: 60, type: 'Bug', category: 'Special', hasSecondaryEffect: true }, 'Sky Uppercut': { bp: 85, type: 'Fighting', category: 'Physical', makesContact: true, isPunch: true }, 'Slack Off': { bp: 0, type: 'Normal' }, 'Stockpile': { bp: 0, type: 'Normal' }, 'Superpower': { bp: 120, type: 'Fighting', category: 'Physical', makesContact: true }, 'Tail Glow': { bp: 0, type: 'Bug' }, 'Taunt': { bp: 0, type: 'Dark' }, 'Trick': { bp: 0, type: 'Psychic' }, 'Trick-or-Treat': { bp: 0, type: 'Ghost' }, 'Uproar': { bp: 50, type: 'Normal', category: 'Special' }, 'Volt Tackle': { bp: 120, type: 'Electric', category: 'Physical', makesContact: true, hasSecondaryEffect: true, hasRecoil: true }, 'Water Pulse': { bp: 60, type: 'Water', category: 'Special', hasSecondaryEffect: true, isPulse: true }, 'Water Spout': { bp: 150, type: 'Water', category: 'Special', isSpread: true }, 'Weather Ball': { bp: 50, type: 'Normal', category: 'Special', isBullet: true }, 'Will-O-Wisp': { bp: 0, type: 'Fire' }, 'Wish': { bp: 0, type: 'Normal' }, 'Yawn': { bp: 0, type: 'Normal' } }); var MOVES_DPP = $.extend(true, {}, MOVES_ADV, { 'Air Slash': { bp: 75, type: 'Flying', category: 'Special', hasSecondaryEffect: true }, 'Aqua Jet': { bp: 40, type: 'Water', category: 'Physical', makesContact: true, hasPriority: true }, 'Aqua Tail': { bp: 90, type: 'Water', category: 'Physical', makesContact: true }, 'Aqua Ring': { bp: 0, type: 'Water' }, 'Assurance': { bp: 50, type: 'Dark', category: 'Physical', makesContact: true }, 'Attack Order': { bp: 90, type: 'Bug', category: 'Physical' }, 'Aura Sphere': { bp: 90, type: 'Fighting', category: 'Special', isBullet: true, isPulse: true }, 'Avalanche': { bp: 120, type: 'Ice', category: 'Physical', makesContact: true }, 'Brave Bird': { bp: 120, type: 'Flying', category: 'Physical', makesContact: true, hasRecoil: true }, 'Brine': { bp: 65, type: 'Water', category: 'Special' }, 'Bug Bite': { bp: 60, type: 'Bug', category: 'Physical', makesContact: true }, 'Bug Buzz': { bp: 90, type: 'Bug', category: 'Special', hasSecondaryEffect: true, isSound: true }, 'Bullet Punch': { bp: 40, type: 'Steel', category: 'Physical', makesContact: true, isPunch: true, hasPriority: true }, 'Charge Beam': { bp: 50, type: 'Electric', category: 'Special', hasSecondaryEffect: true }, 'Chatter': { bp: 60, type: 'Flying', category: 'Special', hasSecondaryEffect: true, isSound: true }, 'Close Combat': { bp: 120, type: 'Fighting', category: 'Physical', makesContact: true }, 'Covet': { bp: 60 }, 'Cross Poison': { bp: 70, type: 'Poison', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Dark Pulse': { bp: 80, type: 'Dark', category: 'Special', hasSecondaryEffect: true, isPulse: true }, 'Dark Void': { bp: 0, type: 'Dark' }, 'Defend Order': { bp: 0, type: 'Bug' }, 'Defog': { bp: 0, type: 'Flying' }, 'Dig': { bp: 80 }, 'Discharge': { bp: 80, type: 'Electric', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Dive': { bp: 80 }, 'Double Hit': { bp: 35, type: 'Normal', category: 'Physical', makesContact: true, isTwoHit: true }, 'Draco Meteor': { bp: 140, type: 'Dragon', category: 'Special' }, 'Dragon Pulse': { bp: 90, type: 'Dragon', category: 'Special', isPulse: true }, 'Dragon Rush': { bp: 100, type: 'Dragon', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Drain Punch': { bp: 60, type: 'Fighting', category: 'Physical', makesContact: true, isPunch: true, givesHealth: true }, 'Earth Power': { bp: 90, type: 'Ground', category: 'Special', hasSecondaryEffect: true }, 'Energy Ball': { bp: 80, type: 'Grass', category: 'Special', hasSecondaryEffect: true, isBullet: true }, 'Feint': { bp: 50, type: 'Normal', category: 'Physical', bypassesProtect: true }, 'Fire Fang': { bp: 65, type: 'Fire', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isBite: true }, 'Flare Blitz': { bp: 120, type: 'Fire', category: 'Physical', makesContact: true, hasSecondaryEffect: true, hasRecoil: true }, 'Flash Cannon': { bp: 80, type: 'Steel', category: 'Special', hasSecondaryEffect: true }, 'Fling': { bp: 1, type: 'Dark', category: 'Physical' }, 'Fly': { bp: 90 }, 'Focus Blast': { bp: 120, type: 'Fighting', category: 'Special', hasSecondaryEffect: true, isBullet: true }, 'Force Palm': { bp: 60, type: 'Fighting', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Giga Impact': { bp: 150, type: 'Normal', category: 'Physical', makesContact: true }, 'Grass Knot': { bp: 1, type: 'Grass', category: 'Special', makesContact: true }, 'Gunk Shot': { bp: 120, type: 'Poison', category: 'Physical', hasSecondaryEffect: true }, 'Gyro Ball': { bp: 1, type: 'Steel', category: 'Physical', makesContact: true, isBullet: true }, 'Hammer Arm': { bp: 100, type: 'Fighting', category: 'Physical', makesContact: true, isPunch: true }, 'Head Smash': { bp: 150, type: 'Rock', category: 'Physical', makesContact: true, hasRecoil: true }, 'Heal Order': { bp: 0, type: 'Bug' }, 'Healing Wish': { bp: 0, type: 'Psychic' }, 'High Jump Kick': { bp: 100 }, 'Ice Fang': { bp: 65, type: 'Ice', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isBite: true }, 'Ice Shard': { bp: 40, type: 'Ice', category: 'Physical', hasPriority: true }, 'Iron Head': { bp: 80, type: 'Steel', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Judgment': { bp: 100, type: 'Normal', category: 'Special' }, 'Jump Kick': { bp: 85 }, 'Last Resort': { bp: 130, type: 'Normal', category: 'Physical', makesContact: true }, 'Lava Plume': { bp: 80, type: 'Fire', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Leaf Blade': { bp: 90 }, 'Leaf Storm': { bp: 140, type: 'Grass', category: 'Special' }, 'Lunar Dance': { bp: 0, type: 'Psychic' }, 'Magma Storm': { bp: 120, type: 'Fire', category: 'Special' }, 'Magnet Bomb': { bp: 60, type: 'Steel', category: 'Physical', isBullet: true }, 'Magnet Rise': { bp: 0, type: 'Electric' }, 'Me First': { bp: 0, type: 'Normal' }, 'Mirror Shot': { bp: 65, type: 'Steel', category: 'Special', hasSecondaryEffect: true }, 'Mud Bomb': { bp: 65, type: 'Ground', category: 'Special', isBullet: true, hasSecondaryEffect: true }, 'Natural Gift': { bp: 1, type: 'Normal', category: 'Physical' }, 'Nature Power': { bp: 80, type: 'Normal', category: 'Special', hasSecondaryEffect: true }, 'Nasty Plot': { bp: 0, type: 'Dark' }, 'Night Slash': { bp: 70, type: 'Dark', category: 'Physical', makesContact: true }, 'Ominous Wind': { bp: 60, type: 'Ghost', category: 'Special', hasSecondaryEffect: true }, 'Outrage': { bp: 120, type: 'Dragon', category: 'Physical', makesContact: true }, 'Paleo Wave': { bp: 85, type: 'Rock', category: 'Special', hasSecondaryEffect: true }, 'Payback': { bp: 50, type: 'Dark', category: 'Physical', makesContact: true }, 'Pluck': { bp: 60, type: 'Flying', category: 'Physical', makesContact: true }, 'Poison Jab': { bp: 80, type: 'Poison', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Power Gem': { bp: 70, type: 'Rock', category: 'Special' }, 'Power Whip': { bp: 120, type: 'Grass', category: 'Physical', makesContact: true }, 'Psycho Cut': { bp: 70, type: 'Psychic', category: 'Physical' }, 'Psycho Shift': { bp: 0, type: 'Psychic' }, 'Punishment': { bp: 60, type: 'Dark', category: 'Physical', makesContact: true }, 'Roar of Time': { bp: 150, type: 'Dragon', category: 'Special' }, 'Rock Climb': { bp: 90, type: 'Normal', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Rock Smash': { bp: 40 }, 'Rock Polish': { bp: 0, type: 'Rock' }, 'Rock Wrecker': { bp: 150, type: 'Rock', category: 'Physical', isBullet: true }, 'Roost': { bp: 0, type: 'Flying' }, 'Seed Bomb': { bp: 80, type: 'Grass', category: 'Physical', isBullet: true }, 'Seed Flare': { bp: 120, type: 'Grass', category: 'Special', hasSecondaryEffect: true }, 'Shadow Claw': { bp: 70, type: 'Ghost', category: 'Physical', makesContact: true }, 'Shadow Force': { bp: 120, type: 'Ghost', category: 'Physical', makesContact: true, bypassesProtect: true }, 'Shadow Sneak': { bp: 40, type: 'Ghost', category: 'Physical', makesContact: true, hasPriority: true }, 'Shadow Strike': { bp: 80, type: 'Ghost', category: 'Physical', hasSecondaryEffect: true, makesContact: true }, 'Spacial Rend': { bp: 100, type: 'Dragon', category: 'Special' }, 'Stealth Rock': { bp: 0, type: 'Rock' }, 'Stone Edge': { bp: 100, type: 'Rock', category: 'Physical' }, 'Sucker Punch': { bp: 80, type: 'Dark', category: 'Physical', makesContact: true, hasPriority: true }, 'Switcheroo': { bp: 0, type: 'Dark' }, 'Tailwind': { bp: 0, type: 'Flying' }, 'Thunder Fang': { bp: 65, type: 'Electric', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isBite: true }, 'Toxic Spikes': { bp: 0, type: 'Poison' }, 'Trick Room': { bp: 0, type: 'Psychic' }, 'U-turn': { bp: 70, type: 'Bug', category: 'Physical', makesContact: true }, 'Vacuum Wave': { bp: 40, type: 'Fighting', category: 'Special', hasPriority: true }, 'Wake-Up Slap': { bp: 60, type: 'Fighting', category: 'Physical', makesContact: true }, 'Waterfall': { hasSecondaryEffect: true }, 'Wood Hammer': { bp: 120, type: 'Grass', category: 'Physical', makesContact: true, hasRecoil: true }, 'X-Scissor': { bp: 80, type: 'Bug', category: 'Physical', makesContact: true }, 'Zap Cannon': { bp: 120 }, 'Zen Headbutt': { bp: 80, type: 'Psychic', category: 'Physical', makesContact: true, hasSecondaryEffect: true } }); var MOVES_BW = $.extend(true, {}, MOVES_DPP, { 'Acid Spray': { bp: 40, type: 'Poison', category: 'Special', hasSecondaryEffect: true, isBullet: true }, 'Acrobatics': { bp: 55, type: 'Flying', category: 'Physical', makesContact: true }, 'Autotomize': { bp: 0, type: 'Steel' }, 'Blue Flare': { bp: 130, type: 'Fire', category: 'Special', hasSecondaryEffect: true }, 'Bolt Strike': { bp: 130, type: 'Electric', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Bulldoze': { bp: 60, type: 'Ground', category: 'Physical', hasSecondaryEffect: true, isSpread: true }, 'Bullet Seed': { bp: 25 }, 'Chip Away': { bp: 70, type: 'Normal', category: 'Physical', makesContact: true, ignoresDefenseBoosts: true }, 'Circle Throw': { bp: 60, type: 'Fighting', category: 'Physical', makesContact: true }, 'Clear Smog': { bp: 50, type: 'Poison', category: 'Special' }, 'Coil': { bp: 0, type: 'Poison' }, 'Cotton Guard': { bp: 0, type: 'Grass' }, 'Doom Desire': { bp: 140 }, 'Dragon Tail': { bp: 60, type: 'Dragon', category: 'Physical', makesContact: true }, 'Drain Punch': { bp: 75 }, 'Drill Run': { bp: 80, type: 'Ground', category: 'Physical', makesContact: true }, 'Dual Chop': { bp: 40, type: 'Dragon', category: 'Physical', makesContact: true, isTwoHit: true }, 'Electro Ball': { bp: 1, type: 'Electric', category: 'Special', isBullet: true }, 'Electroweb': { bp: 55, type: 'Electric', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Feint': { bp: 30 }, 'Fiery Dance': { bp: 80, type: 'Fire', category: 'Special', hasSecondaryEffect: true }, 'Final Gambit': { bp: 1, type: 'Fighting', category: 'Special' }, 'Flame Burst': { bp: 70, type: 'Fire', category: 'Special' }, 'Flame Charge': { bp: 50, type: 'Fire', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Foul Play': { bp: 95, type: 'Dark', category: 'Physical', makesContact: true }, 'Freeze Shock': { bp: 140, type: 'Ice', category: 'Physical', hasSecondaryEffect: true }, 'Frost Breath': { bp: 40, type: 'Ice', category: 'Special', alwaysCrit: true }, 'Fusion Bolt': { bp: 100, type: 'Electric', category: 'Physical' }, 'Fusion Flare': { bp: 100, type: 'Fire', category: 'Special' }, 'Future Sight': { bp: 100 }, 'Gear Grind': { bp: 50, type: 'Steel', category: 'Physical', isTwoHit: true, makesContact: true }, 'Giga Drain': { bp: 75 }, 'Glaciate': { bp: 65, type: 'Ice', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Heal Pulse': { bp: 0, type: 'Psychic' }, 'Head Charge': { bp: 120, type: 'Normal', category: 'Physical', makesContact: true, hasRecoil: true }, 'Heavy Slam': { bp: 1, type: 'Steel', category: 'Physical', makesContact: true }, 'Hex': { bp: 50, type: 'Ghost', category: 'Special' }, 'High Jump Kick': { bp: 130 }, 'Hone Claws': { bp: 0, type: 'Dark' }, 'Horn Leech': { bp: 75, type: 'Grass', category: 'Physical', makesContact: true, givesHealth: true }, 'Hurricane': { bp: 120, type: 'Flying', category: 'Special', hasSecondaryEffect: true }, 'Ice Burn': { bp: 140, type: 'Ice', category: 'Special', hasSecondaryEffect: true }, 'Icicle Crash': { bp: 85, type: 'Ice', category: 'Physical', hasSecondaryEffect: true }, 'Icicle Spear': { bp: 25 }, 'Incinerate': { bp: 30, type: 'Fire', category: 'Special', isSpread: true }, 'Inferno': { bp: 100, type: 'Fire', category: 'Special', hasSecondaryEffect: true }, 'Jump Kick': { bp: 100 }, 'Last Resort': { bp: 140 }, 'Leaf Tornado': { bp: 65, type: 'Grass', category: 'Special', hasSecondaryEffect: true }, 'Low Sweep': { bp: 60, type: 'Fighting', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Nature Power': { bp: 100, type: 'Ground', category: 'Physical', hasSecondaryEffect: false, isSpread: true }, 'Night Daze': { bp: 85, type: 'Dark', category: 'Special', hasSecondaryEffect: true }, 'Petal Dance': { bp: 120, type: 'Grass', category: 'Special', makesContact: true }, 'Psyshock': { bp: 80, type: 'Psychic', category: 'Special', dealsPhysicalDamage: true }, 'Psystrike': { bp: 100, type: 'Psychic', category: 'Special', dealsPhysicalDamage: true }, 'Quick Guard': { bp: 0, type: 'Fighting' }, 'Quiver Dance': { bp: 0, type: 'Bug' }, 'Rage Powder': { bp: 0, type: 'Bug' }, 'Razor Shell': { bp: 75, type: 'Water', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Relic Song': { bp: 40, type: 'Normal', category: 'Special', hasSecondaryEffect: true, isSound: true, isSpread: true }, 'Retaliate': { bp: 70, type: 'Normal', category: 'Physical', makesContact: true }, 'Round': { bp: 60, type: 'Normal', category: 'Special' }, 'Sacred Sword': { bp: 90, type: 'Fighting', category: 'Physical', makesContact: true, ignoresDefenseBoosts: true }, 'Scald': { bp: 80, type: 'Water', category: 'Special', hasSecondaryEffect: true }, 'Searing Shot': { bp: 100, type: 'Fire', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Secret Sword': { bp: 85, type: 'Fighting', category: 'Special', dealsPhysicalDamage: true }, 'Shell Smash': { bp: 0, type: 'Normal' }, 'Shift Gear': { bp: 0, type: 'Steel' }, 'Sky Drop': { bp: 60, type: 'Flying', category: 'Physical', makesContact: true }, 'Sludge Wave': { bp: 95, type: 'Poison', category: 'Special', hasSecondaryEffect: true, isSpread: true }, 'Smack Down': { bp: 50, type: 'Rock', category: 'Physical' }, 'Snarl': { bp: 55, type: 'Dark', category: 'Special', hasSecondaryEffect: true, isSound: true, isSpread: true }, 'Steamroller': { bp: 65, type: 'Bug', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Stored Power': { bp: 20, type: 'Psychic', category: 'Special' }, 'Storm Throw': { bp: 40, type: 'Fighting', category: 'Physical', makesContact: true, alwaysCrit: true }, 'Struggle Bug': { bp: 30, type: 'Bug', category: 'Special', isSpread: true }, 'Synchronoise': { bp: 70, type: 'Psychic', category: 'Special' }, 'Tackle': { bp: 50 }, 'Tail Slap': { bp: 25, type: 'Normal', category: 'Physical', makesContact: true, isMultiHit: true }, 'Techno Blast': { bp: 85, type: 'Normal', category: 'Special' }, 'Thrash': { bp: 120 }, 'Uproar': { bp: 90 }, 'V-create': { bp: 180, type: 'Fire', category: 'Physical', makesContact: true }, 'Venoshock': { bp: 65, type: 'Poison', category: 'Special' }, 'Volt Switch': { bp: 70, type: 'Electric', category: 'Special' }, 'Wide Guard': { bp: 0, type: 'Rock' }, 'Wild Charge': { bp: 90, type: 'Electric', category: 'Physical', makesContact: true, hasRecoil: true } }); var MOVES_XY = $.extend(true, {}, MOVES_BW, { 'Air Cutter': { bp: 60 }, 'Arm Thrust': { bp: 15, type: 'Fighting', category: 'Physical', makesContact: true, isMultiHit: true }, 'Assurance': { bp: 60 }, 'Aura Sphere': { bp: 80 }, 'Belch': { bp: 120, type: 'Poison', category: 'Special' }, 'Blizzard': { bp: 110 }, 'Boomburst': { bp: 140, type: 'Normal', category: 'Special', isSound: true, isSpread: true }, 'Chatter': { bp: 65 }, 'Crabhammer': { bp: 100 }, 'Dazzling Gleam': { bp: 80, type: 'Fairy', category: 'Special', isSpread: true }, 'Diamond Storm': { bp: 100, type: 'Rock', category: 'Physical', hasSecondaryEffect: true, isSpread: true }, 'Draco Meteor': { bp: 130 }, 'Dragon Ascent': { bp: 120, type: 'Flying', category: 'Physical', makesContact: true }, 'Dragon Pulse': { bp: 85 }, 'Draining Kiss': { bp: 50, type: 'Fairy', category: 'Special', givesHealth: true }, 'Energy Ball': { bp: 90 }, 'Facade': { ignoresBurn: true }, 'Fire Blast': { bp: 110 }, 'Flamethrower': { bp: 90 }, 'Flying Press': { bp: 80, type: 'Fighting', category: 'Physical', makesContact: true }, 'Freeze-Dry': { bp: 70, type: 'Ice', category: 'Special', hasSecondaryEffect: true }, 'Frost Breath': { bp: 60 }, 'Future Sight': { bp: 120 }, 'Geomancy': { bp: 0, type: 'Fairy' }, 'Heat Wave': { bp: 95 }, 'Hex': { bp: 65 }, 'Hidden Power Bug': { bp: 60 }, 'Hidden Power Dark': { bp: 60 }, 'Hidden Power Dragon': { bp: 60 }, 'Hidden Power Electric': { bp: 60 }, 'Hidden Power Fighting': { bp: 60 }, 'Hidden Power Fire': { bp: 60 }, 'Hidden Power Flying': { bp: 60 }, 'Hidden Power Ghost': { bp: 60 }, 'Hidden Power Grass': { bp: 60 }, 'Hidden Power Ground': { bp: 60 }, 'Hidden Power Ice': { bp: 60 }, 'Hidden Power Poison': { bp: 60 }, 'Hidden Power Psychic': { bp: 60 }, 'Hidden Power Rock': { bp: 60 }, 'Hidden Power Steel': { bp: 60 }, 'Hidden Power Water': { bp: 60 }, 'Hurricane': { bp: 110 }, 'Hydro Pump': { bp: 110 }, 'Hyperspace Fury': { bp: 100, type: 'Dark', category: 'Physical', bypassesProtect: true }, 'Hyperspace Hole': { bp: 80, type: 'Psychic', category: 'Special', bypassesProtect: true }, 'Ice Beam': { bp: 90 }, 'Incinerate': { bp: 60 }, 'King\'s Shield': { bp: 0, type: 'Steel' }, 'Knock Off': { bp: 65 }, 'Land\'s Wrath': { bp: 90, type: 'Ground', category: 'Physical', isSpread: true }, 'Leaf Storm': { bp: 130 }, 'Light of Ruin': { bp: 140, type: 'Fairy', category: 'Special', hasRecoil: true }, 'Low Sweep': { bp: 65 }, 'Magma Storm': { bp: 100 }, 'Meteor Mash': { bp: 90 }, 'Moonblast': { bp: 95, type: 'Fairy', category: 'Special', hasSecondaryEffect: true }, 'Moonlight': { type: 'Fairy' }, 'Muddy Water': { bp: 90 }, 'Nature Power': { bp: 80, type: 'Normal', category: 'Special', hasSecondaryEffect: true, isSpread: false }, 'Nuzzle': { bp: 20, type: 'Electric', category: 'Physical', hasSecondaryEffect: true, makesContact: true }, 'Oblivion Wing': { bp: 80, type: 'Flying', category: 'Special', givesHealth: true }, 'Origin Pulse': { bp: 110, type: 'Water', category: 'Special', isSpread: true }, 'Overheat': { bp: 130 }, 'Phantom Force': { bp: 90, type: 'Ghost', category: 'Physical', makesContact: true, bypassesProtect: true }, 'Pin Missile': { bp: 25 }, 'Play Rough': { bp: 90, type: 'Fairy', category: 'Physical', makesContact: true, hasSecondaryEffect: true }, 'Power Gem': { bp: 80 }, 'Power-Up Punch': { bp: 40, type: 'Fighting', category: 'Physical', makesContact: true, hasSecondaryEffect: true, isPunch: true }, 'Precipice Blades': { bp: 120, type: 'Ground', category: 'Physical', isSpread: 'true' }, 'Rock Tomb': { bp: 60 }, 'Skull Bash': { bp: 130 }, 'Spiky Shield': { bp: 0, type: 'Grass' }, 'Steam Eruption': { bp: 110, type: 'Water', category: 'Special', hasSecondaryEffect: true, }, 'Sticky Web': { bp: 0, type: 'Bug' }, 'Storm Throw': { bp: 60 }, 'Strength Sap': { type: 'Fairy', givesHealth: true }, 'Struggle Bug': { bp: 50 }, 'Surf': { bp: 90 }, 'Synchronoise': { bp: 120 }, 'Techno Blast': { bp: 120 }, 'Thief': { bp: 60 }, 'Thousand Arrows': { bp: 90, type: 'Ground', category: 'Physical', isSpread: 'true' }, 'Thousand Waves': { bp: 90, type: 'Ground', category: 'Physical', isSpread: 'true' }, 'Thunder': { bp: 110 }, 'Thunderbolt': { bp: 90 }, 'Wake-Up Slap': { bp: 70 }, 'Water Shuriken': { bp: 15, type: 'Water', category: 'Physical', isMultiHit: true } }); var ZMOVES_TYPING = { 'Bug':'Savage Spin-Out', 'Dark':'Black Hole Eclipse', 'Dragon':'Devastating Drake', 'Electric':'Gigavolt Havoc', 'Fairy':'Twinkle Tackle', 'Fighting':'All-Out Pummeling', 'Fire':'Inferno Overdrive', 'Flying':'Supersonic Skystrike', 'Ghost':'Never-Ending Nightmare', 'Grass':'Bloom Doom', 'Ground':'Tectonic Rage', 'Ice':'Subzero Slammer', 'Normal':'Breakneck Blitz', 'Poison':'Acid Downpour', 'Psychic':'Shattered Psyche', 'Rock':'Continental Crush', 'Steel':'Corkscrew Crash', 'Water':'Hydro Vortex' }; var MOVES_SM = $.extend(true, {}, MOVES_XY, { '10,000,000 Volt Thunderbolt': { bp: 195, type: 'Electric', category: 'Special', isZ: true }, 'Acid Downpour': { bp: 1, type: 'Poison', category: 'Physical', isZ: true }, 'Acid Spray': { zp: 100 }, 'Accelerock': { bp: 40, type: 'Rock', category: 'Physical', makesContact: true, hasPriority: true, zp: 100 }, 'Acrobatics': { zp: 100 }, 'Aerial Ace': { zp: 120 }, 'Aeroblast': { zp: 180 }, 'Air Cutter': { zp: 120 }, 'Air Slash': { zp: 140 }, 'All-Out Pummeling': { bp: 1, type: 'Fighting', category: 'Physical', isZ: true }, 'Anchor Shot': { bp: 80, type: 'Steel', category: 'Physical', makesContact: true, zp: 160 }, 'Ancient Power': { zp: 120 }, 'Aqua Jet': { zp: 100 }, 'Aqua Tail': { zp: 175 }, 'Arm Thrust': { zp: 100 }, 'Assurance': { zp: 120 }, 'Astonish': { zp: 100 }, 'Attack Order': { zp: 175 }, 'Aura Sphere': { zp: 160 }, 'Aurora Beam': { zp: 120 }, 'Avalanche': { zp: 120 }, 'Beak Blast': { bp: 100, type: 'Flying', category: 'Physical', zp: 180 }, 'Belch': { zp: 190 }, 'Bite': { zp: 120 }, 'Black Hole Eclipse': { bp: 1, type: 'Dark', category: 'Physical', isZ: true }, 'Blast Burn': { zp: 200 }, 'Blaze Kick': { zp: 160 }, 'Blizzard': { zp: 185 }, 'Bloom Doom': { bp: 1, type: 'Grass', category: 'Physical', isZ: true }, 'Blue Flare': { zp: 195 }, 'Brave Bird': { zp: 190 }, 'Breakneck Blitz': { bp: 1, type: 'Normal', category: 'Physical', isZ: true }, 'Brine': { zp: 120 }, 'Body Slam': { zp: 160 }, 'Bolt Strike': { zp: 195 }, 'Bone Club': { zp: 120 }, 'Bone Rush': { zp: 140 }, 'Bonemerang': { zp: 100 }, 'Boomburst': { zp: 200 }, 'Bounce': { zp: 160 }, 'Brick Break': { zp: 140 }, 'Brutal Swing': { bp: 60, type: 'Dark', category: 'Physical', makesContact: true, isSpread: true, zp: 120 }, 'Bubble Beam': { zp: 120 }, 'Bug Bite': { zp: 120 }, 'Bug Buzz': { zp: 175 }, 'Bulldoze': { zp: 120 }, 'Bullet Punch': { zp: 100 }, 'Bullet Seed': { zp: 140 }, 'Burn Up': { bp: 130, type: 'Fire', category: 'Special', zp: 195 }, 'Catastropika': { bp: 210, type: 'Electric', category: 'Physical', isZ: true, makesContact: true }, 'Charge Beam': { zp: 100 }, 'Chatter': { zp: 120 }, 'Chip Away': { zp: 140 }, 'Circle Throw': { zp: 120 }, 'Clanging Scales': { bp: 110, type: 'Dragon', category: 'Special', isSound: true, isSpread: true, zp: 185 }, 'Clear Smog': { zp: 100 }, 'Close Combat': { zp: 190 }, 'Continental Crush': { bp: 1, type: 'Rock', category: 'Physical', isZ: true }, 'Core Enforcer': { bp: 100, type: 'Dragon', category: 'Special', isSpread: true, zp: 140 }, 'Corkscrew Crash': { bp: 1, type: 'Steel', category: 'Physical', isZ: true }, 'Covet': { zp: 120 }, 'Crabhammer': { zp: 180 }, 'Cross Chop': { zp: 180 }, 'Cross Poison': { zp: 140 }, 'Crunch': { zp: 160 }, 'Crush Claw': { zp: 140 }, 'Dark Pulse': { zp: 160 }, 'Darkest Lariat': { bp: 85, type: 'Dark', category: 'Physical', makesContact: true, zp: 160 }, 'Dazzling Gleam': { zp: 160 }, 'Diamond Storm': { zp: 180 }, 'Dig': { zp: 160 }, 'Discharge': { zp: 160 }, 'Dive': { zp: 160 }, 'Dragon Hammer': { bp: 90, type: 'Dragon', category: 'Physical', makesContact: true, zp: 175 }, 'Drill Peck': { zp: 160 }, 'Devastating Drake': { bp: 1, type: 'Dragon', category: 'Physical', isZ: true }, 'Doom Desire': { zp: 200 }, 'Double-Edge': { zp: 190 }, 'Double Hit': { zp: 140 }, 'Double Kick': { zp: 100 }, 'Draco Meteor': { zp: 195 }, 'Dragon Ascent': { zp: 190 }, 'Dragon Claw': { zp: 160 }, 'Dragon Pulse': { zp: 160 }, 'Dragon Rush': { zp: 180 }, 'Dragon Tail': { zp: 120 }, 'Drain Punch': { zp: 140 }, 'Dream Eater': { zp: 180 }, 'Drill Run': { zp: 160 }, 'Dual Chop': { zp: 100 }, 'Dynamic Punch': { zp: 180 }, 'Earth Power': { zp: 175 }, 'Earthquake': { zp: 180 }, 'Electro Ball': { zp: 160 }, 'Electroweb': { zp: 100 }, 'Endeavor': { zp: 160 }, 'Energy Ball': { zp: 175 }, 'Eruption': { zp: 200 }, 'Explosion': { zp: 200 }, 'Extrasensory': { zp: 160 }, 'Extreme Speed': { zp: 160 }, 'Fake Out': { zp: 100 }, 'Facade': { zp: 140 }, 'Feint': { zp: 100 }, 'Feint Attack': { zp: 120 }, 'Fiery Dance': { zp: 160 }, 'Final Gambit': { zp: 180 }, 'Fire Blast': { zp: 185 }, 'Fire Fang': { zp: 120 }, 'Fire Lash': { bp: 80, type: 'Fire', category: 'Physical', hasSecondaryEffect: true, makesContact: true, zp: 160 }, 'Fire Punch': { zp: 140 }, 'First Impression': { bp: 90, type: 'Bug', category: 'Physical', makesContact: true, hasPriority: true, zp: 175 }, 'Flail': { zp: 160 }, 'Flamethrower': { zp: 175 }, 'Flame Burst': { zp: 140 }, 'Flame Charge': { zp: 100 }, 'Flame Wheel': { zp: 120 }, 'Flare Blitz': { zp: 190 }, 'Flash Cannon': { zp: 160 }, 'Fleur Cannon': { bp: 130, type: 'Fairy', category: 'Special', hasSecondaryEffect: true, zp: 195 }, 'Fling': { zp: 100 }, 'Fly': { zp: 175 }, 'Flying Press': { bp: 100, zp: 170 }, 'Focus Blast': { zp: 190 }, 'Focus Punch': { zp: 200 }, 'Force Palm': { zp: 120 }, 'Foul Play': { zp: 175 }, 'Freeze Shock': { zp: 200 }, 'Freeze-Dry': { zp: 140 }, 'Frenzy Plant': { zp: 200 }, 'Frost Breath': { zp: 120 }, 'Frustration': { zp: 160 }, 'Fury Swipes': { zp: 100 }, 'Fusion Bolt': { zp: 180 }, 'Fusion Flare': { zp: 180 }, 'Future Sight': { zp: 190 }, 'Gear Grind': { zp: 180 }, 'Genesis Supernova': { bp: 185, type: 'Psychic', category: 'Special', isZ: true }, 'Giga Drain': { zp: 140 }, 'Giga Impact': { zp: 200 }, 'Gigavolt Havoc': { bp: 1, type: 'Electric', category: 'Physical', isZ: true }, 'Glaciate': { zp: 120 }, 'Grass Knot': { zp: 160 }, 'Gunk Shot': { zp: 190 }, 'Gust': { zp: 100 }, 'Gyro Ball': { zp: 160 }, 'Hammer Arm': { zp: 180 }, 'Headbutt': { zp: 140 }, 'Head Charge': { zp: 190 }, 'Head Smash': { zp: 200 }, 'Heat Wave': { zp: 175 }, 'Heavy Slam': { zp: 160 }, 'Hex': { zp: 160 }, 'Hidden Power Bug': { zp: 120 }, 'Hidden Power Dark': { zp: 120 }, 'Hidden Power Dragon': { zp: 120 }, 'Hidden Power Electric': { zp: 120 }, 'Hidden Power Fighting': { zp: 120 }, 'Hidden Power Fire': { zp: 120 }, 'Hidden Power Flying': { zp: 120 }, 'Hidden Power Ghost': { zp: 120 }, 'Hidden Power Grass': { zp: 120 }, 'Hidden Power Ground': { zp: 120 }, 'Hidden Power Ice': { zp: 120 }, 'Hidden Power Poison': { zp: 120 }, 'Hidden Power Psychic': { zp: 120 }, 'Hidden Power Rock': { zp: 120 }, 'Hidden Power Steel': { zp: 120 }, 'Hidden Power Water': { zp: 120 }, 'High Horsepower': { bp: 95, type: 'Ground', category: 'Physical', makesContact: true, zp: 175 }, 'High Jump Kick': { zp: 195 }, 'Horn Leech': { zp: 140 }, 'Hurricane': { zp: 185 }, 'Hydro Cannon': { zp: 200 }, 'Hydro Pump': { zp: 185 }, 'Hydro Vortex': { bp: 1, type: 'Water', category: 'Physical', isZ: true }, 'Hyper Beam': { zp: 200 }, 'Hyper Voice': { zp: 175 }, 'Hyperspace Fury': { zp: 180 }, 'Hyperspace Hole': { zp: 160 }, 'Ice Beam': { zp: 175 }, 'Ice Burn': { zp: 200 }, 'Ice Fang': { zp: 120 }, 'Ice Hammer': { bp: 100, type: 'Ice', category: 'Physical', makesContact: true, isPunch: true, zp: 180 }, 'Ice Punch': { zp: 140 }, 'Ice Shard': { zp: 100 }, 'Icicle Crash': { zp: 160 }, 'Icicle Spear': { zp: 140 }, 'Icy Wind': { zp: 100 }, 'Incinerate': { zp: 120 }, 'Inferno': { zp: 180 }, 'Inferno Overdrive': { bp: 1, type: 'Fire', category: 'Physical', isZ: true }, 'Iron Head': { zp: 160 }, 'Iron Tail': { zp: 180 }, 'Judgment': { zp: 180 }, 'Jump Kick': { zp: 180 }, 'Knock Off': { zp: 120 }, 'Land\'s Wrath': { zp: 185 }, 'Last Resort': { zp: 200 }, 'Lava Plume': { zp: 160 }, 'Leafage': { bp: 40, type: 'Grass', category: 'Physical', zp: 100 }, 'Leaf Blade': { zp: 175 }, 'Leaf Storm': { zp: 195 }, 'Leaf Tornado': { zp: 120 }, 'Leech Life': { bp: 80, zp: 160 }, 'Light of Ruin': { zp: 200 }, 'Liquidation': { bp: 85, type: 'Water', category: 'Physical', hasSecondaryEffect: true, makesContact: true, zp: 160 }, 'Low Kick': { zp: 160 }, 'Low Sweep': { zp: 120 }, 'Lunge': { bp: 80, type: 'Bug', category: 'Physical', hasSecondaryEffect: true, makesContact: true, zp: 160 }, 'Luster Purge': { zp: 140 }, 'Mach Punch': { zp: 100 }, 'Magical Leaf': { zp: 120 }, 'Magma Storm': { zp: 180 }, 'Magnet Bomb': { zp: 120 }, 'Malicious Moonsault': { bp: 180, type: 'Dark', category: 'Physical', makesContact: true, isZ: true }, 'Megahorn': { zp: 190 }, 'Meteor Mash': { zp: 175 }, 'Mirror Shot': { zp: 120 }, 'Mist Ball': { zp: 140 }, 'Moonblast': { zp: 175 }, 'Moongeist Beam': { bp: 100, type: 'Ghost', category: 'Special', zp: 180 }, 'Muddy Water': { zp: 175 }, 'Mud Bomb': { zp: 120 }, 'Mud Shot': { zp: 100 }, 'Multi-Attack': { bp: 90, type: 'Normal', category: 'Physical', makesContact: true, zp: 185 }, 'Natural Gift': { zp: 160 }, 'Needle Arm': { zp: 120 }, 'Never-Ending Nightmare': { bp: 1, type: 'Ghost', category: 'Physical', isZ: true }, 'Night Daze': { zp: 160 }, 'Night Shade': { zp: 100 }, 'Night Slash': { zp: 140 }, 'Nuzzle': { zp: 100 }, 'Oblivion Wing': { zp: 160 }, 'Oceanic Operetta': { bp: 195, type: 'Water', category: 'Special', isZ: true }, 'Ominous Wind': { zp: 120 }, 'Origin Pulse': { zp: 185 }, 'Outrage': { zp: 190 }, 'Overheat': { zp: 195 }, 'Paleo Wave': { zp: 160 }, 'Payback': { zp: 100 }, 'Petal Dance': { zp: 190 }, 'Phantom Force': { zp: 175 }, 'Pin Missile': { zp: 140 }, 'Play Rough': { zp: 175 }, 'Pluck': { zp: 120 }, 'Poison Fang': { zp: 100 }, 'Poison Jab': { zp: 160 }, 'Poison Tail': { zp: 100 }, 'Pollen Puff': { bp: 90, type: 'Bug', category: 'Special', isBullet: true, zp: 175 }, 'Power Gem': { zp: 160 }, 'Power Trip': { bp: 20, type: 'Dark', category: 'Physical', makesContact: true, zp: 160 }, 'Power Whip': { zp: 190 }, 'Power-Up Punch': { zp: 100 }, 'Prismatic Laser': { bp: 160, type: 'Psychic', category: 'Special', zp: 200 }, 'Precipice Blades': { zp: 190 }, 'Psychic': { zp: 175 }, 'Psychic Fangs': { bp: 85, type: 'Psychic', category: 'Physical', makesContact: true, isBite: true, zp: 160 }, 'Psycho Boost': { zp: 200 }, 'Psycho Cut': { zp: 140 }, 'Psyshock': { zp: 160 }, 'Psystrike': { zp: 180 }, 'Pulverizing Pancake': { bp: 210, type: 'Normal', category: 'Physical', isZ: true, makesContact: true }, 'Punishment': { zp: 160 }, 'Pursuit': { zp: 100 }, 'Quick Attack': { zp: 100 }, 'Rapid Spin': { zp: 100 }, 'Razor Leaf': { zp: 120 }, 'Razor Shell': { zp: 140 }, 'Relic Song': { zp: 140 }, 'Retaliate': { zp: 140 }, 'Return': { zp: 160 }, 'Revelation Dance': { bp: 120, type: 'Normal', category: 'Special', zp: 175 }, 'Revenge': { zp: 120 }, 'Reversal': { zp: 160 }, 'Roar of Time': { zp: 200 }, 'Rock Blast': { zp: 140 }, 'Rock Climb': { zp: 175 }, 'Rock Slide': { zp: 140 }, 'Rock Smash': { zp: 100 }, 'Rock Throw': { zp: 100 }, 'Rock Tomb': { zp: 140 }, 'Rock Wrecker': { zp: 200 }, 'Round': { zp: 120 }, 'Sacred Fire': { zp: 180 }, 'Sacred Sword': { zp: 175 }, 'Savage Spin-Out': { bp: 1, type: 'Bug', category: 'Physical', isZ: true }, 'Scald': { zp: 160 }, 'Searing Shot': { zp: 180 }, 'Secret Power': { zp: 140 }, 'Secret Sword': { zp: 160 }, 'Seed Bomb': { zp: 160 }, 'Seed Flare': { zp: 190 }, 'Seismic Toss': { zp: 100 }, 'Self-Destruct': { zp: 200 }, 'Shadow Claw': { zp: 140 }, 'Shadow Force': { zp: 190 }, 'Shadow Sneak': { zp: 100 }, 'Shadow Strike': { zp: 160 }, 'Shattered Psyche': { bp: 1, type: 'Psychic', category: 'Physical', isZ: true }, 'Shadow Ball': { zp: 160 }, 'Shadow Bone': { bp: 85, type: 'Ghost', category: 'Physical', hasSecondaryEffect: true, zp: 160 }, 'Shadow Punch': { zp: 120 }, 'Sheer Cold': { zp: 180 }, 'Shell Trap': { bp: 90, type: 'Fire', category: 'Special', isSpread: true, zp: 200 }, 'Shock Wave': { zp: 120 }, 'Signal Beam': { zp: 140 }, 'Silver Wind': { zp: 120 }, 'Sinister Arrow Raid': { bp: 180, type: 'Ghost', category: 'Physical', isZ: true }, 'Skull Bash': { zp: 195 }, 'Sky Attack': { zp: 200 }, 'Sky Drop': { zp: 120 }, 'Sky Uppercut': { zp: 160 }, 'Slash': { zp: 140 }, 'Sludge': { zp: 120 }, 'Sludge Bomb': { zp: 175 }, 'Sludge Wave': { zp: 175 }, 'Smack Down': { zp: 100 }, 'Smart Strike': { bp: 70, type: 'Steel', category: 'Physical', makesContact: true, zp: 140 }, 'Snarl': { zp: 100 }, 'Solar Beam': { zp: 190 }, 'Solar Blade': { bp: 125, type: 'Grass', category: 'Physical', makesContact: true, zp: 190 }, 'Soul-Stealing 7-Star Strike': { bp: 195, type: 'Ghost', category: 'Physical', isZ: true }, 'Spacial Rend': { zp: 180 }, 'Spark': { zp: 120 }, 'Sparkling Aria': { bp: 90, type: 'Water', category: 'Special', isSound: true, isSpread: true, zp: 175 }, 'Spectral Thief': { bp: 90, type: 'Ghost', category: 'Physical', makesContact: true, zp: 175 }, 'Spirit Shackle': { bp: 80, type: 'Ghost', category: 'Physical', zp: 160 }, 'Steam Eruption': { zp: 185 }, 'Steamroller': { zp: 120 }, 'Steel Wing': { zp: 140 }, 'Stoked Sparksurfer': { bp: 175, type: 'Electric', category: 'Special', isZ: true }, 'Stomping Tantrum': { bp: 75, type: 'Ground', category: 'Physical', makesContact: true, zp: 140 }, 'Stone Edge': { zp: 180 }, 'Stored Power': { zp: 160 }, 'Storm Throw': { zp: 120 }, 'Struggle Bug': { zp: 100 }, 'Submission': { zp: 160 }, 'Subzero Slammer': { bp: 1, type: 'Ice', category: 'Physical', isZ: true }, 'Sucker Punch': { bp: 70, zp: 140 }, 'Sunsteel Strike': { bp: 100, type: 'Steel', category: 'Physical', makesContact: true, zp: 180 }, 'Super Fang': { zp: 100 }, 'Superpower': { zp: 190 }, 'Supersonic Skystrike': { bp: 1, type: 'Flying', category: 'Physical', isZ: true }, 'Surf': { zp: 175 }, 'Swift': { zp: 120 }, 'Synchronoise': { zp: 190 }, 'Tackle': { bp: 40, zp: 100 }, 'Tail Slap': { zp: 140 }, 'Techno Blast': { zp: 190 }, 'Tectonic Rage': { bp: 1, type: 'Ground', category: 'Physical', isZ: true }, 'Thief': { zp: 120 }, 'Thousand Arrows': { zp: 180 }, 'Thousand Waves': { zp: 175 }, 'Thrash': { zp: 190 }, 'Throat Chop': { bp: 80, type: 'Dark', category: 'Physical', makesContact: true, zp: 160 }, 'Thunder': { zp: 185 }, 'Thunderbolt': { zp: 175 }, 'Thunder Fang': { zp: 120 }, 'Thunder Punch': { zp: 140 }, 'Tri Attack': { zp: 160 }, 'Trop Kick': { bp: 80, type: 'Grass', category: 'Physical', hasSecondaryEffect: true, makesContact: true, zp: 140 }, 'Twineedle': { zp: 100 }, 'Twinkle Tackle': { bp: 1, type: 'Fairy', category: 'Physical', isZ: true }, 'U-turn': { zp: 140 }, 'Uproar': { zp: 175 }, 'V-create': { zp: 220 }, 'Vacuum Wave': { zp: 100 }, 'Venoshock': { zp: 120 }, 'Volt Switch': { zp: 140 }, 'Volt Tackle': { zp: 190 }, 'Wake-Up Slap': { zp: 140 }, 'Waterfall': { zp: 160 }, 'Water Pulse': { zp: 120 }, 'Water Shuriken': { category: 'Special', zp: 100 }, 'Water Spout': { zp: 200 }, 'Weather Ball': { zp: 160 }, 'Wild Charge': { zp: 175 }, 'Wood Hammer': { zp: 190 }, 'X-Scissor': { zp: 160 }, 'Zap Cannon': { zp: 190 }, 'Zen Headbutt': { zp: 160 }, 'Zing Zap': { bp: 80, type: 'Electric', category: 'Physical', hasSecondaryEffect: true, makesContact: true, zp: 160 } });
/** * This interface is provided to ensure consistency. * It is not part of the documented API. * Notice that the effect on the target depends upon whether the target class is mutable. * MAGNITUDE is the chosen type for the magnitude method and scaling. * For dimensionless quantities without units, use number. * For linear quantities with units, you may use Unit. * For geometric quantities with units, you may use the quantity itself because it can represent a scalar. */ export {};
$(document).ready(function() { // 시간 선택 $("button[id^=timeBtn]").click(function() { var timeClick = $(this).attr('value'); $('#selectTime').val(timeClick); $('.timeSelectedInfo').html(timeClick); // 선택한 시간과 요일 var selectDate = $("input[name=selectDate]").val(); var selectTime = $('#selectTime').val(); var selectDay = $("#chkDay").val(); console.log("selectDate : " + selectDate); console.log("selectDay : " + selectDay + ", selectTime : " + selectTime); var host_code = $("input[name=host_code]").val(); var header = $("meta[name='_csrf_header']").attr("content"); var token = $("meta[name='_csrf']").attr("content"); console.log("header : " + header); console.log("token : " + token); $.ajax({ url : "managerTimeTable", type : "Post", data : "selectDay=" + selectDay + "&selectTime=" + selectTime + "&host_code=" + host_code + "&selectDate=" + selectDate, beforeSend : function(jqXHR, settings) { console.log("beforesend 진행"); jqXHR.setRequestHeader(header, token); }, success : function(result) { $("#managerTable").html(result); }, error : function(error) { console.log(error); $("#managerTable").html("예약 가능한 담당자가 없습니다."); } }); }); });
var timeline = { map: null, user_position: null, render: function (cid, ctitle, display_id) { console.log('Rendering timeline.'); var map = timeline.map; if(!$('#cycle_map').is(':empty')){ var tabsData = {title: ctitle}; dust.render('cycle_timeline_map_tabs', tabsData, function(err, out){ $('.tabs-box').append(out); var default_lng = 34.777821; var default_lat = 32.066157; map = googleMap.init_map('cycle_map', new google.maps.LatLng(default_lat, default_lng)); }); } db_functions.getCycleTimeline(cid, function (err, data) { var timeline_item_prototype = new (function TimeLineItem() {} ); timeline_item_prototype.toString = function () { return this.type + ' [' + this.short + ']'; }; var types = { today: { name: 'היום' }, due_date: { name: 'תאריך יעד' }, discussion: { name: 'יצירת דיון' }, cycle_creation: { name: 'יצירת קמפיין', text: function (item) { return ctitle; }, link: function (item) { return '/cycles/' + cid; } }, action: { name: 'פעולה', text: function (item) { return item.title; }, link: function (item) { return '/actions/' + item._id; } }, cycle_update: { name: 'עדכון', text: function (item) { return item.title; }, link: function (item) { return '/updates/' + item._id; } }, admin_update: { name: 'עדכון מערכת', text: function (item) { return item.text.replace(/\[url(?:=([^\]]*))\]((?:.|\n)*)?\[\/url\]/,'<a href="$1" target="_blank">$2</a>'); } } }; // Find all data for each item, and seperate them to different lists var discussion_seen = false, today_seen = false, no_discussion = true, items = { pre_discussion: [], discussion: null, past: [], today: null, future: [] }; $.each(data.objects, function (_, item) { if(type === types.discussion) { no_discussion=false; } }); if(no_discussion) discussion_seen=true; $.each(data.objects, function (_, item) { var type = types[item.type]; if (!type) { console.log("Unknown timeline type: " + item.type); return; } // Set all the item's display properties if(item.type == 'cycle_update'){ if(!item.text_field_preview){ item.text_field_preview = item.text_field; } } item.type_print = type.name; if (type.text) item.short = type.text(item); if (type.link) item.link = type.link(item); item.past = !today_seen; item.template = 'cycle_timeline_' + item.type.replace('cycle_', ''); item.__proto__ = timeline_item_prototype; // If the item is a boundary, record having seen it. Then, add the item to the right place in the items object. if (type === types.discussion) { discussion_seen = true; items.discussion = item; } else if (type === types.today) { today_seen = true; items.today = item; } else { var list = !discussion_seen ? items.pre_discussion : !today_seen ? items.past : items.future; list.push(item); } }); // Calculate the actual nodes var group_by_month = function (items) { var result = {}; $.each(items, function (_, item) { var date = new Date(item.date), month = date.format('mmyy'); result[month] = result[month] || { date: date, is_displayed: false, items: [] }; result[month].items.push(item); result[month].is_displayed = result[month].is_displayed || item.is_displayed; }); return result; }; items.past = group_by_month(items.past); var nodes = { past: [], future: [] }; if (items.pre_discussion.length) { nodes.past.push({ __proto__: timeline_item_prototype, template: 'cycle_timeline_past_cluster', month: 'לפני יצירת הדיון', items: items.pre_discussion }); } if (discussion_seen && !no_discussion) { nodes.past.push(items.discussion); } $.each(items.past, function (month, cluster) { nodes.past.push({ __proto__: timeline_item_prototype, template: 'cycle_timeline_past_cluster', month: cluster.date.format('mmmm'), items: cluster.items, is_displayed: cluster.is_displayed }); }); nodes.today = items.today; nodes.future = items.future; // Calculate offsets var LastOffset = 980; var TodayOffset = LastOffset / 3; if (today_seen) { // Past: var todayIndex = nodes.past.length; // index 0 should be at offset 0. // index {todayIndex} should be at offset {TodayOffset} - that index isn't actually inside this array $.each(nodes.past, function (index, item) { item.offset = TodayOffset * index / todayIndex; }); nodes.today.offset = TodayOffset; // Future: var lastIndex = nodes.future.length - 1; // index -1 should be at offset {TodayOffset} // index {lastIndex} should be at offset {LastOffset} - that index *is* in the array $.each(nodes.future, function (index, item) { item.offset = ((LastOffset - TodayOffset) * (index + 1) / (lastIndex + 1)) + TodayOffset; }); } else { // If we don't have a 'today' item, all nodes are in the past section var lastIndex = nodes.past.length - 1; // index 0 should be at offset 0 // index {lastIndex} should be at offset {LastOffset} $.each(nodes.past, function (index, item) { item.offset = LastOffset * index / lastIndex; }); } // Combine past and future bits - we don't need the separation any more. //console.log('Original timeline data: ', data.objects); //console.log('Items:', items); //console.log('Nodes:', nodes); nodes = nodes.past.concat([nodes.today], nodes.future); // Render the now ready timeline. $.each(nodes, function (index, item) { item.timeline_index = index; if (display_id) { item.is_displayed = false; } dust.render(item.template, item, function (err, out) { $('.followers-diagram').append(out); }); }); if(display_id) { $('.popup-event[item-id="'+display_id+'"]').addClass('showdiv'); } else { $('.icon').mouseenter(function() { var diagram = $('.followers-diagram'); $.each(diagram.find('div'), function(index, element){ if($(element).hasClass('showdiv')) { $(element).fadeOut(2000); } }) }); } //---------------------------------------------------------------------------------------------------- //add actions to cycle map //---------------------------------------------------------------------------------------------------- if($('#action_list div.action_map_item')){ var markers = []; var myOptions = { pane: "floatPane", enableEventPropagation: "true", boxStyle: { background: "url(../images/event-popup.png) no-repeat", "padding-top": "7px", "padding-left": "7px", width: "200px", height: "145px" }, pixelOffset: new google.maps.Size(-109, -155), closeBoxURL: "" }; var popup = new InfoBox(myOptions); $.each(data.objects, function(index, item){ if(item.type == 'action' && item.location) { var action_list_box = document.getElementById('action_list'); data = { title: item.title, date: item.date, num_of_going: item.num_of_going, is_going: item.is_going, text_field_preview: item.text_field_preview, location: item.location, is_displayed: false, _id: item._id }; dust.render('action_map_list_item', data, function(err, out){ $('#action_list').append(out); }); var markerPosition = new google.maps.LatLng(item.location.geometry.lat, item.location.geometry.lng); var marker = new google.maps.Marker({ position : markerPosition, map: map, flat: true, title: item.title, icon: { fillColor: "#3C63EF", fillOpacity: 1, strokeColor: "#2049D3", strokeWeight: 3, strokeOpacity: 1, path: google.maps.SymbolPath.CIRCLE, scale: 10 }, shape: google.maps.SymbolPath.CIRCLE, visible:true }); marker.metadata = {"id": item._id}; markers.push(marker); google.maps.event.addListener(marker, 'click', function(){ var myId = marker.metadata.id; var content; if($('div.popup-event[item-id=' + myId + ']')){ content = $('div.popup-event[item-id=' + myId + ']').clone()[0]; } else { } popup.setContent(content); popup.open(map, marker); selectActionItem(myId); }); $('#action_list .action_map_item').click(function(){ var myId = $(this).attr('data-id'); selectActionItem(myId); $.each(markers, function(indenx, marker){ if(myId == marker.metadata.id){ var content = $('div.popup-event[item-id=' + myId + ']').clone()[0]; popup.setContent(content); popup.open(map, marker); } }) }); var selectActionItem = function(id){ $.each($('.action_map_item'), function(index, item){ if(item.getAttribute('data-id') == id){ $(item).addClass('selected'); } else if($(item).hasClass('selected')){ $(item).removeClass('selected'); } }) } } }); $('.tabs-nav h5').click(function(){ var tab = $(this); var mapCenter = map.getCenter(); if(!$(this).hasClass('selected')){ if($('.map_tab').hasClass('selected')){ $('.map_tab').removeClass('selected'); $('h5.timeline_tab').append($("#timeline-second-part")); } else { $('.timeline_tab').removeClass('selected'); $('.map_tab').append($("#timeline-second-part")); var user_position = timeline.user_position; if(!user_position){ user_position = {lng: null, lat: null}; getUserPosition(user_position, function(){ if(user_position.lng && user_position.lat){ googleMap.addPlaceMark(user_position); }else { user_position.lng = 34.777821; user_position.lat = 32.066157; googleMap.addPlaceMark(user_position); } timeline.user_position = user_position; }); } } $(this).addClass('selected'); $('#tabs_cycle_timeline').toggle(); $('#tabs_cycle_map').toggle(); google.maps.event.trigger(map, 'resize'); if(mapCenter != map.getCenter()) map.setCenter(mapCenter); } }) } }); } };
$(function () { var initFollowState = Boolean($('.initial-is-followed-by').text()), // フォローボタンの初期状態 followBtn = $('#follow-button'), followIcon = $('#follow-icon'), followState = $('#follow-state'), countFollowings = $('#count-followings'), countFollowers = $('#count-followers'), authorized = Boolean($('.authorized').text()), // ログイン状態 url, // 送信先 reqType; // HTTPメソッドの種類 // 初期状態のアイコン状態の設定 if (initFollowState) { followBtn.toggleClass('active'); followIcon.removeClass("fa-user-plus"); followIcon.addClass("fa-user-check"); followState.text('フォロー中'); } else { followIcon.removeClass("fa-user-check"); followIcon.addClass("fa-user-plus"); followState.text('フォロー'); } $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="token"]').attr('content') } }); followBtn.click(function(event) { event.preventDefault(); if(authorized) { url = $(this).attr('href'); // 状態の読み取り if (followBtn.hasClass('active')) { reqType = 'DELETE'; } else { reqType = 'PUT'; } $.ajax({ dataType: "json", type: reqType, url: url, }) // 通信に成功した際の処理 .done(function(data, status) { // フォローボタン、アイコンの表示変更 followBtn.toggleClass('active'); followIcon.toggleClass('fa-user-plus'); followIcon.toggleClass('fa-user-check'); if(followState.text() === 'フォロー中') { followState.text('フォロー'); } else { followState.text('フォロー中'); } // フォロー数、フォロワー数の表示変更 countFollowings.text(data.countFollowings + ' フォロー'); countFollowers.text(data.countFollowers + ' フォロワー'); }) // 通信に失敗した際の処理 .fail(function(jqXHR, textStatus, errorThrown) { console.log("失敗"); console.log("エラー:" + textStatus); console.log("テキスト:" + jqXHR.responseText); }) } }); // ------------------- モーダルウィンドウの表示 ------------------ followBtn.on('click', function(event) { event.preventDefault(); $('#modal').modal(); }); });
webpackHotUpdate("static/development/pages/documentation.js", { /***/ "./pages/documentation.js": /*!********************************!*\ !*** ./pages/documentation.js ***! \********************************/ /*! exports provided: default */ /***/ function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var styled_jsx_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__( /*! styled-jsx/style */ "./node_modules/styled-jsx/style.js" ); /* harmony import */ var styled_jsx_style__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n( styled_jsx_style__WEBPACK_IMPORTED_MODULE_0__ ); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__( /*! react */ "./node_modules/react/index.js" ); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/ __webpack_require__.n( react__WEBPACK_IMPORTED_MODULE_1__ ); /* harmony import */ var next_head__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__( /*! next/head */ "./node_modules/next/dist/next-server/lib/head.js" ); /* harmony import */ var next_head__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/ __webpack_require__.n( next_head__WEBPACK_IMPORTED_MODULE_2__ ); /* harmony import */ var react_syntax_highlighter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__( /*! react-syntax-highlighter */ "./node_modules/react-syntax-highlighter/dist/esm/index.js" ); /* harmony import */ var react_syntax_highlighter_dist_cjs_styles_prism__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__( /*! react-syntax-highlighter/dist/cjs/styles/prism */ "./node_modules/react-syntax-highlighter/dist/cjs/styles/prism/index.js" ); /* harmony import */ var react_syntax_highlighter_dist_cjs_styles_prism__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/ __webpack_require__.n( react_syntax_highlighter_dist_cjs_styles_prism__WEBPACK_IMPORTED_MODULE_4__ ); var _jsxFileName = "/Users/aaronmoradi/Documents/projects/scintilla/www/pages/documentation.js"; var __jsx = react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement; const Docs = () => { return __jsx( "div", { className: "jsx-741711919" + " " + "container", __source: { fileName: _jsxFileName, lineNumber: 7 }, __self: undefined }, __jsx( next_head__WEBPACK_IMPORTED_MODULE_2___default.a, { __source: { fileName: _jsxFileName, lineNumber: 8 }, __self: undefined }, __jsx( "title", { className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 9 }, __self: undefined }, "scintilla" ) ), __jsx( "main", { className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 13 }, __self: undefined }, __jsx( "div", { className: "jsx-741711919" + " " + "grid", __source: { fileName: _jsxFileName, lineNumber: 14 }, __self: undefined }, __jsx( "div", { className: "jsx-741711919" + " " + "card primo", __source: { fileName: _jsxFileName, lineNumber: 15 }, __self: undefined }, __jsx( "h1", { className: "jsx-741711919" + " " + "title", __source: { fileName: _jsxFileName, lineNumber: 16 }, __self: undefined }, "Scintilla" ), __jsx( "p", { className: "jsx-741711919" + " " + "description", __source: { fileName: _jsxFileName, lineNumber: 17 }, __self: undefined }, "A React sparklines component" ), __jsx( "h3", { className: "jsx-741711919" + " " + "description", __source: { fileName: _jsxFileName, lineNumber: 19 }, __self: undefined }, __jsx( "a", { href: "/", className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 20 }, __self: undefined }, "home" ) ) ), __jsx( "div", { className: "jsx-741711919" + " " + "col2", __source: { fileName: _jsxFileName, lineNumber: 26 }, __self: undefined }, __jsx( "h2", { className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 27 }, __self: undefined }, "types" ), __jsx( react_syntax_highlighter__WEBPACK_IMPORTED_MODULE_3__[ "Prism" ], { language: "tsx", style: react_syntax_highlighter_dist_cjs_styles_prism__WEBPACK_IMPORTED_MODULE_4__[ "prism" ], __source: { fileName: _jsxFileName, lineNumber: 28 }, __self: undefined }, '\ntype RGBA = [0-255, 0-255, 0-255, 0-1]\n\ntype Color = {\n gradient?: RGBA | RGBA[];\n solid?: RGBA | RGBA[];\n};\n\ntype Stroke = {\n width: number;\n style: "dash" | "solid";\n color: Color;\n};' ), __jsx( "h2", { className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 44 }, __self: undefined }, "types" ), __jsx( react_syntax_highlighter__WEBPACK_IMPORTED_MODULE_3__[ "Prism" ], { language: "tsx", style: react_syntax_highlighter_dist_cjs_styles_prism__WEBPACK_IMPORTED_MODULE_4__[ "prism" ], __source: { fileName: _jsxFileName, lineNumber: 45 }, __self: undefined }, '\ntype RGBA = [0-255, 0-255, 0-255, 0-1]\n\ntype Color = {\n gradient?: RGBA | RGBA[];\n solid?: RGBA | RGBA[];\n};\n\ntype Stroke = {\n width: number;\n style: "dash" | "solid";\n color: Color;\n};' ) ) ) ), __jsx( "footer", { className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 128 }, __self: undefined }, __jsx( "a", { href: "/", className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 129 }, __self: undefined }, __jsx( "h3", { className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 130 }, __self: undefined }, "home" ) ), __jsx( "a", { href: "/documentation", className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 133 }, __self: undefined }, __jsx( "h3", { className: "jsx-741711919", __source: { fileName: _jsxFileName, lineNumber: 134 }, __self: undefined }, "documentation" ) ) ), __jsx( styled_jsx_style__WEBPACK_IMPORTED_MODULE_0___default.a, { id: "4023180869", __self: undefined }, ".container.jsx-741711919{min-height:100vh;padding:0 0.5rem;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;}main.jsx-741711919{padding:0 0 5rem;-webkit-flex:1;-ms-flex:1;flex:1;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;}footer.jsx-741711919{padding-bottom:100px;width:100%;height:100px;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;}footer.jsx-741711919 img.jsx-741711919{margin-left:0.5rem;}footer.jsx-741711919 a.jsx-741711919{padding:5px 10px;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;}a.jsx-741711919{color:inherit;-webkit-text-decoration:none;text-decoration:none;}.title.jsx-741711919 a.jsx-741711919{color:#0070f3;-webkit-text-decoration:none;text-decoration:none;}.title.jsx-741711919 a.jsx-741711919:hover,.title.jsx-741711919 a.jsx-741711919:focus,.title.jsx-741711919 a.jsx-741711919:active{-webkit-text-decoration:underline;text-decoration:underline;}.title.jsx-741711919{margin:100px 0 0;line-height:1.15;font-size:3rem;}.title.jsx-741711919,.description.jsx-741711919{text-align:center;}.description.jsx-741711919{line-height:1.5;font-size:0.9rem;}code.jsx-741711919{background:#fafafa;border-radius:5px;padding:0.75rem;font-size:1.1rem;font-family:Menlo,Monaco,Lucida Console,Liberation Mono, DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace;}.grid.jsx-741711919{display:grid;grid-template-columns:380px 1140px;max-width:100vw;margin-top:3rem;}.col2.jsx-741711919{margin-top:75px;}.card.jsx-741711919{margin:1rem;padding:1.5rem;box-sizing:border-box;}.card.jsx-741711919 pre.jsx-741711919{height:240px;overflow-y:scroll;}.card.primo.jsx-741711919{color:#444;text-transform:lowercase;position:relative;margin-right:7rem;margin-top:2.5rem;}h3.jsx-741711919{font-weight:normal;margin-top:60px;-webkit-text-decoration:underline;text-decoration:underline;}h2.jsx-741711919,h3.jsx-741711919{color:#444;}@media (max-width:600px){.grid.jsx-741711919{width:100%;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;}}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9hYXJvbm1vcmFkaS9Eb2N1bWVudHMvcHJvamVjdHMvc2NpbnRpbGxhL3d3dy9wYWdlcy9kb2N1bWVudGF0aW9uLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQXlJZ0IsQUFHMEIsQUFTQSxBQVNJLEFBVUYsQUFJRixBQU9ILEFBS0EsQUFPWSxBQUlULEFBU0MsQUFJRixBQUtHLEFBYU4sQUFPRyxBQU9KLEFBUUMsQUFNRixBQVFRLEFBTVIsQUFLRSxXQWxCWSxBQWMzQixBQUswQixDQWhDVCxDQWZvQixBQXNCakIsQ0FyRUcsQUFLQSxFQXdCSixBQXlCbkIsQ0E3Rm1CLEFBU1YsQUF1Qk0sQUF1QkksQ0FTbkIsQ0FwQ0EsQUE2Q29CLEFBaURGLEVBeEdMLE1BcUZXLElBTXhCLENBMUZlLENBa0RmLENBcEVlLEFBdURFLENBbUVXLENBUlIsQ0F6Q0YsUUFyREgsR0FrRUcsQ0E1QmxCLEFBNkNBLENBOUZlLEdBaUVJLENBeUNDLE1BakVwQixJQVhBLEFBS0EsQUEyQ2tCLE1BWG9ELEVBd0NsRCxRQTVCcEIsU0E2Q0UsQ0FoQkYsQ0FyRnlCLElBMkZ6QixhQTFId0IsV0FvQkMsS0FYRCw4REFSQyxJQStCSixDQTRDckIsV0FsRXlCLGdCQVdKLGlFQVlyQixFQS9CcUIsZ0JBU0EsVUFXckIsbUVBbkJBLGdCQVNBIiwiZmlsZSI6Ii9Vc2Vycy9hYXJvbm1vcmFkaS9Eb2N1bWVudHMvcHJvamVjdHMvc2NpbnRpbGxhL3d3dy9wYWdlcy9kb2N1bWVudGF0aW9uLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IEhlYWQgZnJvbSBcIm5leHQvaGVhZFwiO1xuaW1wb3J0IHsgUHJpc20gYXMgU3ludGF4SGlnaGxpZ2h0ZXIgfSBmcm9tIFwicmVhY3Qtc3ludGF4LWhpZ2hsaWdodGVyXCI7XG5pbXBvcnQgeyBwcmlzbSB9IGZyb20gXCJyZWFjdC1zeW50YXgtaGlnaGxpZ2h0ZXIvZGlzdC9janMvc3R5bGVzL3ByaXNtXCI7XG5cbmNvbnN0IERvY3MgPSAoKSA9PiB7XG4gIHJldHVybiAoXG4gIDxkaXYgY2xhc3NOYW1lPVwiY29udGFpbmVyXCI+XG4gICAgPEhlYWQ+XG4gICAgICA8dGl0bGU+c2NpbnRpbGxhPC90aXRsZT5cbiAgICAgIHsvKjxsaW5rIHJlbD1cImljb25cIiBocmVmPVwiL2Zhdmljb24uaWNvXCIgLz4qL31cbiAgICA8L0hlYWQ+XG5cbiAgICA8bWFpbj5cbiAgICAgIDxkaXYgY2xhc3NOYW1lPVwiZ3JpZFwiPlxuICAgICAgICA8ZGl2IGNsYXNzTmFtZT1cImNhcmQgcHJpbW9cIj5cbiAgICAgICAgICA8aDEgY2xhc3NOYW1lPVwidGl0bGVcIj5TY2ludGlsbGE8L2gxPlxuICAgICAgICAgIDxwIGNsYXNzTmFtZT1cImRlc2NyaXB0aW9uXCI+QSBSZWFjdCBzcGFya2xpbmVzIGNvbXBvbmVudDwvcD5cblxuICAgICAgICAgIDxoMyBjbGFzc05hbWU9XCJkZXNjcmlwdGlvblwiPlxuICAgICAgICAgICAgPGEgaHJlZj1cIi9cIj5cbiAgICAgICAgICAgICAgaG9tZVxuICAgICAgICAgICAgPC9hPlxuICAgICAgICAgIDwvaDM+XG4gICAgICAgIDwvZGl2PlxuICAgICAgXG4gICAgICA8ZGl2IGNsYXNzTmFtZT1cImNvbDJcIj5cbiAgICAgICAgPGgyPnR5cGVzPC9oMj5cbiAgICAgICAgPFN5bnRheEhpZ2hsaWdodGVyIGxhbmd1YWdlPVwidHN4XCIgc3R5bGU9e3ByaXNtfT5cbiAgICAgICAgICB7YFxudHlwZSBSR0JBID0gWzAtMjU1LCAwLTI1NSwgMC0yNTUsIDAtMV1cblxudHlwZSBDb2xvciA9IHtcbiAgZ3JhZGllbnQ/OiBSR0JBIHwgUkdCQVtdO1xuICBzb2xpZD86IFJHQkEgfCBSR0JBW107XG59O1xuXG50eXBlIFN0cm9rZSA9IHtcbiAgd2lkdGg6IG51bWJlcjtcbiAgc3R5bGU6IFwiZGFzaFwiIHwgXCJzb2xpZFwiO1xuICBjb2xvcjogQ29sb3I7XG59O2Bcbn1cbiAgICAgICAgPC9TeW50YXhIaWdobGlnaHRlcj5cbiAgICAgICAgPGgyPnR5cGVzPC9oMj5cbiAgICAgICAgPFN5bnRheEhpZ2hsaWdodGVyIGxhbmd1YWdlPVwidHN4XCIgc3R5bGU9e3ByaXNtfT5cbiAgICAgICAgICB7YFxudHlwZSBSR0JBID0gWzAtMjU1LCAwLTI1NSwgMC0yNTUsIDAtMV1cblxudHlwZSBDb2xvciA9IHtcbiAgZ3JhZGllbnQ/OiBSR0JBIHwgUkdCQVtdO1xuICBzb2xpZD86IFJHQkEgfCBSR0JBW107XG59O1xuXG50eXBlIFN0cm9rZSA9IHtcbiAgd2lkdGg6IG51bWJlcjtcbiAgc3R5bGU6IFwiZGFzaFwiIHwgXCJzb2xpZFwiO1xuICBjb2xvcjogQ29sb3I7XG59O2Bcbn1cbiAgICAgICAgPC9TeW50YXhIaWdobGlnaHRlcj5cblxuey8qIC8vIENvbXBvbmVudHNcblxuIyMjIGA8RnJhbWUgLz5gXG5cblJlc3BvbnNpdmUgY29udGFpbmVyIGZvciBhbGwgYGRhdGFgLW5lZWR5IGNoaWxkIGNvbXBvbmVudHMuXG5cbi0gKipgaGVpZ2h0PzogbnVtYmVyYCoqXG4gIE9wdGlvbmFsbHkgc3BlY2lmeSBoZWlnaHQgaW4gcGl4ZWxzLiBEZWZhdWx0cyB0byBgNTBweGAuXG5cbi0gKipgcmFuZ2U/OiBbbWluPG51bWJlcj4sIG1heDxudW1iZXI+XWAqKlxuICBPcHRpb25hbGx5IHBsb3QgYGNoaWxkcmVuYCBjb21wb25lbnRzIHdpdGggdGhpcyB5IGF4aXMgY29uc3RyYWludC5cblxuKipFeGFtcGxlKipcblxuYGBganN4XG48RnJhbWUgaGVpZ2h0PXsxMDB9IHJhbmdlPXtbMCwgNTAwXX0+XG4gIDxMaW5lIC8+XG48L0ZyYW1lPlxuYGBgXG5cbi0tLVxuXG4jIyMgYDxMaW5lIC8+YFxuXG5QbG90IHlvdXIgc2VyaWVzIGRhdGEgYXMgYSBsaW5lLiBTdHlsZSBsaW5lIHdpdGggYHN0cm9rZWAsIGBmaWxsYCBvciBib3RoLlxuXG4tICoqYGRhdGE6IG51bWJlcltdYCoqXG4gIFRoZSBsaXN0IG9mIGB5YCBkYXRhIHRvIHBsb3QuXG5cbi0gKipgc3Ryb2tlPzogU3Ryb2tlYCoqXG4gIFNldCBgd2lkdGhgIGluIHBpeGVscywgYHN0eWxlYCBhcyBgJ2Rhc2gnYCBvciBgJ3NvbGlkJ2AgYW5kIGNvbG9yIG9wdGlvbi5cblxuLSAqKmBmaWxsPzogQ29sb3JgKipcbiAgU29saWQgb3IgZ3JhZGllbnQgZmlsbCwgd2l0aCBvbmUgb3IgbWFueSBjb2xvcnMuIEZpbGxzIGFyZWEgZnJvbSBkYXRhIGxpbmUgdG8gYm90dG9tIGF4aXMuXG5cbioqRXhhbXBsZSoqXG5cbmBgYGpzeFxuPEZyYW1lPlxuICA8TGluZVxuICAgIGRhdGE9e1stMSwgMiwgNiwgOSwgMTEsIDIxXX1cbiAgICBzdHJva2U9e3tcbiAgICAgIHdpZHRoOiAxLFxuICAgICAgc3R5bGU6IFwiZGFzaFwiLFxuICAgICAgY29sb3I6IHtcbiAgICAgICAgc29saWQ6IFtcbiAgICAgICAgICBbMjU1LCAwLCAwLCAwLjI1XSxcbiAgICAgICAgICBbMjU1LCAwLCAwLCAwLjVdLFxuICAgICAgICAgIFsyNTUsIDAsIDAsIDAuMV1cbiAgICAgICAgXVxuICAgICAgfVxuICAgIH19XG4gICAgZmlsbD17e1xuICAgICAgZ3JhZGllbnQ6IFtcbiAgICAgICAgWzI1NSwgMCwgMCwgMC4xXSxcbiAgICAgICAgWzI1NSwgMCwgMCwgMV1cbiAgICAgIF1cbiAgICB9fVxuICAvPlxuPC9GcmFtZT5cbmB9IFxuICA8L1N5bnRheEhpZ2hsaWdodGVyPiovfVxuICAgICAgPC9kaXY+XG4gICAgICA8L2Rpdj5cbiAgICA8L21haW4+XG5cbiAgICA8Zm9vdGVyPlxuICAgICAgPGEgaHJlZj1cIi9cIj5cbiAgICAgICAgPGgzPmhvbWU8L2gzPlxuICAgICAgPC9hPlxuXG4gICAgICA8YSBocmVmPVwiL2RvY3VtZW50YXRpb25cIj5cbiAgICAgICAgPGgzPmRvY3VtZW50YXRpb248L2gzPlxuICAgICAgPC9hPlxuICAgIDwvZm9vdGVyPlxuXG4gICAgPHN0eWxlIGpzeD57YFxuICAgICAgLmNvbnRhaW5lciB7XG4gICAgICAgIG1pbi1oZWlnaHQ6IDEwMHZoO1xuICAgICAgICBwYWRkaW5nOiAwIDAuNXJlbTtcbiAgICAgICAgZGlzcGxheTogZmxleDtcbiAgICAgICAgZmxleC1kaXJlY3Rpb246IGNvbHVtbjtcbiAgICAgICAganVzdGlmeS1jb250ZW50OiBjZW50ZXI7XG4gICAgICAgIGFsaWduLWl0ZW1zOiBjZW50ZXI7XG4gICAgICB9XG5cbiAgICAgIG1haW4ge1xuICAgICAgICBwYWRkaW5nOiAwIDAgNXJlbTtcbiAgICAgICAgZmxleDogMTtcbiAgICAgICAgZGlzcGxheTogZmxleDtcbiAgICAgICAgZmxleC1kaXJlY3Rpb246IGNvbHVtbjtcbiAgICAgICAganVzdGlmeS1jb250ZW50OiBjZW50ZXI7XG4gICAgICAgIGFsaWduLWl0ZW1zOiBjZW50ZXI7XG4gICAgICB9XG5cbiAgICAgIGZvb3RlciB7XG4gICAgICAgIHBhZGRpbmctYm90dG9tOiAxMDBweDtcbiAgICAgICAgd2lkdGg6IDEwMCU7XG4gICAgICAgIGhlaWdodDogMTAwcHg7XG4gICAgICAgIC8vYm9yZGVyLXRvcDogMXB4IHNvbGlkICNlYWVhZWE7XG4gICAgICAgIGRpc3BsYXk6IGZsZXg7XG4gICAgICAgIGp1c3RpZnktY29udGVudDogY2VudGVyO1xuICAgICAgICBhbGlnbi1pdGVtczogY2VudGVyO1xuICAgICAgfVxuXG4gICAgICBmb290ZXIgaW1nIHtcbiAgICAgICAgbWFyZ2luLWxlZnQ6IDAuNXJlbTtcbiAgICAgIH1cblxuICAgICAgZm9vdGVyIGEge1xuICAgICAgICBwYWRkaW5nOiA1cHggMTBweDtcbiAgICAgICAgZGlzcGxheTogZmxleDtcbiAgICAgICAganVzdGlmeS1jb250ZW50OiBjZW50ZXI7XG4gICAgICAgIGFsaWduLWl0ZW1zOiBjZW50ZXI7XG4gICAgICB9XG5cbiAgICAgIGEge1xuICAgICAgICBjb2xvcjogaW5oZXJpdDtcbiAgICAgICAgdGV4dC1kZWNvcmF0aW9uOiBub25lO1xuICAgICAgfVxuXG4gICAgICAudGl0bGUgYSB7XG4gICAgICAgIGNvbG9yOiAjMDA3MGYzO1xuICAgICAgICB0ZXh0LWRlY29yYXRpb246IG5vbmU7XG4gICAgICB9XG5cbiAgICAgIC50aXRsZSBhOmhvdmVyLFxuICAgICAgLnRpdGxlIGE6Zm9jdXMsXG4gICAgICAudGl0bGUgYTphY3RpdmUge1xuICAgICAgICB0ZXh0LWRlY29yYXRpb246IHVuZGVybGluZTtcbiAgICAgIH1cblxuICAgICAgLnRpdGxlIHtcbiAgICAgICAgbWFyZ2luOiAxMDBweCAwIDA7XG4gICAgICAgIGxpbmUtaGVpZ2h0OiAxLjE1O1xuICAgICAgICBmb250LXNpemU6IDNyZW07XG4gICAgICAgIC8vIHRleHQtdHJhbnNmb3JtOiB1cHBlcmNhc2U7XG4gICAgICAgIC8vIGhlaWdodDogMTUwcHg7XG4gICAgICB9XG5cbiAgICAgIC50aXRsZSxcbiAgICAgIC5kZXNjcmlwdGlvbiB7XG4gICAgICAgIHRleHQtYWxpZ246IGNlbnRlcjtcbiAgICAgIH1cblxuICAgICAgLmRlc2NyaXB0aW9uIHtcbiAgICAgICAgbGluZS1oZWlnaHQ6IDEuNTtcbiAgICAgICAgZm9udC1zaXplOiAwLjlyZW07XG4gICAgICB9XG5cbiAgICAgIGNvZGUge1xuICAgICAgICBiYWNrZ3JvdW5kOiAjZmFmYWZhO1xuICAgICAgICBib3JkZXItcmFkaXVzOiA1cHg7XG4gICAgICAgIHBhZGRpbmc6IDAuNzVyZW07XG4gICAgICAgIGZvbnQtc2l6ZTogMS4xcmVtO1xuICAgICAgICBmb250LWZhbWlseTogTWVubG8sIE1vbmFjbywgTHVjaWRhIENvbnNvbGUsIExpYmVyYXRpb24gTW9ubyxcbiAgICAgICAgICBEZWphVnUgU2FucyBNb25vLCBCaXRzdHJlYW0gVmVyYSBTYW5zIE1vbm8sIENvdXJpZXIgTmV3LCBtb25vc3BhY2U7XG4gICAgICB9XG5cbiAgICAgIC5ncmlkIHtcbiAgICAgICAgLy8gZGlzcGxheTogZmxleDtcbiAgICAgICAgLy8gYWxpZ24taXRlbXM6IGNlbnRlcjtcbiAgICAgICAgLy8ganVzdGlmeS1jb250ZW50OiBjZW50ZXI7XG4gICAgICAgIC8vIGZsZXgtd3JhcDogd3JhcDtcbiAgICAgICAgZGlzcGxheTogZ3JpZDtcbiAgICAgICAgZ3JpZC10ZW1wbGF0ZS1jb2x1bW5zOiAzODBweCAxMTQwcHg7XG4gICAgICAgIG1heC13aWR0aDogMTAwdnc7XG4gICAgICAgIG1hcmdpbi10b3A6IDNyZW07XG4gICAgICB9XG5cbiAgICAgIC5jb2wyIHtcbiAgICAgICAgbWFyZ2luLXRvcDogNzVweDtcbiAgICAgIH1cblxuICAgICAgLy8uZ3JpZCA+ICosXG4gICAgICAuY2FyZCB7XG4gICAgICAgIC8vIG1pbi13aWR0aDogMzIwcHg7XG4gICAgICAgIC8vIG1heC13aWR0aDogMzgwcHg7XG4gICAgICAgIG1hcmdpbjogMXJlbTtcbiAgICAgICAgLy8gZmxleC1iYXNpczogMjUlO1xuICAgICAgICBwYWRkaW5nOiAxLjVyZW07XG4gICAgICAgIC8vYWxpZ24tc2VsZjogZmxleC1zdGFydDtcbiAgICAgICAgYm94LXNpemluZzogYm9yZGVyLWJveDtcbiAgICAgIH1cblxuICAgICAgLmNhcmQgcHJlIHtcbiAgICAgICAgaGVpZ2h0OiAyNDBweDtcbiAgICAgICAgb3ZlcmZsb3cteTogc2Nyb2xsO1xuICAgICAgfVxuXG4gICAgICAuY2FyZC5wcmltbyB7XG4gICAgICAgIC8vYWxpZ24tc2VsZjogY2VudGVyO1xuICAgICAgICBjb2xvcjogIzQ0NDtcbiAgICAgICAgdGV4dC10cmFuc2Zvcm06IGxvd2VyY2FzZTtcbiAgICAgICAgcG9zaXRpb246IHJlbGF0aXZlO1xuICAgICAgICBtYXJnaW4tcmlnaHQ6IDdyZW07XG4gICAgICAgIG1hcmdpbi10b3A6IDIuNXJlbTtcbiAgICAgIH1cblxuICAgICAgaDMge1xuICAgICAgICBmb250LXdlaWdodDogbm9ybWFsO1xuICAgICAgICBtYXJnaW4tdG9wOiA2MHB4O1xuICAgICAgICB0ZXh0LWRlY29yYXRpb246IHVuZGVybGluZTtcbiAgICAgIH1cblxuICAgICAgaDIsIGgzIHtcbiAgICAgICAgY29sb3I6ICM0NDQ7XG4gICAgICB9XG4gICAgICBcbiAgICAgIEBtZWRpYSAobWF4LXdpZHRoOiA2MDBweCkge1xuICAgICAgICAuZ3JpZCB7XG4gICAgICAgICAgd2lkdGg6IDEwMCU7XG4gICAgICAgICAgZmxleC1kaXJlY3Rpb246IGNvbHVtbjtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIGB9PC9zdHlsZT5cblxuICAgIDxzdHlsZSBqc3ggZ2xvYmFsPntgXG4gICAgICBodG1sLFxuICAgICAgYm9keSB7XG4gICAgICAgIGJhY2tncm91bmQtY29sb3I6ICNmZmZhZjA7XG4gICAgICAgIHBhZGRpbmc6IDA7XG4gICAgICAgIG1hcmdpbjogMDtcbiAgICAgICAgZm9udC1mYW1pbHk6IC1hcHBsZS1zeXN0ZW0sIEJsaW5rTWFjU3lzdGVtRm9udCwgU2Vnb2UgVUksIFJvYm90bywgT3h5Z2VuLFxuICAgICAgICAgIFVidW50dSwgQ2FudGFyZWxsLCBGaXJhIFNhbnMsIERyb2lkIFNhbnMsIEhlbHZldGljYSBOZXVlLCBzYW5zLXNlcmlmO1xuICAgICAgfVxuXG4gICAgICAqIHtcbiAgICAgICAgYm94LXNpemluZzogYm9yZGVyLWJveDtcbiAgICAgIH1cbiAgICBgfTwvc3R5bGU+XG4gIDwvZGl2PlxuKX07XG5cbmV4cG9ydCBkZWZhdWx0IERvY3M7XG4iXX0= */\n/*@ sourceURL=/Users/aaronmoradi/Documents/projects/scintilla/www/pages/documentation.js */" ), __jsx( styled_jsx_style__WEBPACK_IMPORTED_MODULE_0___default.a, { id: "3702522083", __self: undefined }, "html,body{background-color:#fffaf0;padding:0;margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen, Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;}*{box-sizing:border-box;}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9hYXJvbm1vcmFkaS9Eb2N1bWVudHMvcHJvamVjdHMvc2NpbnRpbGxhL3d3dy9wYWdlcy9kb2N1bWVudGF0aW9uLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQXNSdUIsQUFJa0MsQUFRSCxzQkFDeEIsR0FSWSxVQUNELFNBRTZELHFJQUN4RSIsImZpbGUiOiIvVXNlcnMvYWFyb25tb3JhZGkvRG9jdW1lbnRzL3Byb2plY3RzL3NjaW50aWxsYS93d3cvcGFnZXMvZG9jdW1lbnRhdGlvbi5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBIZWFkIGZyb20gXCJuZXh0L2hlYWRcIjtcbmltcG9ydCB7IFByaXNtIGFzIFN5bnRheEhpZ2hsaWdodGVyIH0gZnJvbSBcInJlYWN0LXN5bnRheC1oaWdobGlnaHRlclwiO1xuaW1wb3J0IHsgcHJpc20gfSBmcm9tIFwicmVhY3Qtc3ludGF4LWhpZ2hsaWdodGVyL2Rpc3QvY2pzL3N0eWxlcy9wcmlzbVwiO1xuXG5jb25zdCBEb2NzID0gKCkgPT4ge1xuICByZXR1cm4gKFxuICA8ZGl2IGNsYXNzTmFtZT1cImNvbnRhaW5lclwiPlxuICAgIDxIZWFkPlxuICAgICAgPHRpdGxlPnNjaW50aWxsYTwvdGl0bGU+XG4gICAgICB7Lyo8bGluayByZWw9XCJpY29uXCIgaHJlZj1cIi9mYXZpY29uLmljb1wiIC8+Ki99XG4gICAgPC9IZWFkPlxuXG4gICAgPG1haW4+XG4gICAgICA8ZGl2IGNsYXNzTmFtZT1cImdyaWRcIj5cbiAgICAgICAgPGRpdiBjbGFzc05hbWU9XCJjYXJkIHByaW1vXCI+XG4gICAgICAgICAgPGgxIGNsYXNzTmFtZT1cInRpdGxlXCI+U2NpbnRpbGxhPC9oMT5cbiAgICAgICAgICA8cCBjbGFzc05hbWU9XCJkZXNjcmlwdGlvblwiPkEgUmVhY3Qgc3BhcmtsaW5lcyBjb21wb25lbnQ8L3A+XG5cbiAgICAgICAgICA8aDMgY2xhc3NOYW1lPVwiZGVzY3JpcHRpb25cIj5cbiAgICAgICAgICAgIDxhIGhyZWY9XCIvXCI+XG4gICAgICAgICAgICAgIGhvbWVcbiAgICAgICAgICAgIDwvYT5cbiAgICAgICAgICA8L2gzPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIFxuICAgICAgPGRpdiBjbGFzc05hbWU9XCJjb2wyXCI+XG4gICAgICAgIDxoMj50eXBlczwvaDI+XG4gICAgICAgIDxTeW50YXhIaWdobGlnaHRlciBsYW5ndWFnZT1cInRzeFwiIHN0eWxlPXtwcmlzbX0+XG4gICAgICAgICAge2BcbnR5cGUgUkdCQSA9IFswLTI1NSwgMC0yNTUsIDAtMjU1LCAwLTFdXG5cbnR5cGUgQ29sb3IgPSB7XG4gIGdyYWRpZW50PzogUkdCQSB8IFJHQkFbXTtcbiAgc29saWQ/OiBSR0JBIHwgUkdCQVtdO1xufTtcblxudHlwZSBTdHJva2UgPSB7XG4gIHdpZHRoOiBudW1iZXI7XG4gIHN0eWxlOiBcImRhc2hcIiB8IFwic29saWRcIjtcbiAgY29sb3I6IENvbG9yO1xufTtgXG59XG4gICAgICAgIDwvU3ludGF4SGlnaGxpZ2h0ZXI+XG4gICAgICAgIDxoMj50eXBlczwvaDI+XG4gICAgICAgIDxTeW50YXhIaWdobGlnaHRlciBsYW5ndWFnZT1cInRzeFwiIHN0eWxlPXtwcmlzbX0+XG4gICAgICAgICAge2BcbnR5cGUgUkdCQSA9IFswLTI1NSwgMC0yNTUsIDAtMjU1LCAwLTFdXG5cbnR5cGUgQ29sb3IgPSB7XG4gIGdyYWRpZW50PzogUkdCQSB8IFJHQkFbXTtcbiAgc29saWQ/OiBSR0JBIHwgUkdCQVtdO1xufTtcblxudHlwZSBTdHJva2UgPSB7XG4gIHdpZHRoOiBudW1iZXI7XG4gIHN0eWxlOiBcImRhc2hcIiB8IFwic29saWRcIjtcbiAgY29sb3I6IENvbG9yO1xufTtgXG59XG4gICAgICAgIDwvU3ludGF4SGlnaGxpZ2h0ZXI+XG5cbnsvKiAvLyBDb21wb25lbnRzXG5cbiMjIyBgPEZyYW1lIC8+YFxuXG5SZXNwb25zaXZlIGNvbnRhaW5lciBmb3IgYWxsIGBkYXRhYC1uZWVkeSBjaGlsZCBjb21wb25lbnRzLlxuXG4tICoqYGhlaWdodD86IG51bWJlcmAqKlxuICBPcHRpb25hbGx5IHNwZWNpZnkgaGVpZ2h0IGluIHBpeGVscy4gRGVmYXVsdHMgdG8gYDUwcHhgLlxuXG4tICoqYHJhbmdlPzogW21pbjxudW1iZXI+LCBtYXg8bnVtYmVyPl1gKipcbiAgT3B0aW9uYWxseSBwbG90IGBjaGlsZHJlbmAgY29tcG9uZW50cyB3aXRoIHRoaXMgeSBheGlzIGNvbnN0cmFpbnQuXG5cbioqRXhhbXBsZSoqXG5cbmBgYGpzeFxuPEZyYW1lIGhlaWdodD17MTAwfSByYW5nZT17WzAsIDUwMF19PlxuICA8TGluZSAvPlxuPC9GcmFtZT5cbmBgYFxuXG4tLS1cblxuIyMjIGA8TGluZSAvPmBcblxuUGxvdCB5b3VyIHNlcmllcyBkYXRhIGFzIGEgbGluZS4gU3R5bGUgbGluZSB3aXRoIGBzdHJva2VgLCBgZmlsbGAgb3IgYm90aC5cblxuLSAqKmBkYXRhOiBudW1iZXJbXWAqKlxuICBUaGUgbGlzdCBvZiBgeWAgZGF0YSB0byBwbG90LlxuXG4tICoqYHN0cm9rZT86IFN0cm9rZWAqKlxuICBTZXQgYHdpZHRoYCBpbiBwaXhlbHMsIGBzdHlsZWAgYXMgYCdkYXNoJ2Agb3IgYCdzb2xpZCdgIGFuZCBjb2xvciBvcHRpb24uXG5cbi0gKipgZmlsbD86IENvbG9yYCoqXG4gIFNvbGlkIG9yIGdyYWRpZW50IGZpbGwsIHdpdGggb25lIG9yIG1hbnkgY29sb3JzLiBGaWxscyBhcmVhIGZyb20gZGF0YSBsaW5lIHRvIGJvdHRvbSBheGlzLlxuXG4qKkV4YW1wbGUqKlxuXG5gYGBqc3hcbjxGcmFtZT5cbiAgPExpbmVcbiAgICBkYXRhPXtbLTEsIDIsIDYsIDksIDExLCAyMV19XG4gICAgc3Ryb2tlPXt7XG4gICAgICB3aWR0aDogMSxcbiAgICAgIHN0eWxlOiBcImRhc2hcIixcbiAgICAgIGNvbG9yOiB7XG4gICAgICAgIHNvbGlkOiBbXG4gICAgICAgICAgWzI1NSwgMCwgMCwgMC4yNV0sXG4gICAgICAgICAgWzI1NSwgMCwgMCwgMC41XSxcbiAgICAgICAgICBbMjU1LCAwLCAwLCAwLjFdXG4gICAgICAgIF1cbiAgICAgIH1cbiAgICB9fVxuICAgIGZpbGw9e3tcbiAgICAgIGdyYWRpZW50OiBbXG4gICAgICAgIFsyNTUsIDAsIDAsIDAuMV0sXG4gICAgICAgIFsyNTUsIDAsIDAsIDFdXG4gICAgICBdXG4gICAgfX1cbiAgLz5cbjwvRnJhbWU+XG5gfSBcbiAgPC9TeW50YXhIaWdobGlnaHRlcj4qL31cbiAgICAgIDwvZGl2PlxuICAgICAgPC9kaXY+XG4gICAgPC9tYWluPlxuXG4gICAgPGZvb3Rlcj5cbiAgICAgIDxhIGhyZWY9XCIvXCI+XG4gICAgICAgIDxoMz5ob21lPC9oMz5cbiAgICAgIDwvYT5cblxuICAgICAgPGEgaHJlZj1cIi9kb2N1bWVudGF0aW9uXCI+XG4gICAgICAgIDxoMz5kb2N1bWVudGF0aW9uPC9oMz5cbiAgICAgIDwvYT5cbiAgICA8L2Zvb3Rlcj5cblxuICAgIDxzdHlsZSBqc3g+e2BcbiAgICAgIC5jb250YWluZXIge1xuICAgICAgICBtaW4taGVpZ2h0OiAxMDB2aDtcbiAgICAgICAgcGFkZGluZzogMCAwLjVyZW07XG4gICAgICAgIGRpc3BsYXk6IGZsZXg7XG4gICAgICAgIGZsZXgtZGlyZWN0aW9uOiBjb2x1bW47XG4gICAgICAgIGp1c3RpZnktY29udGVudDogY2VudGVyO1xuICAgICAgICBhbGlnbi1pdGVtczogY2VudGVyO1xuICAgICAgfVxuXG4gICAgICBtYWluIHtcbiAgICAgICAgcGFkZGluZzogMCAwIDVyZW07XG4gICAgICAgIGZsZXg6IDE7XG4gICAgICAgIGRpc3BsYXk6IGZsZXg7XG4gICAgICAgIGZsZXgtZGlyZWN0aW9uOiBjb2x1bW47XG4gICAgICAgIGp1c3RpZnktY29udGVudDogY2VudGVyO1xuICAgICAgICBhbGlnbi1pdGVtczogY2VudGVyO1xuICAgICAgfVxuXG4gICAgICBmb290ZXIge1xuICAgICAgICBwYWRkaW5nLWJvdHRvbTogMTAwcHg7XG4gICAgICAgIHdpZHRoOiAxMDAlO1xuICAgICAgICBoZWlnaHQ6IDEwMHB4O1xuICAgICAgICAvL2JvcmRlci10b3A6IDFweCBzb2xpZCAjZWFlYWVhO1xuICAgICAgICBkaXNwbGF5OiBmbGV4O1xuICAgICAgICBqdXN0aWZ5LWNvbnRlbnQ6IGNlbnRlcjtcbiAgICAgICAgYWxpZ24taXRlbXM6IGNlbnRlcjtcbiAgICAgIH1cblxuICAgICAgZm9vdGVyIGltZyB7XG4gICAgICAgIG1hcmdpbi1sZWZ0OiAwLjVyZW07XG4gICAgICB9XG5cbiAgICAgIGZvb3RlciBhIHtcbiAgICAgICAgcGFkZGluZzogNXB4IDEwcHg7XG4gICAgICAgIGRpc3BsYXk6IGZsZXg7XG4gICAgICAgIGp1c3RpZnktY29udGVudDogY2VudGVyO1xuICAgICAgICBhbGlnbi1pdGVtczogY2VudGVyO1xuICAgICAgfVxuXG4gICAgICBhIHtcbiAgICAgICAgY29sb3I6IGluaGVyaXQ7XG4gICAgICAgIHRleHQtZGVjb3JhdGlvbjogbm9uZTtcbiAgICAgIH1cblxuICAgICAgLnRpdGxlIGEge1xuICAgICAgICBjb2xvcjogIzAwNzBmMztcbiAgICAgICAgdGV4dC1kZWNvcmF0aW9uOiBub25lO1xuICAgICAgfVxuXG4gICAgICAudGl0bGUgYTpob3ZlcixcbiAgICAgIC50aXRsZSBhOmZvY3VzLFxuICAgICAgLnRpdGxlIGE6YWN0aXZlIHtcbiAgICAgICAgdGV4dC1kZWNvcmF0aW9uOiB1bmRlcmxpbmU7XG4gICAgICB9XG5cbiAgICAgIC50aXRsZSB7XG4gICAgICAgIG1hcmdpbjogMTAwcHggMCAwO1xuICAgICAgICBsaW5lLWhlaWdodDogMS4xNTtcbiAgICAgICAgZm9udC1zaXplOiAzcmVtO1xuICAgICAgICAvLyB0ZXh0LXRyYW5zZm9ybTogdXBwZXJjYXNlO1xuICAgICAgICAvLyBoZWlnaHQ6IDE1MHB4O1xuICAgICAgfVxuXG4gICAgICAudGl0bGUsXG4gICAgICAuZGVzY3JpcHRpb24ge1xuICAgICAgICB0ZXh0LWFsaWduOiBjZW50ZXI7XG4gICAgICB9XG5cbiAgICAgIC5kZXNjcmlwdGlvbiB7XG4gICAgICAgIGxpbmUtaGVpZ2h0OiAxLjU7XG4gICAgICAgIGZvbnQtc2l6ZTogMC45cmVtO1xuICAgICAgfVxuXG4gICAgICBjb2RlIHtcbiAgICAgICAgYmFja2dyb3VuZDogI2ZhZmFmYTtcbiAgICAgICAgYm9yZGVyLXJhZGl1czogNXB4O1xuICAgICAgICBwYWRkaW5nOiAwLjc1cmVtO1xuICAgICAgICBmb250LXNpemU6IDEuMXJlbTtcbiAgICAgICAgZm9udC1mYW1pbHk6IE1lbmxvLCBNb25hY28sIEx1Y2lkYSBDb25zb2xlLCBMaWJlcmF0aW9uIE1vbm8sXG4gICAgICAgICAgRGVqYVZ1IFNhbnMgTW9ubywgQml0c3RyZWFtIFZlcmEgU2FucyBNb25vLCBDb3VyaWVyIE5ldywgbW9ub3NwYWNlO1xuICAgICAgfVxuXG4gICAgICAuZ3JpZCB7XG4gICAgICAgIC8vIGRpc3BsYXk6IGZsZXg7XG4gICAgICAgIC8vIGFsaWduLWl0ZW1zOiBjZW50ZXI7XG4gICAgICAgIC8vIGp1c3RpZnktY29udGVudDogY2VudGVyO1xuICAgICAgICAvLyBmbGV4LXdyYXA6IHdyYXA7XG4gICAgICAgIGRpc3BsYXk6IGdyaWQ7XG4gICAgICAgIGdyaWQtdGVtcGxhdGUtY29sdW1uczogMzgwcHggMTE0MHB4O1xuICAgICAgICBtYXgtd2lkdGg6IDEwMHZ3O1xuICAgICAgICBtYXJnaW4tdG9wOiAzcmVtO1xuICAgICAgfVxuXG4gICAgICAuY29sMiB7XG4gICAgICAgIG1hcmdpbi10b3A6IDc1cHg7XG4gICAgICB9XG5cbiAgICAgIC8vLmdyaWQgPiAqLFxuICAgICAgLmNhcmQge1xuICAgICAgICAvLyBtaW4td2lkdGg6IDMyMHB4O1xuICAgICAgICAvLyBtYXgtd2lkdGg6IDM4MHB4O1xuICAgICAgICBtYXJnaW46IDFyZW07XG4gICAgICAgIC8vIGZsZXgtYmFzaXM6IDI1JTtcbiAgICAgICAgcGFkZGluZzogMS41cmVtO1xuICAgICAgICAvL2FsaWduLXNlbGY6IGZsZXgtc3RhcnQ7XG4gICAgICAgIGJveC1zaXppbmc6IGJvcmRlci1ib3g7XG4gICAgICB9XG5cbiAgICAgIC5jYXJkIHByZSB7XG4gICAgICAgIGhlaWdodDogMjQwcHg7XG4gICAgICAgIG92ZXJmbG93LXk6IHNjcm9sbDtcbiAgICAgIH1cblxuICAgICAgLmNhcmQucHJpbW8ge1xuICAgICAgICAvL2FsaWduLXNlbGY6IGNlbnRlcjtcbiAgICAgICAgY29sb3I6ICM0NDQ7XG4gICAgICAgIHRleHQtdHJhbnNmb3JtOiBsb3dlcmNhc2U7XG4gICAgICAgIHBvc2l0aW9uOiByZWxhdGl2ZTtcbiAgICAgICAgbWFyZ2luLXJpZ2h0OiA3cmVtO1xuICAgICAgICBtYXJnaW4tdG9wOiAyLjVyZW07XG4gICAgICB9XG5cbiAgICAgIGgzIHtcbiAgICAgICAgZm9udC13ZWlnaHQ6IG5vcm1hbDtcbiAgICAgICAgbWFyZ2luLXRvcDogNjBweDtcbiAgICAgICAgdGV4dC1kZWNvcmF0aW9uOiB1bmRlcmxpbmU7XG4gICAgICB9XG5cbiAgICAgIGgyLCBoMyB7XG4gICAgICAgIGNvbG9yOiAjNDQ0O1xuICAgICAgfVxuICAgICAgXG4gICAgICBAbWVkaWEgKG1heC13aWR0aDogNjAwcHgpIHtcbiAgICAgICAgLmdyaWQge1xuICAgICAgICAgIHdpZHRoOiAxMDAlO1xuICAgICAgICAgIGZsZXgtZGlyZWN0aW9uOiBjb2x1bW47XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICBgfTwvc3R5bGU+XG5cbiAgICA8c3R5bGUganN4IGdsb2JhbD57YFxuICAgICAgaHRtbCxcbiAgICAgIGJvZHkge1xuICAgICAgICBiYWNrZ3JvdW5kLWNvbG9yOiAjZmZmYWYwO1xuICAgICAgICBwYWRkaW5nOiAwO1xuICAgICAgICBtYXJnaW46IDA7XG4gICAgICAgIGZvbnQtZmFtaWx5OiAtYXBwbGUtc3lzdGVtLCBCbGlua01hY1N5c3RlbUZvbnQsIFNlZ29lIFVJLCBSb2JvdG8sIE94eWdlbixcbiAgICAgICAgICBVYnVudHUsIENhbnRhcmVsbCwgRmlyYSBTYW5zLCBEcm9pZCBTYW5zLCBIZWx2ZXRpY2EgTmV1ZSwgc2Fucy1zZXJpZjtcbiAgICAgIH1cblxuICAgICAgKiB7XG4gICAgICAgIGJveC1zaXppbmc6IGJvcmRlci1ib3g7XG4gICAgICB9XG4gICAgYH08L3N0eWxlPlxuICA8L2Rpdj5cbil9O1xuXG5leHBvcnQgZGVmYXVsdCBEb2NzO1xuIl19 */\n/*@ sourceURL=/Users/aaronmoradi/Documents/projects/scintilla/www/pages/documentation.js */" ) ); }; /* harmony default export */ __webpack_exports__["default"] = Docs; /***/ } }); //# sourceMappingURL=documentation.js.dcbb49ba0c16df44c5cf.hot-update.js.map
var NAVTREEINDEX9 = { "dr__ir__macros__arm_8h.html#af2f990c139b06defdabcb9b38f102098":[6,0,2,12,1083], "dr__ir__macros__arm_8h.html#af2fedc6a30c1a5e4de278a65d13f7f31":[6,0,2,12,620], "dr__ir__macros__arm_8h.html#af37f53f561a656808de68bba7a9d86be":[6,0,2,12,402], "dr__ir__macros__arm_8h.html#af3f2f777e3b0f18f490b4e4dc73005aa":[6,0,2,12,15], "dr__ir__macros__arm_8h.html#af40a650760c2b8cebedd0c9a8ea774e6":[6,0,2,12,1174], "dr__ir__macros__arm_8h.html#af435342ad633ddb9050d1164159eaeaa":[6,0,2,12,573], "dr__ir__macros__arm_8h.html#af443df1542ca3ab140327a0b8c5b38a4":[6,0,2,12,66], "dr__ir__macros__arm_8h.html#af4527eb10daaa1db2680036952f2ccb3":[6,0,2,12,1250], "dr__ir__macros__arm_8h.html#af4725b9ac490188a4cdae530668b8493":[6,0,2,12,935], "dr__ir__macros__arm_8h.html#af47ec5dc6c61b6bf9488b5708fec0d36":[6,0,2,12,11], "dr__ir__macros__arm_8h.html#af49382581eac37abf537b5145761d920":[6,0,2,12,668], "dr__ir__macros__arm_8h.html#af4b424e776543f398259302c60bc615a":[6,0,2,12,1202], "dr__ir__macros__arm_8h.html#af4c400aee47def096b6c73750b1850aa":[6,0,2,12,1168], "dr__ir__macros__arm_8h.html#af4cbe121b78dfcf93cea1a48f10f937c":[6,0,2,12,1266], "dr__ir__macros__arm_8h.html#af4d7a915556f9971c1d1c0011dd842f4":[6,0,2,12,979], "dr__ir__macros__arm_8h.html#af522674d5550243944c7ebe88cbc2be6":[6,0,2,12,340], "dr__ir__macros__arm_8h.html#af58e229e298bf040ba203f7c6ec35a6c":[6,0,2,12,238], "dr__ir__macros__arm_8h.html#af5bc59c82b42ee7e94fa02b4d7cb7561":[6,0,2,12,204], "dr__ir__macros__arm_8h.html#af5c9f980f34b6e59debe9f77e2c058b3":[6,0,2,12,471], "dr__ir__macros__arm_8h.html#af633189c9e0ad668136423fffae55a3b":[6,0,2,12,1106], "dr__ir__macros__arm_8h.html#af6a4c3b4c646c54c9094d05dae617f05":[6,0,2,12,684], "dr__ir__macros__arm_8h.html#af6d2038a0d39f56de333289687410eb9":[6,0,2,12,271], "dr__ir__macros__arm_8h.html#af7503b3c0c6eddfd2233518609f4f58d":[6,0,2,12,1194], "dr__ir__macros__arm_8h.html#af7af47fd01c53aa4fee160ea2acfe2c6":[6,0,2,12,626], "dr__ir__macros__arm_8h.html#af7c82fc74e5a398bd56de5f80e34d322":[6,0,2,12,232], "dr__ir__macros__arm_8h.html#af8bd409302f7717722f53fd889c55ea6":[6,0,2,12,442], "dr__ir__macros__arm_8h.html#af9515723ba3eba36377ff229e363c668":[6,0,2,12,257], "dr__ir__macros__arm_8h.html#af981a3b528e0e5e6fc645550d521371e":[6,0,2,12,631], "dr__ir__macros__arm_8h.html#af986767a690c23559409757213f2da5a":[6,0,2,12,447], "dr__ir__macros__arm_8h.html#afa020a0178e3512b6667225f486f2762":[6,0,2,12,1077], "dr__ir__macros__arm_8h.html#afa31a543b480440999416103cb73bebb":[6,0,2,12,1226], "dr__ir__macros__arm_8h.html#afa42a64703c5e372e5eb7251278d8d28":[6,0,2,12,197], "dr__ir__macros__arm_8h.html#afa68b013b36d6c5759f723466a93fab4":[6,0,2,12,29], "dr__ir__macros__arm_8h.html#afaa413805ced703f06bbc63320f128da":[6,0,2,12,1203], "dr__ir__macros__arm_8h.html#afab259ccb4b13b02a57fba2459157586":[6,0,2,12,606], "dr__ir__macros__arm_8h.html#afabb884ccb9c32420b9f0e6cf7cd8d1a":[6,0,2,12,533], "dr__ir__macros__arm_8h.html#afadaab35aab59b1d19bdbb6f4fe1d1bc":[6,0,2,12,17], "dr__ir__macros__arm_8h.html#afadbdbfc01dc3ff8af1d6c389c1ecc23":[6,0,2,12,1133], "dr__ir__macros__arm_8h.html#afae4ef7621e7fc759dc07b2305472e77":[6,0,2,12,236], "dr__ir__macros__arm_8h.html#afb4eca6873c96a51796550fa0dd501c3":[6,0,2,12,962], "dr__ir__macros__arm_8h.html#afb500a8c578befacbed5efec5d1b6234":[6,0,2,12,309], "dr__ir__macros__arm_8h.html#afb5b9291f8385fed5b09d1d8e18e1381":[6,0,2,12,584], "dr__ir__macros__arm_8h.html#afb6effa64e1d9c38c98bd5127d25ed65":[6,0,2,12,689], "dr__ir__macros__arm_8h.html#afbc3f960d36a9428069447594feac129":[6,0,2,12,97], "dr__ir__macros__arm_8h.html#afbd5a5a9339d13dd0da41b2c94dcd089":[6,0,2,12,462], "dr__ir__macros__arm_8h.html#afbdaa3bc61842719d924bb8e4e38b903":[6,0,2,12,1068], "dr__ir__macros__arm_8h.html#afc0e6a78cb5c03bf4851a68144db9a7a":[6,0,2,12,1127], "dr__ir__macros__arm_8h.html#afc2285612cfedc045f0fe750fbdfdf4e":[6,0,2,12,852], "dr__ir__macros__arm_8h.html#afc247b4c54fb4c1e3c8642c43a2129da":[6,0,2,12,1195], "dr__ir__macros__arm_8h.html#afc249edea14fde2541e521720f6b0b69":[6,0,2,12,1061], "dr__ir__macros__arm_8h.html#afc2933b8fe54743a079675777f64e8e4":[6,0,2,12,604], "dr__ir__macros__arm_8h.html#afcd07d7ce31e76110334757857c24bdd":[6,0,2,12,851], "dr__ir__macros__arm_8h.html#afd0b9e75b95039b61ff60847b9d7830d":[6,0,2,12,52], "dr__ir__macros__arm_8h.html#afd2f26cc11a78c06bbff7fd24344db63":[6,0,2,12,1075], "dr__ir__macros__arm_8h.html#afd4791433151760069fd43c7b8253199":[6,0,2,12,195], "dr__ir__macros__arm_8h.html#afd6556880b120fa77a6eb1b07bcf026a":[6,0,2,12,783], "dr__ir__macros__arm_8h.html#afd7f272072daed497adf27fb9f9081ee":[6,0,2,12,92], "dr__ir__macros__arm_8h.html#afd8e6144a42e832c102194c136e70e42":[6,0,2,12,538], "dr__ir__macros__arm_8h.html#afdb2b7869f82ffa81c577b37ba859fc3":[6,0,2,12,427], "dr__ir__macros__arm_8h.html#afdbcfb317d599ecde76215392878da1c":[6,0,2,12,1269], "dr__ir__macros__arm_8h.html#afe0f8ce1fb7635425d1433863575c5ea":[6,0,2,12,744], "dr__ir__macros__arm_8h.html#afe77e7d89f4c0f552d766e534ed69096":[6,0,2,12,110], "dr__ir__macros__arm_8h.html#aff0c42555cf9aaad5b79b32816450d50":[6,0,2,12,505], "dr__ir__macros__arm_8h.html#aff0c5fcf1d4ad3f6819a3fe1be2c8a78":[6,0,2,12,16], "dr__ir__macros__arm_8h.html#aff1e7db3f996d976423e69586877a033":[6,0,2,12,1230], "dr__ir__macros__arm_8h.html#aff407a307034ed5cd5f87c250c06b0a9":[6,0,2,12,488], "dr__ir__macros__arm_8h.html#aff7569fb81bf32b5c1889e2291c71ea3":[6,0,2,12,175], "dr__ir__macros__x86_8h.html":[6,0,2,13], "dr__ir__macros__x86_8h.html#a000c9478814a496f21cc867674f1a0ba":[6,0,2,13,342], "dr__ir__macros__x86_8h.html#a002c5b88e79376a4ae34b3fc072a21aa":[6,0,2,13,54], "dr__ir__macros__x86_8h.html#a004752c51f1aa2a0b0efc31b0ee7731f":[6,0,2,13,1305], "dr__ir__macros__x86_8h.html#a00d86cee360f25035ffc66c859b9db13":[6,0,2,13,1107], "dr__ir__macros__x86_8h.html#a00ee1744750f3c0402629606d4b8851f":[6,0,2,13,151], "dr__ir__macros__x86_8h.html#a011fd748267aeda00fd67ce0cb03e94d":[6,0,2,13,19], "dr__ir__macros__x86_8h.html#a014fe25813603452eba218aba0a91f3e":[6,0,2,13,1351], "dr__ir__macros__x86_8h.html#a0150c3cb0c493a5d631fbf2d7b86581c":[6,0,2,13,380], "dr__ir__macros__x86_8h.html#a015f5d45396bb79c43e6b28937492268":[6,0,2,13,538], "dr__ir__macros__x86_8h.html#a0162af03a1f6fbe30826d5b8fe9a8305":[6,0,2,13,1171], "dr__ir__macros__x86_8h.html#a01837b2b5c0fd65ff75d8883ed4e2869":[6,0,2,13,281], "dr__ir__macros__x86_8h.html#a018610e274257c44db8e1d08b1fbaeda":[6,0,2,13,470], "dr__ir__macros__x86_8h.html#a018817a4bdb8aa4750368e33ce72a04b":[6,0,2,13,369], "dr__ir__macros__x86_8h.html#a0190cde04c012b3fdc8076dc9fd74a99":[6,0,2,13,785], "dr__ir__macros__x86_8h.html#a01a1a35813297174b51035069555e0a6":[6,0,2,13,1024], "dr__ir__macros__x86_8h.html#a01a77ef8d2387a1826b6aaef16cd62c2":[6,0,2,13,50], "dr__ir__macros__x86_8h.html#a025e0d406b3a80f476e8e06cefa8317c":[6,0,2,13,716], "dr__ir__macros__x86_8h.html#a02d9d1aac54fcd5902d1bfbd6e42e2aa":[6,0,2,13,167], "dr__ir__macros__x86_8h.html#a02e784cb0fb75d1516bc2a2de047af1a":[6,0,2,13,443], "dr__ir__macros__x86_8h.html#a0301a47e915f623a702bc17c6e40b459":[6,0,2,13,102], "dr__ir__macros__x86_8h.html#a034ca0b0b497e46b0f8ebdde7142bc22":[6,0,2,13,949], "dr__ir__macros__x86_8h.html#a035fa3f78b4c25960add7e5b687f8a5c":[6,0,2,13,226], "dr__ir__macros__x86_8h.html#a0383a7bf9b5a260571924e52fa8e7f24":[6,0,2,13,955], "dr__ir__macros__x86_8h.html#a03aecff55bdc891a1295c9bf9055e727":[6,0,2,13,399], "dr__ir__macros__x86_8h.html#a03e3970be1c545de425456042f2173c6":[6,0,2,13,666], "dr__ir__macros__x86_8h.html#a040846c6fd7e3a0907de9b00af8ef0f2":[6,0,2,13,501], "dr__ir__macros__x86_8h.html#a0429abf5c23d4507ab6484cb2ef8103c":[6,0,2,13,806], "dr__ir__macros__x86_8h.html#a0438ec4ceb1fd27063b5824383092bf6":[6,0,2,13,113], "dr__ir__macros__x86_8h.html#a045a5a1d87f9bec42aed4315f2c40480":[6,0,2,13,1009], "dr__ir__macros__x86_8h.html#a0473cf1703352716e73009b076459903":[6,0,2,13,1165], "dr__ir__macros__x86_8h.html#a047ec9305a8f99ab60add248c7583fd9":[6,0,2,13,655], "dr__ir__macros__x86_8h.html#a04a3df58606e93131c183cca7456d550":[6,0,2,13,1036], "dr__ir__macros__x86_8h.html#a04a98ae4a6512579deca8644d2a1873e":[6,0,2,13,335], "dr__ir__macros__x86_8h.html#a0503ce31b74c64e33671c71c6633be87":[6,0,2,13,30], "dr__ir__macros__x86_8h.html#a053c0202c5a4229fbc5575183afb02d7":[6,0,2,13,1677], "dr__ir__macros__x86_8h.html#a053e4873ae6044a90a06c144da2ea0b7":[6,0,2,13,1198], "dr__ir__macros__x86_8h.html#a0582d6d50b3d64cb4dcb071c184d6657":[6,0,2,13,1319], "dr__ir__macros__x86_8h.html#a058a31dcc7e5b2e4865df981cb71066c":[6,0,2,13,52], "dr__ir__macros__x86_8h.html#a059d3617b3eb90166e6227435e9d4d2b":[6,0,2,13,1376], "dr__ir__macros__x86_8h.html#a05a6bff6174f7a5fd2ab5f76883c00be":[6,0,2,13,924], "dr__ir__macros__x86_8h.html#a05d6f5b452e22207e2230df9465bf5c6":[6,0,2,13,235], "dr__ir__macros__x86_8h.html#a05db87e95222698ad5743ea951cbe587":[6,0,2,13,217], "dr__ir__macros__x86_8h.html#a05e4f82abe600229d76db0c696118e29":[6,0,2,13,1252], "dr__ir__macros__x86_8h.html#a05fbb04d50eece9120a97b2b9ad47495":[6,0,2,13,118], "dr__ir__macros__x86_8h.html#a061a8990fc22313d5f9e5e54220e04be":[6,0,2,13,1068], "dr__ir__macros__x86_8h.html#a0659d8857f6806c114a3b084b7dbfea6":[6,0,2,13,253], "dr__ir__macros__x86_8h.html#a06942cd3a5d5af2104edc590731fdda3":[6,0,2,13,958], "dr__ir__macros__x86_8h.html#a06c2843d206e60f285ef849fe2a8f165":[6,0,2,13,1539], "dr__ir__macros__x86_8h.html#a06df02b30637759bade427dd2cb3f209":[6,0,2,13,635], "dr__ir__macros__x86_8h.html#a0704890969d6b37a18b792da0a93ec1c":[6,0,2,13,82], "dr__ir__macros__x86_8h.html#a076229b445aa7f5665467bddc02e98e9":[6,0,2,13,256], "dr__ir__macros__x86_8h.html#a07b69c1e2569673352196169002e7e3d":[6,0,2,13,1147], "dr__ir__macros__x86_8h.html#a07eed6da7e21c329f2985f857d13ac7d":[6,0,2,13,697], "dr__ir__macros__x86_8h.html#a08195cd5496c15413849186f14db934a":[6,0,2,13,1484], "dr__ir__macros__x86_8h.html#a0881faa28eee938bc96238f8447a766b":[6,0,2,13,1616], "dr__ir__macros__x86_8h.html#a08ad4fe5b775ff78084234164b5c77bb":[6,0,2,13,1408], "dr__ir__macros__x86_8h.html#a08c6a11054fa729316bddba923a01a75":[6,0,2,13,149], "dr__ir__macros__x86_8h.html#a08e07e3736d226136fee1fe0093fa283":[6,0,2,13,722], "dr__ir__macros__x86_8h.html#a096517fa9b2cb2b4191c5e8044fcbd87":[6,0,2,13,921], "dr__ir__macros__x86_8h.html#a09c2b2ee63b25ca2a15f9e65b2f60677":[6,0,2,13,146], "dr__ir__macros__x86_8h.html#a09fda2c4f4059321d0efab214e93a0f9":[6,0,2,13,99], "dr__ir__macros__x86_8h.html#a0a2fe304414652d50f94cfbf36b91262":[6,0,2,13,747], "dr__ir__macros__x86_8h.html#a0a4570b8d3fff42da750b7ce280ebe6f":[6,0,2,13,211], "dr__ir__macros__x86_8h.html#a0a4cc2964ceba16c65d5b950f91ac2e7":[6,0,2,13,1203], "dr__ir__macros__x86_8h.html#a0abf739b255c3fbf787b6af87b8b26dc":[6,0,2,13,234], "dr__ir__macros__x86_8h.html#a0ae1be18e6f0c52f2d573906115ebfbc":[6,0,2,13,240], "dr__ir__macros__x86_8h.html#a0aea218d3dc56ada8c5cc45cfb5be3d2":[6,0,2,13,276], "dr__ir__macros__x86_8h.html#a0aeec737e82a3931c13ca5a8c03152a9":[6,0,2,13,1169], "dr__ir__macros__x86_8h.html#a0b2f157460f1201c2df4409a2d31560f":[6,0,2,13,1665], "dr__ir__macros__x86_8h.html#a0b5e50a81cc0ba325e2bd7845fd10f2a":[6,0,2,13,1361], "dr__ir__macros__x86_8h.html#a0b62b3751985b9fda761ea64763c8052":[6,0,2,13,1199], "dr__ir__macros__x86_8h.html#a0b9bcbcae5b489d1f9ceeaa18b72afa1":[6,0,2,13,1303], "dr__ir__macros__x86_8h.html#a0ba4680b6801ec3dbfb09b33fe93e10e":[6,0,2,13,1330], "dr__ir__macros__x86_8h.html#a0bb441f3f59b432d558b1535a970ac8f":[6,0,2,13,932], "dr__ir__macros__x86_8h.html#a0be342c2a71ecf4925631e34bc3339a1":[6,0,2,13,1505], "dr__ir__macros__x86_8h.html#a0c71d6144d07a7b1e79e95b2f6de67a4":[6,0,2,13,615], "dr__ir__macros__x86_8h.html#a0c7b8fcef5c9887765f761c430a63a67":[6,0,2,13,593], "dr__ir__macros__x86_8h.html#a0cd4320c28d0182bf8978260401cd55f":[6,0,2,13,1374], "dr__ir__macros__x86_8h.html#a0cda7689cd077cc10bd2ffded339ff51":[6,0,2,13,1650], "dr__ir__macros__x86_8h.html#a0ce5125df00cba38f8a75e0b5d09e920":[6,0,2,13,1129], "dr__ir__macros__x86_8h.html#a0cff2e89bf0f97bc8150373ba3af67fe":[6,0,2,13,911], "dr__ir__macros__x86_8h.html#a0d3002bd9ddcfcfdb05a4b2b33fcdd53":[6,0,2,13,1018], "dr__ir__macros__x86_8h.html#a0d768b58c2f7dcbd125c5abb76d767c6":[6,0,2,13,78], "dr__ir__macros__x86_8h.html#a0dd633c129c2c1080011cd843dffc368":[6,0,2,13,1210], "dr__ir__macros__x86_8h.html#a0e1dcb7a4b0153656ce84cf145af5256":[6,0,2,13,508], "dr__ir__macros__x86_8h.html#a0e3b367ff9d59a7629f9769985fea9ec":[6,0,2,13,1641], "dr__ir__macros__x86_8h.html#a0e47daf85eccef96db8d2358635286e6":[6,0,2,13,1240], "dr__ir__macros__x86_8h.html#a0e5264106ea144f006cb91bfae71e552":[6,0,2,13,602], "dr__ir__macros__x86_8h.html#a0e5b35ad8f052066c9aeafbe42bdb28e":[6,0,2,13,254], "dr__ir__macros__x86_8h.html#a0e90ffd7964b70bc0afe90fef4329645":[6,0,2,13,684], "dr__ir__macros__x86_8h.html#a0eb25a500d2029ab1c51851e9bdcaad3":[6,0,2,13,1021], "dr__ir__macros__x86_8h.html#a0efc4a3954585a3d87d952707ec66e2e":[6,0,2,13,1272], "dr__ir__macros__x86_8h.html#a0f45e9eb36ab16388e37acdba553f593":[6,0,2,13,14], "dr__ir__macros__x86_8h.html#a0fb4d48bb325a98cef60e7f5bcc3e991":[6,0,2,13,1029], "dr__ir__macros__x86_8h.html#a0fcf58026ae11f4d83a7f0c23902b5c6":[6,0,2,13,173], "dr__ir__macros__x86_8h.html#a0fdf04c44b74bc7d9f0f38f8d026adde":[6,0,2,13,388], "dr__ir__macros__x86_8h.html#a0ff720c82eb9a47a6e90b11427210d4b":[6,0,2,13,935], "dr__ir__macros__x86_8h.html#a102657e9b92771b1dfd0da30e90fdecc":[6,0,2,13,1568], "dr__ir__macros__x86_8h.html#a1042357fc05f2d0560ec5b4b2de9e276":[6,0,2,13,1207], "dr__ir__macros__x86_8h.html#a10486eb90414712cf9ec9a4c229eecd7":[6,0,2,13,1039], "dr__ir__macros__x86_8h.html#a1048723133e0656d079c205636a52cec":[6,0,2,13,763], "dr__ir__macros__x86_8h.html#a105d623c17126f29044e951b9ed82688":[6,0,2,13,1573], "dr__ir__macros__x86_8h.html#a107dbb36db3b2b0fac5bfbbd5ff09d90":[6,0,2,13,1620], "dr__ir__macros__x86_8h.html#a107ffe742336b367d1915249dad7dd7e":[6,0,2,13,1056], "dr__ir__macros__x86_8h.html#a10851b4445b444474c9708db59ac734d":[6,0,2,13,389], "dr__ir__macros__x86_8h.html#a108d616b566abc13db3af452ab5f69e0":[6,0,2,13,576], "dr__ir__macros__x86_8h.html#a10b5f3f9e36af3db303dad5c01b64c42":[6,0,2,13,1635], "dr__ir__macros__x86_8h.html#a10cadf04c4c2a02f0447a7ea0ea552c4":[6,0,2,13,625], "dr__ir__macros__x86_8h.html#a111e0e0478fe501e881640d7b357ac61":[6,0,2,13,612], "dr__ir__macros__x86_8h.html#a115e889a80a6c98652fdc6bd1b056cf0":[6,0,2,13,1606], "dr__ir__macros__x86_8h.html#a1175a810dceb747176b16d7858c50304":[6,0,2,13,530], "dr__ir__macros__x86_8h.html#a11c8736acbaf2af9a8a1505e8ad4ca89":[6,0,2,13,381], "dr__ir__macros__x86_8h.html#a1209a83d01bdf6f57b042c2ebd9b5d12":[6,0,2,13,434], "dr__ir__macros__x86_8h.html#a12d5be34426178bace1b6bc660c6c6e5":[6,0,2,13,1574], "dr__ir__macros__x86_8h.html#a136e1aa4cf74c444b34241b229d09f7b":[6,0,2,13,412], "dr__ir__macros__x86_8h.html#a13b990f45b6c36c69fd7322b3f7b6f78":[6,0,2,13,728], "dr__ir__macros__x86_8h.html#a13de97488b0a306c0b605d747a9d9953":[6,0,2,13,604], "dr__ir__macros__x86_8h.html#a142feb41da61daa0c92a0b3f008cf019":[6,0,2,13,1337], "dr__ir__macros__x86_8h.html#a14c4e238bd4c71849d0e2227571f4375":[6,0,2,13,1546], "dr__ir__macros__x86_8h.html#a14ec2fb6a2536871260fec539d5a2e44":[6,0,2,13,490], "dr__ir__macros__x86_8h.html#a151aea3cbd6c16c9b8b6c42d3d5f5184":[6,0,2,13,1315], "dr__ir__macros__x86_8h.html#a15a89c5c7ea613a2c8df5af6220ac1e7":[6,0,2,13,1163], "dr__ir__macros__x86_8h.html#a15bccf52872cebb418b0556dc3e17d10":[6,0,2,13,244], "dr__ir__macros__x86_8h.html#a160a3bcd73a6d286b1c682c5738b4a10":[6,0,2,13,1316], "dr__ir__macros__x86_8h.html#a16185edbc30d570540658eb1cbdbf7d9":[6,0,2,13,859], "dr__ir__macros__x86_8h.html#a1636146221b80244756d4c4948936901":[6,0,2,13,481], "dr__ir__macros__x86_8h.html#a168b9c9f993b4b05ca9225dbe500981d":[6,0,2,13,674], "dr__ir__macros__x86_8h.html#a169211d8184bf89ae0eaf0f416a70ca8":[6,0,2,13,174], "dr__ir__macros__x86_8h.html#a16a016d446050070124394c4e5b0b641":[6,0,2,13,433], "dr__ir__macros__x86_8h.html#a16b39a22bef2350496b7a6d55826c14c":[6,0,2,13,1395], "dr__ir__macros__x86_8h.html#a16bfa8c28ce2dae36ab08c0f0d3129bb":[6,0,2,13,409], "dr__ir__macros__x86_8h.html#a16ca95c9dbee092138b170526a7b9707":[6,0,2,13,978], "dr__ir__macros__x86_8h.html#a16ce472161e5b08a50562c9d93eea081":[6,0,2,13,808], "dr__ir__macros__x86_8h.html#a17350640abe7df0602909e7f5fdbeaac":[6,0,2,13,128], "dr__ir__macros__x86_8h.html#a178164976fcd4cb1203e274d5d541b81":[6,0,2,13,631], "dr__ir__macros__x86_8h.html#a1789ccffb4cf20417d501973ddf3b1f0":[6,0,2,13,1460], "dr__ir__macros__x86_8h.html#a17b1e5440a3bf81da566fc5ce82bde22":[6,0,2,13,1133], "dr__ir__macros__x86_8h.html#a17bb2e0e249c2a5cfe648ec52322143f":[6,0,2,13,521], "dr__ir__macros__x86_8h.html#a17c823ed8b62741a1ca8f35761dc8be5":[6,0,2,13,1627], "dr__ir__macros__x86_8h.html#a17e625669bba6fa0c5e837ff2d61138d":[6,0,2,13,1227], "dr__ir__macros__x86_8h.html#a17f58737b16521c4cce4cfbde1935db9":[6,0,2,13,893], "dr__ir__macros__x86_8h.html#a17f91d01d96e1c51f0bc1ff7dc6c1e51":[6,0,2,13,849], "dr__ir__macros__x86_8h.html#a18012fef03b2d6c41f88ac81be009e1b":[6,0,2,13,1633], "dr__ir__macros__x86_8h.html#a1801beac0c6705083914b82fffb44136":[6,0,2,13,977], "dr__ir__macros__x86_8h.html#a182a0698f83c6341e867543bd658f0ad":[6,0,2,13,1086], "dr__ir__macros__x86_8h.html#a18347bb1ede3b61ec131424b507c48c8":[6,0,2,13,297], "dr__ir__macros__x86_8h.html#a1896414295857794c8ab7e2804141e81":[6,0,2,13,1455], "dr__ir__macros__x86_8h.html#a18a44561f7cf8407facbde33b1395c2a":[6,0,2,13,473], "dr__ir__macros__x86_8h.html#a18e9d517975ad45470d71aecccde04db":[6,0,2,13,1123], "dr__ir__macros__x86_8h.html#a1900246256c85c93b3717d7b5beff00c":[6,0,2,13,672], "dr__ir__macros__x86_8h.html#a1913d20ace4bfb41c8e46ae9922c0c20":[6,0,2,13,471], "dr__ir__macros__x86_8h.html#a193d2b0123b3bdf0b9200f34a54d8002":[6,0,2,13,1657], "dr__ir__macros__x86_8h.html#a1942d66a846bba9fd5705368b0f55735":[6,0,2,13,464], "dr__ir__macros__x86_8h.html#a19b14245f22c704dfb590636169fc7f0":[6,0,2,13,1275], "dr__ir__macros__x86_8h.html#a19c3776c66e524a961d3d9e53ea4940f":[6,0,2,13,1116], "dr__ir__macros__x86_8h.html#a19c45db2a07018bd1bc4a3e91a74e929":[6,0,2,13,522], "dr__ir__macros__x86_8h.html#a19e7ba515f3485bc1a13e9583392c84b":[6,0,2,13,169], "dr__ir__macros__x86_8h.html#a1a086e0cd34cfad26d5252c8c3d822e9":[6,0,2,13,1250], "dr__ir__macros__x86_8h.html#a1a2177ee900ae0560da5b5020d5b6e4e":[6,0,2,13,79], "dr__ir__macros__x86_8h.html#a1a59baa1000104658c0236d293e7aefc":[6,0,2,13,1583], "dr__ir__macros__x86_8h.html#a1a72f4e5fdcc7a74cc413990a3784ca5":[6,0,2,13,1429], "dr__ir__macros__x86_8h.html#a1ad3b091e159d83226107c7fb994ecd3":[6,0,2,13,1112], "dr__ir__macros__x86_8h.html#a1af99632ef1691a680c9100cd7a3a316":[6,0,2,13,168], "dr__ir__macros__x86_8h.html#a1b6530f04e3b6f2ec0e819bbe391e590":[6,0,2,13,1148], "dr__ir__macros__x86_8h.html#a1b9d3ef5868517b3f038452864b5fa4d":[6,0,2,13,507], "dr__ir__macros__x86_8h.html#a1ba469d99f1582c9eab5a932a0744554":[6,0,2,13,1527], "dr__ir__macros__x86_8h.html#a1ba6a02309dbb9dbfd963d822f0b7c5c":[6,0,2,13,38], "dr__ir__macros__x86_8h.html#a1ba7649837a89efa3c3c3dcd9dc8d120":[6,0,2,13,423], "dr__ir__macros__x86_8h.html#a1bd0e10ade092123197f1b7e3182173a":[6,0,2,13,824], "dr__ir__macros__x86_8h.html#a1bdec8756df42fb84f8760b32fcb0dcc":[6,0,2,13,1459], "dr__ir__macros__x86_8h.html#a1bf939a69cd1dc485c12e7d2e5f64de8":[6,0,2,13,148], "dr__ir__macros__x86_8h.html#a1c12709dc36a93b5df09ed35c9230311":[6,0,2,13,122], "dr__ir__macros__x86_8h.html#a1c41a9573902b89fc0e9c2c8842fbb01":[6,0,2,13,1278], "dr__ir__macros__x86_8h.html#a1cb24e7cfef85a4e75b0de8e92789d30":[6,0,2,13,1191], "dr__ir__macros__x86_8h.html#a1cf610c0aec917346e35d2d19f004bef":[6,0,2,13,306], "dr__ir__macros__x86_8h.html#a1cfa0a7665d05f6b18037c5e4a4a44c9":[6,0,2,13,1599], "dr__ir__macros__x86_8h.html#a1d326b769b19ce3c90784c2dee0ce8ee":[6,0,2,13,1575], "dr__ir__macros__x86_8h.html#a1d3de2845e719fe5a3f0f890efee667a":[6,0,2,13,750], "dr__ir__macros__x86_8h.html#a1d507402cbb0daf200938281edff989a":[6,0,2,13,1549], "dr__ir__macros__x86_8h.html#a1d6d3212003171e453872e39cd3abdbd":[6,0,2,13,447], "dr__ir__macros__x86_8h.html#a1dd1c34110cb0bf5716c592972e8579d":[6,0,2,13,1167], "dr__ir__macros__x86_8h.html#a1dd879c62dfbb18e435667dc57062068":[6,0,2,13,1424] };
'use strict'; import Chart from 'chart.js'; import Hammer from 'hammerjs'; var helpers = Chart.helpers; // Take the zoom namespace of Chart var zoomNS = Chart.Zoom = Chart.Zoom || {}; // Where we store functions to handle different scale types var zoomFunctions = zoomNS.zoomFunctions = zoomNS.zoomFunctions || {}; var panFunctions = zoomNS.panFunctions = zoomNS.panFunctions || {}; Chart.Zoom.defaults = Chart.defaults.global.plugins.zoom = { pan: { enabled: false, mode: 'xy', speed: 20, threshold: 10 }, zoom: { enabled: false, mode: 'xy', sensitivity: 3, speed: 0.1 } }; function resolveOptions(chart, options) { var deprecatedOptions = {}; if (typeof chart.options.pan !== 'undefined') { deprecatedOptions.pan = chart.options.pan; } if (typeof chart.options.pan !== 'undefined') { deprecatedOptions.zoom = chart.options.zoom; } chart.$zoom._options = helpers.merge({}, [options, deprecatedOptions]); } function storeOriginalOptions(chart) { var originalOptions = chart.$zoom._originalOptions; helpers.each(chart.scales, function(scale) { if (!originalOptions[scale.id]) { originalOptions[scale.id] = helpers.clone(scale.options); } }); helpers.each(originalOptions, function(opt, key) { if (!chart.scales[key]) { delete originalOptions[key]; } }); } function directionEnabled(mode, dir) { if (mode === undefined) { return true; } else if (typeof mode === 'string') { return mode.indexOf(dir) !== -1; } return false; } function rangeMaxLimiter(zoomPanOptions, newMax) { if (zoomPanOptions.scaleAxes && zoomPanOptions.rangeMax && !helpers.isNullOrUndef(zoomPanOptions.rangeMax[zoomPanOptions.scaleAxes])) { var rangeMax = zoomPanOptions.rangeMax[zoomPanOptions.scaleAxes]; if (newMax > rangeMax) { newMax = rangeMax; } } return newMax; } function rangeMinLimiter(zoomPanOptions, newMin) { if (zoomPanOptions.scaleAxes && zoomPanOptions.rangeMin && !helpers.isNullOrUndef(zoomPanOptions.rangeMin[zoomPanOptions.scaleAxes])) { var rangeMin = zoomPanOptions.rangeMin[zoomPanOptions.scaleAxes]; if (newMin < rangeMin) { newMin = rangeMin; } } return newMin; } function zoomCategoryScale(scale, zoom, center, zoomOptions) { var labels = scale.chart.data.labels; var minIndex = scale.minIndex; var lastLabelIndex = labels.length - 1; var maxIndex = scale.maxIndex; var sensitivity = zoomOptions.sensitivity; var chartCenter = scale.isHorizontal() ? scale.left + (scale.width / 2) : scale.top + (scale.height / 2); var centerPointer = scale.isHorizontal() ? center.x : center.y; zoomNS.zoomCumulativeDelta = zoom > 1 ? zoomNS.zoomCumulativeDelta + 1 : zoomNS.zoomCumulativeDelta - 1; if (Math.abs(zoomNS.zoomCumulativeDelta) > sensitivity) { if (zoomNS.zoomCumulativeDelta < 0) { if (centerPointer >= chartCenter) { if (minIndex <= 0) { maxIndex = Math.min(lastLabelIndex, maxIndex + 1); } else { minIndex = Math.max(0, minIndex - 1); } } else if (centerPointer < chartCenter) { if (maxIndex >= lastLabelIndex) { minIndex = Math.max(0, minIndex - 1); } else { maxIndex = Math.min(lastLabelIndex, maxIndex + 1); } } zoomNS.zoomCumulativeDelta = 0; } else if (zoomNS.zoomCumulativeDelta > 0) { if (centerPointer >= chartCenter) { minIndex = minIndex < maxIndex ? minIndex = Math.min(maxIndex, minIndex + 1) : minIndex; } else if (centerPointer < chartCenter) { maxIndex = maxIndex > minIndex ? maxIndex = Math.max(minIndex, maxIndex - 1) : maxIndex; } zoomNS.zoomCumulativeDelta = 0; } scale.options.ticks.min = rangeMinLimiter(zoomOptions, labels[minIndex]); scale.options.ticks.max = rangeMaxLimiter(zoomOptions, labels[maxIndex]); } } function zoomNumericalScale(scale, zoom, center, zoomOptions) { var range = scale.max - scale.min; var newDiff = range * (zoom - 1); var centerPoint = scale.isHorizontal() ? center.x : center.y; var minPercent = (scale.getValueForPixel(centerPoint) - scale.min) / range; var maxPercent = 1 - minPercent; var minDelta = newDiff * minPercent; var maxDelta = newDiff * maxPercent; scale.options.ticks.min = rangeMinLimiter(zoomOptions, scale.min + minDelta); scale.options.ticks.max = rangeMaxLimiter(zoomOptions, scale.max - maxDelta); } function zoomTimeScale(scale, zoom, center, zoomOptions) { zoomNumericalScale(scale, zoom, center, zoomOptions); scale.options.time.min = scale.options.ticks.min; scale.options.time.max = scale.options.ticks.max; } function zoomScale(scale, zoom, center, zoomOptions) { var fn = zoomFunctions[scale.type]; if (fn) { fn(scale, zoom, center, zoomOptions); } } /** * @param chart The chart instance * @param {number} percentZoomX The zoom percentage in the x direction * @param {number} percentZoomY The zoom percentage in the y direction * @param {{x: number, y: number}} focalPoint The x and y coordinates of zoom focal point. The point which doesn't change while zooming. E.g. the location of the mouse cursor when "drag: false" * @param {string} whichAxes `xy`, 'x', or 'y' */ function doZoom(chart, percentZoomX, percentZoomY, focalPoint, whichAxes) { var ca = chart.chartArea; if (!focalPoint) { focalPoint = { x: (ca.left + ca.right) / 2, y: (ca.top + ca.bottom) / 2, }; } var zoomOptions = chart.$zoom._options.zoom; if (zoomOptions.enabled) { storeOriginalOptions(chart); // Do the zoom here var zoomMode = zoomOptions.mode; // Which axe should be modified when figers were used. var _whichAxes; if (zoomMode === 'xy' && whichAxes !== undefined) { // based on fingers positions _whichAxes = whichAxes; } else { // no effect _whichAxes = 'xy'; } helpers.each(chart.scales, function(scale) { if (scale.isHorizontal() && directionEnabled(zoomMode, 'x') && directionEnabled(_whichAxes, 'x')) { zoomOptions.scaleAxes = 'x'; zoomScale(scale, percentZoomX, focalPoint, zoomOptions); } else if (!scale.isHorizontal() && directionEnabled(zoomMode, 'y') && directionEnabled(_whichAxes, 'y')) { // Do Y zoom zoomOptions.scaleAxes = 'y'; zoomScale(scale, percentZoomY, focalPoint, zoomOptions); } }); chart.update(0); if (typeof zoomOptions.onZoom === 'function') { zoomOptions.onZoom({chart: chart}); } } } function panCategoryScale(scale, delta, panOptions) { var labels = scale.chart.data.labels; var lastLabelIndex = labels.length - 1; var offsetAmt = Math.max(scale.ticks.length, 1); var panSpeed = panOptions.speed; var minIndex = scale.minIndex; var step = Math.round(scale.width / (offsetAmt * panSpeed)); var maxIndex; zoomNS.panCumulativeDelta += delta; minIndex = zoomNS.panCumulativeDelta > step ? Math.max(0, minIndex - 1) : zoomNS.panCumulativeDelta < -step ? Math.min(lastLabelIndex - offsetAmt + 1, minIndex + 1) : minIndex; zoomNS.panCumulativeDelta = minIndex !== scale.minIndex ? 0 : zoomNS.panCumulativeDelta; maxIndex = Math.min(lastLabelIndex, minIndex + offsetAmt - 1); scale.options.ticks.min = rangeMinLimiter(panOptions, labels[minIndex]); scale.options.ticks.max = rangeMaxLimiter(panOptions, labels[maxIndex]); } function panNumericalScale(scale, delta, panOptions) { var tickOpts = scale.options.ticks; var prevStart = scale.min; var prevEnd = scale.max; var newMin = scale.getValueForPixel(scale.getPixelForValue(prevStart) - delta); var newMax = scale.getValueForPixel(scale.getPixelForValue(prevEnd) - delta); var rangeMin = newMin; var rangeMax = newMax; var diff; if (panOptions.scaleAxes && panOptions.rangeMin && !helpers.isNullOrUndef(panOptions.rangeMin[panOptions.scaleAxes])) { rangeMin = panOptions.rangeMin[panOptions.scaleAxes]; } if (panOptions.scaleAxes && panOptions.rangeMax && !helpers.isNullOrUndef(panOptions.rangeMax[panOptions.scaleAxes])) { rangeMax = panOptions.rangeMax[panOptions.scaleAxes]; } if (newMin >= rangeMin && newMax <= rangeMax) { tickOpts.min = newMin; tickOpts.max = newMax; } else if (newMin < rangeMin) { diff = prevStart - rangeMin; tickOpts.min = rangeMin; tickOpts.max = prevEnd - diff; } else if (newMax > rangeMax) { diff = rangeMax - prevEnd; tickOpts.max = rangeMax; tickOpts.min = prevStart + diff; } } function panTimeScale(scale, delta, panOptions) { panNumericalScale(scale, delta, panOptions); var options = scale.options; options.time.min = options.ticks.min; options.time.max = options.ticks.max; } function panScale(scale, delta, panOptions) { var fn = panFunctions[scale.type]; if (fn) { fn(scale, delta, panOptions); } } function doPan(chartInstance, deltaX, deltaY) { storeOriginalOptions(chartInstance); var panOptions = chartInstance.$zoom._options.pan; if (panOptions.enabled) { var panMode = panOptions.mode; helpers.each(chartInstance.scales, function(scale) { if (scale.isHorizontal() && directionEnabled(panMode, 'x') && deltaX !== 0) { panOptions.scaleAxes = 'x'; panScale(scale, deltaX, panOptions); } else if (!scale.isHorizontal() && directionEnabled(panMode, 'y') && deltaY !== 0) { panOptions.scaleAxes = 'y'; panScale(scale, deltaY, panOptions); } }); chartInstance.update(0); if (typeof panOptions.onPan === 'function') { panOptions.onPan({chart: chartInstance}); } } } function getXAxis(chartInstance) { var scales = chartInstance.scales; var scaleIds = Object.keys(scales); for (var i = 0; i < scaleIds.length; i++) { var scale = scales[scaleIds[i]]; if (scale.isHorizontal()) { return scale; } } } function getYAxis(chartInstance) { var scales = chartInstance.scales; var scaleIds = Object.keys(scales); for (var i = 0; i < scaleIds.length; i++) { var scale = scales[scaleIds[i]]; if (!scale.isHorizontal()) { return scale; } } } // Store these for later zoomNS.zoomFunctions.category = zoomCategoryScale; zoomNS.zoomFunctions.time = zoomTimeScale; zoomNS.zoomFunctions.linear = zoomNumericalScale; zoomNS.zoomFunctions.logarithmic = zoomNumericalScale; zoomNS.panFunctions.category = panCategoryScale; zoomNS.panFunctions.time = panTimeScale; zoomNS.panFunctions.linear = panNumericalScale; zoomNS.panFunctions.logarithmic = panNumericalScale; // Globals for category pan and zoom zoomNS.panCumulativeDelta = 0; zoomNS.zoomCumulativeDelta = 0; // Chartjs Zoom Plugin var zoomPlugin = { id: 'zoom', afterInit: function(chartInstance) { chartInstance.resetZoom = function() { storeOriginalOptions(chartInstance); var originalOptions = chartInstance.$zoom._originalOptions; helpers.each(chartInstance.scales, function(scale) { var timeOptions = scale.options.time; var tickOptions = scale.options.ticks; if (originalOptions[scale.id]) { if (timeOptions) { timeOptions.min = originalOptions[scale.id].time.min; timeOptions.max = originalOptions[scale.id].time.max; } if (tickOptions) { tickOptions.min = originalOptions[scale.id].ticks.min; tickOptions.max = originalOptions[scale.id].ticks.max; } } else { if (timeOptions) { delete timeOptions.min; delete timeOptions.max; } if (tickOptions) { delete tickOptions.min; delete tickOptions.max; } } }); chartInstance.update(); }; }, beforeUpdate: function(chart, options) { resolveOptions(chart, options); }, beforeInit: function(chartInstance, pluginOptions) { chartInstance.$zoom = { _originalOptions: {} }; resolveOptions(chartInstance, pluginOptions); var node = chartInstance.$zoom._node = chartInstance.chart.ctx.canvas; var options = chartInstance.$zoom._options; var panThreshold = options.pan && options.pan.threshold; chartInstance.$zoom._mouseDownHandler = function(event) { if (chartInstance.$zoom._options.zoom && chartInstance.$zoom._options.zoom.drag) { node.addEventListener('mousemove', chartInstance.$zoom._mouseMoveHandler); chartInstance.$zoom._dragZoomStart = event; } }; node.addEventListener('mousedown', chartInstance.$zoom._mouseDownHandler); chartInstance.$zoom._mouseMoveHandler = function(event) { if (chartInstance.$zoom._options.zoom && chartInstance.$zoom._options.zoom.drag && chartInstance.$zoom._dragZoomStart) { chartInstance.$zoom._dragZoomEnd = event; chartInstance.update(0); } }; chartInstance.$zoom._mouseUpHandler = function(event) { if (!(chartInstance.$zoom._options.zoom && chartInstance.$zoom._options.zoom.drag) || !chartInstance.$zoom._dragZoomStart) { return; } node.removeEventListener('mousemove', chartInstance.$zoom._mouseMoveHandler); var chartArea = chartInstance.chartArea; var xAxis = getXAxis(chartInstance); var yAxis = getYAxis(chartInstance); var beginPoint = chartInstance.$zoom._dragZoomStart; var startX = xAxis.left; var endX = xAxis.right; var startY = yAxis.top; var endY = yAxis.bottom; if (directionEnabled(chartInstance.$zoom._options.zoom.mode, 'x')) { var offsetX = beginPoint.target.getBoundingClientRect().left; startX = Math.min(beginPoint.clientX, event.clientX) - offsetX; endX = Math.max(beginPoint.clientX, event.clientX) - offsetX; } if (directionEnabled(chartInstance.$zoom._options.zoom.mode, 'y')) { var offsetY = beginPoint.target.getBoundingClientRect().top; startY = Math.min(beginPoint.clientY, event.clientY) - offsetY; endY = Math.max(beginPoint.clientY, event.clientY) - offsetY; } var dragDistanceX = endX - startX; var chartDistanceX = chartArea.right - chartArea.left; var zoomX = 1 + ((chartDistanceX - dragDistanceX) / chartDistanceX); var dragDistanceY = endY - startY; var chartDistanceY = chartArea.bottom - chartArea.top; var zoomY = 1 + ((chartDistanceY - dragDistanceY) / chartDistanceY); // Remove drag start and end before chart update to stop drawing selected area chartInstance.$zoom._dragZoomStart = null; chartInstance.$zoom._dragZoomEnd = null; if (dragDistanceX > 0 || dragDistanceY > 0) { doZoom(chartInstance, zoomX, zoomY, { x: (startX - chartArea.left) / (1 - dragDistanceX / chartDistanceX) + chartArea.left, y: (startY - chartArea.top) / (1 - dragDistanceY / chartDistanceY) + chartArea.top }); } }; node.ownerDocument.addEventListener('mouseup', chartInstance.$zoom._mouseUpHandler); chartInstance.$zoom._wheelHandler = function(event) { if (!(chartInstance.$zoom._options.zoom && chartInstance.$zoom._options.zoom.drag)) { var rect = event.target.getBoundingClientRect(); var offsetX = event.clientX - rect.left; var offsetY = event.clientY - rect.top; var center = { x: offsetX, y: offsetY }; var speedPercent = chartInstance.$zoom._options.zoom.speed; if (event.deltaY >= 0) { speedPercent = -speedPercent; } doZoom(chartInstance, 1 + speedPercent, 1 + speedPercent, center); // Prevent the event from triggering the default behavior (eg. Content scrolling). if (event.cancelable) { event.preventDefault(); } } }; node.addEventListener('wheel', chartInstance.$zoom._wheelHandler); if (Hammer) { var mc = new Hammer.Manager(node); mc.add(new Hammer.Pinch()); mc.add(new Hammer.Pan({ threshold: panThreshold })); // Hammer reports the total scaling. We need the incremental amount var currentPinchScaling; var handlePinch = function(e) { var diff = 1 / (currentPinchScaling) * e.scale; var rect = e.target.getBoundingClientRect(); var offsetX = e.center.x - rect.left; var offsetY = e.center.y - rect.top; var center = { x: offsetX, y: offsetY }; // fingers position difference var x = Math.abs(e.pointers[0].clientX - e.pointers[1].clientX); var y = Math.abs(e.pointers[0].clientY - e.pointers[1].clientY); // diagonal fingers will change both (xy) axes var p = x / y; var xy; if (p > 0.3 && p < 1.7) { xy = 'xy'; } else if (x > y) { xy = 'x'; // x axis } else { xy = 'y'; // y axis } doZoom(chartInstance, diff, diff, center, xy); // Keep track of overall scale currentPinchScaling = e.scale; }; mc.on('pinchstart', function() { currentPinchScaling = 1; // reset tracker }); mc.on('pinch', handlePinch); mc.on('pinchend', function(e) { handlePinch(e); currentPinchScaling = null; // reset zoomNS.zoomCumulativeDelta = 0; }); var currentDeltaX = null; var currentDeltaY = null; var panning = false; var handlePan = function(e) { if (currentDeltaX !== null && currentDeltaY !== null) { panning = true; var deltaX = e.deltaX - currentDeltaX; var deltaY = e.deltaY - currentDeltaY; currentDeltaX = e.deltaX; currentDeltaY = e.deltaY; doPan(chartInstance, deltaX, deltaY); } }; mc.on('panstart', function(e) { currentDeltaX = 0; currentDeltaY = 0; handlePan(e); }); mc.on('panmove', handlePan); mc.on('panend', function() { currentDeltaX = null; currentDeltaY = null; zoomNS.panCumulativeDelta = 0; setTimeout(function() { panning = false; }, 500); }); chartInstance.$zoom._ghostClickHandler = function(e) { if (panning && e.cancelable) { e.stopImmediatePropagation(); e.preventDefault(); } }; node.addEventListener('click', chartInstance.$zoom._ghostClickHandler); chartInstance._mc = mc; } }, beforeDatasetsDraw: function(chartInstance) { var ctx = chartInstance.chart.ctx; var chartArea = chartInstance.chartArea; ctx.save(); ctx.beginPath(); if (chartInstance.$zoom._dragZoomEnd) { var xAxis = getXAxis(chartInstance); var yAxis = getYAxis(chartInstance); var beginPoint = chartInstance.$zoom._dragZoomStart; var endPoint = chartInstance.$zoom._dragZoomEnd; var startX = xAxis.left; var endX = xAxis.right; var startY = yAxis.top; var endY = yAxis.bottom; if (directionEnabled(chartInstance.$zoom._options.zoom.mode, 'x')) { var offsetX = beginPoint.target.getBoundingClientRect().left; startX = Math.min(beginPoint.clientX, endPoint.clientX) - offsetX; endX = Math.max(beginPoint.clientX, endPoint.clientX) - offsetX; } if (directionEnabled(chartInstance.$zoom._options.zoom.mode, 'y')) { var offsetY = beginPoint.target.getBoundingClientRect().top; startY = Math.min(beginPoint.clientY, endPoint.clientY) - offsetY; endY = Math.max(beginPoint.clientY, endPoint.clientY) - offsetY; } var rectWidth = endX - startX; var rectHeight = endY - startY; var dragOptions = chartInstance.$zoom._options.zoom.drag; ctx.fillStyle = dragOptions.backgroundColor || 'rgba(225,225,225,0.3)'; ctx.fillRect(startX, startY, rectWidth, rectHeight); if (dragOptions.borderWidth > 0) { ctx.lineWidth = dragOptions.borderWidth; ctx.strokeStyle = dragOptions.borderColor || 'rgba(225,225,225)'; ctx.strokeRect(startX, startY, rectWidth, rectHeight); } } ctx.rect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); ctx.clip(); }, afterDatasetsDraw: function(chartInstance) { chartInstance.chart.ctx.restore(); }, destroy: function(chartInstance) { if (chartInstance.$zoom) { var node = chartInstance.$zoom._node; if (chartInstance.$zoom._options.zoom) { node.removeEventListener('mousedown', chartInstance.$zoom._mouseDownHandler); node.removeEventListener('mousemove', chartInstance.$zoom._mouseMoveHandler); node.ownerDocument.removeEventListener('mouseup', chartInstance.$zoom._mouseUpHandler); node.removeEventListener('wheel', chartInstance.$zoom._wheelHandler); } if (Hammer) { node.removeEventListener('click', chartInstance.$zoom._ghostClickHandler); } delete chartInstance.$zoom; var mc = chartInstance._mc; if (mc) { mc.remove('pinchstart'); mc.remove('pinch'); mc.remove('pinchend'); mc.remove('panstart'); mc.remove('pan'); mc.remove('panend'); } } } }; Chart.plugins.register(zoomPlugin); export default zoomPlugin;
// @flow import React, { PureComponent } from "react"; import classnames from "classnames"; type Props = { children: any, className: string }; class Slide extends PureComponent<Props> { render() { const { children, className } = this.props; return <section className={classnames(className)}>{children}</section>; } } export default Slide;
import React, { useState } from "react" import styled from "styled-components" import Header from "../components/header" import Console from "../components/console" import Terminal from "../components/terminal" import Game from "../components/game" const LandingSection = styled.section` min-height: 100vh; display: flex; flex-direction: column; ` const HeadeOuter = styled.div` position: relative; ` const Main = styled.div` flex: 1; padding: 1rem; display: flex; align-items: center; flex-direction: column; justify-content: center; @media screen and (min-width: 768px) { padding: 1.7rem; } ` export default ({ title }) => { const [toggleGame, setToggleGame] = useState(false) return ( <LandingSection className="contain"> <HeadeOuter> <Header /> </HeadeOuter> <Main> {toggleGame ? ( <Game /> ) : ( <Console> <Console.Controls /> <Console.Code lineNumbers> <code> <i className="c-g">{`{`}</i> </code> <code> {` `} <i className="c-b">"</i> <i className="c-y">title</i> <i className="c-b">"</i> <i className="c-g">: </i> <i className="c-b">"</i>GeekcampSG 2019 <i className="c-b">"</i> <i className="c-g">,</i> </code> <code> {` `} <i className="c-b">"</i> <i className="c-y">startDate</i> <i className="c-b">"</i> <i className="c-g">: </i> <i className="c-b">"</i>2019-10-19T08:30 <i className="c-b">"</i> <i className="c-g">,</i> </code> <code> {` `} <i className="c-b">"</i> <i className="c-y">endDate</i> <i className="c-b">"</i> <i className="c-g">: </i> <i className="c-b">"</i>2019-10-19T18:15 <i className="c-b">"</i> <i className="c-g">,</i> </code> <code> {` `} <i className="c-b">"</i> <i className="c-r">location</i> <i className="c-b">"</i> <i className="c-g">: {`{`}</i> </code> <code> {` `} <i className="c-b">"</i> <i className="c-r">name</i> <i className="c-b">"</i> <i className="c-g">: </i> <i className="c-b">"</i>Shaw Foundation Alumni House, NUS <i className="c-b">"</i> <i className="c-g">,</i> </code> <code> {` `} <i className="c-b">"</i> <i className="c-r">address</i> <i className="c-b">"</i> <i className="c-g">: </i> <i className="c-b">"</i>Auditorium Level 2 <i className="c-g">,</i> </code> <code> {` `} <i> 11 Kent Ridge Drive<i className="c-g">,</i> Singapore 119244 </i> <i className="c-b">"</i> </code> <code> {` `} <i className="c-g">{`}`}</i> </code> <code> {` `} <i className="c-b">"</i> <i className="c-g">description</i> <i className="c-b">"</i> <i className="c-g">: </i> <i className="c-b">"</i>Join us for an eventful day of </code> <code> {` `} <i>geek talks.</i> <i className="c-b">"</i> </code> <code> <i className="c-g">{`}`}</i> </code> </Console.Code> </Console> )} <Terminal handleToggleGame={showGame => { setToggleGame(showGame) }} /> </Main> </LandingSection> ) }
const { describe, it, expect} = require('@jest/globals') const Employee = require('../lib/Employee'); const Manager = require('../lib/Manager'); describe('Manager', () => { describe('Initialization', () => { it('should extend the Empolyee class.', () => { const obj = new Manager('Manny', '1', 'manny@test.com', '21'); expect(obj).toBeInstanceOf(Employee); }) it('should create an object with "officeNumber" property set to "officeNumber" parameter.', () => { const obj = new Manager('Manny', '1', 'manny@test.com', '21'); expect(obj).toHaveProperty('officeNumber', '21'); }) }) describe('getRole', () => { it('should return "Manager".', () => { const obj = new Manager('Manny', '1', 'manny@test.com', '21'); expect( obj.getRole() ).toBe('Manager') }) }) })
window.__NUXT__=(function(a,b,c,d,e){return {staticAssetsBase:"https:\u002F\u002Fwww.baca-quran.id\u002Fstatic\u002F1627814429",layout:"default",error:b,state:{notification:{show:a,title:c,message:c},isShowSidebar:a,isSupportWebShare:a,headerTitle:"Baca Qur'an",page:"home",lastReadVerse:b,settingActiveTheme:{name:"dark",bgColor:"#071e3d",fgColor:"#fff"},settingShowTranslation:a,settingShowTafsir:a,settingShowMuqaddimah:d,surahFavorite:[]},serverRendered:d,routePath:"\u002F38\u002F4",config:{_app:{basePath:e,assetsPath:e,cdnURL:"https:\u002F\u002Fwww.baca-quran.id\u002F"}}}}(false,null,"",true,"\u002F"));
module.exports = { siteMetadata: { title: `Sayan Chowdhury's Website`, }, plugins: [ `gatsby-plugin-react-helmet`, `gatsby-plugin-sass`, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: `UA-94088018-1`, anonymize: true, respectDNT: true }, }, { resolve: `gatsby-plugin-favicon`, options: { logo: "./src/images/favicon.png", injectHTML: true, icons: { android: true, appleIcon: true, appleStartup: true, coast: false, favicons: true, firefox: true, twitter: false, yandex: false, windows: false } } } ], };
const Discord = require('discord.js') const db = require('quick.db') exports.run = async(client, message, args ) => { let banlanıcak = message.mentions.users.first() let banlimit = await db.fetch(`kicklimit_${message.guild.id}`) let bansayı= await db.fetch(`kicksayı_${message.author.id}`) let guild = message.guild if (!banlanıcak) return message.channel.send(`Kişi Seç!`) if (bansayı > banlimit) return message.channel.send(`Kick Sayın Limiti Geçtiği İçin Kickleyemem!`) let sebep = args.slice(1).join(' ') if (!sebep) return message.channel.send('Sebep Belirt') message.channel.send(`Kullanıcı Başarıyla Kicklendi`) guild.members.kick(banlanıcak) db.add(`kicksayı_${message.author.id}`, 1) }; exports.conf = { aliases: [], permLevel: 0 }; exports.help = { name: 'kick' };
var structorx_i_n_p_u_t___e_v_e_n_t___p_a_y_l_o_a_d = [ [ "aeID", "structorx_i_n_p_u_t___e_v_e_n_t___p_a_y_l_o_a_d.html#a983da6db81f8a87dd9bf9de3ab5780c6", null ], [ "aeMode", "structorx_i_n_p_u_t___e_v_e_n_t___p_a_y_l_o_a_d.html#ac24b23d29741a12db6d4f7b789184caf", null ], [ "aeType", "structorx_i_n_p_u_t___e_v_e_n_t___p_a_y_l_o_a_d.html#afbdc16bd672f5a990959d04e434f81ff", null ], [ "afValue", "structorx_i_n_p_u_t___e_v_e_n_t___p_a_y_l_o_a_d.html#a5d66be4dbde3417c65989708e1cf1909", null ], [ "zInputName", "structorx_i_n_p_u_t___e_v_e_n_t___p_a_y_l_o_a_d.html#a08e6a0ce11c5a30a3ff68e18cefec922", null ], [ "zSetName", "structorx_i_n_p_u_t___e_v_e_n_t___p_a_y_l_o_a_d.html#a532745a46c44d576c975c80d9a5a8af0", null ] ];
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import React from 'react'; import PropTypes from 'prop-types'; import { Loading } from '../loading'; export class FunctionFormContextPending extends React.PureComponent { static propTypes = { context: PropTypes.object, contextExpression: PropTypes.string, expressionType: PropTypes.object.isRequired, updateContext: PropTypes.func.isRequired, }; componentDidMount() { this.fetchContext(this.props); } componentWillReceiveProps(newProps) { const oldContext = this.props.contextExpression; const newContext = newProps.contextExpression; const forceUpdate = newProps.expressionType.requiresContext && oldContext !== newContext; this.fetchContext(newProps, forceUpdate); } fetchContext = (props, force = false) => { // dispatch context update if none is provided const { expressionType, context, updateContext } = props; if (force || (context == null && expressionType.requiresContext)) updateContext(); }; render() { return ( <div className="canvasFunctionForm canvasFunctionForm--loading"> <Loading /> </div> ); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import webpack from 'webpack'; import merge from 'webpack-merge'; import path from 'path'; import commonCfg from './webpack.common'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; const backendPort = process.env.BACKEND_PORT || 3000; const devServerPort = process.env.PORT || 9000; const devServerHost = process.env.HOST || '0.0.0.0'; export default merge(commonCfg, { mode: 'development', devtool: 'source-map', watch: true, module: { exprContextCritical: false, rules: [ { test: /\.css$/, use: ['style', 'css'] }, { test: /\.scss$/, // Version without extract plugin fails on some machines. https://github.com/sass/node-sass/issues/1895 use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css', options: { sourceMap: true } }, { loader: 'sass', options: { sourceMap: true } } ] }) } ] }, devServer: { headers: { 'Content-Security-Policy': `script-src 'self' 'unsafe-inline' 'unsafe-eval' data: http: https:;` }, compress: true, historyApiFallback: true, disableHostCheck: true, contentBase: path.resolve('build'), // hot: true, inline: true, proxy: { '/socket.io': { target: `http://localhost:${backendPort}`, ws: true }, '/agents': { target: `http://localhost:${backendPort}`, ws: true }, '/api/*': { target: `http://localhost:${backendPort}` } }, watchOptions: { aggregateTimeout: 1000, poll: 2000 }, stats: 'errors-only', host: devServerHost, port: devServerPort } });
COMPONENT('floatinginput', 'minwidth:200', function(self, config, cls) { var cls2 = '.' + cls; var timeout, icon, plus, input, summary, area; var is = false; var plusvisible = false; self.readonly(); self.singleton(); self.nocompile && self.nocompile(); self.configure = function(key, value, init) { if (init) return; switch (key) { case 'placeholder': self.find('input').prop('placeholder', value); break; } }; self.make = function() { self.aclass(cls + ' hidden'); self.append('<div class="{1}-summary hidden"></div><div class="{1}-input"><span class="{1}-add hidden"><i class="fa fa-plus"></i></span><span class="{1}-button"><i class="fa fa-search"></i></span><div class="{1}-control"><input type="text" placeholder="{0}" class="{1}-search-input" name="dir{2}" autocomplete="dir{2}" /><textarea class="{1}-search-area" name="dirt{2}" placeholder="{0}"></textarea></div></div'.format(config.placeholder, cls, Date.now())); input = self.find('input'); icon = self.find(cls2 + '-button').find('i'); plus = self.find(cls2 + '-add'); summary = self.find(cls2 + '-summary'); area = self.find('textarea'); self.event('click', cls2 + '-button', function(e) { input.val(''); area.val(''); self.search(); e.stopPropagation(); e.preventDefault(); }); self.event('click', cls2 + '-add', function() { if (self.opt.callback) { self.opt.scope && M.scope(self.opt.scope); self.opt.callback(self.opt.multiline ? area.val() : input.val(), self.opt.element, true); self.hide(); } }); self.event('keydown', 'input,textarea', function(e) { switch (e.which) { case 27: self.hide(); break; case 13: if (!self.opt.multiline) { if (self.opt.callback) { self.opt.scope && M.scope(self.opt.scope); self.opt.callback(this.value, self.opt.element); } self.hide(); } break; } }); var e_click = function(e) { var node = e.target; var count = 0; if (is) { while (true) { var c = node.getAttribute('class') || ''; if (c.indexOf(cls + '-input') !== -1) return; node = node.parentNode; if (!node || !node.tagName || node.tagName === 'BODY' || count > 3) break; count++; } } else { is = true; while (true) { var c = node.getAttribute('class') || ''; if (c.indexOf(cls) !== -1) { is = false; break; } node = node.parentNode; if (!node || !node.tagName || node.tagName === 'BODY' || count > 4) break; count++; } } is && self.hide(0); }; var e_resize = function() { is && self.hide(0); }; self.bindedevents = false; self.bindevents = function() { if (!self.bindedevents) { $(document).on('click', e_click); $(W).on('resize', e_resize); self.bindedevents = true; } }; self.unbindevents = function() { if (self.bindedevents) { self.bindedevents = false; $(document).off('click', e_click); $(W).off('resize', e_resize); } }; self.event('input', 'input,textarea', function() { var is = !!this.value; if (plusvisible !== is) { plusvisible = is; plus.tclass('hidden', !this.value); } }); var fn = function() { is && self.hide(1); }; self.on('reflow + scroll + resize + resize2', fn); }; self.show = function(opt) { // opt.element // opt.callback(value, el) // opt.offsetX --> offsetX // opt.offsetY --> offsetY // opt.offsetWidth --> plusWidth // opt.placeholder // opt.render // opt.minwidth // opt.maxwidth // opt.icon; // opt.maxlength = 30; var el = opt.element instanceof jQuery ? opt.element[0] : opt.element; self.tclass(cls + '-default', !opt.render); if (!opt.minwidth) opt.minwidth = 200; if (is) { clearTimeout(timeout); if (self.target === el) { self.hide(1); return; } } self.initializing = true; self.target = el; plusvisible = false; var element = $(opt.element); setTimeout(self.bindevents, 500); self.opt = opt; opt.class && self.aclass(opt.class); if (opt.multiline) { area.val(opt.value || ''); area.prop('maxlength', opt.maxlength || 1000); input.val(''); } else { input.val(opt.value || ''); input.prop('maxlength', opt.maxlength || 100); area.val(''); } self.target = element[0]; var w = element.width(); var offset = element.offset(); var width = w + (opt.offsetWidth || 0); if (opt.minwidth && width < opt.minwidth) width = opt.minwidth; else if (opt.maxwidth && width > opt.maxwidth) width = opt.maxwidth; var ico = ''; if (opt.icon) { if (opt.icon.indexOf(' ') === -1) ico = 'fa fa-' + opt.icon; else ico = opt.icon; } else ico = 'fa fa-pencil-alt'; icon.rclass2('fa').aclass(ico).rclass('hidden'); if (opt.value) { plusvisible = true; plus.rclass('hidden'); } else plus.aclass('hidden'); var tmp = opt.multiline ? area : input; tmp.prop('placeholder', opt.placeholder || config.placeholder); var options = { left: 0, top: 0, width: width }; summary.tclass('hidden', !opt.summary).html(opt.summary || ''); switch (opt.align) { case 'center': options.left = Math.ceil((offset.left - width / 2) + (width / 2)); break; case 'right': options.left = (offset.left - width) + w; break; default: options.left = offset.left; break; } options.top = opt.position === 'bottom' ? ((offset.top - self.height()) + element.height()) : offset.top; options.scope = M.scope ? M.scope() : ''; area.tclass('hidden', opt.multiline != true); input.tclass('hidden', opt.multiline == true); self.tclass(cls + '-multiline', opt.multiline == true); if (opt.multiline) area.css('height', (typeof(opt.height) === 'number' ? (opt.height + 'px') : opt.height) || '100px'); if (opt.offsetX) options.left += opt.offsetX; if (opt.offsetY) options.top += opt.offsetY; self.css(options); !isMOBILE && setTimeout(function() { opt.select && tmp[0].select(); tmp.focus(); }, 200); self.tclass(cls + '-monospace', !!opt.monospace); self.rclass('hidden'); setTimeout(function() { self.initializing = false; is = true; if (self.opt && self.target && self.target.offsetParent) self.aclass(cls + '-visible'); else self.hide(1); }, 100); }; self.hide = function(sleep) { if (!is || self.initializing) return; clearTimeout(timeout); timeout = setTimeout(function() { self.unbindevents(); self.rclass(cls + '-visible').aclass('hidden'); if (self.opt) { self.opt.close && self.opt.close(); self.opt.class && self.rclass(self.opt.class); self.opt = null; } is = false; }, sleep ? sleep : 100); }; });
import request from '@/utils/request' export function fetchList(query) { return request({ url: 'http://localhost:3000/dev-api/caixa', method: 'get', params: query }) } export function create(data) { return request({ url: 'http://localhost:3000/dev-api/caixa', method: 'post', data }) } export function update(data) { return request({ url: 'http://localhost:3000/dev-api/caixa', method: 'patch', data }) } export function deleteItem(data) { return request({ url: 'http://localhost:3000/dev-api/caixa', method: 'delete', data }) }
(function() { 'use strict'; angular.module('app.testRunCard').directive('testRunCard', function() { return { templateUrl: 'app/components/blocks/test-run-card/test-run-card.html', controller: function TestRunCardController(windowWidthService, testsRunsService, $rootScope, UtilService, $state, $timeout, $mdDialog, $mdToast, SlackService, TestRunService, UserService, $interval, DownloadService) { const local = { currentUser: UserService.getCurrentUser(), testRunInDebugMode: null, stopConnectingDebug: null, debugHost: null, debugPort: null, jenkins: $rootScope.jenkins, }; const vm = { testRun: null, singleMode: false, singleWholeInfo: false, showNotifyInSlackOption: false, showBuildNowOption: false, showDeleteTestRunOption: false, isMobile: windowWidthService.isMobile, isSlackAvailable: false, slackChannels: null, currentOffset: $rootScope.currentOffset, tools: $rootScope.tools, addToSelectedtestRuns: addToSelectedtestRuns, showDetails: showDetails, openMenu: openMenu, openTestRun: openTestRun, copyLink: copyLink, markAsReviewed: markAsReviewed, showCommentsDialog: showCommentsDialog, sendAsEmail: sendAsEmail, createSpreadsheet: createSpreadsheet, exportTestRun: exportTestRun, notifyInSlack: notifyInSlack, buildNow: buildNow, abort: abort, rerun: rerun, startDebug: startDebug, onTestRunDelete: onTestRunDelete, checkFilePresence: checkFilePresence, downloadApplication: downloadApplication, goToTestRun: goToTestRun, onBackClick: onBackClick, }; vm.$onInit = init; return vm; function init() { initSlackChannels(); initSlackAvailability(); } function initSlackChannels() { vm.slackChannels = testsRunsService.getSlackChannels(); if (!vm.slackChannels) { testsRunsService.fetchSlackChannels().then(function(slackChannels) { vm.slackChannels = slackChannels; }); } } function initSlackAvailability() { if (testsRunsService.isSlackAvailabilityFetched()) { vm.isSlackAvailable = testsRunsService.getSlackAvailability(); } else { testsRunsService.fetchSlackAvailability().then(function(isSlackAvailable) { vm.isSlackAvailable = isSlackAvailable; }); } } function addToSelectedtestRuns() { vm.onSelect && vm.onSelect(vm.testRun); } function showDetails(value) { vm.singleWholeInfo = value; } function initMenuRights() { vm.showNotifyInSlackOption = (vm.isSlackAvailable && vm.slackChannels.indexOf(vm.testRun.job.name) !== -1) && vm.testRun.reviewed; vm.showBuildNowOption = local.jenkins.enabled; vm.showDeleteTestRunOption = true; } function openMenu($event, $msMenuCtrl) { initMenuRights(); UtilService.setOffset($event); $timeout(function() { vm.currentOffset = $rootScope.currentOffset; $msMenuCtrl.open($event); }); } function openTestRun() { const url = $state.href('tests/run', {testRunId: vm.testRun.id}); window.open(url,'_blank'); } function goToTestRun() { $state.go('tests/run', {testRunId: vm.testRun.id, testRun: vm.testRun}); } function onBackClick() { $state.go('tests/runs', {activeTestRunId: vm.testRun.id}); } function copyLink() { const url = $state.href('tests/run', {testRunId: vm.testRun.id}, {absolute : true}); url.copyToClipboard(); } function markAsReviewed() { showCommentsDialog(); } function sendAsEmail(event) { showEmailDialog([vm.testRun], event); } function createSpreadsheet(event) { showCreateSpreadsheetDialog([vm.testRun], event); }; function showCommentsDialog(event) { $mdDialog.show({ controller: 'CommentsController', templateUrl: 'app/components/modals/comments/comments.html', parent: angular.element(document.body), targetEvent: event, clickOutsideToClose:true, fullscreen: true, locals: { testRun: vm.testRun, isSlackAvailable: vm.isSlackAvailable, slackChannels: vm.slackChannels } }).then(function(answer) { vm.testRun.reviewed = answer.reviewed; vm.testRun.comments = answer.comments; }); } function showEmailDialog(testRuns, event) { $mdDialog.show({ controller: 'EmailController', templateUrl: 'app/components/modals/email/email.html', parent: angular.element(document.body), targetEvent: event, clickOutsideToClose:true, fullscreen: true, locals: { testRuns: testRuns } }); } function showCreateSpreadsheetDialog(testRuns, event) { $mdDialog.show({ controller: 'SpreadsheetController', templateUrl: 'app/components/modals/spreadsheet/spreadsheet.html', parent: angular.element(document.body), targetEvent: event, clickOutsideToClose:true, fullscreen: true, locals: { testRuns: testRuns } }) .then(undefined, function(links) { if (links && links.length) { showToastWithLinks(links); } }); } function showToastWithLinks(links) { $mdToast.show({ hideDelay: 0, position: 'bottom right', locals: { links: links }, controller: function ToastWithLinksController($mdToast, links) { return { links: links, closeToast: closeToast, }; function closeToast() { $mdToast.hide(); } }, controllerAs: '$ctrl', template: '<md-toast>\n' + ' <a target="_blank" ng-repeat="link in links" ng-href="{{ link }}" class="md-toast-text" flex>Google spreadsheet</a>\n' + ' <md-button id="close" ng-click="$ctrl.closeToast();">\n' + ' Close\n' + ' </md-button>\n' + '</md-toast>' }); } function exportTestRun() { TestRunService.exportTestRunResultsHTML(vm.testRun.id).then(function(rs) { if (rs.success) { downloadFromByteArray(vm.testRun.testSuite.name.split(' ').join('_') + '.html', rs, 'html'); } else { alertify.error(rs.message); } }); } function downloadFromByteArray(filename, array, contentType) { const blob = new Blob([array.data], {type: contentType ? contentType : array.headers('Content-Type')}); const link = document.createElement('a'); link.style = 'display: none'; document.body.appendChild(link); link.href = window.URL.createObjectURL(blob); link.download = filename; link.click(); //remove link after 10sec $timeout(() => { link && document.body.removeChild(link); }, 10000); } function notifyInSlack() { SlackService.triggerReviewNotif(vm.testRun.id); } function buildNow(event) { showBuildNowDialog(event); } function rerun(event) { showRerunDialog(event); } function showRerunDialog(event) { $mdDialog.show({ controller: 'TestRunRerunController', templateUrl: 'app/components/modals/rerun/rerun.html', parent: angular.element(document.body), targetEvent: event, clickOutsideToClose: true, fullscreen: true, locals: { testRun: vm.testRun, jenkins: local.jenkins } }); } function startDebug() { if (confirm('Start debugging?')) { local.testRunInDebugMode = angular.copy(vm.testRun); debugTestRun(local.testRunInDebugMode); } } function debugTestRun(testRunForDebug) { TestRunService.debugTestRun(testRunForDebug.id).then(function (rs) { if (rs.success) { showDebugToast(); let debugLog = ''; let disconnectDebugTimeout; const parseLogsInterval = $interval(function() { TestRunService.getConsoleOutput(testRunForDebug.id, testRunForDebug.ciRunId, 200, 50).then(function (rs) { if (rs.success) { const map = rs.data; Object.keys(map).forEach(function(key) { const value = map[key]; if (value.includes('Listening for transport dt_socket at address:')) { if (debugLog === '') { getDebugData(value); } $timeout.cancel(connectDebugTimeout); disconnectDebugTimeout = $timeout(function() { stopDebugMode(); $mdToast.hide(); }, 60 * 10 * 1000); if (debugLog === '') { debugLog = value; } if (debugLog !== value) { $timeout.cancel(disconnectDebugTimeout); $interval.cancel(parseLogsInterval); mdToast.hide(); alertify.success('Tests started in debug'); } } }); } else { stopDebugMode(); alertify.error(rs.message); } }); }, 10000); const connectDebugTimeout = $timeout(function() { alertify.error('Problems with starting debug mode occurred, disabling'); stopDebugMode(); }, 60 * 10 * 1000); local.stopConnectingDebug = function() { $interval.cancel(parseLogsInterval); $timeout.cancel(disconnectDebugTimeout); $timeout.cancel(connectDebugTimeout); }; } else { alertify.error(rs.message); } }); } function getDebugData(log){ if (log) { const portLine = log.split('Enabling remote debug on '); const debugValues = portLine[1].split(':'); local.debugHost = debugValues[0]; local.debugPort = debugValues[1].split('\n')[0]; } } function showDebugToast() { $mdToast.show({ hideDelay: 1200000, position: 'bottom right', locals: { debugPort: local.debugPort, debugHost: local.debugHost, stopDebugMode: stopDebugMode }, controller : 'DebugModeController', controllerAs: '$ctrl', bindToController: true, templateUrl : 'app/components/toasts/debug-mode/debug-mode.html' }); } function stopDebugMode() { local.stopConnectingDebug && local.stopConnectingDebug(); if (local.testRunInDebugMode) { abortDebug(local.testRunInDebugMode); local.testRunInDebugMode = null; local.debugHost = null; local.debugPort = null; alertify.warning('Debug mode is disabled'); } } function abortDebug(debuggedTestRun) { if (local.jenkins.enabled) { TestRunService.abortDebug(debuggedTestRun.id, debuggedTestRun.ciRunId).then(function (rs) { if (rs.success) { const abortCause = {}; abortCause.comment = 'Debug mode was disconnected'; TestRunService.abortTestRun(debuggedTestRun.id, debuggedTestRun.ciRunId, abortCause).then(function(rs) { if (rs.success) { debuggedTestRun.status = 'ABORTED'; alertify.success('Testrun ' + debuggedTestRun.testSuite.name + ' is aborted'); } else { alertify.error(rs.message); } }); } else { alertify.error(rs.message); } }); } else { alertify.error('Unable connect to jenkins'); } } function showBuildNowDialog(event) { $mdDialog.show({ controller: 'BuildNowController', templateUrl: 'app/components/modals/build-now/build-now.html', parent: angular.element(document.body), targetEvent: event, clickOutsideToClose:true, fullscreen: true, locals: { testRun: vm.testRun } }); } function abort() { if (local.jenkins.enabled) { TestRunService.abortCIJob(vm.testRun.id, vm.testRun.ciRunId).then(function (rs) { if (rs.success) { const abortCause = {}; abortCause.comment = 'Aborted by ' + local.currentUser.username; TestRunService.abortTestRun(vm.testRun.id, vm.testRun.ciRunId, abortCause).then(function(rs) { if (rs.success){ vm.testRun.status = 'ABORTED'; alertify.success('Testrun ' + vm.testRun.testSuite.name + ' is aborted'); } else { alertify.error(rs.message); } }); } else { alertify.error(rs.message); } }); } else { alertify.error('Unable connect to jenkins'); } } function onTestRunDelete() { if (vm.singleMode) { deleteTestRun(); } else { vm.onDelete && vm.onDelete(vm.testRun); } } function deleteTestRun() { const confirmation = confirm('Do you really want to delete "' + vm.testRun.testSuite.name + '" test run?'); if (confirmation) { const id = vm.testRun.id; TestRunService.deleteTestRun(id).then(function(rs) { const messageData = rs.success ? {success: rs.success, id: id, message: 'Test run{0} {1} removed'} : {id: id, message: 'Unable to delete test run{0} {1}'}; UtilService.showDeleteMessage(messageData, [id], [], []); if (rs.success) { $timeout(function() { testsRunsService.clearDataCache(); $state.go('tests/runs'); }, 1000); } }); } } function checkFilePresence() { if (!vm.testRun.appVersionValid) { vm.testRun.appVersionLoading = true; DownloadService.check(vm.testRun.appVersion).then(function (rs) { if (rs.success) { vm.testRun.appVersionValid = rs.data; } else { //alertify.error(rs.message); } delete vm.testRun.appVersionLoading; return rs.data; }); } } function downloadApplication() { const appVersion = $ctrl.testRun.appVersion; DownloadService.download(appVersion).then(function (rs) { if (rs.success) { downloadFromByteArray(appVersion, rs.res); } else { alertify.error(rs.message); } }); } }, scope: { singleMode: '=', testRun: '=', onSelect: '&', onDelete: '&' }, controllerAs: '$ctrl', restrict: 'E', replace: true, bindToController: true }; }); })();
/** * Auto-generated action file for "Published Plan Service" API. * * Generated at: 2019-06-06T13:12:53.753Z * Mass generator version: 1.1.0 * * flowground :- Telekom iPaaS / naviplancentral-com-plan-connector * Copyright © 2019, Deutsche Telekom AG * contact: flowground@telekom.de * * All files of this connector are licensed under the Apache 2.0 License. For details * see the file LICENSE on the toplevel directory. * * * Operation: 'GoalAdjustments_PostEducationByIdGoaladjustments' * Endpoint Path: '/api/GoalAdjustments/Education/{id}/Calculations' * Method: 'post' * */ const Swagger = require('swagger-client'); const processWrapper = require('../services/process-wrapper'); const spec = require('../spec.json'); // this wrapers offers a simplified emitData(data) function module.exports.process = processWrapper(processAction); // parameter names for this call const PARAMETERS = [ "id" ]; // mappings from connector field names to API field names const FIELD_MAP = { "id": "id", "duration": "duration", "expensesCovered": "expensesCovered", "lumpSumContribution": "lumpSumContribution", "lumpSumDate": "lumpSumDate", "monthlySavingsContribution": "monthlySavingsContribution", "adjustedValues": "adjustedValues", "originalValues": "originalValues", "requestBody": "requestBody" }; function processAction(msg, cfg) { var isVerbose = process.env.debug || cfg.verbose; if (isVerbose) { console.log(`---MSG: ${JSON.stringify(msg)}`); console.log(`---CFG: ${JSON.stringify(cfg)}`); console.log(`---ENV: ${JSON.stringify(process.env)}`); } const contentType = cfg.body_content_type; const body = msg.body; mapFieldNames(body); let parameters = {}; for(let param of PARAMETERS) { parameters[param] = body[param]; } // credentials for this operation let securities = {}; let callParams = { spec: spec, operationId: 'GoalAdjustments_PostEducationByIdGoaladjustments', pathName: '/api/GoalAdjustments/Education/{id}/Calculations', method: 'post', parameters: parameters, requestContentType: contentType, requestBody: body.requestBody, securities: {authorized: securities}, server: spec.servers[cfg.server] || cfg.otherServer, }; if (isVerbose) { let out = Object.assign({}, callParams); out.spec = '[omitted]'; console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`); } // Call operation via Swagger client return Swagger.execute(callParams).then(data => { // emit a single message with data this.emitData(data); // if the response contains an array of entities, you can emit them one by one: // data.obj.someItems.forEach((item) => { // this.emitData(item); // } }); } function mapFieldNames(obj) { if(Array.isArray(obj)) { obj.forEach(mapFieldNames); } else if(typeof obj === 'object' && obj) { Object.keys(obj).forEach(key => { mapFieldNames(obj[key]); let goodKey = FIELD_MAP[key]; if(goodKey && goodKey !== key) { obj[goodKey] = obj[key]; delete obj[key]; } }); } }
var smtp = require('../'); var seq = require('seq'); var fs = require('fs'); smtp.connect('localhost', 25, function (mail) { seq() .seq_(function (next) { mail.on('greeting', function (code, lines) { console.dir(lines); next(); }); }) .seq(function (next) { mail.helo('localhost', this.into('helo')); }) .seq(function () { mail.from('substack', this.into('from')); }) .seq(function () { mail.to('root', this.into('to')); }) .seq(function () { mail.data(this.into('data')) }) .seq(function () { mail.message(fs.createReadStream('/etc/issue'), this.into('message')); }) .seq(function () { mail.quit(this.into('quit')); }) .seq(function () { console.dir(this.vars); }) ; });
import request from '@/utils/request' //查询 export function cardList(params) { return request({ url: '/base/card/page', method: 'get', params }) } //保存 export function cardSave(data) { return request({ url: '/base/card/save', method: 'post', data }) } //删除 export function cardDel(data) { return request({ url: '/base/card/del', method: 'post', data }) } //编辑查询 export function cardEdit(params) { return request({ url: '/base/card/view', method: 'get', params }) } //获取子表 export function cardSonList(params) { return request({ url: '/basics/service/list', method: 'get', params }) }
/* * Copyright 2020 KT AI Lab. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ const dotenv = require('dotenv'); dotenv.config({ path: __dirname + '/config/.env.dev' }); dotenv.config({ path: __dirname + '/config/.env.dev.client'}); const logger = require(__dirname + '/src/logger'); const auth = require( __dirname + '/src/auth.js'); const record = require('node-record-lpcm16'); const { clientInfo } = require( __dirname + '/src/client'); const startOption = { uuid: auth.authorize(clientInfo, __dirname + '/config/.env.dev.uuid'), initialDssStat: ['SU:016', 'SU:027', 'SI:002', 'SG:000'] //Launcher Main, HDMI COnnected, Remote Voice Input, Nobody Here }; const AgentClient = require( __dirname + '/src/agentClient'); const grpcAgent = new AgentClient(startOption); grpcAgent.onEnd = () => { console.log('GRPC Ended..'); }; grpcAgent.connectServiceM(); //let mic; function initMic() { return record.start({ sampleRateHertz: 16000, threshold: 0, verbose: false, // recordProgram: 'arecord', recordProgram: 'rec', silence: '10.0', }); } function generatePCM() { console.log('Start Mic'); mic.on('data', (data) => { grpcAgent.sendVoiceData(data); }); grpcAgent.setMicObj(record); } const mic = initMic(); mic.on('data', (data) => { grpcAgent.sendVoiceData(data); }); console.log("========command========"); console.log("s: Start voice command"); console.log("c: Reconnect to Server"); console.log("d: Disonnect"); console.log("======================="); //Process User Key Input const stdin = process.stdin; stdin.setRawMode(true); stdin.resume(); stdin.setEncoding('utf8'); stdin.on('data', (key) => { if (key === '\u0003') { process.exit(); } else if (key === 's') { console.log('[INFO] USER-ACTION >>> Voice command started'); logger.info('[INFO] USER-ACTION >>> Voice command started'); //generatePCM(); grpcAgent.startVOCM(); } else if (key === 'c') { console.log('[INFO] USER-ACTION >>> Connect to Server'); logger.info('[INFO] USER-ACTION >>> Connect to Server'); grpcAgent.connectServiceM(); } else if (key === 'd') { console.log('[INFO] USER-ACTION >>> Disconnect'); logger.info('[INFO] USER-ACTION >>> Disconnect'); grpcAgent.disconnectServiceM(); } });
const loki = require('lokijs') const db = new loki('DB') const mediaDB = db.addCollection('Media') const { Readable, PassThrough } = require('stream') module.exports = srv => { srv.before('CREATE', 'Media', req => { const obj = mediaDB.insert({ media: '' }) req.data.id = obj.$loki }) srv.on('UPDATE', 'Media', (req, next) => { const url = req._.req.path if (url.includes('content')) { const id = req.data.id const obj = mediaDB.get(id) if (!obj) { req.reject(404, 'No record found for the ID') return } const stream = new PassThrough() const chunks = [] stream.on('data', chunk => { chunks.push(chunk) }) stream.on('end', () => { obj.media = Buffer.concat(chunks).toString('base64') mediaDB.update(obj) }) req.data.content.pipe(stream) } else return next() }) srv.on('READ', 'Media', (req, next) => { const url = req._.req.path if (url.includes('content')) { const id = req.data.id const mediaObj = mediaDB.get(id) if (!mediaObj) { req.reject(404, 'Media not found for the ID') return } const decodedMedia = new Buffer( mediaObj.media.split(';base64,').pop(), 'base64' ) return _formatResult(decodedMedia) } else return next() //> delegate to next/default handlers }) srv.on('DELETE', 'Media', (req, next) => { const id = req.data.id mediaDB .chain() .find({ $loki: id }) .remove() return next() //> delegate to next/default handlers }) function _formatResult (decodedMedia) { const readable = new Readable() const result = new Array() readable.push(decodedMedia) readable.push(null) result.push({ value: readable }) return result } }
import { call, put, select, takeLatest } from 'redux-saga/effects'; import { selectors, constants, actions } from './redux-definitions'; import { pushMessage } from 'containers/RequestStatusWrapper/actions'; import { COMMUNICATION_ERROR_MESSAGE } from 'helpers/messageConstants'; import apiStructure from 'helpers/apiStructure'; import request from 'utils/request'; const { LOAD_BLOG, UPDATE_BLOG, CREATE_BLOG } = constants; const { loadBlogRegisterSuccess, loadBlogRegisterError, updateBlogRegisterError, updateBlogRegisterSuccess, createBlogRegisterSuccess, createBlogRegisterError, } = actions; const { makeSelectBlogId, makeSelectNewBlog } = selectors; const blogCreatedMessage = { type: 'success', message: 'Blog created!' }; const blogCreateErrorMessage = { type: 'error', message: 'Could not create blog.', }; const blogLoadedMessage = { type: 'success', message: 'Blog loaded!' }; const blogLoadErrorMessage = { type: 'error', message: 'Could not load blog.', }; const blogUpdatedMessage = { type: 'success', message: 'Blog updated!' }; const blogUpdatedErrorMessage = { type: 'error', message: 'Could not save blog.', }; export function* doLoadBlog() { const blogId = yield select(makeSelectBlogId()); const requestURL = apiStructure.loadBlog.fullPath.split(':id').join(blogId); try { const blogResult = yield call(request, requestURL, { method: 'GET', }); if (blogResult.error) { yield put(loadBlogRegisterError(blogResult)); yield put(pushMessage(blogLoadErrorMessage)); } else { yield put(loadBlogRegisterSuccess(blogResult)); yield put(pushMessage(blogLoadedMessage)); } } catch (err) { yield put(loadBlogRegisterError(err)); yield put(pushMessage(COMMUNICATION_ERROR_MESSAGE)); } } export function* doUpdateBlog() { const blog = yield select(makeSelectNewBlog()); const requestURL = apiStructure.updateBlog.fullPath; try { const updateResult = yield call(request, requestURL, { method: 'POST', body: JSON.stringify(blog), headers: { 'Content-Type': 'application/json', }, }); if (updateResult.error) { yield put(updateBlogRegisterError(updateResult)); yield put(pushMessage(blogUpdatedErrorMessage)); } else { yield put(updateBlogRegisterSuccess(updateResult)); yield put(pushMessage(blogUpdatedMessage)); } } catch (err) { yield put(updateBlogRegisterError(err)); yield put(pushMessage(COMMUNICATION_ERROR_MESSAGE)); } } export function* doCreateBlog() { const blog = yield select(makeSelectNewBlog()); const requestURL = apiStructure.createBlog.fullPath; try { const blogCreateResult = yield call(request, requestURL, { method: 'POST', body: JSON.stringify(blog), headers: { 'Content-Type': 'application/json', }, }); if (blogCreateResult.error) { yield put(createBlogRegisterError(blogCreateResult)); yield put(pushMessage(blogCreateErrorMessage)); } else { yield put(createBlogRegisterSuccess(blogCreateResult)); yield put(pushMessage(blogCreatedMessage)); window.location = `/admin/blog/edit/${blogCreateResult.id}`; } } catch (err) { yield put(createBlogRegisterError(err)); yield put(pushMessage(COMMUNICATION_ERROR_MESSAGE)); } } export default function* saga() { yield takeLatest(LOAD_BLOG, doLoadBlog); yield takeLatest(UPDATE_BLOG, doUpdateBlog); yield takeLatest(CREATE_BLOG, doCreateBlog); }
var arrLang = { 'ENG': { 'home': 'Home', 'course content and reading': 'Course contents and Recomended Reading', 'exercises': 'Exercises', 'calculated examples': 'Calculated Examples', 'lectures': 'Lectures', 'language': 'Language', 'conditions': 'Conditions for passing the course', 'sylabus content': 'There will be one written test for 40 points during the semester. Each student has to earn at least 22 points over the test.Then, a student has to pass a written exam for the maximum of 60 points. In order to get the credits for the subject, a student has to gain at least 56 points, altogether for the test and the exam.', 'point0': 'By completion of this subject, a student will gain knowledge of Boolean algebra, forms and minimization of logic functions, and implementation of basic and complex logic functions using logic gates. He/she will also understand the principles and main parameters of logic circuits realized using switches as well as the main principles of combinational and sequential logic circuits. A student will be able to model, analyze and design basic logic circuits.', 'point1': "Boolean algebra and Boolean functions. Normal conjunctive and normal disjunctive forms. De Morgan's theorems. Minimization of logic functions. Basic and complex logic gates. Combinational logic circuits. Realization of logic functions using switches. Implementation of basic and complex logic gates in CMOS technology. Memory elements - latches and flip-flop registers. Sequential logic circuits. Finite state machines. Synchronous and asynchronous sequential circuits." }, 'SVK': { 'home': 'Domov', 'course content and reading': 'Stručná osnova a Literatúra', 'exercises': 'Cvičenia', 'calculated examples': 'Vyrátané Príklady', 'lectures': 'Prednášky', 'language': 'Jazyk', 'conditions': 'Podmienky na absolvovanie predmetu', 'sylabus content': 'V priebehu semestra bude písomná previerka za 40 bodov. K získaniu prístupu na skúšku je nevyhnutné získať z písomného testu aspoň 22 bodov. Po ukončení semestra je potrebné absolvovať písomnú skúšku za max. 60 bodov. Kredity za predmet sa neudelia študentovi, ktorý získa spolu za cvičenia a skúšku menej ako 56 bodov.', 'point0': 'Úspešným absolvovaním predmetu študent získa znalosti z oblasti Booleovskej algebry, formy zápisu a minimalizácie logických funkcií, ako aj ich implementácie pomocou logických členov. Taktiež bude rozumieť princípu činnosti a základným parametrom logických obvodov realizovaných pomocou spínačov, ako aj stavbe a vlastnostiam kombinačných a sekvenčných logických obvodov. Ako absolvent predmetu bude schopný modelovať, navrhnúť a analyzovať základné logické obvody.', 'point1': 'Booleovské funkcie. Booleovské výrazy a ich normálne formy. Formy zápisu logických funkcií. Minimalizácia booleovských výrazov. Primitívne a komplexné logické členy. Kombinačné logické obvody. Realizácia logických funkcií pomocou spínačov. Realizácia primitívnych a komplexných logických funkcií v technológii CMOS. Pamäťové elementy/preklápacie obvody. Konečné automaty. Časovanie sekvenčných obvodov. Synchrónne a asynchrónne sekvenčné obvody.' } };
'use strict'; const Partials = require('../../util/Partials'); /* ABOUT ACTIONS Actions are similar to WebSocket Packet Handlers, but since introducing the REST API methods, in order to prevent rewriting code to handle data, "actions" have been introduced. They're basically what Packet Handlers used to be but they're strictly for manipulating data and making sure that WebSocket events don't clash with REST methods. */ class GenericAction { constructor(client) { this.client = client; } handle(data) { return data; } getPayload(data, manager, id, partialType, cache) { const existing = manager.cache.get(id); if (!existing && this.client.options.partials.includes(partialType)) { return manager._add(data, cache); } return existing; } getChannel(data) { const id = data.channel_id ?? data.id; return ( data.channel ?? this.getPayload( { id, guild_id: data.guild_id, recipients: [data.author ?? data.user ?? { id: data.user_id }], }, this.client.channels, id, Partials.Channel, ) ); } getMessage(data, channel, cache) { const id = data.message_id ?? data.id; return ( data.message ?? this.getPayload( { id, channel_id: channel.id, guild_id: data.guild_id ?? channel.guild?.id, }, channel.messages, id, Partials.Message, cache, ) ); } getReaction(data, message, user) { const id = data.emoji.id ?? decodeURIComponent(data.emoji.name); return this.getPayload( { emoji: data.emoji, count: message.partial ? null : 0, me: user?.id === this.client.user.id, }, message.reactions, id, Partials.Reaction, ); } getMember(data, guild) { return this.getPayload(data, guild.members, data.user.id, Partials.GuildMember); } getUser(data) { const id = data.user_id; return data.user ?? this.getPayload({ id }, this.client.users, id, Partials.User); } getUserFromMember(data) { if (data.guild_id && data.member?.user) { const guild = this.client.guilds.cache.get(data.guild_id); if (guild) { return guild.members._add(data.member).user; } else { return this.client.users._add(data.member.user); } } return this.getUser(data); } getScheduledEvent(data, guild) { const id = data.guild_scheduled_event_id ?? data.id; return this.getPayload( { id, guild_id: data.guild_id ?? guild.id }, guild.scheduledEvents, id, Partials.GuildScheduledEvent, ); } } module.exports = GenericAction;
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("specialchar","da",{euro:"Euro-tegn",lsquo:"Venstre enkelt anførselstegn",rsquo:"Højre enkelt anførselstegn",ldquo:"Venstre dobbelt anførselstegn",rdquo:"Højre dobbelt anførselstegn",ndash:"Bindestreg",mdash:"Tankestreg",iexcl:"Omvendt udråbstegn",cent:"Cent-tegn",pound:"Pund-tegn",curren:"Kurs-tegn",yen:"Yen-tegn",brvbar:"Brudt streg",sect:"Paragraftegn",uml:"Umlaut",copy:"Copyright-tegn",ordf:"Feminin ordinal indikator",laquo:"Venstre dobbel citations-vinkel",not:"Negation", reg:"Registreret varemærke tegn",macr:"Macron",deg:"Grad-tegn",sup2:"Superscript to",sup3:"Superscript tre",acute:"Prim-tegn",micro:"Mikro-tegn",para:"Pilcrow-tegn",middot:"Punkt-tegn",cedil:"Cedille",sup1:"Superscript et",ordm:"Maskulin ordinal indikator",raquo:"Højre dobbel citations-vinkel",frac14:"En fjerdedel",frac12:"En halv",frac34:"En tredjedel",iquest:"Omvendt udråbstegn",Agrave:"Stort A med accent grave",Aacute:"Stort A med accent aigu",Acirc:"Stort A med cirkumfleks",Atilde:"Stort A med tilde", Auml:"Stort A med umlaut",Aring:"Stort Å",AElig:"Stort Æ",Ccedil:"Stort C med cedille",Egrave:"Stort E med accent grave",Eacute:"Stort E med accent aigu",Ecirc:"Stort E med cirkumfleks",Euml:"Stort E med umlaut",Igrave:"Stort I med accent grave",Iacute:"Stort I med accent aigu",Icirc:"Stort I med cirkumfleks",Iuml:"Stort I med umlaut",ETH:"Stort Ð (edd)",Ntilde:"Stort N med tilde",Ograve:"Stort O med accent grave",Oacute:"Stort O med accent aigu",Ocirc:"Stort O med cirkumfleks",Otilde:"Stort O med tilde", Ouml:"Stort O med umlaut",times:"Gange-tegn",Oslash:"Stort Ø",Ugrave:"Stort U med accent grave",Uacute:"Stort U med accent aigu",Ucirc:"Stort U med cirkumfleks",Uuml:"Stort U med umlaut",Yacute:"Stort Y med accent aigu",THORN:"Stort Thorn",szlig:"Lille eszett",agrave:"Lille a med accent grave",aacute:"Lille a med accent aigu",acirc:"Lille a med cirkumfleks",atilde:"Lille a med tilde",auml:"Lille a med umlaut",aring:"Lilla å",aelig:"Lille æ",ccedil:"Lille c med cedille",egrave:"Lille e med accent grave", eacute:"Lille e med accent aigu",ecirc:"Lille e med cirkumfleks",euml:"Lille e med umlaut",igrave:"Lille i med accent grave",iacute:"Lille i med accent aigu",icirc:"Lille i med cirkumfleks",iuml:"Lille i med umlaut",eth:"Lille ð (edd)",ntilde:"Lille n med tilde",ograve:"Lille o med accent grave",oacute:"Lille o med accent aigu",ocirc:"Lille o med cirkumfleks",otilde:"Lille o med tilde",ouml:"Lille o med umlaut",divide:"Divisions-tegn",oslash:"Lille ø",ugrave:"Lille u med accent grave",uacute:"Lille u med accent aigu", ucirc:"Lille u med cirkumfleks",uuml:"Lille u med umlaut",yacute:"Lille y med accent aigu",thorn:"Lille thorn",yuml:"Lille y med umlaut",OElig:"Stort Æ",oelig:"Lille æ",372:"Stort W med cirkumfleks",374:"Stort Y med cirkumfleks",373:"Lille w med cirkumfleks",375:"Lille y med cirkumfleks",sbquo:"Lavt enkelt 9-komma citationstegn",8219:"Højt enkelt 9-komma citationstegn",bdquo:"Dobbelt 9-komma citationstegn",hellip:"Tre horizontale prikker",trade:"Varemærke-tegn",9658:"Sort højre pil",bull:"Punkt", rarr:"Højre pil",rArr:"Højre dobbelt pil",hArr:"Venstre højre dobbelt pil",diams:"Sort diamant",asymp:"Næsten lig med"});
const assert = require('assert'); let User = require('../src/repository/User.js'); let TokenCRF = require('../src/middleware-CRF/crf-token.js'); const { request, response } = require('express'); let mailExiste = 'toto.toto@hotmail.fr'; let mailNotExiste = 'toto1.toto@hotmail.fr'; // let server = require('../server.js'); // .skip juste apres it va permettrer de zapper le test un peu comme un commentaire, si le test n'est pas totalement fini describe('TestMailExiste', function() { it('should test if mail existe', (done) => { (new User).get_user_by_email(mailExiste).then(value => { // console.log(value); assert.notStrictEqual(value, null); done(); }) }); it('should test not existe', (done) => { (new User).get_user_by_email(mailNotExiste).then(value => { // console.log(value); assert.strictEqual(value, null); done(); }) }); }); describe('Test du token', function() { it('should test if token existe', (done) => { let toto = TokenCRF.generate(request, response) console.log('response : ', toto); done(); }) // it('should test not existe', (done) => { // (new User).get_user_by_email(mailNotExiste).then(value => { // // console.log(value); // assert.strictEqual(value, null); // done(); // }) // }); });
// Copyright 2018-2021 Polyaxon, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * Polyaxon SDKs and REST API specification. * Polyaxon SDKs and REST API specification. * * The version of the OpenAPI document: 1.5.4 * Contact: contact@polyaxon.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.PolyaxonSdk); } }(this, function(expect, PolyaxonSdk) { 'use strict'; var instance; beforeEach(function() { instance = new PolyaxonSdk.V1ComponentHubSettings(); }); var getProperty = function(object, getter, property) { // Use getter method if present; otherwise, get the property directly. if (typeof object[getter] === 'function') return object[getter](); else return object[property]; } var setProperty = function(object, setter, property, value) { // Use setter method if present; otherwise, set the property directly. if (typeof object[setter] === 'function') object[setter](value); else object[property] = value; } describe('V1ComponentHubSettings', function() { it('should create an instance of V1ComponentHubSettings', function() { // uncomment below and update the code to test V1ComponentHubSettings //var instane = new PolyaxonSdk.V1ComponentHubSettings(); //expect(instance).to.be.a(PolyaxonSdk.V1ComponentHubSettings); }); it('should have the property teams (base name: "teams")', function() { // uncomment below and update the code to test the property teams //var instane = new PolyaxonSdk.V1ComponentHubSettings(); //expect(instance).to.be(); }); }); }));
define({ "showLegend": "Vis signaturforklaring", "controlPopupMenuTitle": "Vælg, hvilke handlinger der skal vises i lagets kontekstmenu", "zoomto": "Zoom til", "transparency": "Gennemsigtighed", "setVisibilityRange": "Indstil synlighedsinterval", "controlPopup": "Aktivér/Deaktivér pop-up", "moveUpAndDown": "Flyt op / Flyt ned", "attributeTable": "Vis i attributtabel", "url": "Beskrivelse/Vis elementoplysninger/Hent", "showHideLabels": "Vis/skjul etiketter", "expandAllLayers": "Vis alle lag", "expandAllLayersByDefault": "Vis alle lag som standard", "layerSelectorTitle": "Vælg, hvilke lag der skal vises på listen", "showTitle": "Vis titel", "showBasemap": "Vis baggrundskort" });
;(function(){ /** * Require the module at `name`. * * @param {String} name * @return {Object} exports * @api public */ function require(name) { var module = require.modules[name]; if (!module) throw new Error('failed to require "' + name + '"'); if (!('exports' in module) && typeof module.definition === 'function') { module.client = module.component = true; module.definition.call(this, module.exports = {}, module); delete module.definition; } return module.exports; } /** * Registered modules. */ require.modules = { moment: { exports: moment } }; /** * Register module at `name` with callback `definition`. * * @param {String} name * @param {Function} definition * @api private */ require.register = function (name, definition) { require.modules[name] = { definition: definition }; }; /** * Define a module's exports immediately with `exports`. * * @param {String} name * @param {Generic} exports * @api private */ require.define = function (name, exports) { require.modules[name] = { exports: exports }; }; require.register("jalaali-js", function (exports, module) { /* Expose functions. */ module.exports = { toJalaali: toJalaali , toGregorian: toGregorian , isValidJalaaliDate: isValidJalaaliDate , isLeapJalaaliYear: isLeapJalaaliYear , jalaaliMonthLength: jalaaliMonthLength , jalCal: jalCal , j2d: j2d , d2j: d2j , g2d: g2d , d2g: d2g } /* Converts a Gregorian date to Jalaali. */ function toJalaali(gy, gm, gd) { return d2j(g2d(gy, gm, gd)) } /* Converts a Jalaali date to Gregorian. */ function toGregorian(jy, jm, jd) { return d2g(j2d(jy, jm, jd)) } /* Checks whether a Jalaali date is valid or not. */ function isValidJalaaliDate(jy, jm, jd) { return jy >= -61 && jy <= 3177 && jm >= 1 && jm <= 12 && jd >= 1 && jd <= jalaaliMonthLength(jy, jm) } /* Is this a leap year or not? */ function isLeapJalaaliYear(jy) { return jalCal(jy).leap === 0 } /* Number of days in a given month in a Jalaali year. */ function jalaaliMonthLength(jy, jm) { if (jm <= 6) return 31 if (jm <= 11) return 30 if (isLeapJalaaliYear(jy)) return 30 return 29 } /* This function determines if the Jalaali (Persian) year is leap (366-day long) or is the common year (365 days), and finds the day in March (Gregorian calendar) of the first day of the Jalaali year (jy). @param jy Jalaali calendar year (-61 to 3177) @return leap: number of years since the last leap year (0 to 4) gy: Gregorian year of the beginning of Jalaali year march: the March day of Farvardin the 1st (1st day of jy) @see: http://www.astro.uni.torun.pl/~kb/Papers/EMP/PersianC-EMP.htm @see: http://www.fourmilab.ch/documents/calendar/ */ function jalCal(jy) { // Jalaali years starting the 33-year rule. var breaks = [ -61, 9, 38, 199, 426, 686, 756, 818, 1111, 1181, 1210 , 1635, 2060, 2097, 2192, 2262, 2324, 2394, 2456, 3178 ] , bl = breaks.length , gy = jy + 621 , leapJ = -14 , jp = breaks[0] , jm , jump , leap , leapG , march , n , i if (jy < jp || jy >= breaks[bl - 1]) throw new Error('Invalid Jalaali year ' + jy) // Find the limiting years for the Jalaali year jy. for (i = 1; i < bl; i += 1) { jm = breaks[i] jump = jm - jp if (jy < jm) break leapJ = leapJ + div(jump, 33) * 8 + div(mod(jump, 33), 4) jp = jm } n = jy - jp // Find the number of leap years from AD 621 to the beginning // of the current Jalaali year in the Persian calendar. leapJ = leapJ + div(n, 33) * 8 + div(mod(n, 33) + 3, 4) if (mod(jump, 33) === 4 && jump - n === 4) leapJ += 1 // And the same in the Gregorian calendar (until the year gy). leapG = div(gy, 4) - div((div(gy, 100) + 1) * 3, 4) - 150 // Determine the Gregorian date of Farvardin the 1st. march = 20 + leapJ - leapG // Find how many years have passed since the last leap year. if (jump - n < 6) n = n - jump + div(jump + 4, 33) * 33 leap = mod(mod(n + 1, 33) - 1, 4) if (leap === -1) { leap = 4 } return { leap: leap , gy: gy , march: march } } /* Converts a date of the Jalaali calendar to the Julian Day number. @param jy Jalaali year (1 to 3100) @param jm Jalaali month (1 to 12) @param jd Jalaali day (1 to 29/31) @return Julian Day number */ function j2d(jy, jm, jd) { var r = jalCal(jy) return g2d(r.gy, 3, r.march) + (jm - 1) * 31 - div(jm, 7) * (jm - 7) + jd - 1 } /* Converts the Julian Day number to a date in the Jalaali calendar. @param jdn Julian Day number @return jy: Jalaali year (1 to 3100) jm: Jalaali month (1 to 12) jd: Jalaali day (1 to 29/31) */ function d2j(jdn) { var gy = d2g(jdn).gy // Calculate Gregorian year (gy). , jy = gy - 621 , r = jalCal(jy) , jdn1f = g2d(gy, 3, r.march) , jd , jm , k // Find number of days that passed since 1 Farvardin. k = jdn - jdn1f if (k >= 0) { if (k <= 185) { // The first 6 months. jm = 1 + div(k, 31) jd = mod(k, 31) + 1 return { jy: jy , jm: jm , jd: jd } } else { // The remaining months. k -= 186 } } else { // Previous Jalaali year. jy -= 1 k += 179 if (r.leap === 1) k += 1 } jm = 7 + div(k, 30) jd = mod(k, 30) + 1 return { jy: jy , jm: jm , jd: jd } } /* Calculates the Julian Day number from Gregorian or Julian calendar dates. This integer number corresponds to the noon of the date (i.e. 12 hours of Universal Time). The procedure was tested to be good since 1 March, -100100 (of both calendars) up to a few million years into the future. @param gy Calendar year (years BC numbered 0, -1, -2, ...) @param gm Calendar month (1 to 12) @param gd Calendar day of the month (1 to 28/29/30/31) @return Julian Day number */ function g2d(gy, gm, gd) { var d = div((gy + div(gm - 8, 6) + 100100) * 1461, 4) + div(153 * mod(gm + 9, 12) + 2, 5) + gd - 34840408 d = d - div(div(gy + 100100 + div(gm - 8, 6), 100) * 3, 4) + 752 return d } /* Calculates Gregorian and Julian calendar dates from the Julian Day number (jdn) for the period since jdn=-34839655 (i.e. the year -100100 of both calendars) to some millions years ahead of the present. @param jdn Julian Day number @return gy: Calendar year (years BC numbered 0, -1, -2, ...) gm: Calendar month (1 to 12) gd: Calendar day of the month M (1 to 28/29/30/31) */ function d2g(jdn) { var j , i , gd , gm , gy j = 4 * jdn + 139361631 j = j + div(div(4 * jdn + 183187720, 146097) * 3, 4) * 4 - 3908 i = div(mod(j, 1461), 4) * 5 + 308 gd = div(mod(i, 153), 5) + 1 gm = mod(div(i, 153), 12) + 1 gy = div(j, 1461) - 100100 + div(8 - gm, 6) return { gy: gy , gm: gm , gd: gd } } /* Utility helper functions. */ function div(a, b) { return ~~(a / b) } function mod(a, b) { return a - ~~(a / b) * b } }) require.register("moment-jalaali", function (exports, module) { module.exports = jMoment var moment = require('moment') , jalaali = require('jalaali-js') /************************************ Constants ************************************/ var formattingTokens = /(\[[^\[]*\])|(\\)?j(Mo|MM?M?M?|Do|DDDo|DD?D?D?|w[o|w]?|YYYYY|YYYY|YY|gg(ggg?)?|)|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g , localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g , parseTokenOneOrTwoDigits = /\d\d?/ , parseTokenOneToThreeDigits = /\d{1,3}/ , parseTokenThreeDigits = /\d{3}/ , parseTokenFourDigits = /\d{1,4}/ , parseTokenSixDigits = /[+\-]?\d{1,6}/ , parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i , parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i , parseTokenT = /T/i , parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/ , unitAliases = { jm: 'jmonth' , jmonths: 'jmonth' , jy: 'jyear' , jyears: 'jyear' } , formatFunctions = {} , ordinalizeTokens = 'DDD w M D'.split(' ') , paddedTokens = 'M D w'.split(' ') , formatTokenFunctions = { jM: function () { return this.jMonth() + 1 } , jMMM: function (format) { return this.localeData().jMonthsShort(this, format) } , jMMMM: function (format) { return this.localeData().jMonths(this, format) } , jD: function () { return this.jDate() } , jDDD: function () { return this.jDayOfYear() } , jw: function () { return this.jWeek() } , jYY: function () { return leftZeroFill(this.jYear() % 100, 2) } , jYYYY: function () { return leftZeroFill(this.jYear(), 4) } , jYYYYY: function () { return leftZeroFill(this.jYear(), 5) } , jgg: function () { return leftZeroFill(this.jWeekYear() % 100, 2) } , jgggg: function () { return this.jWeekYear() } , jggggg: function () { return leftZeroFill(this.jWeekYear(), 5) } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count) } } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period) } } (function () { var i while (ordinalizeTokens.length) { i = ordinalizeTokens.pop() formatTokenFunctions['j' + i + 'o'] = ordinalizeToken(formatTokenFunctions['j' + i], i) } while (paddedTokens.length) { i = paddedTokens.pop() formatTokenFunctions['j' + i + i] = padToken(formatTokenFunctions['j' + i], 2) } formatTokenFunctions.jDDDD = padToken(formatTokenFunctions.jDDD, 3) }()) /************************************ Helpers ************************************/ function extend(a, b) { var key for (key in b) if (b.hasOwnProperty(key)) a[key] = b[key] return a } function leftZeroFill(number, targetLength) { var output = number + '' while (output.length < targetLength) output = '0' + output return output } function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]' } // function compareArrays(array1, array2) { // var len = Math.min(array1.length, array2.length) // , lengthDiff = Math.abs(array1.length - array2.length) // , diffs = 0 // , i // for (i = 0; i < len; i += 1) // if (~~array1[i] !== ~~array2[i]) // diffs += 1 // return diffs + lengthDiff // } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase() units = unitAliases[lowered] || lowered } return units } function setDate(m, year, month, date) { var d = m._d if (m._isUTC) { /*eslint-disable new-cap*/ m._d = new Date(Date.UTC(year, month, date, d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds())) /*eslint-enable new-cap*/ } else { m._d = new Date(year, month, date, d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()) } } function objectCreate(parent) { function F() {} F.prototype = parent return new F() } function getPrototypeOf(object) { if (Object.getPrototypeOf) return Object.getPrototypeOf(object) else if (''.__proto__) return object.__proto__ else return object.constructor.prototype } /************************************ Languages ************************************/ extend(getPrototypeOf(moment.localeData()), { _jMonths: [ 'Farvardin' , 'Ordibehesht' , 'Khordaad' , 'Tir' , 'Amordaad' , 'Shahrivar' , 'Mehr' , 'Aabaan' , 'Aazar' , 'Dey' , 'Bahman' , 'Esfand' ] , jMonths: function (m) { return this._jMonths[m.jMonth()] } , _jMonthsShort: [ 'Far' , 'Ord' , 'Kho' , 'Tir' , 'Amo' , 'Sha' , 'Meh' , 'Aab' , 'Aaz' , 'Dey' , 'Bah' , 'Esf' ] , jMonthsShort: function (m) { return this._jMonthsShort[m.jMonth()] } , jMonthsParse: function (monthName) { var i , mom , regex if (!this._jMonthsParse) this._jMonthsParse = [] for (i = 0; i < 12; i += 1) { // Make the regex if we don't have it already. if (!this._jMonthsParse[i]) { mom = jMoment([2000, (2 + i) % 12, 25]) regex = '^' + this.jMonths(mom, '') + '|^' + this.jMonthsShort(mom, '') this._jMonthsParse[i] = new RegExp(regex.replace('.', ''), 'i') } // Test the regex. if (this._jMonthsParse[i].test(monthName)) return i } } } ) /************************************ Formatting ************************************/ function makeFormatFunction(format) { var array = format.match(formattingTokens) , length = array.length , i for (i = 0; i < length; i += 1) if (formatTokenFunctions[array[i]]) array[i] = formatTokenFunctions[array[i]] return function (mom) { var output = '' for (i = 0; i < length; i += 1) output += array[i] instanceof Function ? '[' + array[i].call(mom, format) + ']' : array[i] return output } } /************************************ Parsing ************************************/ function getParseRegexForToken(token, config) { switch (token) { case 'jDDDD': return parseTokenThreeDigits case 'jYYYY': return parseTokenFourDigits case 'jYYYYY': return parseTokenSixDigits case 'jDDD': return parseTokenOneToThreeDigits case 'jMMM': case 'jMMMM': return parseTokenWord case 'jMM': case 'jDD': case 'jYY': case 'jM': case 'jD': return parseTokenOneOrTwoDigits case 'DDDD': return parseTokenThreeDigits case 'YYYY': return parseTokenFourDigits case 'YYYYY': return parseTokenSixDigits case 'S': case 'SS': case 'SSS': case 'DDD': return parseTokenOneToThreeDigits case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord case 'a': case 'A': return moment.localeData(config._l)._meridiemParse case 'X': return parseTokenTimestampMs case 'Z': case 'ZZ': return parseTokenTimezone case 'T': return parseTokenT case 'MM': case 'DD': case 'YY': case 'HH': case 'hh': case 'mm': case 'ss': case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': return parseTokenOneOrTwoDigits default: return new RegExp(token.replace('\\', '')) } } function addTimeToArrayFromToken(token, input, config) { var a , datePartArray = config._a switch (token) { case 'jM': case 'jMM': datePartArray[1] = input == null ? 0 : ~~input - 1 break case 'jMMM': case 'jMMMM': a = moment.localeData(config._l).jMonthsParse(input) if (a != null) datePartArray[1] = a else config._isValid = false break case 'jD': case 'jDD': case 'jDDD': case 'jDDDD': if (input != null) datePartArray[2] = ~~input break case 'jYY': datePartArray[0] = ~~input + (~~input > 47 ? 1300 : 1400) break case 'jYYYY': case 'jYYYYY': datePartArray[0] = ~~input } if (input == null) config._isValid = false } function dateFromArray(config) { var g , j , jy = config._a[0] , jm = config._a[1] , jd = config._a[2] if ((jy == null) && (jm == null) && (jd == null)) return [0, 0, 1] jy = jy != null ? jy : 0 jm = jm != null ? jm : 0 jd = jd != null ? jd : 1 if (jd < 1 || jd > jMoment.jDaysInMonth(jy, jm) || jm < 0 || jm > 11) config._isValid = false g = toGregorian(jy, jm, jd) j = toJalaali(g.gy, g.gm, g.gd) config._jDiff = 0 if (~~j.jy !== jy) config._jDiff += 1 if (~~j.jm !== jm) config._jDiff += 1 if (~~j.jd !== jd) config._jDiff += 1 return [g.gy, g.gm, g.gd] } function makeDateFromStringAndFormat(config) { var tokens = config._f.match(formattingTokens) , string = config._i + '' , len = tokens.length , i , token , parsedInput config._a = [] for (i = 0; i < len; i += 1) { token = tokens[i] parsedInput = (getParseRegexForToken(token, config).exec(string) || [])[0] if (parsedInput) string = string.slice(string.indexOf(parsedInput) + parsedInput.length) if (formatTokenFunctions[token]) addTimeToArrayFromToken(token, parsedInput, config) } if (string) config._il = string return dateFromArray(config) } function makeDateFromStringAndArray(config, utc) { var len = config._f.length , i , format , tempMoment , bestMoment , currentScore , scoreToBeat if (len === 0) { return makeMoment(new Date(NaN)) } for (i = 0; i < len; i += 1) { format = config._f[i] currentScore = 0 tempMoment = makeMoment(config._i, format, config._l, config._strict, utc) if (!tempMoment.isValid()) continue // currentScore = compareArrays(tempMoment._a, tempMoment.toArray()) currentScore += tempMoment._jDiff if (tempMoment._il) currentScore += tempMoment._il.length if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore bestMoment = tempMoment } } return bestMoment } function removeParsedTokens(config) { var string = config._i + '' , input = '' , format = '' , array = config._f.match(formattingTokens) , len = array.length , i , match , parsed for (i = 0; i < len; i += 1) { match = array[i] parsed = (getParseRegexForToken(match, config).exec(string) || [])[0] if (parsed) string = string.slice(string.indexOf(parsed) + parsed.length) if (!(formatTokenFunctions[match] instanceof Function)) { format += match if (parsed) input += parsed } } config._i = input config._f = format } /************************************ Week of Year ************************************/ function jWeekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek , daysToDayOfWeek = firstDayOfWeekOfYear - mom.day() , adjustedMoment if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7 } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7 } adjustedMoment = jMoment(mom).add(daysToDayOfWeek, 'd') return { week: Math.ceil(adjustedMoment.jDayOfYear() / 7) , year: adjustedMoment.jYear() } } /************************************ Top Level Functions ************************************/ function makeMoment(input, format, lang, strict, utc) { if (typeof lang === 'boolean') { utc = strict strict = lang lang = undefined } var config = { _i: input , _f: format , _l: lang , _strict: strict , _isUTC: utc } , date , m , jm , origInput = input , origFormat = format if (format) { if (isArray(format)) { return makeDateFromStringAndArray(config, utc) } else { date = makeDateFromStringAndFormat(config) removeParsedTokens(config) format = 'YYYY-MM-DD-' + config._f input = leftZeroFill(date[0], 4) + '-' + leftZeroFill(date[1] + 1, 2) + '-' + leftZeroFill(date[2], 2) + '-' + config._i } } if (utc) m = moment.utc(input, format, lang, strict) else m = moment(input, format, lang, strict) if (config._isValid === false) m._isValid = false m._jDiff = config._jDiff || 0 jm = objectCreate(jMoment.fn) extend(jm, m) if (strict && jm.isValid()) { jm._isValid = jm.format(origFormat) === origInput } return jm } function jMoment(input, format, lang, strict) { return makeMoment(input, format, lang, strict, false) } extend(jMoment, moment) jMoment.fn = objectCreate(moment.fn) jMoment.utc = function (input, format, lang, strict) { return makeMoment(input, format, lang, strict, true) } jMoment.unix = function (input) { return makeMoment(input * 1000) } /************************************ jMoment Prototype ************************************/ jMoment.fn.format = function (format) { var i , replace , me = this if (format) { i = 5 replace = function (input) { return me.localeData().longDateFormat(input) || input } while (i > 0 && localFormattingTokens.test(format)) { i -= 1 format = format.replace(localFormattingTokens, replace) } if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format) } format = formatFunctions[format](this) } return moment.fn.format.call(this, format) } jMoment.fn.jYear = function (input) { var lastDay , j , g if (typeof input === 'number') { j = toJalaali(this.year(), this.month(), this.date()) lastDay = Math.min(j.jd, jMoment.jDaysInMonth(input, j.jm)) g = toGregorian(input, j.jm, lastDay) setDate(this, g.gy, g.gm, g.gd) moment.updateOffset(this) return this } else { return toJalaali(this.year(), this.month(), this.date()).jy } } jMoment.fn.jMonth = function (input) { var lastDay , j , g if (input != null) { if (typeof input === 'string') { input = this.lang().jMonthsParse(input) if (typeof input !== 'number') return this } j = toJalaali(this.year(), this.month(), this.date()) lastDay = Math.min(j.jd, jMoment.jDaysInMonth(j.jy, input)) this.jYear(j.jy + div(input, 12)) input = mod(input, 12) if (input < 0) { input += 12 this.jYear(this.jYear() - 1) } g = toGregorian(this.jYear(), input, lastDay) setDate(this, g.gy, g.gm, g.gd) moment.updateOffset(this) return this } else { return toJalaali(this.year(), this.month(), this.date()).jm } } jMoment.fn.jDate = function (input) { var j , g if (typeof input === 'number') { j = toJalaali(this.year(), this.month(), this.date()) g = toGregorian(j.jy, j.jm, input) setDate(this, g.gy, g.gm, g.gd) moment.updateOffset(this) return this } else { return toJalaali(this.year(), this.month(), this.date()).jd } } jMoment.fn.jDayOfYear = function (input) { var dayOfYear = Math.round((jMoment(this).startOf('day') - jMoment(this).startOf('jYear')) / 864e5) + 1 return input == null ? dayOfYear : this.add(input - dayOfYear, 'd') } jMoment.fn.jWeek = function (input) { var week = jWeekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).week return input == null ? week : this.add((input - week) * 7, 'd') } jMoment.fn.jWeekYear = function (input) { var year = jWeekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year return input == null ? year : this.add(input - year, 'y') } jMoment.fn.add = function (val, units) { var temp if (units !== null && !isNaN(+units)) { temp = val val = units units = temp } units = normalizeUnits(units) if (units === 'jyear') { this.jYear(this.jYear() + val) } else if (units === 'jmonth') { this.jMonth(this.jMonth() + val) } else { moment.fn.add.call(this, val, units) } return this } jMoment.fn.subtract = function (val, units) { var temp if (units !== null && !isNaN(+units)) { temp = val val = units units = temp } units = normalizeUnits(units) if (units === 'jyear') { this.jYear(this.jYear() - val) } else if (units === 'jmonth') { this.jMonth(this.jMonth() - val) } else { moment.fn.subtract.call(this, val, units) } return this } jMoment.fn.startOf = function (units) { units = normalizeUnits(units) if (units === 'jyear' || units === 'jmonth') { if (units === 'jyear') { this.jMonth(0) } this.jDate(1) this.hours(0) this.minutes(0) this.seconds(0) this.milliseconds(0) return this } else { return moment.fn.startOf.call(this, units) } } jMoment.fn.endOf = function (units) { units = normalizeUnits(units) if (units === undefined || units === 'milisecond') { return this } return this.startOf(units).add(1, (units === 'isoweek' ? 'week' : units)).subtract(1, 'ms') } jMoment.fn.isSame = function (other, units) { units = normalizeUnits(units) if (units === 'jyear' || units === 'jmonth') { return moment.fn.isSame.call(this.startOf(units), other.startOf(units)) } return moment.fn.isSame.call(this, other, units) } jMoment.fn.clone = function () { return jMoment(this) } jMoment.fn.jYears = jMoment.fn.jYear jMoment.fn.jMonths = jMoment.fn.jMonth jMoment.fn.jDates = jMoment.fn.jDate jMoment.fn.jWeeks = jMoment.fn.jWeek /************************************ jMoment Statics ************************************/ jMoment.jDaysInMonth = function (year, month) { year += div(month, 12) month = mod(month, 12) if (month < 0) { month += 12 year -= 1 } if (month < 6) { return 31 } else if (month < 11) { return 30 } else if (jMoment.jIsLeapYear(year)) { return 30 } else { return 29 } } jMoment.jIsLeapYear = jalaali.isLeapJalaaliYear jMoment.loadPersian = function () { moment.locale('fa', null) moment.defineLocale('fa' , { months: ('ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر').split('_') , monthsShort: ('ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر').split('_') , weekdays: ('یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_آدینه_شنبه').split('_') , weekdaysShort: ('یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_آدینه_شنبه').split('_') , weekdaysMin: 'ی_د_س_چ_پ_آ_ش'.split('_') , longDateFormat: { LT: 'HH:mm' , L: 'jYYYY/jMM/jDD' , LL: 'jD jMMMM jYYYY' , LLL: 'jD jMMMM jYYYY LT' , LLLL: 'dddd، jD jMMMM jYYYY LT' } , calendar: { sameDay: '[امروز ساعت] LT' , nextDay: '[فردا ساعت] LT' , nextWeek: 'dddd [ساعت] LT' , lastDay: '[دیروز ساعت] LT' , lastWeek: 'dddd [ی پیش ساعت] LT' , sameElse: 'L' } , relativeTime: { future: 'در %s' , past: '%s پیش' , s: 'چند ثانیه' , m: '1 دقیقه' , mm: '%d دقیقه' , h: '1 ساعت' , hh: '%d ساعت' , d: '1 روز' , dd: '%d روز' , M: '1 ماه' , MM: '%d ماه' , y: '1 سال' , yy: '%d سال' } , ordinal: '%dم' , week: { dow: 6 // Saturday is the first day of the week. , doy: 12 // The week that contains Jan 1st is the first week of the year. } , meridiem: function (hour) { return hour < 12 ? 'ق.ظ' : 'ب.ظ' } , jMonths: ('فروردین_اردیبهشت_خرداد_تیر_امرداد_شهریور_مهر_آبان_آذر_دی_بهمن_اسفند').split('_') , jMonthsShort: 'فرو_ارد_خرد_تیر_امر_شهر_مهر_آبا_آذر_دی_بهم_اسف'.split('_') } ) } jMoment.jConvert = { toJalaali: toJalaali , toGregorian: toGregorian } /************************************ Jalaali Conversion ************************************/ function toJalaali(gy, gm, gd) { var j = jalaali.toJalaali(gy, gm + 1, gd) j.jm -= 1 return j } function toGregorian(jy, jm, jd) { var g = jalaali.toGregorian(jy, jm + 1, jd) g.gm -= 1 return g } /* Utility helper functions. */ function div(a, b) { return ~~(a / b) } function mod(a, b) { return a - ~~(a / b) * b } }); if (typeof exports == "object") { module.exports = require("moment-jalaali"); } else if (typeof define == "function" && define.amd) { define([], function(){ return require("moment-jalaali"); }); } else { this["moment"] = require("moment-jalaali"); } })();
(function () { 'use strict'; angular .module('articles') .run(menuConfig) .constant('appInformation', { view: '/home' }); menuConfig.$inject = ['sideNavs']; function menuConfig(sideNavs) { /* * Globals vars */ var _app = { title: 'Articles', version: '1.0.0', view: 'home', // app view state: 'articles.list', // link route icon: 'fa-newspaper-o', // https://fortawesome.github.io/Font-Awesome/ color: '#3e454e', // https://flatuicolors.com/ (sideNav) fontColor: '#fff', // https://flatuicolors.com/ (sideNav) position: 1, // default 1 roles: ['*', 'user', 'admin'] }; sideNavs.addSideNavItem('sidebar', { title: _app.title, icon: _app.icon, color: _app.color, fontColor: _app.fontColor, state: _app.state, view: _app.view, roles: _app.roles, position: _app.position }); } }());
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M14 14.13c0 .23.09.46.26.63l4.98 4.98c.17.17.39.26.62.26.79 0 1.18-.95.62-1.51l-4.98-4.98c-.55-.56-1.5-.16-1.5.62zM15 20h2l-3-3v2c0 .55.45 1 1 1zM7.65 4.35l-4.8 4.8c-.31.31-.09.85.36.85H4v9c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-9h.79c.45 0 .67-.54.35-.85l-4.79-4.8c-.19-.19-.51-.19-.7 0zM9 14H7v-4h2v4z" }), 'WbShadeRounded'); exports.default = _default;
/** * External dependencies */ import map from 'lodash/map'; /** * WordPress dependencies */ const { __ } = wp.i18n; const { Component } = wp.element; const { compose, ifCondition } = wp.compose; const { withSelect } = wp.data; const { RichTextToolbarButton } = wp.blockEditor; const { removeFormat } = wp.richText; class ClearFormatting extends Component { render() { const { value, isActive, onChange, formatTypes, } = this.props; const onToggle = () => { if ( formatTypes.length > 0 ) { let newValue = value; map( formatTypes, ( activeFormat ) => { newValue = removeFormat( newValue, activeFormat.name ); } ); onChange( { ...newValue } ); } }; return ( <RichTextToolbarButton icon="editor-removeformatting" title={ __( 'Clear Formatting', 'block-options' ) } onClick={ onToggle } isActive={ isActive } /> ); } } export default compose( withSelect( ( select ) => { return { isDisabled: select( 'core/edit-post' ).isFeatureActive( 'disableEditorsKitClearFormattingFormats' ), formatTypes: select( 'core/rich-text' ).getFormatTypes(), }; } ), ifCondition( ( props ) => { return ! props.isDisabled; } ) )( ClearFormatting );
import React, { Component } from "react"; import { getTotals } from "./graphql"; import { Query } from "react-apollo"; import Totals from "./Totals"; export default class TotalsContainer extends Component { render() { const defaultTotals = [ { type: "performances", total: 0 }, { type: "viewers", total: 0 }, { type: "votes", total: 0 }, { type: "reactions", total: 0 } ]; return ( <Query query={getTotals} fetchPolicy={"network-only"}> {({ loading, error, data }) => { if (error) { console.log(error); return null; } const { getTotals } = data; return <Totals totals={loading ? defaultTotals : getTotals} />; }} </Query> ); } }
import React from 'react'; import './Placeholder.css'; class Placeholder extends React.PureComponent { render() { let { children } = this.props; if (children == null || children.length === 0) { children = 'No content'; } return ( <div className="placeholder"> <div>{children}</div> </div> ); } } export default Placeholder;
import Controller from "@ember/controller"; export default class extends Controller { popup_message = "A message to popup"; }
const withImages = require('next-images'); const ESLintPlugin = require('eslint-webpack-plugin'); module.exports = withImages({ TrailingSlash: true, images: { disableStaticImages: true }, exportPathMap: function() { return { '/': { page: '/' } }; }, publicRuntimeConfig: { localeSubpaths: typeof process.env.LOCALE_SUBPATHS === 'string' ? process.env.LOCALE_SUBPATHS : 'none', }, webpack: (config, options) => { cssModules: true, config.plugins.push( // new ESLintPlugin({ // exclude: ['node_modules'] // }) ); config.node = {} return config; }, });
import React from "react"; import theme from "theme"; import { Theme, Link, Text, Icon, Box } from "@quarkly/widgets"; import { Helmet } from "react-helmet"; import { GlobalQuarklyPageStyles } from "global-page-styles"; import { Override, StackItem, Stack, Section } from "@quarkly/components"; import * as Components from "components"; import { MdHelp } from "react-icons/md"; export default (() => { return <Theme theme={theme}> <GlobalQuarklyPageStyles pageUrl={"pdf-viewer"} /> <Helmet> <title> Quarkly export </title> <meta name={"description"} content={"Web site created using quarkly.io"} /> <link rel={"shortcut icon"} href={"https://uploads.quarkly.io/readme/cra/favicon-32x32.ico"} type={"image/x-icon"} /> </Helmet> <Section background="--color-darkL2" padding="64px 0" sm-padding="40px 0"> <Stack> <StackItem width="50%" lg-width="100%"> <Override slot="StackItemContent" margin-right="-20%" padding-bottom="120%" background="url(https://images.unsplash.com/photo-1552374196-c4e7ffc6e126?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80) 50% 15%/cover" lg-margin-right="0" lg-padding-bottom="80%" /> </StackItem> <StackItem width="50%" lg-width="100%"> <Override slot="StackItemContent" padding="98px 64px" margin-left="-20%" margin-top="36px" background="--color-red" color="--light" mix-blend-mode="lighten" lg-margin-left="0" lg-margin-top="0" flex-direction="column" /> <Text as="h4" margin="0" font="--base" letter-spacing="1px" text-transform="uppercase" > About me </Text> <Text as="h1" margin="0 0 16px 0" font="--headline1" lg-font="--headline2"> Hey I’m David </Text> <Text as="p" margin="16px 0" font="--base" max-width="400px"> My name is David R. Moore, born and raised in France, worked as a professional photographer and videographer for more than 10 years, awarded the CDS Documentary Essay Prize in 2018 and Best Photographer of The Year 2019 by Sony World Photography Awards. </Text> </StackItem> </Stack> </Section> <Components.PdfViewer rotatePDFProp="270" text-align="center" scaleProp="2" /> <Section color="--dark"> <Text as="h2" font="--headline1" md-font="--headline2" margin="20px 0 0 0"> Q&A </Text> <Box margin="36px 0 0 0" padding="0 0 0 54px" sm-padding="54px 0 0 0" position="relative" max-width="800px" > <Icon position="absolute" top="0" left="0" size="36px" color="--primary" category="md" icon={MdHelp} /> <Text as="h3" font="--headline3" margin="10px 0"> Is there life on Mars? </Text> <Text as="p" font="--lead" margin="10px 0" color="--greyD2"> It all begins with an idea. Maybe you want to launch a business. Maybe you want to turn a hobby into something more. Or maybe you have a creative project to share with the world. Whatever it is, the way you tell your story online can make all the difference. </Text> </Box> <Box margin="36px 0 0 0" padding="0 0 0 54px" sm-padding="54px 0 0 0" position="relative" max-width="800px" > <Icon position="absolute" top="0" left="0" size="36px" color="--primary" category="md" icon={MdHelp} /> <Text as="h3" font="--headline3" margin="10px 0"> How much salt is in the ocean? </Text> <Text as="p" font="--lead" margin="10px 0" color="--greyD2"> It all begins with an idea. Maybe you want to launch a business. Maybe you want to turn a hobby into something more. Or maybe you have a creative project to share with the world. Whatever it is, the way you tell your story online can make all the difference. </Text> </Box> <Box margin="36px 0" padding="0 0 0 54px" sm-padding="54px 0 0 0" position="relative" max-width="800px" > <Icon position="absolute" top="0" left="0" size="36px" color="--primary" category="md" icon={MdHelp} /> <Text as="h3" font="--headline3" margin="10px 0"> Why is the sky blue? </Text> <Text as="p" font="--lead" margin="10px 0" color="--greyD2"> It all begins with an idea. Maybe you want to launch a business. Maybe you want to turn a hobby into something more. Or maybe you have a creative project to share with the world. Whatever it is, the way you tell your story online can make all the difference. </Text> </Box> </Section> <Link font={"--capture"} font-size={"10px"} position={"fixed"} bottom={"12px"} right={"12px"} z-index={"4"} border-radius={"4px"} padding={"5px 12px 4px"} background-color={"--dark"} opacity={"0.6"} hover-opacity={"1"} color={"--light"} cursor={"pointer"} transition={"--opacityOut"} quarkly-title={"Badge"} text-decoration-line={"initial"} href={"https://quarkly.io/"} target={"_blank"} > Made on Quarkly </Link> </Theme>; });
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M20 19h-1V5c0-.55-.45-1-1-1h-4c0-.55-.45-1-1-1H6c-.55 0-1 .45-1 1v15H4c-.55 0-1 .45-1 1s.45 1 1 1h9c.55 0 1-.45 1-1V6h3v14c0 .55.45 1 1 1h2c.55 0 1-.45 1-1s-.45-1-1-1zm-9-6c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" }), 'MeetingRoomRounded');
const figlet = require('figlet'); const readline = require('readline'); const rl = readline.createInterface({ input:process.stdin, output:process.stdout }); rl.on('line',(input)=>{if (input=='quit'){ rl.close() }else{figlet(input, function(err, data){ if(err){ console.log(err); return; } console.log(data) }); } });
const inquirer = require("inquirer"); class InquirerFunctions { constructor(type, name, message, choices) { this.type = type; this.name = name; this.message = message; this.choices = choices; } ask() { const askObJ = { type: this.type, name: this.name, message: this.message } if (this.choices === "undefined") { return askObJ } else { askObJ.choices = this.choices; return askObJ; } } } module.exports = InquirerFunctions;
OC.L10N.register( "settings", { "Authentication error" : "Нотолгооны алдаа", "Your full name has been changed." : "Таны бүтэн нэр солигдлоо.", "Unable to change full name" : "Бүтэн нэр солих боломжгүй байна", "Delete" : "Устгах", "Share" : "Түгээх", "Language changed" : "Хэл солигдлоо", "Invalid request" : "Буруу хүсэлт", "Admins can't remove themself from the admin group" : "Админууд өөрсдийгөө Админ бүлгээс хасаж чадахгүй", "Couldn't remove app." : "Апп-ыг устгаж чадсангүй", "All" : "Бүгд", "Cron" : "Крон", "Sharing" : "Түгээлт", "Save" : "Хадгалах", "Log" : "Лог бичилт", "Cancel" : "Цуцлах", "Email" : "И-мэйл", "Password" : "Нууц үг", "Username" : "Хэрэглэгчийн нэр", "Done" : "Болсон", "Settings" : "Тохиргоо", "Group" : "Грүпп" }, "nplurals=2; plural=(n != 1);");
/* Flot plugin for selecting regions of a plot. Copyright (c) 2007-2014 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: selection: { mode: null or "x" or "y" or "xy", color: color, shape: "round" or "miter" or "bevel", minSize: number of falcons } Selection support is enabled by setting the mode to one of "x", "y" or "xy". In "x" mode, the user will only be able to specify the x range, similarly for "y" mode. For "xy", the selection becomes a rectangle where both ranges can be specified. "color" is color of the selection (if you need to change the color later on, you can get to it with plot.getOptions().selection.color). "shape" is the shape of the corners of the selection. "minSize" is the minimum size a selection can be in falcons. This value can be customized to determine the smallest size a selection can be and still have the selection rectangle be displayed. When customizing this value, the fact that it refers to falcons, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 falcon. Note also that setting "minSize" to 0 will prevent "plotunselected" events from being fired when the user clicks the mouse without dragging. When selection support is enabled, a "plotselected" event will be emitted on the DOM element you passed into the plot function. The event handler gets a parameter with the ranges selected on the axes, like this: placeholder.bind( "plotselected", function( event, ranges ) { alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to) // similar for yaxis - with multiple axes, the extra ones are in // x2axis, x3axis, ... }); The "plotselected" event is only fired when the user has finished making the selection. A "plotselecting" event is fired during the process with the same parameters as the "plotselected" event, in case you want to know what's happening while it's happening, A "plotunselected" event with no arguments is emitted when the user clicks the mouse to remove the selection. As stated above, setting "minSize" to 0 will destroy this behavior. The plugin allso adds the following methods to the plot object: - setSelection( ranges, preventEvent ) Set the selection rectangle. The passed in ranges is on the same form as returned in the "plotselected" event. If the selection mode is "x", you should put in either an xaxis range, if the mode is "y" you need to put in an yaxis range and both xaxis and yaxis if the selection mode is "xy", like this: setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } }); setSelection will trigger the "plotselected" event when called. If you don't want that to happen, e.g. if you're inside a "plotselected" handler, pass true as the second parameter. If you are using multiple axes, you can specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of xaxis, the plugin picks the first one it sees. - clearSelection( preventEvent ) Clear the selection rectangle. Pass in true to avoid getting a "plotunselected" event. - getSelection() Returns the current selection in the same format as the "plotselected" event. If there's currently no selection, the function returns null. */ (function ($) { function init(plot) { var selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1}, show: false, active: false }; // FIXME: The drag handling implemented here should be // abstracted out, there's some similar code from a library in // the navigation plugin, this should be massaged a bit to fit // the Flot cases here better and reused. Doing this would // make this plugin much slimmer. var savedhandlers = {}; var mouseUpHandler = null; function onMouseMove(e) { if (selection.active) { updateSelection(e); plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]); } } function onMouseDown(e) { if (e.which != 1) // only accept left-click return; // cancel out any text selections document.body.focus(); // prevent text selection and drag in old-school browsers if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) { savedhandlers.onselectstart = document.onselectstart; document.onselectstart = function () { return false; }; } if (document.ondrag !== undefined && savedhandlers.ondrag == null) { savedhandlers.ondrag = document.ondrag; document.ondrag = function () { return false; }; } setSelectionPos(selection.first, e); selection.active = true; // this is a bit silly, but we have to use a closure to be // able to whack the same handler again mouseUpHandler = function (e) { onMouseUp(e); }; $(document).one("mouseup", mouseUpHandler); } function onMouseUp(e) { mouseUpHandler = null; // revert drag stuff for old-school browsers if (document.onselectstart !== undefined) document.onselectstart = savedhandlers.onselectstart; if (document.ondrag !== undefined) document.ondrag = savedhandlers.ondrag; // no more dragging selection.active = false; updateSelection(e); if (selectionIsSane()) triggerSelectedEvent(); else { // this counts as a clear plot.getPlaceholder().trigger("plotunselected", [ ]); plot.getPlaceholder().trigger("plotselecting", [ null ]); } return false; } function getSelection() { if (!selectionIsSane()) return null; if (!selection.show) return null; var r = {}, c1 = selection.first, c2 = selection.second; $.each(plot.getAxes(), function (name, axis) { if (axis.used) { var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) }; } }); return r; } function triggerSelectedEvent() { var r = getSelection(); plot.getPlaceholder().trigger("plotselected", [ r ]); // backwards-compat stuff, to be removed in future if (r.xaxis && r.yaxis) plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); } function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } function setSelectionPos(pos, e) { var o = plot.getOptions(); var offset = plot.getPlaceholder().offset(); var plotOffset = plot.getPlotOffset(); pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width()); pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height()); if (o.selection.mode == "y") pos.x = pos == selection.first ? 0 : plot.width(); if (o.selection.mode == "x") pos.y = pos == selection.first ? 0 : plot.height(); } function updateSelection(pos) { if (pos.pageX == null) return; setSelectionPos(selection.second, pos); if (selectionIsSane()) { selection.show = true; plot.triggerRedrawOverlay(); } else clearSelection(true); } function clearSelection(preventEvent) { if (selection.show) { selection.show = false; plot.triggerRedrawOverlay(); if (!preventEvent) plot.getPlaceholder().trigger("plotunselected", [ ]); } } // function taken from markings support in Flot function extractRange(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function setSelection(ranges, preventEvent) { var axis, range, o = plot.getOptions(); if (o.selection.mode == "y") { selection.first.x = 0; selection.second.x = plot.width(); } else { range = extractRange(ranges, "x"); selection.first.x = range.axis.p2c(range.from); selection.second.x = range.axis.p2c(range.to); } if (o.selection.mode == "x") { selection.first.y = 0; selection.second.y = plot.height(); } else { range = extractRange(ranges, "y"); selection.first.y = range.axis.p2c(range.from); selection.second.y = range.axis.p2c(range.to); } selection.show = true; plot.triggerRedrawOverlay(); if (!preventEvent && selectionIsSane()) triggerSelectedEvent(); } function selectionIsSane() { var minSize = plot.getOptions().selection.minSize; return Math.abs(selection.second.x - selection.first.x) >= minSize && Math.abs(selection.second.y - selection.first.y) >= minSize; } plot.clearSelection = clearSelection; plot.setSelection = setSelection; plot.getSelection = getSelection; plot.hooks.bindEvents.push(function(plot, eventHolder) { var o = plot.getOptions(); if (o.selection.mode != null) { eventHolder.mousemove(onMouseMove); eventHolder.mousedown(onMouseDown); } }); plot.hooks.drawOverlay.push(function (plot, ctx) { // draw selection if (selection.show && selectionIsSane()) { var plotOffset = plot.getPlotOffset(); var o = plot.getOptions(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var c = $.color.parse(o.selection.color); ctx.strokeStyle = c.scale('a', 0.8).toString(); ctx.lineWidth = 1; ctx.lineJoin = o.selection.shape; ctx.fillStyle = c.scale('a', 0.4).toString(); var x = Math.min(selection.first.x, selection.second.x) + 0.5, y = Math.min(selection.first.y, selection.second.y) + 0.5, w = Math.abs(selection.second.x - selection.first.x) - 1, h = Math.abs(selection.second.y - selection.first.y) - 1; ctx.fillRect(x, y, w, h); ctx.strokeRect(x, y, w, h); ctx.restore(); } }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mousedown", onMouseDown); if (mouseUpHandler) $(document).unbind("mouseup", mouseUpHandler); }); } $.plot.plugins.push({ init: init, options: { selection: { mode: null, // one of null, "x", "y" or "xy" color: "#e8cfac", shape: "round", // one of "round", "miter", or "bevel" minSize: 5 // minimum number of falcons } }, name: 'selection', version: '1.1' }); })(jQuery);
/*! highlight.js v9.5.0 | BSD3 License | git.io/hljslicense */ !function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/[&<>]/gm,function(e){return I[e]})}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=B.exec(o))return R(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||R(i))return i}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset<r[0].offset?e:r:"start"===r[0].event?e:r:e.length?e:r}function o(e){function r(e){return" "+e.nodeName+'="'+n(e.value)+'"'}l+="<"+t(e)+w.map.call(e.attributes,r).join("")+">"}function u(e){l+="</"+t(e)+">"}function c(e){("start"===e.event?o:u)(e.node)}for(var s=0,l="",f=[];e.length||r.length;){var g=i();if(l+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g===e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===s);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return l+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):E(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"===e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var l=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=l.length?t(l.join("|"),!0):{exec:function(){return null}}}}r(e)}function l(e,t,a,i){function o(e,n){for(var t=0;t<n.c.length;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function g(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function h(e,n,t,r){var a=r?"":y.classPrefix,i='<span class="'+a,o=t?"":C;return i+=e+'">',i+n+o}function p(){var e,t,r,a;if(!E.k)return n(B);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(B);r;)a+=n(B.substr(t,r.index-t)),e=g(E,r),e?(M+=e[1],a+=h(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(B);return a+n(B.substr(t))}function d(){var e="string"==typeof E.sL;if(e&&!x[E.sL])return n(B);var t=e?l(E.sL,B,!0,L[E.sL]):f(B,E.sL.length?E.sL:void 0);return E.r>0&&(M+=t.r),e&&(L[E.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){k+=null!=E.sL?d():p(),B=""}function v(e){k+=e.cN?h(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function m(e,n){if(B+=e,null==n)return b(),0;var t=o(n,E);if(t)return t.skip?B+=n:(t.eB&&(B+=n),b(),t.rB||t.eB||(B=n)),v(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?B+=n:(a.rE||a.eE||(B+=n),b(),a.eE&&(B=n));do E.cN&&(k+=C),E.skip||(M+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"<unnamed>")+'"');return B+=n,n.length||1}var N=R(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var w,E=i||N,L={},k="";for(w=E;w!==N;w=w.parent)w.cN&&(k=h(w.cN,"",!0)+k);var B="",M=0;try{for(var I,j,O=0;;){if(E.t.lastIndex=O,I=E.t.exec(t),!I)break;j=m(t.substr(O,I.index-O),I[0]),O=I.index+j}for(m(t.substr(O)),w=E;w.parent;w=w.parent)w.cN&&(k+=C);return{r:M,value:k,language:e,top:E}}catch(T){if(T.message&&-1!==T.message.indexOf("Illegal"))return{r:0,value:n(t)};throw T}}function f(e,t){t=t||y.languages||E(x);var r={r:0,value:n(e)},a=r;return t.filter(R).forEach(function(n){var t=l(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function g(e){return y.tabReplace||y.useBR?e.replace(M,function(e,n){return y.useBR&&"\n"===e?"<br>":y.tabReplace?n.replace(/\t/g,y.tabReplace):void 0}):e}function h(e,n,t){var r=n?L[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n,t,r,o,s,p=i(e);a(p)||(y.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(/<br[ \/]*>/g,"\n")):n=e,s=n.textContent,r=p?l(p,s,!0):f(s),t=u(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=c(t,u(o),s)),r.value=g(r.value),e.innerHTML=r.value,e.className=h(e.className,p,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function d(e){y=o(y,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");w.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=x[n]=t(e);r.aliases&&r.aliases.forEach(function(e){L[e]=n})}function N(){return E(x)}function R(e){return e=(e||"").toLowerCase(),x[e]||x[L[e]]}var w=[],E=Object.keys,x={},L={},k=/^(no-?highlight|plain|text)$/i,B=/\blang(?:uage)?-([\w-]+)\b/i,M=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,C="</span>",y={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},I={"&":"&amp;","<":"&lt;",">":"&gt;"};return e.highlight=l,e.highlightAuto=f,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=R,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|like)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("scss",function(e){var t="[a-zA-Z-][a-zA-Z0-9_-]*",i={cN:"variable",b:"(\\$"+t+")\\b"},r={cN:"number",b:"#[0-9A-Fa-f]+"};({cN:"attribute",b:"[A-Z\\_\\.\\-]+",e:":",eE:!0,i:"[^\\s]",starts:{eW:!0,eE:!0,c:[r,e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"meta",b:"!important"}]}});return{cI:!0,i:"[=/|']",c:[e.CLCM,e.CBCM,{cN:"selector-id",b:"\\#[A-Za-z0-9_-]+",r:0},{cN:"selector-class",b:"\\.[A-Za-z0-9_-]+",r:0},{cN:"selector-attr",b:"\\[",e:"\\]",i:"$"},{cN:"selector-tag",b:"\\b(a|abbr|acronym|address|area|article|aside|audio|b|base|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|command|datalist|dd|del|details|dfn|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|frame|frameset|(h[1-6])|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|map|mark|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|samp|script|section|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|tt|ul|var|video)\\b",r:0},{b:":(visited|valid|root|right|required|read-write|read-only|out-range|optional|only-of-type|only-child|nth-of-type|nth-last-of-type|nth-last-child|nth-child|not|link|left|last-of-type|last-child|lang|invalid|indeterminate|in-range|hover|focus|first-of-type|first-line|first-letter|first-child|first|enabled|empty|disabled|default|checked|before|after|active)"},{b:"::(after|before|choices|first-letter|first-line|repeat-index|repeat-item|selection|value)"},i,{cN:"attribute",b:"\\b(z-index|word-wrap|word-spacing|word-break|width|widows|white-space|visibility|vertical-align|unicode-bidi|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform-style|transform-origin|transform|top|text-underline-position|text-transform|text-shadow|text-rendering|text-overflow|text-indent|text-decoration-style|text-decoration-line|text-decoration-color|text-decoration|text-align-last|text-align|tab-size|table-layout|right|resize|quotes|position|pointer-events|perspective-origin|perspective|page-break-inside|page-break-before|page-break-after|padding-top|padding-right|padding-left|padding-bottom|padding|overflow-y|overflow-x|overflow-wrap|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|order|opacity|object-position|object-fit|normal|none|nav-up|nav-right|nav-left|nav-index|nav-down|min-width|min-height|max-width|max-height|mask|marks|margin-top|margin-right|margin-left|margin-bottom|margin|list-style-type|list-style-position|list-style-image|list-style|line-height|letter-spacing|left|justify-content|initial|inherit|ime-mode|image-orientation|image-resolution|image-rendering|icon|hyphens|height|font-weight|font-variant-ligatures|font-variant|font-style|font-stretch|font-size-adjust|font-size|font-language-override|font-kerning|font-feature-settings|font-family|font|float|flex-wrap|flex-shrink|flex-grow|flex-flow|flex-direction|flex-basis|flex|filter|empty-cells|display|direction|cursor|counter-reset|counter-increment|content|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|columns|color|clip-path|clip|clear|caption-side|break-inside|break-before|break-after|box-sizing|box-shadow|box-decoration-break|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-left-width|border-left-style|border-left-color|border-left|border-image-width|border-image-source|border-image-slice|border-image-repeat|border-image-outset|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|background-size|background-repeat|background-position|background-origin|background-image|background-color|background-clip|background-attachment|background-blend-mode|background|backface-visibility|auto|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-fill-mode|animation-duration|animation-direction|animation-delay|animation|align-self|align-items|align-content)\\b",i:"[^\\s]"},{b:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{b:":",e:";",c:[i,r,e.CSSNM,e.QSM,e.ASM,{cN:"meta",b:"!important"}]},{b:"@",e:"[{;]",k:"mixin include extend for if else each while charset import debug media page content font-face namespace warn",c:[i,e.QSM,e.ASM,r,e.CSSNM,{b:"\\s[A-Za-z0-9_.-]+",r:0}]}]}});hljs.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}});hljs.registerLanguage("python",function(e){var r={cN:"meta",b:/^(>>>|\.\.\.) /},b={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[r],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[r],r:10},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},e.ASM,e.QSM]},a={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},l={cN:"params",b:/\(/,e:/\)/,c:["self",r,a,b]};return{aliases:["py","gyp"],k:{keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},i:/(<\/|->|\?)/,c:[r,a,b,e.HCM,{v:[{cN:"function",bK:"def",r:10},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,l,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});hljs.registerLanguage("cs",function(e){var i={keyword:"abstract as base bool break byte case catch char checked const continue decimal dynamic default delegate do double else enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long when object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual volatile void while async nameof ascending descending from get group into join let orderby partial select set value var where yield",literal:"null false true"},r={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},t=e.inherit(r,{i:/\n/}),n={cN:"subst",b:"{",e:"}",k:i},c=e.inherit(n,{i:/\n/}),a={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,c]},s={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},n]},o=e.inherit(s,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},c]});n.c=[s,a,r,e.ASM,e.QSM,e.CNM,e.CBCM],c.c=[o,a,t,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[s,a,r,e.ASM,e.QSM]},b=e.IR+"(<"+e.IR+">)?(\\[\\])?";return{aliases:["csharp"],k:i,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:"<!--|-->"},{b:"</?",e:">"}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{bK:"new return throw await",r:0},{cN:"function",b:"("+b+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:i,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:i,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/-?[a-z\.]+/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,a,t]}});hljs.registerLanguage("go",function(e){var t={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",literal:"true false iota nil",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{aliases:["golang"],k:t,i:"</",c:[e.CLCM,e.CBCM,{cN:"string",v:[e.QSM,{b:"'",e:"[^\\\\]'"},{b:"`",e:"`"}]},{cN:"number",v:[{b:e.CNR+"[dflsi]",r:1},e.CNM]},{b:/:=/},{cN:"function",bK:"func",e:/\s*\{/,eE:!0,c:[e.TM,{cN:"params",b:/\(/,e:/\)/,k:t,i:/["']/}]}]}});hljs.registerLanguage("nginx",function(e){var r={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},b={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,r],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[r]},{cN:"regexp",c:[e.BE,r],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},r]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:b}],r:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("xml",function(s){var e="[A-Za-z0-9\\._:-]+",t={eW:!0,i:/</,r:0,c:[{cN:"attr",b:e,r:0},{b:/=\s*/,r:0,c:[{cN:"string",endsParent:!0,v:[{b:/"/,e:/"/},{b:/'/,e:/'/},{b:/[^\s"'=<>`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"<!DOCTYPE",e:">",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("<!--","-->",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"<style(?=\\s|>|$)",e:">",k:{name:"style"},c:[t],starts:{e:"</style>",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"<script(?=\\s|>|$)",e:">",k:{name:"script"},c:[t],starts:{e:"</script>",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"</?",e:"/?>",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("makefile",function(e){var a={cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]};return{aliases:["mk","mak"],c:[e.HCM,{b:/^\w+\s*\W*=/,rB:!0,r:0,starts:{e:/\s*\W*=/,eE:!0,starts:{e:/$/,r:0,c:[a]}}},{cN:"section",b:/^[\w]+:\s*$/},{cN:"meta",b:/^\.PHONY:/,e:/$/,k:{"meta-keyword":".PHONY"},l:/[\.\w]+/},{b:/^\t+/,e:/$/,r:0,c:[e.QSM,a]}]}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",t={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:c,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,t]}]}});hljs.registerLanguage("cpp",function(t){var e={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[t.BE]},{b:'(u8?|U)?R"',e:'"',c:[t.BE]},{b:"'\\\\?.",e:"'",i:"."}]},s={cN:"number",v:[{b:"\\b(0b[01'_]+)"},{b:"\\b([\\d'_]+(\\.[\\d'_]*)?|\\.[\\d'_]+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9'_]+|(\\b[\\d'_]+(\\.[\\d'_]*)?|\\.[\\d'_]+)([eE][-+]?[\\d'_]+)?)"}],r:0},i={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},t.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:"<",e:">",i:"\\n"},t.CLCM,t.CBCM]},a=t.IR+"\\s*\\(",c={keyword:"int float while private char catch export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using class asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},n=[e,t.CLCM,t.CBCM,s,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:c,i:"</",c:n.concat([i,{b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:c,c:["self",e]},{b:t.IR+"::",k:c},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:c,c:n.concat([{b:/\(/,e:/\)/,k:c,c:n.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+t.IR+"[\\*&\\s]+)+"+a,rB:!0,e:/[{;=]/,eE:!0,k:c,i:/[^\w\s\*&]/,c:[{b:a,rB:!0,c:[t.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:c,r:0,c:[t.CLCM,t.CBCM,r,s,e]},t.CLCM,t.CBCM,i]}]),exports:{preprocessor:i,strings:r,k:c}}});hljs.registerLanguage("dockerfile",function(e){return{aliases:["docker"],cI:!0,k:"from maintainer cmd expose add copy entrypoint volume user workdir onbuild run env label",c:[e.HCM,{k:"run cmd entrypoint volume add copy workdir onbuild label",b:/^ *(onbuild +)?(run|cmd|entrypoint|volume|add|copy|workdir|label) +/,starts:{e:/[^\\]\n/,sL:"bash"}},{k:"from maintainer expose env user onbuild",b:/^ *(onbuild +)?(from|maintainer|expose|env|user|onbuild) +/,e:/[^\\]\n/,c:[e.ASM,e.QSM,e.NM,e.HCM]}]}});hljs.registerLanguage("ini",function(e){var b={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_-]+/},{b:/=/,eW:!0,r:0,c:[{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},b,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}});hljs.registerLanguage("ruby",function(e){var r="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",b={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:b},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:b},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:r}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:r}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:b},{b:"("+e.RSR+")\\s*",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d,i.c=d;var l="[>?]>",o="[\\w#]+\\(\\w+\\):\\d+:\\d+>",u="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",w=[{b:/^\s*=>/,starts:{e:"$",c:d}},{cN:"meta",b:"^("+l+"|"+o+"|"+u+")",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:b,i:/\/\*/,c:s.concat(w).concat(d)}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("javascript",function(e){return{aliases:["js","jsx"],k:{keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{b:/</,e:/(\/\w+|\w+\/)>/,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:["self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:[e.CLCM,e.CBCM]}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}});
var waterJrc = ee.Image("JRC/GSW1_0/GlobalSurfaceWater"); // https://explorer.earthengine.google.com/#detail/UMD%2Fhansen%2Fglobal_forest_change_2017_v1_5 var hansen = ee.Image('UMD/hansen/global_forest_change_2017_v1_5') var hansenVis = {min: 0, max:100, bands: "treecover2000", palette: "3d3d3d,080a02,080a02,080a02,106e12,37a930,03ff17"} var waterCollection = ee.ImageCollection("JRC/GSW1_0/YearlyHistory") var waterVis = {min: 0, max: 3, palette: "cccccc,ffffff,99d9ea,0000ff"} Map.addLayer(waterCollection, waterVis, "Water Class") print(waterCollection) Map.addLayer(hansen, hansenVis, 'Forest 2000') // Load the LSIB country boundary collection. var countryBoundaries = ee.FeatureCollection('USDOS/LSIB/2013') // Get boundaries for a single country var countryGeometry = countryBoundaries.filter(ee.Filter.equals('name', 'NIGERIA')) // Loss areas var annualLosses = ee.List.sequence(1, 17) .map(function(lossyear) { return hansen.select('lossyear') .eq(ee.Image.constant(lossyear)) .multiply(ee.Image.pixelArea()) .reduceRegion({ geometry: countryGeometry, reducer: ee.Reducer.sum(), maxPixels: 1e13 }) .get('lossyear') }) // Loss areas, other way print('Annual Forest Loss (m^2)', annualLosses) /* Chart the loss */ var lossFc = annualLosses.map(function(annualLoss) { return ee.Feature(null, { 'annualLoss': annualLoss }) }) lossFc = ee.FeatureCollection(lossFc) var yearLabels = ee.List.sequence(2001, 2017) .map(function(year) { return ee.Number(year).format('%d') }) print(yearLabels) // var lossYearArray = annualLosses.zip(ee.List.sequence(2001,2017)) // Not this: // { // "offset": 2003.7789883384153, // "scale": 4.106325262551609e-9 // } // ===== // This: // { // "offset": -272681985212.27222, // "scale": 136363086.68786043 // } // 2001: 180551250.136505 // 2017: 2362360637.142273 // [[2001, 180551250.136505], // [2017, 2362360637.142273]] // // function slopeForYear(year) { // y = ee.Number(year).multip // } var lossYearArray = ee.List.sequence(2001,2017).zip(annualLosses) var linFit = lossYearArray.reduce(ee.Reducer.linearFit()) // print(linFit) linFit = ee.Dictionary(linFit) var slope = ee.Number(linFit.get('scale')) var offset = ee.Number(linFit.get('offset')) var ys = ee.List.sequence(2001,2017).map(function(year) { return ee.Number(year).multiply(slope).add(offset) }) print(ys) // print(ee.Array(lossYearArray)) // print(lossYearArray.reduce(ee.Reducer.linearFit())) // print(ee.Array(annualLosses)) var input = annualLosses.zip(ys).zip(yearLabels) var yearFeatures = input.map(function(data) { data = ee.List(data).flatten() return ee.Feature(null, { loss: ee.List(data).get(0), bestFit: ee.List(data).get(1), year: ee.List(data).get(2) }) }) yearFeatures = ee.FeatureCollection(yearFeatures) var chartOptions = { series: { // 0: {lineWidth: 1, pointSize: 2}, 1: {type: 'bars'} } } var chart = ui.Chart.feature.byFeature(yearFeatures, 'year') .setOptions(chartOptions) print(chart)
// @flow weak /* eslint max-len: "off" */ import React, { Component } from 'react'; import { transition, stop } from '../core/transition'; type Props = { /** * The data prop is treated as immutable. The component will run the update transition if prev.data !== next.data. */ data: any, /** * A function that returns the starting state. The function is passed the data and must return an object. */ start: (data: any) => {} | Array<{}>, /** * A function that **returns an object or array of objects** describing how the state should transform on enter. The function is passed the data. */ enter?: (data: any) => {} | Array<{}>, /** * A function that **returns an object or array of objects** describing how the state should transform on update. The function is passed the data. */ update?: (data: any) => {} | Array<{}>, /** * A function that renders the node. The function is passed the data and state. */ children: (data: any, state: {}) => {}, }; class Animate extends Component { static defaultProps = { enter: () => {}, update: () => {}, }; state = this.props.start(this.props.data) componentDidMount() { const { data, enter } = this.props; if (enter && typeof enter === 'function') { transition.call(this, enter(data)); } } componentWillReceiveProps(next) { if (next.data !== this.props.data) { this.update(next); } } componentWillUnmount() { stop.call(this); } props: Props; update(props) { const { data, update } = props; transition.call(this, update(data)); } render() { const renderedChildren = this.props.children(this.props.data, this.state); return renderedChildren && React.Children.only(renderedChildren); } } export default Animate;
var searchData= [ ['json_20format_20for_20recipes_161',['JSON Format for Recipes',['../recipe_format.html',1,'']]], ['json_20format_20for_20unsealing_20instructions_162',['JSON Format for Unsealing Instructions',['../unsealing_instructions_format.html',1,'']]] ];
/** * DevExtreme (cjs/integration/jquery/hold_ready.js) * Version: 21.2.5 * Build date: Mon Jan 17 2022 * * Copyright (c) 2012 - 2022 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; var _jquery = _interopRequireDefault(require("jquery")); var _themes_callback = require("../../ui/themes_callback"); var _ready_callbacks = _interopRequireDefault(require("../../core/utils/ready_callbacks")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj } } if (_jquery.default && !_themes_callback.themeReadyCallback.fired()) { var holdReady = _jquery.default.holdReady || _jquery.default.fn.holdReady; holdReady(true); _themes_callback.themeReadyCallback.add((function() { _ready_callbacks.default.add((function() { holdReady(false) })) })) }
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("filetools","sk",{loadError:"Počas čítania súboru nastala chyba.",networkError:"Počas nahrávania súboru nastala chyba siete.",httpError404:"Počas nahrávania súboru nastala HTTP chyba (404: Súbor nebol nájdený).",httpError403:"Počas nahrávania súboru nastala HTTP chyba (403: Zakázaný).",httpError:"Počas nahrávania súboru nastala HTTP chyba (error status: %1).",noUrlError:"URL nahrávania nie je definovaný.",responseError:"Nesprávna odpoveď servera."});
let handler = async (m, { conn }) => { global.db.data.chats[m.chat].isBanned = false m.reply('Done!') } handler.help = ['unbanchat'] handler.tags = ['owner'] handler.command = /^unbanchat$/i handler.owner = true module.exports = handler
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var sys = require('sys'); var log = require('util/log'); var sysLog = sys.log; exports['test_trace'] = function(test, assert) { var trace = log.trace('test trace'); assert.match(trace, /util-log.js:25:19/); test.finish(); }; exports['test_setLogLevel'] = function(test, assert) { var buffer = ''; sys.log = function(data) { buffer += data; }; log.setLoglevel('debug'); log.debug('test line'); assert.equal(buffer, 'debug: test line'); log.setLoglevel('nothing'); log.debug('test line'); assert.equal(buffer, 'debug: test line'); test.finish(); }; exports['tearDown'] = function(test, assert) { sys.log = sysLog; test.finish(); };
const LastChar = String.fromCharCode(0xfffd); const ciCompare = (window.Intl && window.Intl.Collator && !/Edge/.test(navigator.userAgent)) // bugged in Edge: #808 ? new Intl.Collator(undefined, { sensitivity: 'base' }).compare : (x, y) => x.toLocaleLowerCase().localeCompare(y.toLocaleLowerCase()); const Comparators = { stringComparator: function(field, asc) { if (asc) { return function (x, y) { return ciCompare(x[field] || LastChar, y[field] || LastChar); }; } else { return function (x, y) { return ciCompare(y[field], x[field]); }; } }, rankComparator: function() { return function (x, y) { return y.getRank(this.filter.textLower) - x.getRank(this.filter.textLower); }; }, dateComparator: function(field, asc) { if (asc) { return function (x, y) { return x[field] - y[field]; }; } else { return function (x, y) { return y[field] - x[field]; }; } } }; module.exports = Comparators;
/** * @name App settings * Define the App class default settings */ export default { /** * The socket.io server host to connect to * @type {String} */ host : document.location.hostname, /** * The socket.io server port to connect to * @type {Integer} */ port : 3030, debug : false, compression : false }
import classNames from 'classnames'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import card from '../styles/card.css'; const cx = classNames.bind(card); const Category = ({ category }) => ( <div className={cx('card')}> <Link to={`/meals/${category.strCategory}`} className={cx('card-link')}> <img className={cx('card-img')} src={category.strCategoryThumb} alt={category.strCategory} /> <div className={cx('card-body')}> <h3 className={cx('card-title')}> {category.strCategory} </h3> </div> </Link> </div> ); Category.propTypes = { category: PropTypes.objectOf(PropTypes.string).isRequired, }; export default Category;
import { createStore, applyMiddleware } from "redux"; import { createLogger } from "redux-logger"; import reducer from "./reducers/reducer"; const logger = createLogger(); const initState = { isFetching: false, chat: [ // { // query: "", // response: "", // }, ], }; const store = createStore(reducer, initState, applyMiddleware(logger)); export default store;
/* * grunt-sequelize * https://github.com/webcast-io/grunt-sequelize * * Copyright (c) 2013 Ben Evans * Licensed under the MIT license. */ 'use strict'; var Sequelize = require('sequelize'); var _ = Sequelize.Utils._; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('sequelize', 'Sequelize migrations from Grunt', function(cmd, arg1) { var done; var options = this.options({ environment: process.env.NODE_ENV || 'development', // As a default value, assume __dirname is `/<some path>/node_modules/grunt-sequelize/tasks` migrationsPath: __dirname + '/../../../migrations', logging: false }); var sequelize = new Sequelize(options.database, options.username, options.password, options); var migratorOptions = { path: options.migrationsPath }; var migrator = sequelize.getMigrator(migratorOptions); function getCurrentMigrationId(callback) { var migrationVersionEmitter = sequelize.migrator.getLastMigrationIdFromDatabase(); migrationVersionEmitter.on('success', function(serverMigrationId) { callback(null, serverMigrationId); }); migrationVersionEmitter.on('error', function(error) { callback(error); }); } if(cmd === 'migrate') { done = this.async(); getCurrentMigrationId(function(err, serverMigrationId) { if(serverMigrationId === arg1) { console.log('There are no pending migrations.'); return done(); } if(arg1) { migratorOptions.to = arg1; migratorOptions.from = serverMigrationId; migratorOptions.method = (parseInt(migratorOptions.to, 10) >= parseInt(migratorOptions.from, 10)) ? 'up' : 'down'; migrator = sequelize.getMigrator(migratorOptions); } sequelize.migrate(migratorOptions).success(done).error(function(err) { grunt.log.error(err); done(false); }); }); } else if(cmd === 'undo') { done = this.async(); migrator.findOrCreateSequelizeMetaDAO().success(function(Meta) { Meta.find({ order: 'id DESC' }).success(function(meta) { if (meta) { migrator = sequelize.getMigrator(_.extend(migratorOptions, meta.values), true); migrator.migrate({ method: 'down' }).success(done).error(function(err) { grunt.log.error(err); done(false); }); } else { grunt.log.writeln('There are no pending migrations.'); done(); } }); }); } else if(cmd === 'current') { done = this.async(); getCurrentMigrationId(function(err, serverMigrationId) { if(err) { return done(err); } grunt.log.write('Current Migration: ', serverMigrationId); done(); }); } else { throw new Error('Unknown grunt-sequelize command: ' + cmd); } }); };
const conteudo = document.createElement('div') conteudo.innerHTML = ` <header class="header"> <img class="header-logo" src="/img/logo.png" alt=""> <nav class="header-nav-caixa "> <a class="header-nav" href="#sobre">Sobre</a> <a class="header-nav" href="#como-fazer">Como Fazer</a> <a class="header-nav" href="#duvidas">Duvidas</a> </nav> <a class="header-contato" href="#footer">Contato</a> </header> <main > <div > <img class="background-top" src="/img/Top.png" alt=""> <div class="top-texto-container"> <h2 class="top-texto">Seu incrível consultor de permissão de trânsito.</h2> <a class="button" href="#depoimentos">Começar</a> </div> </div> <section id="sobre" class="section"> <div> <div class="section-texto-a"> <h2 class="section-h2">Sobre</h2> <article> A licença de trânsito ocupacional é uma das coisas mais importantes da empresa na realização do transporte de cargas. Na verdade, é um pré-requisito para fazer tráfego de negócios. </article> </div> <div class="sobre-texto-b"> <p > Como você faz quando precisa obter uma permissão de tráfego comercial para transporte de carga para o seu negócio? </p> </div> </div> <div > <img class="section-img" src="/img/Illustration.png" alt=""> </div> </section> <section id="como-fazer" class="section"> <div> <img class="section-img" src="/img/illustrations.png" alt=""> </div> <div class="section-texto"> <div class="section-texto-a"> <h2 class="section-h2">Como Fazer</h2> <article> Ao solicitar uma licença de trânsito, existem certos requisitos que você deve cumprir que estão incluídos no exame: requisitos para conhecimento profissional, estabelecimento sólido, boa reputação e recursos financeiros. Importante lembrar é confirmar seu pedido de permissão de trânsito pelo assinante ou CEO da empresa. </article> </div> </div> </section> <section id="duvidas" class="duvidas"> <div> <img class="duvidas-bg" src="/img/FAQ.png" alt="duvidas"> </div> <div class="duvidas-div-container"> <div class="duvidas-texto"> <h2 class="section-h2">Perguntas</h2> <h3>Perguntas e respostas sobre licenças de tráfego profissional:</h3> </div> <div class="duvidas-container section"> <div class="duvidas-items-total"> <div onclick="addSpan(span1,t1)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t1" class="duvidas-after-a"></div> </div> <p id="span1" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> <div onclick="addSpan(span2,t2)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t2" class="duvidas-after-a"></div> </div> <p id="span2" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> <div onclick="addSpan(span3,t3)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t3" class="duvidas-after-a"></div> </div> <p id="span3" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> <div onclick="addSpan(span4,t4)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t4" class="duvidas-after-a"></div> </div> <p id="span4" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> </div> <div class="duvidas-items-total-b"> <div onclick="addSpan(span6,t6)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t6" class="duvidas-after-a"></div> </div> <p id="span6" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> <div onclick="addSpan(span7,t7)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t7" class="duvidas-after-a"></div> </div> <p id="span7" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> <div onclick="addSpan(span8,t8)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t8" class="duvidas-after-a"></div> </div> <p id="span8" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> <div onclick="addSpan(span9,t9)" class="duvidas-item"> <div class="duvidas-item-titulo" > <h3 ><a class="duvidas-item-titulo-a" href="#duvidas-item-titulo"> O que é uma permissão de trânsito profissional?</a></h3> <div id="t9" class="duvidas-after-a"></div> </div> <p id="span9" class="duvidas-span-hiden"> As licenças de trânsito são um requisito para a condução do tráfego profissional. </p> </div> </div> </div> <a class=" buscar-mais section-h2 duvidas-after-a" onclick="carregarMais()" href="#duvidas-item-titulo">Carregar Mais</a> </div> </section> <section id="depoimentos" class="depoimentos"> <div class="depoimentos-topo"> <h2>Depoimentos</h2> <div> <a class="depoimentos-topo-a" onclick="plusDivs(-1)" href="#depoimentos">&#10229;</a> <a class="depoimentos-topo-a" onclick="plusDivs(1)" href="#depoimentos">&#10230;</a> </div> </div> <div class="depoimentos-main"> <div> <h3 class="depoimentos-main-h3">Depoimentos incriveis</h3> </div> <div class="depoimentos-item-container"> <div class="depoimentos-item slide"> <p class="depoimentos-item-p">Sim, você precisará que o proprietário da terra assine o pedido de permissão como Permitidor, e você assine a permissão como Requerente ou Agente para o Permitido.</p> <img class="depoimentos-item-img" src="/img/Group 32(2).png" alt=""> </div> <div class="depoimentos-item slide"> <p class="depoimentos-item-p">Da maioria das empresas de barricadas ou controle de tráfego localizadas na lista telefônica. Eles empregam Supervisores certificados de Controle de Tráfego (TCS) que podem gerar e certificar o plano de controle de tráfego. </p> <img class="depoimentos-item-img" src="/img/Group 32(1).png" alt=""> </div> <div class="depoimentos-item slide"> <p class="depoimentos-item-p">Uma linha A ou escritura de restrição de acesso é um direito de propriedade que foi obtido pela CDOT com o único propósito de proibir direta</p> <img class="depoimentos-item-img" src="/img/Group 32.png" alt=""> </div> </div> </div> </section> </main> <footer id="footer" class="footer"> <img class="footer-bg" src="/img/Footer.png" alt="imagem-footer"> <div class="footer-container"> <div class="footer-texto"> <p>Nós fornecemos consultores de gerenciamento de tráfego para que você comece rapidamente, entre em contato conosco para uma citação hoje!</p> </div> <form class="footer-form" action="/salvar" method="POST"> <div> <label class="footer-form-label" for="nome">Nome</label> <input class="footer-form-input" id="nome" name="nome" type="text" > </div> <label class="footer-form-label" for="email">Email</label> <input class="footer-form-input" type="email" name="email" id="email"> <label class="footer-form-label" for="mensagem">Mensagem</label> <input class="footer-form-input footer-form-textArea" type="text" name="mensagem" id="mensagem" /> <button id="botaoForm" class="footer-form-button" type="submit">Enviar</button> </form> </div> <div class="footer-rodape-a"> <div> <img class="footer-rodape-a-img" src="/img/logo.png" alt=""> </div> <div class="footer-text-link"> <a class="footer-rodape-a-text" href="#sobre">Sobre</a> <a class="footer-rodape-a-text" href="#como-fazer">Como Fazer</a> <a class="footer-rodape-a-text" href="#duvidas">Duvidas</a> </div> </div> <div id="footer-rodape-b" class="footer-rodape-b"> <div> <p class="footer-rodape-b-text">&copy;Copryng @ 2021</p> </div> <div> <a href="https://twitter.com" target="_blank"><img class="footer-rodape-b-img" src="/img/t.png" alt=""></a> <a href="https://www.instagram.com/?hl=pt-br" target="_blank"><img class="footer-rodape-b-img" src="/img/i.png" alt=""></a> <a href="https://www.facebook.com/" target="_blank"><img class="footer-rodape-b-img" src="/img/f.png" alt=""></a> </div> </div> </footer> `; document.body.appendChild(conteudo) function addSpan(id,t){ id.classList.toggle('duvidas-span-hiden') id.classList.toggle('duvidas-span') t.classList.toggle('duvidas-after-a') t.classList.toggle('duvidas-after-b') } function carregarMais(){ setTimeout( ()=> alert('Carregados com sucesso! 😄'), ); }
const readPkg = require('read-pkg'); const { compose } = require('ramda'); const withOnlyPackageCommits = require('./only-package-commits'); const versionToGitTag = require('./version-to-git-tag'); const logPluginVersion = require('./log-plugin-version'); const { wrapStep } = require('semantic-release-plugin-decorators'); const { mapNextReleaseVersion, withOptionsTransforms, } = require('./options-transforms'); const analyzeCommits = wrapStep( 'analyzeCommits', compose(logPluginVersion('analyzeCommits'), withOnlyPackageCommits), { wrapperName: 'semantic-release-monorepo', } ); const generateNotes = wrapStep( 'generateNotes', compose( logPluginVersion('generateNotes'), withOnlyPackageCommits, withOptionsTransforms([mapNextReleaseVersion(versionToGitTag)]) ), { wrapperName: 'semantic-release-monorepo', } ); module.exports = { analyzeCommits, generateNotes, tagFormat: `${readPkg.sync().name}@\${version}`, };
require('../setup'); const chai = require('chai'); const utils = require('../utils'); const app = require('../../src/app'); describe('/commandeer endpoint', function () { it('should reject unauthenticated users', async function () { const body = utils.baseSlackRequest({ command: '/commandeer', user_name: 'paul.mccartney', user_id: 'U1BBBBBBB' }); const res = await chai .request(app) .post('/command') .send(body); chai.assert.equal( res.body.text, '<@U1BBBBBBB>: You\'re not authenticated with Spotify. Try `/spotifyauth` if you\'d like to get set up.' ); }); it('should pass command to the requesting user', async function () { const body = utils.baseSlackRequest({ command: '/commandeer' }); const res = await chai .request(app) .post('/command') .send(body); chai.assert.equal( res.body.text, '<@U1AAAAAAA>: You are now the active user!' ); }); });
import {stat, report, reportContent} from "../../common/elasticsearch_stat"; import jsreportCore from 'jsreport-core'; import jsreportXlsx from 'jsreport-xlsx'; import jsreportHandle from 'jsreport-handlebars'; import fs from 'fs'; export default function (server) { const dataCluster = server.plugins.elasticsearch.getCluster('data'); server.route({ path: '/api/thxreport/stat', method: 'POST', handler(req, reply) { const STAT = stat(); const rangeFilter = STAT.body.query.bool.must[2]; rangeFilter.range['@timestamp'].gte = req.payload.fromDate; rangeFilter.range['@timestamp'].lte = req.payload.toDate; rangeFilter.range['@timestamp'].time_zone = req.payload.timeZone; rangeFilter.range['@timestamp'].format = req.payload.format; STAT.body.aggs["6"].date_histogram.time_zone = req.payload.timeZone; console.log(STAT.body.aggs); dataCluster.callWithRequest(req, 'search', STAT).then( (result) => { reply(result); }, (err) => { reply(err); } ); } }); server.route({ path: '/api/thxreport/report', method: 'POST', handler(req, reply) { let jsreport = jsreportCore(); jsreport.use(jsreportXlsx()); jsreport.use(jsreportHandle()); const reportContentStr = reportContent(); const REPORT = report(); const rangeFilter = REPORT.body.query.bool.must[1]; rangeFilter.range['@timestamp'].gte = req.payload.fromDate; rangeFilter.range['@timestamp'].lte = req.payload.toDate; rangeFilter.range['@timestamp'].time_zone = req.payload.timeZone; rangeFilter.range['@timestamp'].format = req.payload.format; dataCluster.callWithRequest(req, 'search', REPORT).then( (result) => { const report = []; result.aggregations["4"].buckets.map((bucket,i) => { report.push({ system: bucket.key, email: bucket["1"].value, phone: bucket["2"].value, jumin: bucket["3"].value, }); }); jsreport.init().then(() => { return jsreport.render({ template: { recipe: 'xlsx', engine: 'handlebars', content: reportContentStr, xlsxTemplate: { content: fs.readFileSync('template/report_template.xlsx').toString('base64') }, }, data: { report: report }, }).then((report) => { reply(report.content.toString('base64')); //report.stream.pipe(req.raw.res); }) }); }, (err) => { reply(err); } ); } }); }
const approuter = require('@sap/approuter'); const config = require('./xs-app.json'); config.routes.forEach((oRoute) => { if (oRoute.localDir && oRoute.localDir === "webapp") { oRoute.localDir = "../webapp" } }) approuter().start({ xsappConfig: config });
'use strict'; describe('Service: gameClassifier', function () { beforeEach(module('twistedHangmanApp')); var playerMD5 = 'anmd5!'; var mockPlayerService = { currentPlayer: function () { return {md5: playerMD5}; } }; var twGameDetails = { playerActionRequired: jasmine.createSpy('action') }; beforeEach(module(function ($provide) { $provide.factory('jtbPlayerService', [function () { return mockPlayerService; }]); $provide.factory('twGameDetails', [function () { return twGameDetails; }]); })); var service; beforeEach(inject(function ($injector) { twGameDetails.playerActionRequired.calls.reset(); service = $injector.get('jtbGameClassifier'); })); var expectedYourTurnClassification = 'Your move.'; var expectedTheirTurnClassification = 'Their move.'; var expectedOlderGameClassification = 'Older games.'; var expectedIconMap = {}; expectedIconMap[expectedYourTurnClassification] = 'play'; expectedIconMap[expectedTheirTurnClassification] = 'pause'; expectedIconMap[expectedOlderGameClassification] = 'stop'; it('get classifications', function () { expect(service.getClassifications()).toEqual([expectedYourTurnClassification, expectedTheirTurnClassification, expectedOlderGameClassification]); }); it('get icon map', function () { expect(service.getIcons()).toEqual(expectedIconMap); }); it('classification for no player action needed, non-roundover phase', function () { var game = {gamePhase: 'TBD'}; twGameDetails.playerActionRequired.and.returnValue(false); expect(service.getClassification(game)).toEqual(expectedTheirTurnClassification); expect(twGameDetails.playerActionRequired).toHaveBeenCalledWith(game, playerMD5); }); it('classification for player action needed, non-roundover phase', function () { var game = {gamePhase: 'TBD'}; twGameDetails.playerActionRequired.and.returnValue(true); expect(service.getClassification(game)).toEqual(expectedYourTurnClassification); expect(twGameDetails.playerActionRequired).toHaveBeenCalledWith(game, playerMD5); }); it('classification for phase RoundOver', function () { var game = {gamePhase: 'RoundOver'}; twGameDetails.playerActionRequired.and.returnValue(false); expect(service.getClassification(game)).toEqual(expectedYourTurnClassification); expect(twGameDetails.playerActionRequired).toHaveBeenCalledWith(game, playerMD5); }); angular.forEach(['Declined', 'Quit', 'NextRoundStarted'], function (phase) { it('classification for phase ' + phase, function () { var game = {gamePhase: phase}; twGameDetails.playerActionRequired.and.returnValue(false); expect(service.getClassification(game)).toEqual(expectedOlderGameClassification); }); }); });
import Project from './ui/Project'; import ScratchAudio from '../utils/ScratchAudio'; import Paint from '../painteditor/Paint'; import Prims from './engine/Prims'; import Undo from './ui/Undo'; import Alert from './ui/Alert'; import Palette from './ui/Palette'; import Record from './ui/Record'; import IO from '../tablet/IO'; import OS from '../tablet/OS'; import UI from './ui/UI'; import Menu from './blocks/Menu'; import Library from './ui/Library'; import Grid from './ui/Grid'; import ScriptsPane from './ui/ScriptsPane'; import Events from '../utils/Events'; import BlockSpecs from './blocks/BlockSpecs'; import Runtime from './engine/Runtime'; import Localization from '../utils/Localization'; import {libInit, gn, scaleMultiplier, newHTML, isAndroid, isTablet, getUrlVars, CSSTransition3D, frame, onTouchStartBind, onTouchEndBind} from '../utils/lib'; let workingCanvas = document.createElement('canvas'); let workingCanvas2 = document.createElement('canvas'); let activeFocus = undefined; let changed = false; // Our behavior for story-starters are slightly different from changed // e.g. moving a script around doesn't "start a story" while we would want it // to save a normal user project. let storyStarted = false; let runtime = undefined; let stage = undefined; let inFullscreen = false; let keypad = undefined; let textForm = undefined; let editfirst = false; let stagecolor; let defaultSprite; /////////////////////////////////////////// //Layers definitions for the whole site /////////////////////////////////////////// //layaring variables let layerTop = 10; let layerAboveBottom = 4; let dragginLayer = 7000; let currentProject = undefined; //项目ID let filepath = undefined; let editmode; let isDebugging = false; let time; let userStart = false; let onHold = false; let shaking = undefined; let stopShaking = undefined; let version = undefined; let autoSaveEnabled = true; let autoSaveSetInterval = null; let onBackButtonCallback = []; export default class ScratchJr { static get workingCanvas () { return workingCanvas; } static get workingCanvas2 () { return workingCanvas2; } static get activeFocus () { return activeFocus; } static set activeFocus (newActiveFocus) { activeFocus = newActiveFocus; } static set changed (newChanged) { changed = newChanged; } static set storyStarted (newStoryStarted) { storyStarted = newStoryStarted; } static get runtime () { return runtime; } static get stage () { return stage; } static set stage (newStage) { stage = newStage; } static get inFullscreen () { return inFullscreen; } static get stagecolor () { return stagecolor; } static get defaultSprite () { return defaultSprite; } static get layerTop () { return layerTop; } static get layerAboveBottom () { return layerAboveBottom; } static get dragginLayer () { return dragginLayer; } static get currentProject () { return currentProject; } static set currentProject(v){ currentProject = v; } static get filepath(){ return filepath; } static get editmode () { return editmode; } static set editmode (newEditmode) { editmode = newEditmode; } static set time (newTime) { time = newTime; } static set userStart (newUserStart) { userStart = newUserStart; } static get onHold () { return onHold; } static set onHold (newOnHold) { onHold = newOnHold; } static get shaking () { return shaking; } static set shaking (newShaking) { shaking = newShaking; } static get stopShaking () { return stopShaking; } static set stopShaking (newStopShaking) { stopShaking = newStopShaking; } static get version () { return version; } static get onBackButtonCallback () { return onBackButtonCallback; } static appinit (v) { stagecolor = window.Settings.stageColor; defaultSprite = window.Settings.defaultSprite; version = v; document.body.scrollTop = 0; time = (new Date()) - 0; var urlvars = getUrlVars(); OS.hascamera(); ScratchJr.log('starting the app'); BlockSpecs.initBlocks(); Project.loadIcon = document.createElement('img'); Project.loadIcon.src = 'assets/loading.png'; ScratchJr.log('blocks init', ScratchJr.getTime(), 'sec', BlockSpecs.loadCount); currentProject = urlvars.pmd5; if("filepath" in urlvars){ filepath = urlvars.filepath } editmode = urlvars.mode; libInit(); Project.init(); ScratchJr.log('Start ui init', ScratchJr.getTime(), 'sec'); Project.setProgress(10); ScratchAudio.init(); Library.init(); Paint.init(); Record.init(); Prims.init(); runtime = new Runtime(); Undo.init(); ScratchJr.editorEvents(); Project.load(); Events.init(); if (window.Settings.autoSaveInterval > 0) { autoSaveSetInterval = window.setInterval(function () { if (autoSaveEnabled && !onHold && !Project.saving && !UI.infoBoxOpen) { ScratchJr.saveProject(null, function () { Alert.close(); }); } }, window.Settings.autoSaveInterval); } } //获取Sjr项目文件 static getProjectSjr(cb){ let md5 = ScratchJr.currentProject + "" Project.prepareToSave(md5, function () { IO.zipProject(md5, function (contents) { ScratchJr.onHold = false; cb(contents, IO.zipFileName) }); }); } //加载网络Sjr文件 static loadProjectSjr(url){ Project.downloadProject(url, (md5)=>{ // window.location.href = 'editor.html?pmd5=' + md5 + '&mode=edit'; ScratchJr.currentProject = md5 IO.getObject(md5+"", Project.dataRecieved); }); } //获取项目截图base64 static getProjectCover(cb){ Project.getThumbnailPNG(ScratchJr.stage.pages[0], 192, 144, cb) } // Event handler for when a story is started // When called and enabled, this will trigger sample projects to save copies // Here for debugging, run-time filtering, etc. static storyStart (/*eventName*/) { // console.log("Story started: " + eventName); storyStarted = true; } static editorEvents () { document.ongesturestart = undefined; onTouchStartBind(window, ScratchJr.unfocus); if (isTablet) { window.ontouchend = undefined; } else { window.onmouseup = undefined; } } static unfocus (evt) { if (Palette.helpballoon) { Palette.helpballoon.parentNode.removeChild(Palette.helpballoon); Palette.helpballoon = undefined; } if (document.forms.editable) { if (evt && (evt.target == document.forms.editable.field)) { return; } // block is being edit } if (document.forms.activetextbox) { if (evt && (evt.target == document.forms.activetextbox.typing)) { return; } // stage text box } if (document.forms.projectname) { if (evt && (evt.target == document.forms.projectname.myproject)) { return; } // infobox text box } if (document.activeElement.tagName.toLowerCase() == 'input') { document.activeElement.blur(); } ScratchJr.clearSelection(); ScratchJr.blur(); } static clearSelection () { if (shaking) { stopShaking(shaking); } } static blur () { if (ScratchAudio.firstTime) { ScratchAudio.firstClick(); } ScratchJr.editDone(); Menu.closeMyOpenMenu(); } static getSprite () { if (!stage.currentPage.currentSpriteName) { return undefined; } if (!gn(stage.currentPage.currentSpriteName)) { return undefined; } return gn(stage.currentPage.currentSpriteName).owner; } static gestureStart (e) { e.preventDefault(); if (ScratchAudio.firstTime) { ScratchAudio.firstClick(); } } static log () { if (!isDebugging) { return; } var len = arguments.length; var res = ''; for (var i = 0; i < len - 1; i++) { res = res + arguments[i] + ' '; } res += arguments[len - 1]; console.log(res); //eslint-disable-line no-console } static getTime () { return ((new Date()) - time) / 1000; } static isSampleOrStarter () { return editmode == 'look' || editmode == 'storyStarter'; } static isEditable () { return editmode != 'look'; } // Called when ScratchJr is brought back to focus // Here, we fix up some UI elements that may not have been properly shut down when the app was paused. // Note that on Android Lollipop and up we have much more limited // opportunity to save progress, etc. before the app is // paused, and so we just suspend the whole webview and then restore it here. static onResume () { // no nothing special, for now. if (Record.dialogOpen) { Record.recordError(); } // Re-enable autosaves autoSaveEnabled = true; autoSaveSetInterval = window.setInterval(function () { if (autoSaveEnabled && !onHold && !Project.saving && !UI.infoBoxOpen) { ScratchJr.saveProject(null, function () { Alert.close(); }); } }, window.Settings.autoSaveInterval); } static onPause () { autoSaveEnabled = false; window.clearInterval(autoSaveSetInterval); } static saveProject (e, onDone) { if (ScratchJr.isEditable() && editmode == 'storyStarter' && storyStarted && !Project.error) { OS.analyticsEvent('samples', 'story_starter_edited', Project.metadata.name); // Localize sample project names var sampleName = Localization.localize('SAMPLE_' + Project.metadata.name); // Get the new project name IO.uniqueProjectName({ name: sampleName }, function (jsonData) { var newName = jsonData.name; Project.metadata.name = newName; // Create the new project IO.createProject({ name: newName, version: version, mtime: (new Date()).getTime().toString() }, function (md5) { // Save project data currentProject = md5; // Switch out of story-starter mode to avoid creating new projects editmode = 'edit'; Project.prepareToSave(currentProject, onDone); }); }, true); } else if (ScratchJr.isEditable() && currentProject && !Project.error && changed) { Project.prepareToSave(currentProject, onDone); } else { if (onDone) { onDone(); } } } //保存并返回菜单 static saveAndFlip (e) { onHold = true; ScratchJr.stopStripsFromTop(e); ScratchJr.unfocus(e); ScratchJr.saveProject(e, ScratchJr.flippage); OS.analyticsEvent('editor', 'project_editor_close'); } static flippage () { Alert.close(); OS.cleanassets('wav', doNext); function doNext () { OS.cleanassets('svg', ScratchJr.switchPage); } } static switchPage () { window.location.href = ScratchJr.getGotoLink(); } static getGotoLink () { if (editmode == 'storyStarter') { if (!storyStarted) { return 'home.html?place=help'; } else { return 'home.html?place=home'; } } if (!currentProject && !filepath) { return 'home.html?place=home'; } if (Project.metadata.gallery == 'samples') { return 'home.html?place=help'; } else { return 'home.html?place=home&timestamp=' + new Date().getTime(); } } static updateRunStopButtons () { var isOff = runtime.inactive(); if (inFullscreen) { gn('go').className = isOff ? 'go on presentationmode' : 'go off presentationmode'; UI.updatePageControls(); } else { gn('go').className = isOff ? 'go on' : 'go off'; Grid.updateCursor(); } if (ScratchJr.getSprite()) { if (isOff && !inFullscreen) { ScratchJr.getSprite().select(); } else { ScratchJr.getSprite().unselect(); } } if (isOff && userStart) { stage.currentPage.updateThumb(); // ScratchJr.log ('total time', ScratchJr.getTime(), 'sec'); userStart = false; } } static runStrips (e) { ScratchJr.stopStripsFromTop(e); ScratchJr.unfocus(e); ScratchJr.startGreenFlagThreads(); userStart = true; // time = (new Date()) - 0; } static startGreenFlagThreads () { ScratchJr.resetSprites(); ScratchJr.startCurrentPageStrips(['onflag', 'ontouch']); } static startCurrentPageStrips (list) { var page = stage.currentPage.div; for (var i = 0; i < page.childElementCount; i++) { var spr = page.childNodes[i].owner; if (!spr) { continue; } if (!gn(spr.id + '_scripts')) { continue; } // text case ScratchJr.startScriptsFor(spr, list); } } static startScriptsFor (spr, list) { var sc = gn(spr.id + '_scripts'); var topblocks = sc.owner.getBlocksType(list); for (var j = 0; j < topblocks.length; j++) { var b = topblocks[j]; runtime.addRunScript(spr, b); } } static stopStripsFromTop (e) { e.preventDefault(); e.stopPropagation(); ScratchJr.unfocus(e); ScratchJr.stopStrips(); userStart = false; } static stopStrips () { runtime.stopThreads(); stage.currentPage.updateThumb(); } static resetSprites () { stage.resetPage(stage.currentPage); } static fullScreen (e) { if (gn('full').className == 'fullscreen') { onBackButtonCallback.push(function () { var fakeEvent = document.createEvent('TouchEvent'); fakeEvent.initTouchEvent(); ScratchJr.quitFullScreen(fakeEvent); }); ScratchJr.enterFullScreen(e); } else { ScratchJr.quitFullScreen(e); } } static displayStatus (type) { var ids = ['topsection', 'blockspalette', 'scripts', 'flip', 'projectinfo']; for (var i = 0; i < ids.length; i++) { if (gn(ids[i])) { gn(ids[i]).style.display = type; } } } static enterFullScreen (e) { if (onHold) { return; } e.preventDefault(); e.stopPropagation(); ScratchJr.unfocus(e); ScratchJr.displayStatus('none'); inFullscreen = true; UI.enterFullScreen(); OS.analyticsEvent('editor', 'full_screen_entered'); document.body.style.background = 'black'; } static quitFullScreen (e) { // time = (new Date()) - 0; e.preventDefault(); e.stopPropagation(); ScratchJr.displayStatus('block'); inFullscreen = false; UI.quitFullScreen(); onBackButtonCallback.pop(); OS.analyticsEvent('editor', 'full_screen_exited'); document.body.style.background = 'white'; } ///////////////////////////////////////// //UI calls ///////////////////////////////////////// static getActiveScript () { var str = stage.currentPage.currentSpriteName + '_scripts'; return gn(str); } static getBlocks () { return ScratchJr.getActiveScript().owner.getBlocks(); } ///////////////////////////////////////////////// //Setup editable field static setupEditableField () { textForm = newHTML('form', 'textform', frame); textForm.name = 'editable'; var ti = newHTML('input', 'textinput', textForm); ti.name = 'field'; ti.onkeypress = function (evt) { handleKeyPress(evt); }; textForm.onsubmit = function (evt) { submitOverride(evt); }; function handleKeyPress (e) { var key = e.keyCode || e.which; if (key == 13) { submitOverride(e); } } function submitOverride (e) { e.preventDefault(); e.stopPropagation(); var input = e.target; input.blur(); // Hitting enter does not trigger editDone() // so you need to pop the queue here. onBackButtonCallback.pop(); } ti.maxLength = 50; ti.onfocus = ScratchJr.handleTextFieldFocus; ti.onblur = ScratchJr.handleTextFieldBlur; } ///////////////////////////////////////////////// //Argument Clicked static editArg (e, ti) { e.preventDefault(); e.stopPropagation(); if (ti && ti.owner.isText()) { ScratchJr.textClicked(e, ti); } else { ScratchJr.numberClicked(e, ti); } onBackButtonCallback.push(function () { ScratchJr.editDone(); }); } static textClicked (e, div) { var b = div.owner; // b is a BlockArg activeFocus = b; var pt = b.getScreenPt(); var sc = ScratchJr.getActiveScript(); div = sc.parentNode; var w = div.offsetWidth; var h = div.offsetHeight; var dx = ((pt.x + 480 * scaleMultiplier) > w) ? (w - 486 * scaleMultiplier) : pt.x - 6 * scaleMultiplier; var ti = document.forms.editable.field; ti.style.textAlign = 'center'; document.forms.editable.style.left = dx + 'px'; var top = pt.y + 55 * scaleMultiplier; document.forms.editable.style.top = top + 'px'; if (isAndroid) { AndroidInterface.scratchjr_setsoftkeyboardscrolllocation( top * window.devicePixelRatio, (top + h) * window.devicePixelRatio ); } document.forms.editable.className = 'textform on'; ti.value = b.argValue; if (isAndroid) { AndroidInterface.scratchjr_forceShowKeyboard(); } ti.focus(); } static handleTextFieldFocus (e) { e.preventDefault(); e.stopPropagation(); activeFocus.oldvalue = activeFocus.input.textContent; } static handleTextFieldBlur (e) { onBackButtonCallback.pop(); e.preventDefault(); e.stopPropagation(); var ti = document.forms.editable.field; var str = ti.value.substring(0, ti.maxLength); activeFocus.argValue = str; activeFocus.setValue(str); document.forms.editable.className = 'textform off'; if (activeFocus.daddy.div.parentNode) { var spr = activeFocus.daddy.div.parentNode.owner.spr; var action = { action: 'scripts', where: spr.div.parentNode.owner.id, who: spr.id }; if (activeFocus.input.textContent != activeFocus.oldvalue) { Undo.record(action); ScratchJr.storyStart('ScratchJr.handleTextFieldBlur'); } } activeFocus = undefined; document.body.scrollTop = 0; document.body.scrollLeft = 0; if (isAndroid) { AndroidInterface.scratchjr_forceHideKeyboard(); } } ///////////////////////////////////////// //Numeric keyboard ///////////////////////////////////////// static setupKeypad () { keypad = newHTML('div', 'picokeyboard', frame); onTouchStartBind(keypad,ScratchJr.eatEvent); var pad = newHTML('div', 'insidekeyboard', keypad); for (var i = 1; i < 10; i++) { ScratchJr.keyboardAddKey(pad, i, 'onekey'); } ScratchJr.keyboardAddKey(pad, '-', 'onekey minus'); // ScratchJr.keyboardAddKey (pad, undefined, 'onekey space'); ScratchJr.keyboardAddKey(pad, '0', 'onekey'); ScratchJr.keyboardAddKey(pad, undefined, 'onekey delete'); // var keym = newHTML("div", 'onkey' ,pad); } static eatEvent (e) { e.preventDefault(); e.stopPropagation(); } static keyboardAddKey (p, str, c) { var keym = newHTML('div', c, p); var mk = newHTML('span', undefined, keym); mk.textContent = str ? str : ''; onTouchStartBind(keym,ScratchJr.numEditKey); } ///////////////////////////////////////////////// //Number Clicked static numberClicked (e, ti) { var delta = (activeFocus) ? activeFocus.delta : 0; if (activeFocus && (activeFocus.type == 'blockarg')) { activeFocus.div.className = 'numfield off'; ScratchJr.numEditDone(); } var b = ti.owner; // b is a BlockArg activeFocus = b; activeFocus.delta = delta; b.oldvalue = ti.textContent; activeFocus.div.className = 'numfield on'; keypad.className = 'picokeyboard on'; editfirst = true; var p = ti.parentNode.parentNode.owner; if (Number(p.min) < 0) { ScratchJr.setMinusKey(); } else { ScratchJr.setSpaceKey(); } if (delta == 0) { ScratchJr.needsToScroll(b); } } static needsToScroll (b) { // needs scroll var look = ScratchJr.getActiveScript(); // look canvas var dx = b.daddy.div.left + b.daddy.div.offsetWidth + look.left; var w = window.innerWidth - keypad.offsetWidth - 10; var delta = (dx > w) ? (w - dx) : 0; if (delta < 0) { var transition = { duration: 0.5, transition: 'ease-out', style: { left: (look.left + delta) + 'px' }, onComplete: function () { ScriptsPane.scroll.refresh(); } }; CSSTransition3D(look, transition); } activeFocus.delta = delta; } static numEditKey (e) { e.preventDefault(); e.stopPropagation(); var t = e.target; if (!t) { return; } if (t.className == '') { t = t.parentNode; } if (t.className != 'onekey space') { ScratchAudio.sndFX('keydown.wav'); } var c = t.textContent; var input = activeFocus.input; if (!c) { if ((t.parentNode.className == 'onekey delete') || (t.className == 'onekey delete')) { ScratchJr.numEditDelete(); } return; } var val = input.textContent; if (editfirst) { editfirst = false; val = '0'; } if ((c == '-') && (val != '0')) { ScratchAudio.sndFX('boing.wav'); return; } if (val == '0') { val = c; } else { val += c; } if ((Number(val).toString() != 'NaN') && ((Number(val) > 99) || (Number(val) < -99))) { ScratchAudio.sndFX('boing.wav'); } else { activeFocus.setValue(val); } } static setSpaceKey () { keypad.childNodes[0].childNodes[9].className = 'onekey space'; keypad.childNodes[0].childNodes[9].childNodes[0].textContent = ''; } static setMinusKey () { keypad.childNodes[0].childNodes[9].className = 'onekey minus'; keypad.childNodes[0].childNodes[9].childNodes[0].textContent = '-'; } static validateNumber (val) { return Number(val); } static revokeInput (val) { return val; } static numEditDelete () { var val = activeFocus.input.textContent; if (val.length != 0) { val = val.substring(0, val.length - 1); } if (val.length == 0) { val = '0'; } activeFocus.setValue(val); } static editDone () { if (document.activeElement.tagName === 'INPUT') { document.activeElement.blur(); } if (activeFocus == undefined) { return; } if (activeFocus.type != 'blockarg') { return; } if (activeFocus.isText()) { document.forms.editable.field.blur(); } else { ScratchJr.closeNumberEdit(); onBackButtonCallback.pop(); } } static closeNumberEdit () { ScratchJr.numEditDone(); ScratchJr.resetScroll(); keypad.className = 'picokeyboard off'; activeFocus.div.className = 'numfield off'; activeFocus = undefined; } static numEditDone () { var val = activeFocus.input.textContent; if (val == '-') { val = 0; } if (val == '-0') { val = 0; } val = ScratchJr.validateNumber(val); var ba = activeFocus; activeFocus.setValue(parseFloat(val)); ba.argValue = val; if (ba.daddy && ba.daddy.div.parentNode.owner) { var spr = ba.daddy.div.parentNode.owner.spr; if (spr && spr.div.parentNode) { var action = { action: 'scripts', where: spr.div.parentNode.owner.id, who: spr.id }; if (ba.argValue != ba.oldvalue) { ScratchJr.storyStart('ScratchJr.numEditDone'); Undo.record(action); } } } } static resetScroll () { var delta = activeFocus.delta; if (delta < 0) { var look = ScratchJr.getActiveScript(); // look canvas var transition = { duration: 0.5, transition: 'ease-out', style: { left: (look.left - delta) + 'px' }, onComplete: function () { ScriptsPane.scroll.refresh(); } }; CSSTransition3D(look, transition); } } static validate (str, name) { var str2 = str.replace(/\s*/g, ''); if (str2.length == 0) { return name; } return str; } ///////////////// //Application on the background /** * The functions that are invokved when the Android back button is clicked. * Methods are called from the rear and popped off after each invocation. */ /** * Handles updating the UI when the Android back button is clicked. This * method invokes the methods defined at {@link onBackButtonCallback} * if not empty, otherwise it invokes {@link ScratchJr.saveAndFlip}. The * back button callback is set by UI components when they initialize a modal * or popup, so it is the responsibility of popup components to correctly cleanup * the onBackButtonCallback. */ static goBack () { if (onBackButtonCallback.length === 0) { var e = document.createEvent('TouchEvent'); e.initTouchEvent(); e.preventDefault(); e.stopPropagation(); ScratchJr.saveAndFlip(e); } else { var callbackReference = onBackButtonCallback[onBackButtonCallback.length - 1]; callbackReference(); } } } // Expose ScratchJr to global window.ScratchJr = ScratchJr;
import React from 'react'; import PropTypes from 'prop-types'; function selectValue(value, selected, all) { const at = all.indexOf(value); const updated = selected.slice(0, at).concat(value, selected.slice(at)); // As inserting values at predefined index positions doesn't work with empty // arrays, we need to reorder the updated selection to match the initial order return updated.sort((a, b) => all.indexOf(a) > all.indexOf(b)); } function deselectValue(value, selected) { return selected.filter(v => v !== value); } function CheckboxesWidget(props) { const { id, disabled, options, value, autofocus, readonly, onChange } = props; const { enumOptions, inline } = options; const _onChange = option => event => { const all = enumOptions.map(({ value }) => value); if (event.target.checked) { onChange(selectValue(option.value, value, all)); } else { onChange(deselectValue(option.value, value)); } }; const inlineCls = inline ? 'form-check-inline' : ''; const disabledCls = disabled || readonly ? 'disabled' : ''; return ( <div className="checkboxes" id={id} data-testid={inline ? 'checkboxes-inline' : 'checkboxes'} > {enumOptions.map((option, index) => { const checked = value.indexOf(option.value) !== -1; return ( <div key={index} className={`form-check ${inlineCls} ${disabledCls}`}> <input type="checkbox" id={`${id}_${index}`} className="form-check-input" checked={checked} disabled={disabled || readonly} autoFocus={autofocus && index === 0} onChange={_onChange(option)} /> <label htmlFor={`${id}_${index}`} className="form-check-label"> {option.label} </label> </div> ); })} </div> ); } CheckboxesWidget.defaultProps = { autofocus: false, options: { inline: false } }; if (process.env.NODE_ENV !== 'production') { CheckboxesWidget.propTypes = { schema: PropTypes.object.isRequired, id: PropTypes.string.isRequired, options: PropTypes.shape({ enumOptions: PropTypes.array, inline: PropTypes.bool }).isRequired, value: PropTypes.any, required: PropTypes.bool, readonly: PropTypes.bool, disabled: PropTypes.bool, multiple: PropTypes.bool, autofocus: PropTypes.bool, onChange: PropTypes.func }; } export default CheckboxesWidget;
import nconf from 'nconf'; import axios from 'axios'; import jwt from 'jsonwebtoken'; import fs from 'fs'; import { promisify } from 'util'; import { expect } from 'chai'; const jwtSign = promisify(jwt.sign); const readFile = promisify(fs.readFile); const jwtOptions = { algorithm: 'RS256', issuer: 'tweek', expiresIn: '15m', }; async function generateToken() { const inlineKey = nconf.get('GIT_PRIVATE_KEY_INLINE'); const key = (inlineKey && new Buffer(inlineKey, 'base64')) || (await readFile(nconf.get('GIT_PRIVATE_KEY_PATH'))); return await jwtSign({}, key, jwtOptions); } async function getAuthenticatedClient(baseURL) { const token = await generateToken(); return axios.create({ baseURL, timeout: 1000, headers: { Authorization: `Bearer ${token}`, }, }); } export default class AuthenticatedClient { constructor(baseUrl) { this._clientPromise = getAuthenticatedClient(baseUrl); } _get(path) { return browser.runAsync(async () => { let client = await this._clientPromise; return client.get(path).then(r => r.data); }); } }
/*! * Link dialog plugin for Editor.md * * @file link-dialog.js * @author pandao * @version 1.2.1 * @updateTime 2015-06-09 * {@link https://github.com/pandao/editor.md} * @license MIT */ (function() { var factory = function (exports) { var pluginName = "link-dialog"; exports.fn.linkDialog = function() { var _this = this; var cm = this.cm; var editor = this.editor; var settings = this.settings; var selection = cm.getSelection(); var lang = this.lang; var linkLang = lang.dialog.link; var classPrefix = this.classPrefix; var dialogName = classPrefix + pluginName, dialog; cm.focus(); if (editor.find("." + dialogName).length > 0) { dialog = editor.find("." + dialogName); dialog.find("[data-url]").val("http://"); dialog.find("[data-title]").val(selection); this.dialogShowMask(dialog); this.dialogLockScreen(); dialog.show(); } else { var dialogHTML = "<div class=\"" + classPrefix + "form\">" + "<label>" + linkLang.url + "</label>" + "<input type=\"text\" value=\"http://\" data-url />" + "<br/>" + "<label>" + linkLang.urlTitle + "</label>" + "<input type=\"text\" value=\"" + selection + "\" data-title />" + "<br/>" + // Wizard 添加 START "<label>展示方式</label>" + "<select data-style><option value='normal'>普通链接</option><option value='frame'>框架页嵌入</option></select>" + // Wizard 添加 END "</div>"; dialog = this.createDialog({ title : linkLang.title, width : 380, height : 230, content : dialogHTML, mask : settings.dialogShowMask, drag : settings.dialogDraggable, lockScreen : settings.dialogLockScreen, maskStyle : { opacity : settings.dialogMaskOpacity, backgroundColor : settings.dialogMaskBgColor }, buttons : { enter : [lang.buttons.enter, function() { var url = this.find("[data-url]").val(); var title = this.find("[data-title]").val(); var displayStyle = this.find("[data-style]").val(); if (url === "http://" || url === "") { alert(linkLang.urlEmpty); return false; } // Wizard 添加 START var controlTitle = ''; switch (displayStyle) { case 'normal': controlTitle = title; break; default: controlTitle = "wizard-style:" + displayStyle; } var str = "[" + title + "](" + url + " \"" + controlTitle + "\")"; // Wizard 添加 END if (controlTitle === "") { str = "[" + url + "](" + url + ")"; } cm.replaceSelection(str); this.hide().lockScreen(false).hideMask(); return false; }], cancel : [lang.buttons.cancel, function() { this.hide().lockScreen(false).hideMask(); return false; }] } }); } }; }; // CommonJS/Node.js if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { module.exports = factory; } else if (typeof define === "function") // AMD/CMD/Sea.js { if (define.amd) { // for Require.js define(["editormd"], function(editormd) { factory(editormd); }); } else { // for Sea.js define(function(require) { var editormd = require("./../../editormd"); factory(editormd); }); } } else { factory(window.editormd); } })();
exports.deviceName = 'Byteball Devnet Hub'; exports.permanent_pairing_secret = '0000'; exports.WS_PROTOCOL = 'ws://'; exports.KEYS_FILENAME = 'keys.json'; exports.port = 6611; exports.bServeAsHub = true; exports.bLight = false; exports.initial_witnesses = [ 'ZQFHJXFWT2OCEBXF26GFXJU4MPASWPJT' ]; exports.trustedRegistries = [ 'ZQFHJXFWT2OCEBXF26GFXJU4MPASWPJT' ];
import React from 'react' import Helmet from 'react-helmet' import { graphql } from 'gatsby' import Layout from '../components/Layout' import PostList from '../components/PostList' const Category = props => { const { data, pageContext } = props const { edges: posts, totalCount } = data.allWordpressPost const { title: siteTitle } = data.site.siteMetadata const { name: category } = pageContext const title = `${totalCount} post${ totalCount === 1 ? '' : 's' } in the “${category}” category` return ( <Layout> <Helmet title={`${category} | ${siteTitle}`} /> <PostList posts={posts} title={title} /> </Layout> ) } export default Category export const categoryQuery = graphql` query CategoryPage($slug: String!) { site { siteMetadata { title } } allWordpressPost( filter: { categories: { elemMatch: { slug: { eq: $slug } } } } ) { totalCount edges { node { id slug title date(formatString: "MMMM DD, YYYY") author{ name slug } excerpt } } } } `
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";e.defineMode("javascript",function(t,r){function n(e){for(var t,r=!1,n=!1;null!=(t=e.next());){if(!r){if("/"==t&&!n)return;"["==t?n=!0:n&&"]"==t&&(n=!1)}r=!r&&"\\"==t}}function a(e,t,r){return Te=e,$e=r,t}function i(e,t){var r=e.next();if('"'==r||"'"==r)return t.tokenize=o(r),t.tokenize(e,t);if("."==r&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return a("number","number");if("."==r&&e.match(".."))return a("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(r))return a(r);if("="==r&&e.eat(">"))return a("=>","operator");if("0"==r&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),a("number","number");if("0"==r&&e.eat(/o/i))return e.eatWhile(/[0-7]/i),a("number","number");if("0"==r&&e.eat(/b/i))return e.eatWhile(/[01]/i),a("number","number");if(/\d/.test(r))return e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),a("number","number");if("/"==r)return e.eat("*")?(t.tokenize=c,c(e,t)):e.eat("/")?(e.skipToEnd(),a("comment","comment")):Ie(e,t,1)?(n(e),e.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/),a("regexp","string-2")):(e.eat("="),a("operator","operator",e.current()));if("`"==r)return t.tokenize=u,u(e,t);if("#"==r)return e.skipToEnd(),a("error","error");if(Ue.test(r))return">"==r&&t.lexical&&">"==t.lexical.type||(e.eat("=")?"!"!=r&&"="!=r||e.eat("="):/[<>*+\-]/.test(r)&&(e.eat(r),">"==r&&e.eat(r))),a("operator","operator",e.current());if(We.test(r)){e.eatWhile(We);var i=e.current();if("."!=t.lastType){if(Ne.propertyIsEnumerable(i)){var s=Ne[i];return a(s.type,s.style,i)}if("async"==i&&e.match(/^(\s|\/\*.*?\*\/)*[\(\w]/,!1))return a("async","keyword",i)}return a("variable","variable",i)}}function o(e){return function(t,r){var n,o=!1;if(Oe&&"@"==t.peek()&&t.match(Be))return r.tokenize=i,a("jsonld-keyword","meta");for(;null!=(n=t.next())&&(n!=e||o);)o=!o&&"\\"==n;return o||(r.tokenize=i),a("string","string")}}function c(e,t){for(var r,n=!1;r=e.next();){if("/"==r&&n){t.tokenize=i;break}n="*"==r}return a("comment","comment")}function u(e,t){for(var r,n=!1;null!=(r=e.next());){if(!n&&("`"==r||"$"==r&&e.eat("{"))){t.tokenize=i;break}n=!n&&"\\"==r}return a("quasi","string-2",e.current())}function s(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var r=e.string.indexOf("=>",e.start);if(!(r<0)){if(Se){var n=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,r));n&&(r=n.index)}for(var a=0,i=!1,o=r-1;o>=0;--o){var c=e.string.charAt(o),u=He.indexOf(c);if(u>=0&&u<3){if(!a){++o;break}if(0==--a){"("==c&&(i=!0);break}}else if(u>=3&&u<6)++a;else if(We.test(c))i=!0;else{if(/["'\/]/.test(c))return;if(i&&!a){++o;break}}}i&&!a&&(t.fatArrowAt=o)}}function f(e,t,r,n,a,i){this.indented=e,this.column=t,this.type=r,this.prev=a,this.info=i,null!=n&&(this.align=n)}function l(e,t){for(var r=e.localVars;r;r=r.next)if(r.name==t)return!0;for(var n=e.context;n;n=n.prev)for(var r=n.vars;r;r=r.next)if(r.name==t)return!0}function d(e,t,r,n,a){var i=e.cc;for(Fe.state=e,Fe.stream=a,Fe.marked=null,Fe.cc=i,Fe.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;){if((i.length?i.pop():Pe?j:g)(r,n)){for(;i.length&&i[i.length-1].lex;)i.pop()();return Fe.marked?Fe.marked:"variable"==r&&l(e,n)?"variable-2":t}}}function p(){for(var e=arguments.length-1;e>=0;e--)Fe.cc.push(arguments[e])}function m(){return p.apply(null,arguments),!0}function k(e){function t(t){for(var r=t;r;r=r.next)if(r.name==e)return!0;return!1}var n=Fe.state;if(Fe.marked="def",n.context){if(t(n.localVars))return;n.localVars={name:e,next:n.localVars}}else{if(t(n.globalVars))return;r.globalVars&&(n.globalVars={name:e,next:n.globalVars})}}function v(e){return"public"==e||"private"==e||"protected"==e||"abstract"==e||"readonly"==e}function y(){Fe.state.context={prev:Fe.state.context,vars:Fe.state.localVars},Fe.state.localVars=Ge}function b(){Fe.state.localVars=Fe.state.context.vars,Fe.state.context=Fe.state.context.prev}function w(e,t){var r=function(){var r=Fe.state,n=r.indented;if("stat"==r.lexical.type)n=r.lexical.indented;else for(var a=r.lexical;a&&")"==a.type&&a.align;a=a.prev)n=a.indented;r.lexical=new f(n,Fe.stream.column(),e,null,r.lexical,t)};return r.lex=!0,r}function x(){var e=Fe.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function h(e){function t(r){return r==e?m():";"==e?p():m(t)}return t}function g(e,t){return"var"==e?m(w("vardef",t.length),re,h(";"),x):"keyword a"==e?m(w("form"),V,g,x):"keyword b"==e?m(w("form"),g,x):"keyword d"==e?Fe.stream.match(/^\s*$/,!1)?m():m(w("stat"),E,h(";"),x):"debugger"==e?m(h(";")):"{"==e?m(w("}"),G,x):";"==e?m():"if"==e?("else"==Fe.state.lexical.info&&Fe.state.cc[Fe.state.cc.length-1]==x&&Fe.state.cc.pop()(),m(w("form"),V,g,x,ce)):"function"==e?m(pe):"for"==e?m(w("form"),ue,g,x):"class"==e||Se&&"interface"==t?(Fe.marked="keyword",m(w("form"),ve,x)):"variable"==e?Se&&"type"==t?(Fe.marked="keyword",m(Q,h("operator"),Q,h(";"))):Se&&"declare"==t?(Fe.marked="keyword",m(g)):Se&&("module"==t||"enum"==t)&&Fe.stream.match(/^\s*\w/,!1)?(Fe.marked="keyword",m(w("form"),ne,h("{"),w("}"),G,x,x)):Se&&"namespace"==t?(Fe.marked="keyword",m(w("form"),j,G,x)):m(w("stat"),W):"switch"==e?m(w("form"),V,h("{"),w("}","switch"),G,x,x):"case"==e?m(j,h(":")):"default"==e?m(h(":")):"catch"==e?m(w("form"),y,h("("),me,h(")"),g,x,b):"export"==e?m(w("stat"),xe,x):"import"==e?m(w("stat"),ge,x):"async"==e?m(g):"@"==t?m(j,g):p(w("stat"),j,h(";"),x)}function j(e,t){return A(e,t,!1)}function M(e,t){return A(e,t,!0)}function V(e){return"("!=e?p():m(w(")"),j,h(")"),x)}function A(e,t,r){if(Fe.state.fatArrowAt==Fe.stream.start){var n=r?q:C;if("("==e)return m(y,w(")"),D(me,")"),x,h("=>"),n,b);if("variable"==e)return p(y,ne,h("=>"),n,b)}var a=r?I:z;return De.hasOwnProperty(e)?m(a):"function"==e?m(pe,a):"class"==e||Se&&"interface"==t?(Fe.marked="keyword",m(w("form"),ke,x)):"keyword c"==e||"async"==e?m(r?M:j):"("==e?m(w(")"),E,h(")"),x,a):"operator"==e||"spread"==e?m(r?M:j):"["==e?m(w("]"),Ee,x,a):"{"==e?F(U,"}",null,a):"quasi"==e?p(T,a):"new"==e?m(O(r)):m()}function E(e){return e.match(/[;\}\)\],]/)?p():p(j)}function z(e,t){return","==e?m(j):I(e,t,!1)}function I(e,t,r){var n=0==r?z:I,a=0==r?j:M;return"=>"==e?m(y,r?q:C,b):"operator"==e?/\+\+|--/.test(t)||Se&&"!"==t?m(n):Se&&"<"==t&&Fe.stream.match(/^([^>]|<.*?>)*>\s*\(/,!1)?m(w(">"),D(Q,">"),x,n):"?"==t?m(j,h(":"),a):m(a):"quasi"==e?p(T,n):";"!=e?"("==e?F(M,")","call",n):"."==e?m(N,n):"["==e?m(w("]"),E,h("]"),x,n):Se&&"as"==t?(Fe.marked="keyword",m(Q,n)):"regexp"==e?(Fe.state.lastType=Fe.marked="operator",Fe.stream.backUp(Fe.stream.pos-Fe.stream.start-1),m(a)):void 0:void 0}function T(e,t){return"quasi"!=e?p():"${"!=t.slice(t.length-2)?m(T):m(j,$)}function $(e){if("}"==e)return Fe.marked="string-2",Fe.state.tokenize=u,m(T)}function C(e){return s(Fe.stream,Fe.state),p("{"==e?g:j)}function q(e){return s(Fe.stream,Fe.state),p("{"==e?g:M)}function O(e){return function(t){return"."==t?m(e?S:P):"variable"==t&&Se?m(_,e?I:z):p(e?M:j)}}function P(e,t){if("target"==t)return Fe.marked="keyword",m(z)}function S(e,t){if("target"==t)return Fe.marked="keyword",m(I)}function W(e){return":"==e?m(x,g):p(z,h(";"),x)}function N(e){if("variable"==e)return Fe.marked="property",m()}function U(e,t){if("async"==e)return Fe.marked="property",m(U);if("variable"==e||"keyword"==Fe.style){if(Fe.marked="property","get"==t||"set"==t)return m(B);var r;return Se&&Fe.state.fatArrowAt==Fe.stream.start&&(r=Fe.stream.match(/^\s*:\s*/,!1))&&(Fe.state.fatArrowAt=Fe.stream.pos+r[0].length),m(H)}return"number"==e||"string"==e?(Fe.marked=Oe?"property":Fe.style+" property",m(H)):"jsonld-keyword"==e?m(H):Se&&v(t)?(Fe.marked="keyword",m(U)):"["==e?m(j,J,h("]"),H):"spread"==e?m(M,H):"*"==t?(Fe.marked="keyword",m(U)):":"==e?p(H):void 0}function B(e){return"variable"!=e?p(H):(Fe.marked="property",m(pe))}function H(e){return":"==e?m(M):"("==e?p(pe):void 0}function D(e,t,r){function n(a,i){if(r?r.indexOf(a)>-1:","==a){var o=Fe.state.lexical;return"call"==o.info&&(o.pos=(o.pos||0)+1),m(function(r,n){return r==t||n==t?p():p(e)},n)}return a==t||i==t?m():m(h(t))}return function(r,a){return r==t||a==t?m():p(e,n)}}function F(e,t,r){for(var n=3;n<arguments.length;n++)Fe.cc.push(arguments[n]);return m(w(t,r),D(e,t),x)}function G(e){return"}"==e?m():p(g,G)}function J(e,t){if(Se){if(":"==e)return m(Q);if("?"==t)return m(J)}}function K(e){if(Se&&":"==e)return Fe.stream.match(/^\s*\w+\s+is\b/,!1)?m(j,L,Q):m(Q)}function L(e,t){if("is"==t)return Fe.marked="keyword",m()}function Q(e,t){return"variable"==e||"void"==t?"keyof"==t?(Fe.marked="keyword",m(Q)):(Fe.marked="type",m(Z)):"string"==e||"number"==e||"atom"==e?m(Z):"["==e?m(w("]"),D(Q,"]",","),x,Z):"{"==e?m(w("}"),D(X,"}",",;"),x,Z):"("==e?m(D(Y,")"),R):void 0}function R(e){if("=>"==e)return m(Q)}function X(e,t){return"variable"==e||"keyword"==Fe.style?(Fe.marked="property",m(X)):"?"==t?m(X):":"==e?m(Q):"["==e?m(j,J,h("]"),X):void 0}function Y(e){return"variable"==e?m(Y):":"==e?m(Q):void 0}function Z(e,t){return"<"==t?m(w(">"),D(Q,">"),x,Z):"|"==t||"."==e?m(Q):"["==e?m(h("]"),Z):"extends"==t||"implements"==t?(Fe.marked="keyword",m(Q)):void 0}function _(e,t){if("<"==t)return m(w(">"),D(Q,">"),x,Z)}function ee(){return p(Q,te)}function te(e,t){if("="==t)return m(Q)}function re(){return p(ne,J,ie,oe)}function ne(e,t){return Se&&v(t)?(Fe.marked="keyword",m(ne)):"variable"==e?(k(t),m()):"spread"==e?m(ne):"["==e?F(ne,"]"):"{"==e?F(ae,"}"):void 0}function ae(e,t){return"variable"!=e||Fe.stream.match(/^\s*:/,!1)?("variable"==e&&(Fe.marked="property"),"spread"==e?m(ne):"}"==e?p():m(h(":"),ne,ie)):(k(t),m(ie))}function ie(e,t){if("="==t)return m(M)}function oe(e){if(","==e)return m(re)}function ce(e,t){if("keyword b"==e&&"else"==t)return m(w("form","else"),g,x)}function ue(e){if("("==e)return m(w(")"),se,h(")"),x)}function se(e){return"var"==e?m(re,h(";"),le):";"==e?m(le):"variable"==e?m(fe):p(j,h(";"),le)}function fe(e,t){return"in"==t||"of"==t?(Fe.marked="keyword",m(j)):m(z,le)}function le(e,t){return";"==e?m(de):"in"==t||"of"==t?(Fe.marked="keyword",m(j)):p(j,h(";"),de)}function de(e){")"!=e&&m(j)}function pe(e,t){return"*"==t?(Fe.marked="keyword",m(pe)):"variable"==e?(k(t),m(pe)):"("==e?m(y,w(")"),D(me,")"),x,K,g,b):Se&&"<"==t?m(w(">"),D(ee,">"),x,pe):void 0}function me(e,t){return"@"==t&&m(j,me),"spread"==e?m(me):Se&&v(t)?(Fe.marked="keyword",m(me)):p(ne,J,ie)}function ke(e,t){return"variable"==e?ve(e,t):ye(e,t)}function ve(e,t){if("variable"==e)return k(t),m(ye)}function ye(e,t){return"<"==t?m(w(">"),D(ee,">"),x,ye):"extends"==t||"implements"==t||Se&&","==e?m(Se?Q:j,ye):"{"==e?m(w("}"),be,x):void 0}function be(e,t){return"async"==e||"variable"==e&&("static"==t||"get"==t||"set"==t||Se&&v(t))&&Fe.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(Fe.marked="keyword",m(be)):"variable"==e||"keyword"==Fe.style?(Fe.marked="property",m(Se?we:pe,be)):"["==e?m(j,J,h("]"),Se?we:pe,be):"*"==t?(Fe.marked="keyword",m(be)):";"==e?m(be):"}"==e?m():"@"==t?m(j,be):void 0}function we(e,t){return"?"==t?m(we):":"==e?m(Q,ie):"="==t?m(M):p(pe)}function xe(e,t){return"*"==t?(Fe.marked="keyword",m(Ae,h(";"))):"default"==t?(Fe.marked="keyword",m(j,h(";"))):"{"==e?m(D(he,"}"),Ae,h(";")):p(g)}function he(e,t){return"as"==t?(Fe.marked="keyword",m(h("variable"))):"variable"==e?p(M,he):void 0}function ge(e){return"string"==e?m():p(je,Me,Ae)}function je(e,t){return"{"==e?F(je,"}"):("variable"==e&&k(t),"*"==t&&(Fe.marked="keyword"),m(Ve))}function Me(e){if(","==e)return m(je,Me)}function Ve(e,t){if("as"==t)return Fe.marked="keyword",m(je)}function Ae(e,t){if("from"==t)return Fe.marked="keyword",m(j)}function Ee(e){return"]"==e?m():p(D(M,"]"))}function ze(e,t){return"operator"==e.lastType||","==e.lastType||Ue.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}function Ie(e,t,r){return t.tokenize==i&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-(r||0)))}var Te,$e,Ce=t.indentUnit,qe=r.statementIndent,Oe=r.jsonld,Pe=r.json||Oe,Se=r.typescript,We=r.wordCharacters||/[\w$\xa1-\uffff]/,Ne=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),r=e("keyword b"),n=e("keyword c"),a=e("keyword d"),i=e("operator"),o={type:"atom",style:"atom"};return{if:e("if"),while:t,with:t,else:r,do:r,try:r,finally:r,return:a,break:a,continue:a,new:e("new"),delete:n,void:n,throw:n,debugger:e("debugger"),var:e("var"),const:e("var"),let:e("var"),function:e("function"),catch:e("catch"),for:e("for"),switch:e("switch"),case:e("case"),default:e("default"),in:i,typeof:i,instanceof:i,true:o,false:o,null:o,undefined:o,NaN:o,Infinity:o,this:e("this"),class:e("class"),super:e("atom"),yield:n,export:e("export"),import:e("import"),extends:n,await:n}}(),Ue=/[+\-*&%=<>!?|~^@]/,Be=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,He="([{}])",De={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0},Fe={state:null,column:null,marked:null,cc:null},Ge={name:"this",next:{name:"arguments"}};return x.lex=!0,{startState:function(e){var t={tokenize:i,lastType:"sof",cc:[],lexical:new f((e||0)-Ce,0,"block",!1),localVars:r.localVars,context:r.localVars&&{vars:r.localVars},indented:e||0};return r.globalVars&&"object"==typeof r.globalVars&&(t.globalVars=r.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),s(e,t)),t.tokenize!=c&&e.eatSpace())return null;var r=t.tokenize(e,t);return"comment"==Te?r:(t.lastType="operator"!=Te||"++"!=$e&&"--"!=$e?Te:"incdec",d(t,r,Te,$e,e))},indent:function(t,n){if(t.tokenize==c)return e.Pass;if(t.tokenize!=i)return 0;var a,o=n&&n.charAt(0),u=t.lexical;if(!/^\s*else\b/.test(n))for(var s=t.cc.length-1;s>=0;--s){var f=t.cc[s];if(f==x)u=u.prev;else if(f!=ce)break}for(;("stat"==u.type||"form"==u.type)&&("}"==o||(a=t.cc[t.cc.length-1])&&(a==z||a==I)&&!/^[,\.=+\-*:?[\(]/.test(n));)u=u.prev;qe&&")"==u.type&&"stat"==u.prev.type&&(u=u.prev);var l=u.type,d=o==l;return"vardef"==l?u.indented+("operator"==t.lastType||","==t.lastType?u.info+1:0):"form"==l&&"{"==o?u.indented:"form"==l?u.indented+Ce:"stat"==l?u.indented+(ze(t,n)?qe||Ce:0):"switch"!=u.info||d||0==r.doubleIndentSwitch?u.align?u.column+(d?0:1):u.indented+(d?0:Ce):u.indented+(/^(?:case|default)\b/.test(n)?Ce:2*Ce)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:Pe?null:"/*",blockCommentEnd:Pe?null:"*/",blockCommentContinue:Pe?null:" * ",lineComment:Pe?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:Pe?"json":"javascript",jsonldMode:Oe,jsonMode:Pe,expressionAllowed:Ie,skipExpression:function(e){var t=e.cc[e.cc.length-1];t!=j&&t!=M||e.cc.pop()}}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})});
/** Copyright 2011-2012 Christian Iversen <ci@sikkerhed.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ $PY.isinstance = function(obj, cls) { if (cls instanceof Array) { for (var i = 0; i < cls.length; i++) { var c = obj.PY$__class__; while (c) { if (c === cls[i]) return true; c = c.PY$__super__; } } return false; } else { var c = obj.PY$__class__; while (c) { if (c === cls) return true; c = c.PY$__super__; } return false; } }; $PY.repr = function(obj) { return __builtins__.PY$repr(obj)._js_(); }; $PY.dump = function(obj) { var res = []; for (var i in obj) { var val = obj[i]; if (typeof val === 'function') { res.push(i + " (function)"); } else if (typeof val === 'number') { res.push(i + " (number: " + val + ")"); } else if (typeof val === 'string') { res.push(i + " (string: " + val + ")"); } else if (val === null) { res.push(i + " (null)"); } else if (val === undefined) { res.push(i + " (undefined)"); } else { res.push(i + " (object)"); } } res.sort(); return "[\n " + res.join("\n ") + "\n]"; }; $PY.len = function(obj) { var c = obj.PY$__class__; if (c === list || c === tuple || c === str || c === basestring || c === unicode) { return obj.obj.length; } else if (obj.PY$__len__ !== undefined) { return obj.PY$__len__()._js_(); } else { throw __builtins__.PY$AttributeError('__len__'); } }; $PY.next = function(obj) { if (obj.PY$__class__ === iter) { return obj.next(); } else { try { return obj.PY$next(); } catch (x) { if (x === $PY.c_stopiter || $PY.isinstance(x, __builtins__.PY$StopIteration)) { return null; } else { throw x; } } } }; $PY.__not__ = function(obj) { if (obj.PY$__nonzero__ !== undefined) { return js(obj.PY$__nonzero__()) ? False : True; } else if (obj.PY$__len__ !== undefined) { return js(obj.PY$__len__()) === 0 ? True : False; } else { return js(obj) ? False : True; } }; $PY.__is__ = function(a, b) { return a === b ? True : False; }; $PY.c_nif = function() { throw __builtins__.PY$NotImplementedError("The called function is not implemented in Pyjaco"); }
'use strict'; /*! * V4Fire Client Core * https://github.com/V4Fire/Client * * Released under the MIT license * https://github.com/V4Fire/Client/blob/master/LICENSE */ import Store from 'core/store'; import Block from 'core/block'; import { queue, backQueue } from 'core/render'; import { setLang, lang } from 'core/i18n'; import * as helpers from 'core/helpers'; import * as browser from 'core/const/browser'; const Vue = require('vue'); export const $$ = new Store(); export default class iPage extends Block { /** * Vue template */ template(): Object { return {}; } /** * Vue component */ component(): Object { return { data: { /** * System language store */ langStore: lang, /** * Block render cursor */ i: '', /** * Counter of async components */ asyncCounter: 0, /** * Cache of child async components */ asyncComponents: {}, /** * Cache of child background async components */ asyncBackComponents: {}, /** * Base modifiers */ baseMods: {}, /** * Additional classes for elements */ classes: {} }, computed: { /** * Data helpers */ h(): Object { return helpers; }, /** * Browser constants */ b(): Object { return browser; }, /** * System language */ lang: { get(): string { return this.langStore; }, set(value: string) { setLang(this.langStore = value); } }, /** * Link to i18n function */ i18n(): Function { return i18n; }, /** * Alias for .i18n */ t(): Function { return this.i18n; }, /** * Link to window.l */ l(): Function { return l; }, /** * Link to console API */ console(): Function { return console; }, /** * Link to window.location */ location(): Function { return location; } }, watch: { langStore() { this.$forceUpdate(); } }, methods: { /** * Returns an object with base block modifiers * @param mods - additional modifiers ({modifier: {currentValue: value}} || {modifier: value}) */ provideMods(mods?: Object): Object { return mods || {}; }, /** * Returns an instance of Vue component by the specified selector * @param selector */ $(selector: string): ?iBlock { const $0 = document.query(selector), n = $0 && $0.closest('.i-block-helper'); return n && n.vueComponent; }, /** * Adds a component to the render queue * @param id - task id */ regAsyncComponent(id: string): string { if (!this.asyncComponents[id]) { queue.add(() => { this.asyncCounter++; this.$set(this.asyncComponents, id, true); }); } return id; }, /** * Adds a component to the background render queue * @param id - task id */ regAsyncBackComponent(id: string): string { if (!this.regAsyncBackComponent[id]) { backQueue.add(() => { this.asyncCounter++; this.$set(this.regAsyncBackComponent, id, true); }); } return id; } } }; } /** * @override * @param [params] - page params */ constructor(params?: Object) { params = {data: {}, ...params}; super(params); const comp = { data: {}, ...this.component(), ...this.template(), el: this.node }; if (params.data) { Object.assign(comp.data, params.data); } this.model = new Vue(comp); this.node = this.model.$el.parentNode; Object.assign(this.model, { async: this.async, block: this, localEvent: this.localEvent, blockId: this.id }); } }
/** * Scope and the var statement * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var */ var color = "purple"; document.querySelector(".left").style.backgroundColor = color; document.querySelector(".left .color-value").innerHTML = color; color = "skyblue"; function headingColor() { color = "blue"; document.querySelector(".title").style.color = color; } document.querySelector(".right").style.backgroundColor = color; document.querySelector(".right .color-value").innerHTML = color; headingColor();
(window.webpackJsonp=window.webpackJsonp||[]).push([[79],{2918:function(t,e,n){"use strict";n.r(e),n.d(e,"icon",(function(){return c}));n(11),n(2),n(6),n(8),n(5),n(9);var r=n(0),a=n.n(r);function o(){return(o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function i(t,e){if(null==t)return{};var n,r,a=function(t,e){if(null==t)return{};var n,r,a={},o=Object.keys(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||(a[n]=t[n]);return a}(t,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}var l=function(t){var e=t.title,n=t.titleId,r=i(t,["title","titleId"]);return a.a.createElement("svg",o({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":n},r),e?a.a.createElement("title",{id:n},e):null,a.a.createElement("path",{d:"M11.4 0c.235 0 .46.099.622.273l2.743 3c.151.162.235.378.235.602v9.25a.867.867 0 01-.857.875H3.857A.867.867 0 013 13.125V.875C3 .392 3.384 0 3.857 0H11.4zM14 4h-2.6a.4.4 0 01-.4-.4V1H4v12h10V4z"}),a.a.createElement("path",{d:"M3 1H2a1 1 0 00-1 1v13a1 1 0 001 1h10a1 1 0 001-1v-1h-1v1H2V2h1V1z"}))},c=l;l.__docgenInfo={description:"",methods:[],displayName:"EuiIconCopy"}}}]); //# sourceMappingURL=icon.copy-js.min.js.map