language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
_printMessage(logLevel, logMethod, logArguments) { let currentLogLevel = this._allowedLogLevel; if (self && self.goog && self.goog.logLevel) { currentLogLevel = self.goog.logLevel; } if (currentLogLevel === self.goog.LOG_LEVEL.none || logLevel < currentLogLevel) { return; } logMethod(...logArguments); }
_printMessage(logLevel, logMethod, logArguments) { let currentLogLevel = this._allowedLogLevel; if (self && self.goog && self.goog.logLevel) { currentLogLevel = self.goog.logLevel; } if (currentLogLevel === self.goog.LOG_LEVEL.none || logLevel < currentLogLevel) { return; } logMethod(...logArguments); }
JavaScript
async addQueueNameToAllQueues() { if(!this._isQueueNameAddedToAllQueue) { let allQueues = await this._idbQDb.get(allQueuesPlaceholder); allQueues = allQueues || []; if(!allQueues.includes(this._queueName)) { allQueues.push(this._queueName); } this._idbQDb.put(allQueuesPlaceholder, allQueues); this._isQueueNameAddedToAllQueue = true; } }
async addQueueNameToAllQueues() { if(!this._isQueueNameAddedToAllQueue) { let allQueues = await this._idbQDb.get(allQueuesPlaceholder); allQueues = allQueues || []; if(!allQueues.includes(this._queueName)) { allQueues.push(this._queueName); } this._idbQDb.put(allQueuesPlaceholder, allQueues); this._isQueueNameAddedToAllQueue = true; } }
JavaScript
async push({request}) { assert.isInstance({request}, Request); const hash = `${request.url}!${Date.now()}!${_requestCounter++}`; const queuableRequest = await getQueueableRequest({ request, config: this._config, }); try{ this._queue.push(hash); // add to queue this.saveQueue(); this._idbQDb.put(hash, queuableRequest); await this.addQueueNameToAllQueues(); // register sync self.registration && self.registration.sync.register(tagNamePrefix + this._queueName); // broadcast the success of request added to the queue broadcastMessage({ broadcastChannel: this._broadcastChannel, type: broadcastMessageAddedType, id: hash, url: request.url, }); } catch(e) { // broadcast the failure of request added to the queue broadcastMessage({ broadcastChannel: this._broadcastChannel, type: broadcastMessageFailedType, id: hash, url: request.url, }); } }
async push({request}) { assert.isInstance({request}, Request); const hash = `${request.url}!${Date.now()}!${_requestCounter++}`; const queuableRequest = await getQueueableRequest({ request, config: this._config, }); try{ this._queue.push(hash); // add to queue this.saveQueue(); this._idbQDb.put(hash, queuableRequest); await this.addQueueNameToAllQueues(); // register sync self.registration && self.registration.sync.register(tagNamePrefix + this._queueName); // broadcast the success of request added to the queue broadcastMessage({ broadcastChannel: this._broadcastChannel, type: broadcastMessageAddedType, id: hash, url: request.url, }); } catch(e) { // broadcast the failure of request added to the queue broadcastMessage({ broadcastChannel: this._broadcastChannel, type: broadcastMessageFailedType, id: hash, url: request.url, }); } }
JavaScript
isResponseCacheable({response} = {}) { assert.isInstance({response}, Response); let cacheable = true; if (this.statuses) { cacheable = this.statuses.includes(response.status); } if (this.headers && cacheable) { cacheable = Object.keys(this.headers).some((headerName) => { return response.headers.get(headerName) === this.headers[headerName]; }); } return cacheable; }
isResponseCacheable({response} = {}) { assert.isInstance({response}, Response); let cacheable = true; if (this.statuses) { cacheable = this.statuses.includes(response.status); } if (this.headers && cacheable) { cacheable = Object.keys(this.headers).some((headerName) => { return response.headers.get(headerName) === this.headers[headerName]; }); } return cacheable; }
JavaScript
async findExtraEntries({cacheName} = {}) { assert.isType({cacheName}, 'string'); const urls = []; const db = await this.getDB({cacheName}); let tx = db.transaction(cacheName, 'readonly'); let store = tx.objectStore(cacheName); let timestampIndex = store.index(timestampPropertyName); const initialCount = await timestampIndex.count(); if (initialCount > this.maxEntries) { // We need to create a new transaction to make Firefox happy. tx = db.transaction(cacheName, 'readonly'); store = tx.objectStore(cacheName); timestampIndex = store.index(timestampPropertyName); timestampIndex.iterateCursor((cursor) => { if (!cursor) { return; } urls.push(cursor.value[urlPropertyName]); if (initialCount - urls.length > this.maxEntries) { cursor.continue(); } }); } await tx.complete; return urls; }
async findExtraEntries({cacheName} = {}) { assert.isType({cacheName}, 'string'); const urls = []; const db = await this.getDB({cacheName}); let tx = db.transaction(cacheName, 'readonly'); let store = tx.objectStore(cacheName); let timestampIndex = store.index(timestampPropertyName); const initialCount = await timestampIndex.count(); if (initialCount > this.maxEntries) { // We need to create a new transaction to make Firefox happy. tx = db.transaction(cacheName, 'readonly'); store = tx.objectStore(cacheName); timestampIndex = store.index(timestampPropertyName); timestampIndex.iterateCursor((cursor) => { if (!cursor) { return; } urls.push(cursor.value[urlPropertyName]); if (initialCount - urls.length > this.maxEntries) { cursor.continue(); } }); } await tx.complete; return urls; }
JavaScript
async deleteFromCacheAndIDB({cacheName, urls} = {}) { assert.isType({cacheName}, 'string'); assert.isArrayOfType({urls}, 'string'); if (urls.length > 0) { const cache = await this.getCache({cacheName}); const db = await this.getDB({cacheName}); await urls.forEach(async (url) => { await cache.delete(url); const tx = db.transaction(cacheName, 'readwrite'); const store = tx.objectStore(cacheName); await store.delete(url); await tx.complete; }); } }
async deleteFromCacheAndIDB({cacheName, urls} = {}) { assert.isType({cacheName}, 'string'); assert.isArrayOfType({urls}, 'string'); if (urls.length > 0) { const cache = await this.getCache({cacheName}); const db = await this.getDB({cacheName}); await urls.forEach(async (url) => { await cache.delete(url); const tx = db.transaction(cacheName, 'readwrite'); const store = tx.objectStore(cacheName); await store.delete(url); await tx.complete; }); } }
JavaScript
async function initialize({dbName} = {}) { if(dbName) { assert.isType({dbName}, 'string'); setDbName(dbName); } await cleanupQueue(); }
async function initialize({dbName} = {}) { if(dbName) { assert.isType({dbName}, 'string'); setDbName(dbName); } await cleanupQueue(); }
JavaScript
_parseEntry(input) { if (typeof input === 'undefined' || input === null) { throw ErrorFactory.createError('invalid-unrevisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(input))); } if (typeof input === 'string') { return new StringPrecacheEntry(input); } else if (input instanceof Request) { return new RequestCacheEntry(input); } else { throw ErrorFactory.createError('invalid-unrevisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(input)) ); } }
_parseEntry(input) { if (typeof input === 'undefined' || input === null) { throw ErrorFactory.createError('invalid-unrevisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(input))); } if (typeof input === 'string') { return new StringPrecacheEntry(input); } else if (input instanceof Request) { return new RequestCacheEntry(input); } else { throw ErrorFactory.createError('invalid-unrevisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(input)) ); } }
JavaScript
_parseEntry(input) { if (typeof input === 'undefined' || input === null) { throw ErrorFactory.createError('invalid-revisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(input)) ); } let precacheEntry; switch(typeof input) { case 'string': precacheEntry = new StringPrecacheEntry(input); break; case 'object': precacheEntry = new ObjectPrecacheEntry(input); break; default: throw ErrorFactory.createError('invalid-revisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(precacheEntry)) ); } return precacheEntry; }
_parseEntry(input) { if (typeof input === 'undefined' || input === null) { throw ErrorFactory.createError('invalid-revisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(input)) ); } let precacheEntry; switch(typeof input) { case 'string': precacheEntry = new StringPrecacheEntry(input); break; case 'object': precacheEntry = new ObjectPrecacheEntry(input); break; default: throw ErrorFactory.createError('invalid-revisioned-entry', new Error('Invalid file entry: ' + JSON.stringify(precacheEntry)) ); } return precacheEntry; }
JavaScript
_onDuplicateInstallEntryFound(newEntry, previousEntry) { if (previousEntry.revision !== newEntry.revision) { throw ErrorFactory.createError( 'duplicate-entry-diff-revisions', new Error(`${JSON.stringify(previousEntry)} <=> ` + `${JSON.stringify(newEntry)}`)); } }
_onDuplicateInstallEntryFound(newEntry, previousEntry) { if (previousEntry.revision !== newEntry.revision) { throw ErrorFactory.createError( 'duplicate-entry-diff-revisions', new Error(`${JSON.stringify(previousEntry)} <=> ` + `${JSON.stringify(newEntry)}`)); } }
JavaScript
async _isAlreadyCached(precacheEntry) { const revisionDetails = await this._revisionDetailsModel.get(precacheEntry.entryID); if (revisionDetails !== precacheEntry.revision) { return false; } const openCache = await this._getCache(); const cachedResponse = await openCache.match(precacheEntry.request); return cachedResponse ? true : false; }
async _isAlreadyCached(precacheEntry) { const revisionDetails = await this._revisionDetailsModel.get(precacheEntry.entryID); if (revisionDetails !== precacheEntry.revision) { return false; } const openCache = await this._getCache(); const cachedResponse = await openCache.match(precacheEntry.request); return cachedResponse ? true : false; }
JavaScript
cleanup() { return super.cleanup() .then(() => { return this._close(); }); }
cleanup() { return super.cleanup() .then(() => { return this._close(); }); }
JavaScript
cacheRevisionedAssets(revisionedFiles) { // Add a more helpful error message than assertion error. if (!Array.isArray(revisionedFiles)) { throw ErrorFactory.createError('bad-revisioned-cache-list'); } this._revisionedCacheManager.addToCacheList({ revisionedFiles, }); }
cacheRevisionedAssets(revisionedFiles) { // Add a more helpful error message than assertion error. if (!Array.isArray(revisionedFiles)) { throw ErrorFactory.createError('bad-revisioned-cache-list'); } this._revisionedCacheManager.addToCacheList({ revisionedFiles, }); }
JavaScript
warmRuntimeCache(unrevisionedFiles) { // Add a more helpful error message than assertion error. if (!Array.isArray(unrevisionedFiles)) { throw ErrorFactory.createError('bad-revisioned-cache-list'); } this._unrevisionedCacheManager.addToCacheList({ unrevisionedFiles, }); }
warmRuntimeCache(unrevisionedFiles) { // Add a more helpful error message than assertion error. if (!Array.isArray(unrevisionedFiles)) { throw ErrorFactory.createError('bad-revisioned-cache-list'); } this._unrevisionedCacheManager.addToCacheList({ unrevisionedFiles, }); }
JavaScript
_getCachingMechanism(HandlerClass, options = {}) { const pluginParamsToClass = { 'cacheExpiration': CacheExpirationPlugin, 'broadcastCacheUpdate': BroadcastCacheUpdatePlugin, 'cacheableResponse': CacheableResponsePlugin, }; const wrapperOptions = { plugins: [], }; if (options['cacheName']) { wrapperOptions['cacheName'] = options['cacheName']; } // Iterate over known plugins and add them to Request Wrapper options. const pluginKeys = Object.keys(pluginParamsToClass); pluginKeys.forEach((pluginKey) => { if (options[pluginKey]) { const PluginClass = pluginParamsToClass[pluginKey]; const pluginParams = options[pluginKey]; wrapperOptions.plugins.push(new PluginClass(pluginParams)); } }); // Add custom plugins. if (options.plugins) { options.plugins.forEach((plugin) => { wrapperOptions.plugins.push(plugin); }); } return new HandlerClass({ requestWrapper: new RequestWrapper(wrapperOptions), }); }
_getCachingMechanism(HandlerClass, options = {}) { const pluginParamsToClass = { 'cacheExpiration': CacheExpirationPlugin, 'broadcastCacheUpdate': BroadcastCacheUpdatePlugin, 'cacheableResponse': CacheableResponsePlugin, }; const wrapperOptions = { plugins: [], }; if (options['cacheName']) { wrapperOptions['cacheName'] = options['cacheName']; } // Iterate over known plugins and add them to Request Wrapper options. const pluginKeys = Object.keys(pluginParamsToClass); pluginKeys.forEach((pluginKey) => { if (options[pluginKey]) { const PluginClass = pluginParamsToClass[pluginKey]; const pluginParams = options[pluginKey]; wrapperOptions.plugins.push(new PluginClass(pluginParams)); } }); // Add custom plugins. if (options.plugins) { options.plugins.forEach((plugin) => { wrapperOptions.plugins.push(plugin); }); } return new HandlerClass({ requestWrapper: new RequestWrapper(wrapperOptions), }); }
JavaScript
_registerInstallActivateEvents() { self.addEventListener('install', (event) => { event.waitUntil(Promise.all([ this._revisionedCacheManager.install(), this._unrevisionedCacheManager.install(), ])); }); self.addEventListener('activate', (event) => { event.waitUntil(Promise.all([ this._revisionedCacheManager.cleanup(), this._unrevisionedCacheManager.cleanup(), ])); }); }
_registerInstallActivateEvents() { self.addEventListener('install', (event) => { event.waitUntil(Promise.all([ this._revisionedCacheManager.install(), this._unrevisionedCacheManager.install(), ])); }); self.addEventListener('activate', (event) => { event.waitUntil(Promise.all([ this._revisionedCacheManager.cleanup(), this._unrevisionedCacheManager.cleanup(), ])); }); }
JavaScript
_registerDefaultRoutes() { const cacheFirstHandler = this.cacheFirst({ cacheName: this._revisionedCacheManager.getCacheName(), }); const route = new this.Route({ match: ({url, event}) => { const cachedUrls = this._revisionedCacheManager.getCachedUrls(); return cachedUrls.indexOf(url.href) !== -1; }, handler: cacheFirstHandler, }); this.router.registerRoute(route); }
_registerDefaultRoutes() { const cacheFirstHandler = this.cacheFirst({ cacheName: this._revisionedCacheManager.getCacheName(), }); const route = new this.Route({ match: ({url, event}) => { const cachedUrls = this._revisionedCacheManager.getCachedUrls(); return cachedUrls.indexOf(url.href) !== -1; }, handler: cacheFirstHandler, }); this.router.registerRoute(route); }
JavaScript
function processPromiseWrapper(command, args) { return new Promise((resolve, reject) => { const process = childProcess.spawn(command, args, {stdio: 'inherit'}); process.on('error', reject); process.on('close', (code) => { if (code === 0) { resolve(); } else { reject(`Error ${code} returned from ${command} ${args}`); } }); }); }
function processPromiseWrapper(command, args) { return new Promise((resolve, reject) => { const process = childProcess.spawn(command, args, {stdio: 'inherit'}); process.on('error', reject); process.on('close', (code) => { if (code === 0) { resolve(); } else { reject(`Error ${code} returned from ${command} ${args}`); } }); }); }
JavaScript
function taskPromiseWrapper(projects, task, args) { let rejected = []; return projects.reduce((promiseChain, project) => { return promiseChain.then(() => { return task(path.join(__dirname, '..', path.dirname(project)), args) .catch((error) => { rejected.push(error); }); }); }, Promise.resolve()) .then(() => rejected.length ? Promise.reject(rejected.join('\n')) : null); }
function taskPromiseWrapper(projects, task, args) { let rejected = []; return projects.reduce((promiseChain, project) => { return promiseChain.then(() => { return task(path.join(__dirname, '..', path.dirname(project)), args) .catch((error) => { rejected.push(error); }); }); }, Promise.resolve()) .then(() => rejected.length ? Promise.reject(rejected.join('\n')) : null); }
JavaScript
function generateBuildConfigs(formatToPath, projectDir, moduleName) { // This is shared throughout the full permutation of build configs. const baseConfig = { rollupConfig: { entry: path.join(projectDir, 'src', 'index.js'), plugins: PLUGINS, moduleName, }, projectDir, }; // Use Object.assign() throughout to create copies of the config objects. return [true, false].map((minify) => { return Object.assign({}, baseConfig, {minify}); }).map((partialConfig) => { return Object.keys(formatToPath).map((format) => { const fullConfig = Object.assign({}, partialConfig, { buildPath: formatToPath[format], }); fullConfig.rollupConfig = Object.assign({}, partialConfig.rollupConfig, { format, }); // Remove the '.min.' from the file name if the output isn't minified. if (!fullConfig.minify) { fullConfig.buildPath = fullConfig.buildPath.replace('.min.', '.'); } return fullConfig; }); }).reduce((previous, current) => { // Flatten the two-dimensional array. E.g.: // Input is [[umd-minified, umd-unminified], [es-minified, es-unminified]] // Output is [umd-minified, umd-unminified, es-minified, es-unminified] return previous.concat(current); }, []); }
function generateBuildConfigs(formatToPath, projectDir, moduleName) { // This is shared throughout the full permutation of build configs. const baseConfig = { rollupConfig: { entry: path.join(projectDir, 'src', 'index.js'), plugins: PLUGINS, moduleName, }, projectDir, }; // Use Object.assign() throughout to create copies of the config objects. return [true, false].map((minify) => { return Object.assign({}, baseConfig, {minify}); }).map((partialConfig) => { return Object.keys(formatToPath).map((format) => { const fullConfig = Object.assign({}, partialConfig, { buildPath: formatToPath[format], }); fullConfig.rollupConfig = Object.assign({}, partialConfig.rollupConfig, { format, }); // Remove the '.min.' from the file name if the output isn't minified. if (!fullConfig.minify) { fullConfig.buildPath = fullConfig.buildPath.replace('.min.', '.'); } return fullConfig; }); }).reduce((previous, current) => { // Flatten the two-dimensional array. E.g.: // Input is [[umd-minified, umd-unminified], [es-minified, es-unminified]] // Output is [umd-minified, umd-unminified, es-minified, es-unminified] return previous.concat(current); }, []); }
JavaScript
argv(argv) { updateNotifier({pkg}).notify(); const cliArgs = minimist(argv); if (cliArgs._.length > 0) { // We have a command return this.handleCommand(cliArgs._[0], cliArgs._.splice(1), cliArgs) .then(() => { process.exit(0); }) .catch(() => { process.exit(1); }); } else { // we have a flag only request return this.handleFlag(cliArgs) .then(() => { process.exit(0); }) .catch(() => { process.exit(1); }); } }
argv(argv) { updateNotifier({pkg}).notify(); const cliArgs = minimist(argv); if (cliArgs._.length > 0) { // We have a command return this.handleCommand(cliArgs._[0], cliArgs._.splice(1), cliArgs) .then(() => { process.exit(0); }) .catch(() => { process.exit(1); }); } else { // we have a flag only request return this.handleFlag(cliArgs) .then(() => { process.exit(0); }) .catch(() => { process.exit(1); }); } }
JavaScript
printHelpText() { const helpText = fs.readFileSync( path.join(__dirname, 'cli-help.txt'), 'utf8'); logHelper.info(helpText); }
printHelpText() { const helpText = fs.readFileSync( path.join(__dirname, 'cli-help.txt'), 'utf8'); logHelper.info(helpText); }
JavaScript
handleFlag(flags) { let handled = false; if (flags.h || flags.help) { this.printHelpText(); handled = true; } if (flags.v || flags.version) { logHelper.info(pkg.version); handled = true; } if (handled) { return Promise.resolve(); } // This is a fallback this.printHelpText(); return Promise.reject(); }
handleFlag(flags) { let handled = false; if (flags.h || flags.help) { this.printHelpText(); handled = true; } if (flags.v || flags.version) { logHelper.info(pkg.version); handled = true; } if (handled) { return Promise.resolve(); } // This is a fallback this.printHelpText(); return Promise.reject(); }
JavaScript
handleCommand(command, args, flags) { switch (command) { case 'generate:sw': return this._generateSW(); case 'generate:manifest': return this._generateBuildManifest(); default: logHelper.error(`Invlaid command given '${command}'`); return Promise.reject(); } }
handleCommand(command, args, flags) { switch (command) { case 'generate:sw': return this._generateSW(); case 'generate:manifest': return this._generateBuildManifest(); default: logHelper.error(`Invlaid command given '${command}'`); return Promise.reject(); } }
JavaScript
_generateSW() { let config = {}; return getConfigFile() .then((savedConfig) => { if (savedConfig) { config = savedConfig; config.wasSaved = true; } }) .then(() => { if (!config.rootDirectory) { return askForRootOfWebApp() .then((rDirectory) => { // This will give a pretty relative path: // '' => './' // 'build' => './build/' config.rootDirectory = path.join('.', path.relative(process.cwd(), rDirectory), path.sep); }); } }) .then(() => { if (!config.globPatterns) { return askForExtensionsToCache(config.rootDirectory) .then((extensionsToCache) => { config.globPatterns = [ generateGlobPattern(config.rootDirectory, extensionsToCache), ]; }); } }) .then(() => { if (!config.dest) { return askForServiceWorkerName() .then((swName) => { const swDest = path.join(config.rootDirectory, swName); config.dest = swDest; config.globIgnores = [ swDest, ]; }); } }) .then(() => { if (!config.wasSaved) { return askSaveConfigFile(); } // False since it's already saved. return false; }) .then((saveConfig) => { if (saveConfig) { return saveConfigFile(config); } }) .then(() => { return swBuild.generateSW(config); }); }
_generateSW() { let config = {}; return getConfigFile() .then((savedConfig) => { if (savedConfig) { config = savedConfig; config.wasSaved = true; } }) .then(() => { if (!config.rootDirectory) { return askForRootOfWebApp() .then((rDirectory) => { // This will give a pretty relative path: // '' => './' // 'build' => './build/' config.rootDirectory = path.join('.', path.relative(process.cwd(), rDirectory), path.sep); }); } }) .then(() => { if (!config.globPatterns) { return askForExtensionsToCache(config.rootDirectory) .then((extensionsToCache) => { config.globPatterns = [ generateGlobPattern(config.rootDirectory, extensionsToCache), ]; }); } }) .then(() => { if (!config.dest) { return askForServiceWorkerName() .then((swName) => { const swDest = path.join(config.rootDirectory, swName); config.dest = swDest; config.globIgnores = [ swDest, ]; }); } }) .then(() => { if (!config.wasSaved) { return askSaveConfigFile(); } // False since it's already saved. return false; }) .then((saveConfig) => { if (saveConfig) { return saveConfigFile(config); } }) .then(() => { return swBuild.generateSW(config); }); }
JavaScript
_generateBuildManifest() { let rootDirPath; let fileManifestName; let fileExtentionsToCache; return askForRootOfWebApp() .then((rDirectory) => { rootDirPath = rDirectory; return askForExtensionsToCache(rootDirPath); }) .then((extensionsToCache) => { fileExtentionsToCache = extensionsToCache; return askManifestFileName(); }) .then((manifestName) => { fileManifestName = manifestName; }) .then(() => { const globPattern = generateGlobPattern( rootDirPath, fileExtentionsToCache); return swBuild.generateFileManifest({ rootDirectory: rootDirPath, globPatterns: [globPattern], globIgnores: [ path.join(rootDirPath, fileManifestName), ], dest: path.join(rootDirPath, fileManifestName), }); }); }
_generateBuildManifest() { let rootDirPath; let fileManifestName; let fileExtentionsToCache; return askForRootOfWebApp() .then((rDirectory) => { rootDirPath = rDirectory; return askForExtensionsToCache(rootDirPath); }) .then((extensionsToCache) => { fileExtentionsToCache = extensionsToCache; return askManifestFileName(); }) .then((manifestName) => { fileManifestName = manifestName; }) .then(() => { const globPattern = generateGlobPattern( rootDirPath, fileExtentionsToCache); return swBuild.generateFileManifest({ rootDirectory: rootDirPath, globPatterns: [globPattern], globIgnores: [ path.join(rootDirPath, fileManifestName), ], dest: path.join(rootDirPath, fileManifestName), }); }); }
JavaScript
function signAction(identity, callback, action) { callback({ ...action, meta: { ...action.meta, [META_PUBLIC_KEY]: identity.publicKey, [META_SIGNATURE]: identity.sign(encodeAction(action)), } }) }
function signAction(identity, callback, action) { callback({ ...action, meta: { ...action.meta, [META_PUBLIC_KEY]: identity.publicKey, [META_SIGNATURE]: identity.sign(encodeAction(action)), } }) }
JavaScript
function readJson(res, cb, err) { let buffer; /* Register data cb */ res.onData((ab, isLast) => { let chunk = Buffer.from(ab); if (isLast) { let json; if (buffer) { try { json = JSON.parse(Buffer.concat([buffer, chunk])); } catch (e) { /* res.close calls onAborted */ res.close(); return; } cb(json); } else { try { json = JSON.parse(chunk); } catch (e) { /* res.close calls onAborted */ res.close(); return; } cb(json); } } else { if (buffer) { buffer = Buffer.concat([buffer, chunk]); } else { buffer = Buffer.concat([chunk]); } } }); /* Register error cb */ res.onAborted(err); }
function readJson(res, cb, err) { let buffer; /* Register data cb */ res.onData((ab, isLast) => { let chunk = Buffer.from(ab); if (isLast) { let json; if (buffer) { try { json = JSON.parse(Buffer.concat([buffer, chunk])); } catch (e) { /* res.close calls onAborted */ res.close(); return; } cb(json); } else { try { json = JSON.parse(chunk); } catch (e) { /* res.close calls onAborted */ res.close(); return; } cb(json); } } else { if (buffer) { buffer = Buffer.concat([buffer, chunk]); } else { buffer = Buffer.concat([chunk]); } } }); /* Register error cb */ res.onAborted(err); }
JavaScript
function accountForConnection() { /* Open more connections */ if (++openedClientConnections < /*100*/ 1000) { establishNewConnection(); } else { /* Stop listening */ uWS.us_listen_socket_close(listenSocket); } }
function accountForConnection() { /* Open more connections */ if (++openedClientConnections < /*100*/ 1000) { establishNewConnection(); } else { /* Stop listening */ uWS.us_listen_socket_close(listenSocket); } }
JavaScript
function performRandomClientAction(ws) { /* 0, 1, 2 but never 3 */ let action = getRandomInt(3); /* Sending a message should have higher probability */ if (getRandomInt(100) < 80) { action = 1; } switch (action) { case 0: { ws.close(); break; } case 1: { /* Length should be random from small to huge */ try { ws.send('a test message'); } catch (e) { /* Apparently websockets/ws can throw at any moment */ } break; } case 2: { ws.terminate(); break; } } }
function performRandomClientAction(ws) { /* 0, 1, 2 but never 3 */ let action = getRandomInt(3); /* Sending a message should have higher probability */ if (getRandomInt(100) < 80) { action = 1; } switch (action) { case 0: { ws.close(); break; } case 1: { /* Length should be random from small to huge */ try { ws.send('a test message'); } catch (e) { /* Apparently websockets/ws can throw at any moment */ } break; } case 2: { ws.terminate(); break; } } }
JavaScript
function onAbortedOrFinishedResponse(res, readStream) { if (res.id == -1) { console.log("ERROR! onAbortedOrFinishedResponse called twice for the same res!"); } else { console.log('Stream was closed, openStreams: ' + --openStreams); console.timeEnd(res.id); readStream.destroy(); } /* Mark this response already accounted for */ res.id = -1; }
function onAbortedOrFinishedResponse(res, readStream) { if (res.id == -1) { console.log("ERROR! onAbortedOrFinishedResponse called twice for the same res!"); } else { console.log('Stream was closed, openStreams: ' + --openStreams); console.timeEnd(res.id); readStream.destroy(); } /* Mark this response already accounted for */ res.id = -1; }
JavaScript
function pipeStreamOverResponse(res, readStream, totalSize) { /* Careful! If Node.js would emit error before the first res.tryEnd, res will hang and never time out */ /* For this demo, I skipped checking for Node.js errors, you are free to PR fixes to this example */ readStream.on('data', (chunk) => { /* We only take standard V8 units of data */ const ab = toArrayBuffer(chunk); /* Store where we are, globally, in our response */ let lastOffset = res.getWriteOffset(); /* Streaming a chunk returns whether that chunk was sent, and if that chunk was last */ let [ok, done] = res.tryEnd(ab, totalSize); /* Did we successfully send last chunk? */ if (done) { onAbortedOrFinishedResponse(res, readStream); } else if (!ok) { /* If we could not send this chunk, pause */ readStream.pause(); /* Save unsent chunk for when we can send it */ res.ab = ab; res.abOffset = lastOffset; /* Register async handlers for drainage */ res.onWritable((offset) => { /* Here the timeout is off, we can spend as much time before calling tryEnd we want to */ /* On failure the timeout will start */ let [ok, done] = res.tryEnd(res.ab.slice(offset - res.abOffset), totalSize); if (done) { onAbortedOrFinishedResponse(res, readStream); } else if (ok) { /* We sent a chunk and it was not the last one, so let's resume reading. * Timeout is still disabled, so we can spend any amount of time waiting * for more chunks to send. */ readStream.resume(); } /* We always have to return true/false in onWritable. * If you did not send anything, return true for success. */ return ok; }); } }).on('error', () => { /* Todo: handle errors of the stream, probably good to simply close the response */ console.log('Unhandled read error from Node.js, you need to handle this!'); }); /* If you plan to asyncronously respond later on, you MUST listen to onAborted BEFORE returning */ res.onAborted(() => { onAbortedOrFinishedResponse(res, readStream); }); }
function pipeStreamOverResponse(res, readStream, totalSize) { /* Careful! If Node.js would emit error before the first res.tryEnd, res will hang and never time out */ /* For this demo, I skipped checking for Node.js errors, you are free to PR fixes to this example */ readStream.on('data', (chunk) => { /* We only take standard V8 units of data */ const ab = toArrayBuffer(chunk); /* Store where we are, globally, in our response */ let lastOffset = res.getWriteOffset(); /* Streaming a chunk returns whether that chunk was sent, and if that chunk was last */ let [ok, done] = res.tryEnd(ab, totalSize); /* Did we successfully send last chunk? */ if (done) { onAbortedOrFinishedResponse(res, readStream); } else if (!ok) { /* If we could not send this chunk, pause */ readStream.pause(); /* Save unsent chunk for when we can send it */ res.ab = ab; res.abOffset = lastOffset; /* Register async handlers for drainage */ res.onWritable((offset) => { /* Here the timeout is off, we can spend as much time before calling tryEnd we want to */ /* On failure the timeout will start */ let [ok, done] = res.tryEnd(res.ab.slice(offset - res.abOffset), totalSize); if (done) { onAbortedOrFinishedResponse(res, readStream); } else if (ok) { /* We sent a chunk and it was not the last one, so let's resume reading. * Timeout is still disabled, so we can spend any amount of time waiting * for more chunks to send. */ readStream.resume(); } /* We always have to return true/false in onWritable. * If you did not send anything, return true for success. */ return ok; }); } }).on('error', () => { /* Todo: handle errors of the stream, probably good to simply close the response */ console.log('Unhandled read error from Node.js, you need to handle this!'); }); /* If you plan to asyncronously respond later on, you MUST listen to onAborted BEFORE returning */ res.onAborted(() => { onAbortedOrFinishedResponse(res, readStream); }); }
JavaScript
function ImageSlider({ images }) { const [ products, setProducts ] = useState(images); const [ productIndex, setProductIndex ] = useState(0); let firstFourProducts = products.slice(productIndex, productIndex + 1); const nextProduct = () => { const lastProductIndex = products.length - 1; const resetProductIndex = productIndex === lastProductIndex; const index = resetProductIndex ? 0 : productIndex + 1; setProductIndex(index); }; const prevProduct = () => { const lastProductIndex = products.length - 1; const resetProductIndex = productIndex === 0; const index = resetProductIndex ? lastProductIndex : productIndex - 1; setProductIndex(index); }; return ( <Col> <Row className={styles.sliderHolder}> <Col className={styles.buttonGroup} xs={12} sm={7}> <button type="button" className={styles.btn} onClick={prevProduct}> Prev </button> <button type="button" className={styles.btn} onClick={nextProduct}> Next </button> </Col> <Col className={styles.productSlider} xs={12} sm={12}> <Img fluid={firstFourProducts[0].fluid} className={styles.image} /> </Col> </Row> </Col> ); }
function ImageSlider({ images }) { const [ products, setProducts ] = useState(images); const [ productIndex, setProductIndex ] = useState(0); let firstFourProducts = products.slice(productIndex, productIndex + 1); const nextProduct = () => { const lastProductIndex = products.length - 1; const resetProductIndex = productIndex === lastProductIndex; const index = resetProductIndex ? 0 : productIndex + 1; setProductIndex(index); }; const prevProduct = () => { const lastProductIndex = products.length - 1; const resetProductIndex = productIndex === 0; const index = resetProductIndex ? lastProductIndex : productIndex - 1; setProductIndex(index); }; return ( <Col> <Row className={styles.sliderHolder}> <Col className={styles.buttonGroup} xs={12} sm={7}> <button type="button" className={styles.btn} onClick={prevProduct}> Prev </button> <button type="button" className={styles.btn} onClick={nextProduct}> Next </button> </Col> <Col className={styles.productSlider} xs={12} sm={12}> <Img fluid={firstFourProducts[0].fluid} className={styles.image} /> </Col> </Row> </Col> ); }
JavaScript
function chunkString(str, chunkSize) { return Array(Math.ceil(str.length / chunkSize)).fill().map(function(_, i) { return str.slice(i * chunkSize, i * chunkSize + chunkSize); }); }
function chunkString(str, chunkSize) { return Array(Math.ceil(str.length / chunkSize)).fill().map(function(_, i) { return str.slice(i * chunkSize, i * chunkSize + chunkSize); }); }
JavaScript
data(data) { if (arguments.length) { var w = data.type.width if (w.length != 2) throw new Error("NotImplemented"); this.dataWordCellCnt = this.addrStep = Math.ceil(w[w.length - 1] / 8); this.addrRange = [0, w[0] * this.addrStep]; this._data = data; } else { return this._data; } }
data(data) { if (arguments.length) { var w = data.type.width if (w.length != 2) throw new Error("NotImplemented"); this.dataWordCellCnt = this.addrStep = Math.ceil(w[w.length - 1] / 8); this.addrRange = [0, w[0] * this.addrStep]; this._data = data; } else { return this._data; } }
JavaScript
async function refresh() { loadingbar(); console.log("Refreshing Prices.."); moonScraper(); }
async function refresh() { loadingbar(); console.log("Refreshing Prices.."); moonScraper(); }
JavaScript
async function forceRefresh() { var pairWrappers = document.getElementsByClassName("pairWrapper"); for (i = 0; i < pairWrappers.length;) { pairWrappers[i].remove(); } localStorage.removeItem("pairAmountArray"); localStorage.removeItem("pairValueArray"); localStorage.removeItem("pairNameArray"); localStorage.removeItem("totalBalance"); loadingbar(); console.log("Refreshing.."); moonScraper(); }
async function forceRefresh() { var pairWrappers = document.getElementsByClassName("pairWrapper"); for (i = 0; i < pairWrappers.length;) { pairWrappers[i].remove(); } localStorage.removeItem("pairAmountArray"); localStorage.removeItem("pairValueArray"); localStorage.removeItem("pairNameArray"); localStorage.removeItem("totalBalance"); loadingbar(); console.log("Refreshing.."); moonScraper(); }
JavaScript
function deleteProduct(idProdcut) { return productResource.delete({ id: idProdcut }).$promise; }
function deleteProduct(idProdcut) { return productResource.delete({ id: idProdcut }).$promise; }
JavaScript
async function startServer() { await Server.create({ dotStencilFile: dotStencilFile, variationIndex: themeConfig.variationIndex || 0, useCache: cliOptions.cache, themePath: THEME_PATH, }); const buildConfigManger = new BuildConfigManager(); let watchFiles = [ '/assets', '/templates', '/lang', '/.config', ]; let watchIgnored = [ '/assets/scss', '/assets/css', ]; // Display Set up information console.log(getStartUpInfo()); // Watch sccs directory and automatically reload all css files if a file changes Bs.watch(Path.join(THEME_PATH, 'assets/scss'), event => { if (event === 'change') { Bs.reload('*.css'); } }); Bs.watch('config.json', event => { if (event === 'change') { themeConfig.resetVariationSettings(); Bs.reload(); } }); Bs.watch('.config/storefront.json', (event, file) => { if (event === 'change') { console.log("storefront json changed"); Bs.emitter.emit("storefront_config_file:changed", { event: event, path: file, namespace: "", }); Bs.reload(); } }); Bs.watch(templatePath, {ignoreInitial: true}, () => { assembleTemplates(templatePath, (err, results) => { if (err) { return console.error(err); } try { new Cycles(results).detect(); } catch (e) { console.error(e); } }); }); if (buildConfigManger.watchOptions && buildConfigManger.watchOptions.files) { watchFiles = buildConfigManger.watchOptions.files; } if (buildConfigManger.watchOptions && buildConfigManger.watchOptions.ignored) { watchIgnored = buildConfigManger.watchOptions.ignored; } Bs.init({ open: !!cliOptions.open, port: browserSyncPort, files: watchFiles.map(val => Path.join(THEME_PATH, val)), watchOptions: { ignoreInitial: true, ignored: watchIgnored.map(val => Path.join(THEME_PATH, val)), }, proxy: "localhost:" + dotStencilFile.port, tunnel, }); // Handle manual reloading of browsers by typing 'rs'; // Borrowed from https://github.com/remy/nodemon process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', data => { data = (data + '').trim().toLowerCase(); // if the keys entered match the restartable value, then restart! if (data === 'rs') { Bs.reload(); } }); if (buildConfigManger.development) { buildConfigManger.initWorker().development(Bs); } }
async function startServer() { await Server.create({ dotStencilFile: dotStencilFile, variationIndex: themeConfig.variationIndex || 0, useCache: cliOptions.cache, themePath: THEME_PATH, }); const buildConfigManger = new BuildConfigManager(); let watchFiles = [ '/assets', '/templates', '/lang', '/.config', ]; let watchIgnored = [ '/assets/scss', '/assets/css', ]; // Display Set up information console.log(getStartUpInfo()); // Watch sccs directory and automatically reload all css files if a file changes Bs.watch(Path.join(THEME_PATH, 'assets/scss'), event => { if (event === 'change') { Bs.reload('*.css'); } }); Bs.watch('config.json', event => { if (event === 'change') { themeConfig.resetVariationSettings(); Bs.reload(); } }); Bs.watch('.config/storefront.json', (event, file) => { if (event === 'change') { console.log("storefront json changed"); Bs.emitter.emit("storefront_config_file:changed", { event: event, path: file, namespace: "", }); Bs.reload(); } }); Bs.watch(templatePath, {ignoreInitial: true}, () => { assembleTemplates(templatePath, (err, results) => { if (err) { return console.error(err); } try { new Cycles(results).detect(); } catch (e) { console.error(e); } }); }); if (buildConfigManger.watchOptions && buildConfigManger.watchOptions.files) { watchFiles = buildConfigManger.watchOptions.files; } if (buildConfigManger.watchOptions && buildConfigManger.watchOptions.ignored) { watchIgnored = buildConfigManger.watchOptions.ignored; } Bs.init({ open: !!cliOptions.open, port: browserSyncPort, files: watchFiles.map(val => Path.join(THEME_PATH, val)), watchOptions: { ignoreInitial: true, ignored: watchIgnored.map(val => Path.join(THEME_PATH, val)), }, proxy: "localhost:" + dotStencilFile.port, tunnel, }); // Handle manual reloading of browsers by typing 'rs'; // Borrowed from https://github.com/remy/nodemon process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', data => { data = (data + '').trim().toLowerCase(); // if the keys entered match the restartable value, then restart! if (data === 'rs') { Bs.reload(); } }); if (buildConfigManger.development) { buildConfigManger.initWorker().development(Bs); } }
JavaScript
function assembleTemplates(templatePath, callback) { recursiveRead(templatePath, ['!*.html'], (err, files) => { files = files.map(function (file) { return file.replace(templatePath + Path.sep, '').replace('.html', ''); }); Async.map(files, templateAssembler.assemble.bind(null, templatePath), (err, results) => { if (err) { callback(err); } callback(null, results); }); }); }
function assembleTemplates(templatePath, callback) { recursiveRead(templatePath, ['!*.html'], (err, files) => { files = files.map(function (file) { return file.replace(templatePath + Path.sep, '').replace('.html', ''); }); Async.map(files, templateAssembler.assemble.bind(null, templatePath), (err, results) => { if (err) { callback(err); } callback(null, results); }); }); }
JavaScript
function httpRequest (url, method = 'GET', content = null, responseType = '', onUpload = null, onDownload = null, withCredentials = false, headers = null, timeoutInterval = 0) { const completer = new Completer(); /** * @type {goog.net.XhrIo} */ const xhr = new XhrIo(); xhr.setResponseType(/** @type {goog.net.XhrIo.ResponseType} */ (responseType)); xhr.setWithCredentials(withCredentials); xhr.setTimeoutInterval(timeoutInterval); xhr.setProgressEventsEnabled(onUpload != null || onDownload != null); xhr.listenOnce(EventType.SUCCESS, () => { events.removeAll(xhr); completer.resolve({ response: xhr.getResponse(), responseHeaders: xhr.getResponseHeaders() }); }); if (onUpload != null) xhr.listen(EventType.UPLOAD_PROGRESS, onUpload); if (onDownload != null) xhr.listen(EventType.DOWNLOAD_PROGRESS, onDownload); function reject (event) { events.removeAll(xhr); completer.reject(event); } xhr.listenOnce(EventType.ERROR, reject); xhr.listenOnce(EventType.TIMEOUT, reject); xhr.listenOnce(EventType.ABORT, reject); xhr.send(url, method, content, headers); return { promise: completer.getPromise(), cancel: () => { xhr.abort(); } }; }
function httpRequest (url, method = 'GET', content = null, responseType = '', onUpload = null, onDownload = null, withCredentials = false, headers = null, timeoutInterval = 0) { const completer = new Completer(); /** * @type {goog.net.XhrIo} */ const xhr = new XhrIo(); xhr.setResponseType(/** @type {goog.net.XhrIo.ResponseType} */ (responseType)); xhr.setWithCredentials(withCredentials); xhr.setTimeoutInterval(timeoutInterval); xhr.setProgressEventsEnabled(onUpload != null || onDownload != null); xhr.listenOnce(EventType.SUCCESS, () => { events.removeAll(xhr); completer.resolve({ response: xhr.getResponse(), responseHeaders: xhr.getResponseHeaders() }); }); if (onUpload != null) xhr.listen(EventType.UPLOAD_PROGRESS, onUpload); if (onDownload != null) xhr.listen(EventType.DOWNLOAD_PROGRESS, onDownload); function reject (event) { events.removeAll(xhr); completer.reject(event); } xhr.listenOnce(EventType.ERROR, reject); xhr.listenOnce(EventType.TIMEOUT, reject); xhr.listenOnce(EventType.ABORT, reject); xhr.send(url, method, content, headers); return { promise: completer.getPromise(), cancel: () => { xhr.abort(); } }; }
JavaScript
function httpGetJson (url) { const request = httpRequest(url, 'GET', null, ResponseType.TEXT); return { promise: request.promise.then(({response, responseHeaders}) => { return { response: JSON.parse(/** @type {string} */ (response)), responseHeaders }; }), cancel: request.cancel }; }
function httpGetJson (url) { const request = httpRequest(url, 'GET', null, ResponseType.TEXT); return { promise: request.promise.then(({response, responseHeaders}) => { return { response: JSON.parse(/** @type {string} */ (response)), responseHeaders }; }), cancel: request.cancel }; }
JavaScript
function validateFileSize (blob, maxSize) { const bytes = maxSize * 1000000; return blob.size <= bytes; }
function validateFileSize (blob, maxSize) { const bytes = maxSize * 1000000; return blob.size <= bytes; }
JavaScript
function validateFileType (blob, mimeTypes) { return mimeTypes.reduce((old, currentMimeType) => { return blob.type === currentMimeType || old; }, false); }
function validateFileType (blob, mimeTypes) { return mimeTypes.reduce((old, currentMimeType) => { return blob.type === currentMimeType || old; }, false); }
JavaScript
function waitForFrames (frames = 1) { return new Promise(resolve => { let frameCount = 0; function onTick () { if (++frameCount === frames) resolve(); else window.requestAnimationFrame(onTick); } window.requestAnimationFrame(onTick); }); }
function waitForFrames (frames = 1) { return new Promise(resolve => { let frameCount = 0; function onTick () { if (++frameCount === frames) resolve(); else window.requestAnimationFrame(onTick); } window.requestAnimationFrame(onTick); }); }
JavaScript
function cacheAsyncValue (func) { let done = false; let isError = false; let result = null; let error = null; return async function () { if (!done) { try { result = await func(); } catch (e) { error = e; isError = true; } finally { done = true; } } if (isError) throw error; else return result; }; }
function cacheAsyncValue (func) { let done = false; let isError = false; let result = null; let error = null; return async function () { if (!done) { try { result = await func(); } catch (e) { error = e; isError = true; } finally { done = true; } } if (isError) throw error; else return result; }; }
JavaScript
addClass (clazz) { const metadata = /** @type {ComponentMetadata} */ (clazz.metadata); if (metadata == null) throw new Error('Component class must have a static metadata getter.'); this.addComponent_(metadata.type, clazz); }
addClass (clazz) { const metadata = /** @type {ComponentMetadata} */ (clazz.metadata); if (metadata == null) throw new Error('Component class must have a static metadata getter.'); this.addComponent_(metadata.type, clazz); }
JavaScript
addComponentMap (obj) { Object.keys(obj).forEach(key => { this.addComponent_(key, obj[key]); }); }
addComponentMap (obj) { Object.keys(obj).forEach(key => { this.addComponent_(key, obj[key]); }); }
JavaScript
function closest (element, selector) { if (element['closest'] != null) { return /** @type {?Element} */ (element['closest'](selector)); } else { return /** @type {?Element} */ (getAncestor(element, node => { if (isElement(node)) return matches(/** @type {Element} */ (node), selector); else return false; }, true)); } }
function closest (element, selector) { if (element['closest'] != null) { return /** @type {?Element} */ (element['closest'](selector)); } else { return /** @type {?Element} */ (getAncestor(element, node => { if (isElement(node)) return matches(/** @type {Element} */ (node), selector); else return false; }, true)); } }
JavaScript
function isElementVisible (element, factor = null) { /** * @type {goog.math.Size} */ const viewportSize = getViewportSize(); /** * @type {goog.math.Rect} */ const viewportRect = new Rect(0, 0, viewportSize.width, viewportSize.height); const boundingRect = element.getBoundingClientRect(); /** * @type {goog.math.Rect} */ const elementRect = new Rect(boundingRect.left, boundingRect.top, boundingRect.width, boundingRect.height); return rectangleIntersects(viewportRect, elementRect, factor); }
function isElementVisible (element, factor = null) { /** * @type {goog.math.Size} */ const viewportSize = getViewportSize(); /** * @type {goog.math.Rect} */ const viewportRect = new Rect(0, 0, viewportSize.width, viewportSize.height); const boundingRect = element.getBoundingClientRect(); /** * @type {goog.math.Rect} */ const elementRect = new Rect(boundingRect.left, boundingRect.top, boundingRect.width, boundingRect.height); return rectangleIntersects(viewportRect, elementRect, factor); }
JavaScript
function asyncForEach (array, action) { return array.reduce((promise, element, index, arr) => { return promise.then(() => action(element, index, arr)); }, Promise.resolve()); }
function asyncForEach (array, action) { return array.reduce((promise, element, index, arr) => { return promise.then(() => action(element, index, arr)); }, Promise.resolve()); }
JavaScript
function asyncForEachRight (array, action) { return array.reduceRight((promise, element, index, arr) => { return promise.then(() => action(element, index, arr)); }, Promise.resolve()); }
function asyncForEachRight (array, action) { return array.reduceRight((promise, element, index, arr) => { return promise.then(() => action(element, index, arr)); }, Promise.resolve()); }
JavaScript
function sleep (ms) { return new Promise(resolve => { setTimeout(resolve, ms) }) }
function sleep (ms) { return new Promise(resolve => { setTimeout(resolve, ms) }) }
JavaScript
function triageLabelMappedToField (triageConfig, label, field) { const labelValues = Object.keys(triageConfig[label]) return Object.assign( {}, ...labelValues.map(e => { return { [e]: triageConfig[label][e][field] } }) ) }
function triageLabelMappedToField (triageConfig, label, field) { const labelValues = Object.keys(triageConfig[label]) return Object.assign( {}, ...labelValues.map(e => { return { [e]: triageConfig[label][e][field] } }) ) }
JavaScript
function generateTriageConfigLookups (triageConfig) { // Calculate list of levels const levels = Object.keys(triageConfig.levels) // Generate mapping of levels to emoji const levelToEmoji = triageLabelMappedToField( triageConfig, 'levels', 'emoji' ) // Calculate list of statuses const statuses = Object.keys(triageConfig.statuses) // Generate mapping of status to emoji const statusToEmoji = triageLabelMappedToField( triageConfig, 'statuses', 'emoji' ) return { levels, levelToEmoji, statuses, statusToEmoji } }
function generateTriageConfigLookups (triageConfig) { // Calculate list of levels const levels = Object.keys(triageConfig.levels) // Generate mapping of levels to emoji const levelToEmoji = triageLabelMappedToField( triageConfig, 'levels', 'emoji' ) // Calculate list of statuses const statuses = Object.keys(triageConfig.statuses) // Generate mapping of status to emoji const statusToEmoji = triageLabelMappedToField( triageConfig, 'statuses', 'emoji' ) return { levels, levelToEmoji, statuses, statusToEmoji } }
JavaScript
function LoadYoutubeVidOnPreviewClick(id, w, h) { //var code='<iframe src="https://www.youtube.com/embed/'+id+'/?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1" width="'+w+'" height="'+h+'" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>'; var code = '<iframe src="https://www.youtube.com/embed/' + id + '/?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1&rel=0" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>'; var iframe = document.createElement('div'); iframe.innerHTML = code; iframe = iframe.firstChild; var div = document.getElementById("skipser-youtubevid-" + id); div.parentNode.replaceChild(iframe, div) }
function LoadYoutubeVidOnPreviewClick(id, w, h) { //var code='<iframe src="https://www.youtube.com/embed/'+id+'/?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1" width="'+w+'" height="'+h+'" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>'; var code = '<iframe src="https://www.youtube.com/embed/' + id + '/?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1&rel=0" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>'; var iframe = document.createElement('div'); iframe.innerHTML = code; iframe = iframe.firstChild; var div = document.getElementById("skipser-youtubevid-" + id); div.parentNode.replaceChild(iframe, div) }
JavaScript
function flatPromise () { let resolveFn let rejectFn const p = new Promise((resolve, reject) => { resolveFn = resolve rejectFn = reject }) return [p, resolveFn, rejectFn] }
function flatPromise () { let resolveFn let rejectFn const p = new Promise((resolve, reject) => { resolveFn = resolve rejectFn = reject }) return [p, resolveFn, rejectFn] }
JavaScript
function waitableFunction (name = 'func') { const [promise, resolve] = flatPromise() const fn = jasmine.createSpy(name, resolve).and.callThrough() fn.toBeCalled = promise return fn }
function waitableFunction (name = 'func') { const [promise, resolve] = flatPromise() const fn = jasmine.createSpy(name, resolve).and.callThrough() fn.toBeCalled = promise return fn }
JavaScript
function fingerprint (file, options) { if (isReactNative()) { return Promise.resolve(reactNativeFingerprint(file, options)) } return Promise.resolve([ 'tus-br', file.name, file.type, file.size, file.lastModified, options.endpoint, ].join('-')) }
function fingerprint (file, options) { if (isReactNative()) { return Promise.resolve(reactNativeFingerprint(file, options)) } return Promise.resolve([ 'tus-br', file.name, file.type, file.size, file.lastModified, options.endpoint, ].join('-')) }
JavaScript
function concat (a, b) { if (a.concat) { // Is `a` an Array? return a.concat(b) } if (a instanceof Blob) { return new Blob([a, b], { type: a.type }) } if (a.set) { // Is `a` a typed array? var c = new a.constructor(a.length + b.length) c.set(a) c.set(b, a.length) return c } throw new Error('Unknown data type') }
function concat (a, b) { if (a.concat) { // Is `a` an Array? return a.concat(b) } if (a instanceof Blob) { return new Blob([a, b], { type: a.type }) } if (a.set) { // Is `a` a typed array? var c = new a.constructor(a.length + b.length) c.set(a) c.set(b, a.length) return c } throw new Error('Unknown data type') }
JavaScript
function fingerprint (file, options) { if (Buffer.isBuffer(file)) { // create MD5 hash for buffer type const blockSize = 64 * 1024 // 64kb const content = file.slice(0, Math.min(blockSize, file.length)) const hash = createHash('md5').update(content).digest('hex') const fingerprint = ['node-buffer', hash, file.length, options.endpoint].join('-') return Promise.resolve(fingerprint) } if (file instanceof fs.ReadStream && file.path != null) { return new Promise((resolve, reject) => { const name = path.resolve(file.path) fs.stat(file.path, (err, info) => { if (err) { return reject(err) } const fingerprint = [ 'node-file', name, info.size, info.mtime.getTime(), options.endpoint, ].join('-') resolve(fingerprint) }) }) } // fingerprint cannot be computed for file input type return Promise.resolve(null) }
function fingerprint (file, options) { if (Buffer.isBuffer(file)) { // create MD5 hash for buffer type const blockSize = 64 * 1024 // 64kb const content = file.slice(0, Math.min(blockSize, file.length)) const hash = createHash('md5').update(content).digest('hex') const fingerprint = ['node-buffer', hash, file.length, options.endpoint].join('-') return Promise.resolve(fingerprint) } if (file instanceof fs.ReadStream && file.path != null) { return new Promise((resolve, reject) => { const name = path.resolve(file.path) fs.stat(file.path, (err, info) => { if (err) { return reject(err) } const fingerprint = [ 'node-file', name, info.size, info.mtime.getTime(), options.endpoint, ].join('-') resolve(fingerprint) }) }) } // fingerprint cannot be computed for file input type return Promise.resolve(null) }
JavaScript
function uuid () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { var r = Math.random() * 16 | 0 var v = c == 'x' ? r : (r & 0x3 | 0x8) return v.toString(16) }) }
function uuid () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { var r = Math.random() * 16 | 0 var v = c == 'x' ? r : (r & 0x3 | 0x8) return v.toString(16) }) }
JavaScript
function readAsByteArray (chunk) { return new Promise((resolve, reject) => { const reader = new FileReader() reader.onload = () => { const value = new Uint8Array(reader.result) resolve({ value }) } reader.onerror = (err) => { reject(err) } reader.readAsArrayBuffer(chunk) }) }
function readAsByteArray (chunk) { return new Promise((resolve, reject) => { const reader = new FileReader() reader.onload = () => { const value = new Uint8Array(reader.result) resolve({ value }) } reader.onerror = (err) => { reject(err) } reader.readAsArrayBuffer(chunk) }) }
JavaScript
function uriToBlob (uri) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() xhr.responseType = 'blob' xhr.onload = () => { const blob = xhr.response resolve(blob) } xhr.onerror = (err) => { reject(err) } xhr.open('GET', uri) xhr.send() }) }
function uriToBlob (uri) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() xhr.responseType = 'blob' xhr.onload = () => { const blob = xhr.response resolve(blob) } xhr.onerror = (err) => { reject(err) } xhr.open('GET', uri) xhr.send() }) }
JavaScript
function nsSel () { var strBldr = [], prx = ns; $.each(arguments, function () { strBldr.push('.' + (this == '' ? prx : prx + '-' + this)); }); return strBldr.join(' ').trim(); }
function nsSel () { var strBldr = [], prx = ns; $.each(arguments, function () { strBldr.push('.' + (this == '' ? prx : prx + '-' + this)); }); return strBldr.join(' ').trim(); }
JavaScript
function nsClass () { var strBldr = [], prx = ns; $.each(arguments, function () { strBldr.push(this == '' ? prx : prx + '-' + this); }); return strBldr.join(' ').trim(); }
function nsClass () { var strBldr = [], prx = ns; $.each(arguments, function () { strBldr.push(this == '' ? prx : prx + '-' + this); }); return strBldr.join(' ').trim(); }
JavaScript
function withEditable(func, editableHtml, id) { id = id || 'test-editable'; var editable = jQuery("#" + id); if (null != editableHtml) { editable.html(editableHtml); } editable.aloha(); var alohaEditable = Aloha.getEditableById(id) func(alohaEditable); alohaEditable.destroy(); }
function withEditable(func, editableHtml, id) { id = id || 'test-editable'; var editable = jQuery("#" + id); if (null != editableHtml) { editable.html(editableHtml); } editable.aloha(); var alohaEditable = Aloha.getEditableById(id) func(alohaEditable); alohaEditable.destroy(); }
JavaScript
function testGc(editableHtml, expectedXhtml) { withEditable(function(editable){ var contents = editable.getContents(); if (jQuery.isArray(expectedXhtml)) { var foundEqual = false; for (var i = 0; i < expectedXhtml.length; i++) { if (contents == expectedXhtml[i]) { foundEqual = true; break; } } if ( ! foundEqual ) { equal(contents, expectedXhtml[0]); } else { ok(true); } } else { equal(contents, expectedXhtml); } }, editableHtml); }
function testGc(editableHtml, expectedXhtml) { withEditable(function(editable){ var contents = editable.getContents(); if (jQuery.isArray(expectedXhtml)) { var foundEqual = false; for (var i = 0; i < expectedXhtml.length; i++) { if (contents == expectedXhtml[i]) { foundEqual = true; break; } } if ( ! foundEqual ) { equal(contents, expectedXhtml[0]); } else { ok(true); } } else { equal(contents, expectedXhtml); } }, editableHtml); }
JavaScript
function testStyle(styleMap, elementHtml) { withEditable(function(editable){ var element = editable.obj.children().eq(0); var jqStyleMap = {}; for (var style in styleMap) { if (styleMap.hasOwnProperty(style)) { var styleValue = styleMap[style]; jqStyleMap[style] = $.isArray(styleValue) ? styleValue[0] : styleValue; } } element.css(jqStyleMap); var contents = editable.getContents(); // After parsing the serialized XHTML, the styles that were // dynamically set should be still be there. If not, they were // lost during serialization. var reparsedElement = $(contents).eq(0); for (var style in styleMap) { if (styleMap.hasOwnProperty(style)) { var reparsedStyleValue = reparsedElement.css(style); var styleValue = styleMap[style]; if ($.isArray(styleValue)) { var found = false; for (var i = 0; i < styleValue.length; i++) { if (reparsedStyleValue == styleValue[i]) { found = true; } } if ( ! found ) { equal(reparsedStyleValue, styleValue[0]); } else { ok(true); } } else { equal(reparsedStyleValue, styleValue); } } } }, elementHtml); }
function testStyle(styleMap, elementHtml) { withEditable(function(editable){ var element = editable.obj.children().eq(0); var jqStyleMap = {}; for (var style in styleMap) { if (styleMap.hasOwnProperty(style)) { var styleValue = styleMap[style]; jqStyleMap[style] = $.isArray(styleValue) ? styleValue[0] : styleValue; } } element.css(jqStyleMap); var contents = editable.getContents(); // After parsing the serialized XHTML, the styles that were // dynamically set should be still be there. If not, they were // lost during serialization. var reparsedElement = $(contents).eq(0); for (var style in styleMap) { if (styleMap.hasOwnProperty(style)) { var reparsedStyleValue = reparsedElement.css(style); var styleValue = styleMap[style]; if ($.isArray(styleValue)) { var found = false; for (var i = 0; i < styleValue.length; i++) { if (reparsedStyleValue == styleValue[i]) { found = true; } } if ( ! found ) { equal(reparsedStyleValue, styleValue[0]); } else { ok(true); } } else { equal(reparsedStyleValue, styleValue); } } } }, elementHtml); }
JavaScript
function supplant (str, obj) { return str.replace(/\{([a-z0-9\-\_]+)\}/ig, function (str, p1, offset, s) { var replacement = obj[p1] || str; return (typeof replacement === 'function') ? replacement() : replacement; }); }
function supplant (str, obj) { return str.replace(/\{([a-z0-9\-\_]+)\}/ig, function (str, p1, offset, s) { var replacement = obj[p1] || str; return (typeof replacement === 'function') ? replacement() : replacement; }); }
JavaScript
function nsSel () { var strBldr = [], prx = ns; $.each(arguments, function () { strBldr.push('.' + (this == '' ? prx : prx + '-' + this)); }); return $.trim(strBldr.join(' ')); }
function nsSel () { var strBldr = [], prx = ns; $.each(arguments, function () { strBldr.push('.' + (this == '' ? prx : prx + '-' + this)); }); return $.trim(strBldr.join(' ')); }
JavaScript
function hex2rgb (hex) { var hex = hex.replace('#', '').split(''); if (hex.length == 3) { hex[5] = hex[4] = hex[2]; hex[3] = hex[2] = hex[1]; hex[1] = hex[0]; } var rgb = []; for (var i = 0; i < 3; ++i) { rgb[i] = parseInt('0x' + hex[i * 2] + hex[i * 2 + 1], 16); } return rgb; }
function hex2rgb (hex) { var hex = hex.replace('#', '').split(''); if (hex.length == 3) { hex[5] = hex[4] = hex[2]; hex[3] = hex[2] = hex[1]; hex[1] = hex[0]; } var rgb = []; for (var i = 0; i < 3; ++i) { rgb[i] = parseInt('0x' + hex[i * 2] + hex[i * 2 + 1], 16); } return rgb; }
JavaScript
function selectNode(selected_id) { //to ensure that no other node is selected $.jstree._focused().deselect_all(); //handle errors if node does not exist or the position is incorrect if(!$('#tree').find("#"+selected_id).length){ //just select the root deck for now //todo: direct to correct node not root deck selected_id='tree-0-deck-'+deck+'-1'; $("#ajax_progress_indicator").css('display', 'none'); } _isEditing = false; //createBreadCrumb(selected_id); var selected_properties = getPropertiesFromId(selected_id); //open the parent node if(selected_properties['deckId']!=0) $("#tree").jstree("open_node", $('#'+getParentFromId(selected_id)+"-node")); if(selected_properties['type']=='deck' || selected_properties['type']=='slide'){ //fixed a bug: to prevent duplicate slides -- we have class slide for history items as well which conflicts wit view mode $("#itemhistory").html(''); $("#itemhistory").removeClass(); } $(".jstree-hovered").removeClass("jstree-hovered"); $(".jstree-clicked").removeClass("jstree-clicked"); $("#" + selected_id).addClass("jstree-clicked"); //console.log($('#tree').jstree('get_selected')); updateModeAddress(selected_id, 'view',1); if (selected_properties['type'] == 'deck') { updateTabURLs(selected_id,"deck"); $(".deck-" + selected_properties['itemId']).addClass("jstree-clicked"); $("#editlink").show(); $('#slideview').css('min-height','auto'); loadDeck(selected_properties['itemId']); } else { $("#editlink").hide(); $('#slideview').css('min-height','auto'); $(".slide-" + selected_properties['itemId']).addClass("jstree-clicked"); updateTabURLs(selected_id, "slide"); /* if (!is_deck_loaded) loadSlide(selected_properties['deckId'],selected_properties['itemId'], selected_properties['pos']); */ //console.log(loaded_range); checkUnsavedChanges(selected_id,'viewslide') } window.scrollTo(0, 0);//prevent from jumping to anchor }
function selectNode(selected_id) { //to ensure that no other node is selected $.jstree._focused().deselect_all(); //handle errors if node does not exist or the position is incorrect if(!$('#tree').find("#"+selected_id).length){ //just select the root deck for now //todo: direct to correct node not root deck selected_id='tree-0-deck-'+deck+'-1'; $("#ajax_progress_indicator").css('display', 'none'); } _isEditing = false; //createBreadCrumb(selected_id); var selected_properties = getPropertiesFromId(selected_id); //open the parent node if(selected_properties['deckId']!=0) $("#tree").jstree("open_node", $('#'+getParentFromId(selected_id)+"-node")); if(selected_properties['type']=='deck' || selected_properties['type']=='slide'){ //fixed a bug: to prevent duplicate slides -- we have class slide for history items as well which conflicts wit view mode $("#itemhistory").html(''); $("#itemhistory").removeClass(); } $(".jstree-hovered").removeClass("jstree-hovered"); $(".jstree-clicked").removeClass("jstree-clicked"); $("#" + selected_id).addClass("jstree-clicked"); //console.log($('#tree').jstree('get_selected')); updateModeAddress(selected_id, 'view',1); if (selected_properties['type'] == 'deck') { updateTabURLs(selected_id,"deck"); $(".deck-" + selected_properties['itemId']).addClass("jstree-clicked"); $("#editlink").show(); $('#slideview').css('min-height','auto'); loadDeck(selected_properties['itemId']); } else { $("#editlink").hide(); $('#slideview').css('min-height','auto'); $(".slide-" + selected_properties['itemId']).addClass("jstree-clicked"); updateTabURLs(selected_id, "slide"); /* if (!is_deck_loaded) loadSlide(selected_properties['deckId'],selected_properties['itemId'], selected_properties['pos']); */ //console.log(loaded_range); checkUnsavedChanges(selected_id,'viewslide') } window.scrollTo(0, 0);//prevent from jumping to anchor }
JavaScript
function loadDeckFrom(id,from) { var user = getCurrenUserID(); // get the current user_id $.ajax({ url : 'ajax/showDeckPreviewProgressive/' + id+'/from/'+from, success : function(msg) { var data = eval("(" + msg + ")"); data.current_user_id = user; $("#show_more_slides").remove(); $("#deck_preview_partial").tmpl(data).appendTo("#slideview"); if(parseInt(from+data.slides.length)<data.size){ //show the "show more..." button $("#slideview").append('<div id="show_more_slides"><center><a class="btn" onclick="loadDeckFrom('+id+','+parseInt(from+data.slides.length)+')">Show more...</a></center></div>'); } //deck stream $('#deck_stream_button_div').show(); $('#deck_stream_button').attr('deck_id',id); } }); }
function loadDeckFrom(id,from) { var user = getCurrenUserID(); // get the current user_id $.ajax({ url : 'ajax/showDeckPreviewProgressive/' + id+'/from/'+from, success : function(msg) { var data = eval("(" + msg + ")"); data.current_user_id = user; $("#show_more_slides").remove(); $("#deck_preview_partial").tmpl(data).appendTo("#slideview"); if(parseInt(from+data.slides.length)<data.size){ //show the "show more..." button $("#slideview").append('<div id="show_more_slides"><center><a class="btn" onclick="loadDeckFrom('+id+','+parseInt(from+data.slides.length)+')">Show more...</a></center></div>'); } //deck stream $('#deck_stream_button_div').show(); $('#deck_stream_button').attr('deck_id',id); } }); }
JavaScript
function selectOrReload(msg,target_node){ disable_save_button(); resetGolbalVars(); if (msg.root_changed) { if(target_node) if(msg.force_refresh){ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + target_node + '-view'; window.location.reload() }else{ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + target_node + '-view'; } else if(msg.force_refresh){ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + msg.items[0].rev_id + '-view'; window.location.reload() }else{ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + msg.items[0].rev_id + '-view'; } } else { if(target_node) $('#after_refresh_node').text(target_node); else $('#after_refresh_node').text(msg.items[0].rev_id); //preserve the nodes opened $.cookie('my_jstree_open', $.cookie("jstree_open")); var tree = $.jstree._reference("#tree"); if(!msg.refresh_nodes) if(msg.items.length){ tree.refresh('#'+getParentFromId(msg.items[0].rev_id)); }else $("#tree").jstree('refresh'); else $.each(msg.refresh_nodes, function(i,n){ //$.each($('.deck-'+n), function(ii,nn){ //only refresh the affected nodes tree.refresh('.deck-'+n); //}) }) // } }
function selectOrReload(msg,target_node){ disable_save_button(); resetGolbalVars(); if (msg.root_changed) { if(target_node) if(msg.force_refresh){ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + target_node + '-view'; window.location.reload() }else{ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + target_node + '-view'; } else if(msg.force_refresh){ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + msg.items[0].rev_id + '-view'; window.location.reload() }else{ window.location = 'deck/' + msg.root_changed+ '_' + msg.slug_title + '#' + msg.items[0].rev_id + '-view'; } } else { if(target_node) $('#after_refresh_node').text(target_node); else $('#after_refresh_node').text(msg.items[0].rev_id); //preserve the nodes opened $.cookie('my_jstree_open', $.cookie("jstree_open")); var tree = $.jstree._reference("#tree"); if(!msg.refresh_nodes) if(msg.items.length){ tree.refresh('#'+getParentFromId(msg.items[0].rev_id)); }else $("#tree").jstree('refresh'); else $.each(msg.refresh_nodes, function(i,n){ //$.each($('.deck-'+n), function(ii,nn){ //only refresh the affected nodes tree.refresh('.deck-'+n); //}) }) // } }
JavaScript
function confirmNewRevision(selected_id) { var res; var properties = getPropertiesFromId(selected_id); var deckId = (properties['deckId'] != 0) ? properties['deckId'] : deck; $.ajax({ async : false, url : './?url=ajax/checkCreatingNewDeckRev&deck=' + deckId, success : function(msg) { msg = eval(msg); if (!msg) { res = true; //no need to create new revision } else { var answer = confirm("This change will create a new revision for the selected deck(s). Are you sure you want to do it?"); if (answer) { res = true;//no need to create new revision } else { res = false;// need to create new revision } } } }); return res; }
function confirmNewRevision(selected_id) { var res; var properties = getPropertiesFromId(selected_id); var deckId = (properties['deckId'] != 0) ? properties['deckId'] : deck; $.ajax({ async : false, url : './?url=ajax/checkCreatingNewDeckRev&deck=' + deckId, success : function(msg) { msg = eval(msg); if (!msg) { res = true; //no need to create new revision } else { var answer = confirm("This change will create a new revision for the selected deck(s). Are you sure you want to do it?"); if (answer) { res = true;//no need to create new revision } else { res = false;// need to create new revision } } } }); return res; }
JavaScript
function cleanExtraTags(id){ clearMathJaxRendering(id); //disable highlighted code $('#'+id+' .CodeMirror').remove(); $('#'+id+' .deck-codemirror-result').remove(); $.each($('#'+id+' .code'),function(index,value){ $(value).css('display',''); $(value).removeClass('passive-code'); $(value).addClass('passive-code'); }); //re-enable iframes $.each($('#'+id+' iframe'),function(index,value){ $(value).attr('src',$(value)[0]._src); }); $('#'+id+' .slide').removeClass('slide'); $('#'+id+' .deck-current').removeClass('deck-current'); $('#'+id+' .deck-previous').removeClass('deck-previous'); $('#'+id+' .deck-next').removeClass('deck-next'); $('#'+id+' .deck-after').removeClass('deck-after'); $('#'+id+' .deck-before').removeClass('deck-before'); }
function cleanExtraTags(id){ clearMathJaxRendering(id); //disable highlighted code $('#'+id+' .CodeMirror').remove(); $('#'+id+' .deck-codemirror-result').remove(); $.each($('#'+id+' .code'),function(index,value){ $(value).css('display',''); $(value).removeClass('passive-code'); $(value).addClass('passive-code'); }); //re-enable iframes $.each($('#'+id+' iframe'),function(index,value){ $(value).attr('src',$(value)[0]._src); }); $('#'+id+' .slide').removeClass('slide'); $('#'+id+' .deck-current').removeClass('deck-current'); $('#'+id+' .deck-previous').removeClass('deck-previous'); $('#'+id+' .deck-next').removeClass('deck-next'); $('#'+id+' .deck-after').removeClass('deck-after'); $('#'+id+' .deck-before').removeClass('deck-before'); }
JavaScript
function store_active_editor(id){ if($.trim($('#active_editor_id').text())=='' || $.trim($('#active_editor_id').text())!=id){ $('#active_editor_id').text(id); return true; }else{ return false; } }
function store_active_editor(id){ if($.trim($('#active_editor_id').text())=='' || $.trim($('#active_editor_id').text())!=id){ $('#active_editor_id').text(id); return true; }else{ return false; } }
JavaScript
function manual_uniquearr(array){ return $.grep(array,function(el,index){ return index == $.inArray(el,array); }); }
function manual_uniquearr(array){ return $.grep(array,function(el,index){ return index == $.inArray(el,array); }); }
JavaScript
function apply_source_code(){ //var content=$('#html_source_code').val(); var content=editor1.getValue(); //strip the script tags content=content.replace(/<script.*?>.*?<\/.*?script>/gi, ""); content=$.trim(content); //do not allow inline scripts to get executed //content=content.replace('(?<=<.*)javascript.*:[^"]*', ""); var old_content=$('.deck-current').find('.slide-body').html().trim(); if(old_content!=content ){ $('.deck-current').find('.slide-body').html(content); item_change.push($('.deck-current').find('.slide-body').attr('id')); enable_save_button(); } }
function apply_source_code(){ //var content=$('#html_source_code').val(); var content=editor1.getValue(); //strip the script tags content=content.replace(/<script.*?>.*?<\/.*?script>/gi, ""); content=$.trim(content); //do not allow inline scripts to get executed //content=content.replace('(?<=<.*)javascript.*:[^"]*', ""); var old_content=$('.deck-current').find('.slide-body').html().trim(); if(old_content!=content ){ $('.deck-current').find('.slide-body').html(content); item_change.push($('.deck-current').find('.slide-body').attr('id')); enable_save_button(); } }
JavaScript
function disableContextMenu() { var user = getCurrenUserID(); // get the current user_id if (!user) { $("#vakata-contextmenu").remove(); return; } }
function disableContextMenu() { var user = getCurrenUserID(); // get the current user_id if (!user) { $("#vakata-contextmenu").remove(); return; } }
JavaScript
function prepareUsageSiblingDecks(deck_node_id) { var deck_id=getPropertiesFromId(deck_node_id)['itemId']; var tmp=$("#root_deck_sibling").text().trim(); if(!tmp){ $("#root_deck_sibling").html(''); $.ajax({ //url : './?url=ajax/showDeckUsage&id=' + deck_id, url : './?url=ajax/createUsagePath&deck=' + deck_id, success : function(msg) { //var data = eval("(" + msg + ")"); $("#root_deck_sibling").html('Full Usage Path:<br/>'+msg+'<hr/> Current Path:<br/>'); //$("#root_sibling_usage").tmpl(data).appendTo("#root_deck_sibling"); //if($("#root_deck_sibling").text().trim()){ //$("#root_deck_sibling").prepend('<li><center><b>Used in:</b></center></li>'); //}else{ //$("#root_deck_sibling").prepend('<li><center><b>No usage found!</b></center></li>'); //} //showSiblibgs('#'+deck_node_id+'-siblings'); $("#root_deck_sibling").show(); } }); }else{ $("#root_deck_sibling").html(''); //showSiblibgs('#'+deck_node_id+'-siblings'); } }
function prepareUsageSiblingDecks(deck_node_id) { var deck_id=getPropertiesFromId(deck_node_id)['itemId']; var tmp=$("#root_deck_sibling").text().trim(); if(!tmp){ $("#root_deck_sibling").html(''); $.ajax({ //url : './?url=ajax/showDeckUsage&id=' + deck_id, url : './?url=ajax/createUsagePath&deck=' + deck_id, success : function(msg) { //var data = eval("(" + msg + ")"); $("#root_deck_sibling").html('Full Usage Path:<br/>'+msg+'<hr/> Current Path:<br/>'); //$("#root_sibling_usage").tmpl(data).appendTo("#root_deck_sibling"); //if($("#root_deck_sibling").text().trim()){ //$("#root_deck_sibling").prepend('<li><center><b>Used in:</b></center></li>'); //}else{ //$("#root_deck_sibling").prepend('<li><center><b>No usage found!</b></center></li>'); //} //showSiblibgs('#'+deck_node_id+'-siblings'); $("#root_deck_sibling").show(); } }); }else{ $("#root_deck_sibling").html(''); //showSiblibgs('#'+deck_node_id+'-siblings'); } }
JavaScript
function prepareSiblingDecks(deck_node_id) { var output=''; var separator='<span class="separator-icon"> <b>►</b></span>'; if(deck_node_id){ var tmp=$('#'+deck_node_id+'-node')[0].previousSibling; while(tmp){ if(!$(tmp).hasClass("jstree-leaf")) output='<li><a style="cursor:pointer" onclick="selectNode(\''+getPropertiesFromHash(tmp.id)['nodeId']+'\');">'+$($(tmp)[0].children[1]).text()+'</a></li>'+output; tmp=$(tmp)[0].previousSibling; } var tmp=$('#'+deck_node_id+'-node')[0].nextSibling; while(tmp){ if(!$(tmp).hasClass("jstree-leaf")) output=output+'<li><a style="cursor:pointer" onclick="selectNode(\''+getPropertiesFromHash(tmp.id)['nodeId']+'\');">'+$($(tmp)[0].children[1]).text()+'</a></li>'; tmp=$(tmp)[0].nextSibling; } if(output) output='<span id="'+deck_node_id+'-siblings" class="dropdown-sibling" onclick="showSiblibgs(this)" onmouseover="$(this).addClass(\'separator-icon-active\')" onmouseout="$(this).removeClass(\'separator-icon-active\')">'+separator+'<ul class="dropdown-menu">'+output+'</ul></span>'; else output='<span id="'+deck_node_id+'-siblings" class="dropdown-sibling" onclick="showSiblibgs(this)" onmouseover="$(this).addClass(\'separator-icon-active\')" onmouseout="$(this).removeClass(\'separator-icon-active\')">'+separator+'</span>'; return output; } }
function prepareSiblingDecks(deck_node_id) { var output=''; var separator='<span class="separator-icon"> <b>►</b></span>'; if(deck_node_id){ var tmp=$('#'+deck_node_id+'-node')[0].previousSibling; while(tmp){ if(!$(tmp).hasClass("jstree-leaf")) output='<li><a style="cursor:pointer" onclick="selectNode(\''+getPropertiesFromHash(tmp.id)['nodeId']+'\');">'+$($(tmp)[0].children[1]).text()+'</a></li>'+output; tmp=$(tmp)[0].previousSibling; } var tmp=$('#'+deck_node_id+'-node')[0].nextSibling; while(tmp){ if(!$(tmp).hasClass("jstree-leaf")) output=output+'<li><a style="cursor:pointer" onclick="selectNode(\''+getPropertiesFromHash(tmp.id)['nodeId']+'\');">'+$($(tmp)[0].children[1]).text()+'</a></li>'; tmp=$(tmp)[0].nextSibling; } if(output) output='<span id="'+deck_node_id+'-siblings" class="dropdown-sibling" onclick="showSiblibgs(this)" onmouseover="$(this).addClass(\'separator-icon-active\')" onmouseout="$(this).removeClass(\'separator-icon-active\')">'+separator+'<ul class="dropdown-menu">'+output+'</ul></span>'; else output='<span id="'+deck_node_id+'-siblings" class="dropdown-sibling" onclick="showSiblibgs(this)" onmouseover="$(this).addClass(\'separator-icon-active\')" onmouseout="$(this).removeClass(\'separator-icon-active\')">'+separator+'</span>'; return output; } }
JavaScript
function show_editors(deck_id,read_only){ if($("#editors").text().trim()!='') $("#editors").text(''); $.ajax({ url : './?url=ajax/getEditors&deck_id=' + deck_id, success : function(msg) { var data = eval("(" + msg + ")"); data.deck_id=deck_id; if(read_only){ $("#editor_list_ro").tmpl(data).appendTo("#editors"); }else{ $("#editor_list").tmpl(data).appendTo("#editors"); } } }); }
function show_editors(deck_id,read_only){ if($("#editors").text().trim()!='') $("#editors").text(''); $.ajax({ url : './?url=ajax/getEditors&deck_id=' + deck_id, success : function(msg) { var data = eval("(" + msg + ")"); data.deck_id=deck_id; if(read_only){ $("#editor_list_ro").tmpl(data).appendTo("#editors"); }else{ $("#editor_list").tmpl(data).appendTo("#editors"); } } }); }
JavaScript
function reloadTabContent(tab_name,id,prefix){ //using css classes to check the reload of div switch(tab_name){ case 'Questions': if ($("#itemquestions").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemquestions").html(''); $("#itemquestions").removeClass(); $("#itemquestions").addClass(prefix+'-'+id); return 1; } break; case 'History': if ($("#itemhistory").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemhistory").html(''); $("#itemhistory").removeClass(); $("#itemhistory").addClass(prefix+'-'+id); return 1; } break; case 'Usage': if ($("#itemusage").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemusage").html(''); $("#itemusage").removeClass(); $("#itemusage").addClass(prefix+'-'+id); return 1; } break; case 'Discussion': if ($("#itemdiscussion").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemdiscussion").html(''); $("#itemdiscussion").removeClass(); $("#itemdiscussion").addClass(prefix+'-'+id); return 1; } break; } }
function reloadTabContent(tab_name,id,prefix){ //using css classes to check the reload of div switch(tab_name){ case 'Questions': if ($("#itemquestions").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemquestions").html(''); $("#itemquestions").removeClass(); $("#itemquestions").addClass(prefix+'-'+id); return 1; } break; case 'History': if ($("#itemhistory").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemhistory").html(''); $("#itemhistory").removeClass(); $("#itemhistory").addClass(prefix+'-'+id); return 1; } break; case 'Usage': if ($("#itemusage").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemusage").html(''); $("#itemusage").removeClass(); $("#itemusage").addClass(prefix+'-'+id); return 1; } break; case 'Discussion': if ($("#itemdiscussion").hasClass(prefix+'-'+id)) { return 0; }else{ $("#itemdiscussion").html(''); $("#itemdiscussion").removeClass(); $("#itemdiscussion").addClass(prefix+'-'+id); return 1; } break; } }
JavaScript
function isLastItem(selected_id) { if (!$('#' + selected_id + '-node')[0].nextSibling && !$('#' + selected_id + '-node')[0].previousSibling) return true; else return false; }
function isLastItem(selected_id) { if (!$('#' + selected_id + '-node')[0].nextSibling && !$('#' + selected_id + '-node')[0].previousSibling) return true; else return false; }
JavaScript
function jumpBlock( block, isGoingLeft ) { var range = new GENTICS.Utils.RangeObject(); var sibling = isGoingLeft ? prevVisibleNode( block ) : nextVisibleNode( block ); if ( !sibling || isBlock( sibling ) ) { var $landing = jQuery( '<div>&nbsp;</div>' ); if ( isGoingLeft ) { jQuery( block ).before( $landing ); } else { jQuery( block ).after( $landing ); } range.startContainer = range.endContainer = $landing[0]; range.startOffset = range.endOffset = 0; // Clear out any old placeholder first ... cleanupPlaceholders( range ); window.$_alohaPlaceholder = $landing; } else { range.startContainer = range.endContainer = sibling; range.startOffset = range.endOffset = isGoingLeft ? nodeLength( sibling ) : ( isOldIE ? 1 : 0 ); cleanupPlaceholders( range ); } range.select(); Aloha.trigger( 'aloha-block-selected', block ); Aloha.Selection.preventSelectionChanged(); }
function jumpBlock( block, isGoingLeft ) { var range = new GENTICS.Utils.RangeObject(); var sibling = isGoingLeft ? prevVisibleNode( block ) : nextVisibleNode( block ); if ( !sibling || isBlock( sibling ) ) { var $landing = jQuery( '<div>&nbsp;</div>' ); if ( isGoingLeft ) { jQuery( block ).before( $landing ); } else { jQuery( block ).after( $landing ); } range.startContainer = range.endContainer = $landing[0]; range.startOffset = range.endOffset = 0; // Clear out any old placeholder first ... cleanupPlaceholders( range ); window.$_alohaPlaceholder = $landing; } else { range.startContainer = range.endContainer = sibling; range.startOffset = range.endOffset = isGoingLeft ? nodeLength( sibling ) : ( isOldIE ? 1 : 0 ); cleanupPlaceholders( range ); } range.select(); Aloha.trigger( 'aloha-block-selected', block ); Aloha.Selection.preventSelectionChanged(); }
JavaScript
function correctTableStructure ( tableObj ) { var table = tableObj.obj, i, row, rows = tableObj.getRows(), rowsNum = rows.length, cols, colsNum, colsCount, maxColsCount = 0, cachedColsCounts = [], colsCountDiff, colSpan; for ( i = 0; i < rowsNum; i++ ) { row = jQuery( rows[ i ] ); cols = row.children( 'td, th' ); colsNum = cols.length; colsCount = Utils.cellIndexToGridColumn( rows, i, colsNum - 1 ) + 1; // Check if the last cell in this row has a col span, to account // for it in the total number of colums in this row colSpan = parseInt( cols.last().attr( 'colspan' ), 10 ); if ( colSpan == 0 ) { // TODO: support colspan=0 // http://dev.w3.org/html5/markup/td.html#td.attrs.colspan // http://www.w3.org/TR/html401/struct/tables.html#adef-colspan // The value zero ("0") means that the cell spans all columns // from the current column to the last column of the column // group (COLGROUP) in which the cel } else if ( !isNaN( colSpan ) ) { // The default value of this attribute is one ("1"), so where this // is the case, we will remove such superfluous colspan attributes if ( colSpan == 1 ) { cols.last().removeAttr( 'colspan' ); } colsCount += ( colSpan - 1 ); } cachedColsCounts.push( colsCount ); if ( colsCount > maxColsCount ) { maxColsCount = colsCount; } } for ( i = 0; i < rowsNum; i++ ) { colsCountDiff = maxColsCount - cachedColsCounts[ i ]; if ( colsCountDiff > 0 ) { // Create as many td's as we need to complete the row jQuery( rows[ i ] ).append( ( new Array( colsCountDiff + 1 ) ).join( '<td></td>' ) ); } } }
function correctTableStructure ( tableObj ) { var table = tableObj.obj, i, row, rows = tableObj.getRows(), rowsNum = rows.length, cols, colsNum, colsCount, maxColsCount = 0, cachedColsCounts = [], colsCountDiff, colSpan; for ( i = 0; i < rowsNum; i++ ) { row = jQuery( rows[ i ] ); cols = row.children( 'td, th' ); colsNum = cols.length; colsCount = Utils.cellIndexToGridColumn( rows, i, colsNum - 1 ) + 1; // Check if the last cell in this row has a col span, to account // for it in the total number of colums in this row colSpan = parseInt( cols.last().attr( 'colspan' ), 10 ); if ( colSpan == 0 ) { // TODO: support colspan=0 // http://dev.w3.org/html5/markup/td.html#td.attrs.colspan // http://www.w3.org/TR/html401/struct/tables.html#adef-colspan // The value zero ("0") means that the cell spans all columns // from the current column to the last column of the column // group (COLGROUP) in which the cel } else if ( !isNaN( colSpan ) ) { // The default value of this attribute is one ("1"), so where this // is the case, we will remove such superfluous colspan attributes if ( colSpan == 1 ) { cols.last().removeAttr( 'colspan' ); } colsCount += ( colSpan - 1 ); } cachedColsCounts.push( colsCount ); if ( colsCount > maxColsCount ) { maxColsCount = colsCount; } } for ( i = 0; i < rowsNum; i++ ) { colsCountDiff = maxColsCount - cachedColsCounts[ i ]; if ( colsCountDiff > 0 ) { // Create as many td's as we need to complete the row jQuery( rows[ i ] ).append( ( new Array( colsCountDiff + 1 ) ).join( '<td></td>' ) ); } } }
JavaScript
function fixNode(node) { if (!node) { return; } if (node.previousSibling) { return node.previousSibling.nextSibling; } else if (node.nextSibling) { return node.nextSibling.previousSibling; } else if (node.parentNode) { return node.parentNode.firstChild; } else { return node; } }
function fixNode(node) { if (!node) { return; } if (node.previousSibling) { return node.previousSibling.nextSibling; } else if (node.nextSibling) { return node.nextSibling.previousSibling; } else if (node.parentNode) { return node.parentNode.firstChild; } else { return node; } }
JavaScript
function comparePosition(node1, node2) { return (node1.contains(node2) && 16) + (node2.contains(node1) && 8) + (node1.sourceIndex >= 0 && node2.sourceIndex >= 0 ? (node1.sourceIndex < node2.sourceIndex && 4) + (node1.sourceIndex > node2.sourceIndex && 2) : 1); }
function comparePosition(node1, node2) { return (node1.contains(node2) && 16) + (node2.contains(node1) && 8) + (node1.sourceIndex >= 0 && node2.sourceIndex >= 0 ? (node1.sourceIndex < node2.sourceIndex && 4) + (node1.sourceIndex > node2.sourceIndex && 2) : 1); }
JavaScript
function onWindowScroll( floatingmenu ) { if ( !Aloha.activeEditable ) { return; } var element = floatingmenu.obj; var editablePos = Aloha.activeEditable.obj.offset(); var isTopAligned = floatingmenu.behaviour === 'topalign'; var isAppended = floatingmenu.behaviour === 'append'; var isManuallyPinned = floatingmenu.pinned && ( parseInt( element.css( 'left' ), 10 ) != ( editablePos.left + floatingmenu.horizontalOffset ) ); // no calculation when pinned manually or has behaviour 'append' if ( isTopAligned && isManuallyPinned || isAppended ) { return; } var floatingmenuHeight = element.height(); var scrollTop = jQuery( document ).scrollTop(); // This value is what the top position of the floating menu *would* be // if we tried to position it above the active editable. var floatingmenuTop = editablePos.top - floatingmenuHeight + floatingmenu.marginTop - floatingmenu.topalignOffset; // The floating menu does not fit in the space between the top of the // viewport and the editable, so position it at the top of the viewport // and over the editable. if ( scrollTop > floatingmenuTop ) { editablePos.top = isTopAligned ? scrollTop + floatingmenu.marginTop : floatingmenu.marginTop; // There is enough space on top of the editable to fit the entire // floating menu, so we do so. } else if ( scrollTop <= floatingmenuTop ) { editablePos.top -= floatingmenuHeight + ( isTopAligned ? floatingmenu.marginTop + floatingmenu.topalignOffset : 0 ); } floatingmenu.floatTo( editablePos ); }
function onWindowScroll( floatingmenu ) { if ( !Aloha.activeEditable ) { return; } var element = floatingmenu.obj; var editablePos = Aloha.activeEditable.obj.offset(); var isTopAligned = floatingmenu.behaviour === 'topalign'; var isAppended = floatingmenu.behaviour === 'append'; var isManuallyPinned = floatingmenu.pinned && ( parseInt( element.css( 'left' ), 10 ) != ( editablePos.left + floatingmenu.horizontalOffset ) ); // no calculation when pinned manually or has behaviour 'append' if ( isTopAligned && isManuallyPinned || isAppended ) { return; } var floatingmenuHeight = element.height(); var scrollTop = jQuery( document ).scrollTop(); // This value is what the top position of the floating menu *would* be // if we tried to position it above the active editable. var floatingmenuTop = editablePos.top - floatingmenuHeight + floatingmenu.marginTop - floatingmenu.topalignOffset; // The floating menu does not fit in the space between the top of the // viewport and the editable, so position it at the top of the viewport // and over the editable. if ( scrollTop > floatingmenuTop ) { editablePos.top = isTopAligned ? scrollTop + floatingmenu.marginTop : floatingmenu.marginTop; // There is enough space on top of the editable to fit the entire // floating menu, so we do so. } else if ( scrollTop <= floatingmenuTop ) { editablePos.top -= floatingmenuHeight + ( isTopAligned ? floatingmenu.marginTop + floatingmenu.topalignOffset : 0 ); } floatingmenu.floatTo( editablePos ); }
JavaScript
function nestedListInIEWorkaround ( range ) { if (jQuery.browser.msie && range.startContainer === range.endContainer && range.startOffset === range.endOffset && range.startContainer.nodeType == 3 && range.startOffset == range.startContainer.data.length && range.startContainer.nextSibling && ["OL", "UL"].indexOf(range.startContainer.nextSibling.nodeName) !== -1) { if (range.startContainer.data[range.startContainer.data.length-1] == ' ') { range.startOffset = range.endOffset = range.startOffset-1; } else { range.startContainer.data = range.startContainer.data + ' '; } } }
function nestedListInIEWorkaround ( range ) { if (jQuery.browser.msie && range.startContainer === range.endContainer && range.startOffset === range.endOffset && range.startContainer.nodeType == 3 && range.startOffset == range.startContainer.data.length && range.startContainer.nextSibling && ["OL", "UL"].indexOf(range.startContainer.nextSibling.nodeName) !== -1) { if (range.startContainer.data[range.startContainer.data.length-1] == ' ') { range.startOffset = range.endOffset = range.startOffset-1; } else { range.startContainer.data = range.startContainer.data + ' '; } } }
JavaScript
function isAncestor(ancestor, descendant) { return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY); }
function isAncestor(ancestor, descendant) { return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY); }
JavaScript
function isDescendant(descendant, ancestor) { return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY); }
function isDescendant(descendant, ancestor) { return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY); }
JavaScript
function legacySizeToCss(legacyVal) { return { 1: "xx-small", 2: "small", 3: "medium", 4: "large", 5: "x-large", 6: "xx-large", 7: "xxx-large" }[legacyVal]; }
function legacySizeToCss(legacyVal) { return { 1: "xx-small", 2: "small", 3: "medium", 4: "large", 5: "x-large", 6: "xx-large", 7: "xxx-large" }[legacyVal]; }
JavaScript
function isHtmlNamespace(ns) { return ns === null || !ns || ns === htmlNamespace; }
function isHtmlNamespace(ns) { return ns === null || !ns || ns === htmlNamespace; }
JavaScript
function editCommandMethod(command, prop, range, callback) { // Set up our global range magic, but only if we're the outermost function if (executionStackDepth == 0 && typeof range != "undefined") { globalRange = range; } else if (executionStackDepth == 0) { globalRange = null; globalRange = range; } // "If command is not supported, raise a NOT_SUPPORTED_ERR exception." // // We can't throw a real one, but a string will do for our purposes. if (!(command in commands)) { throw "NOT_SUPPORTED_ERR"; } // "If command has no action, raise an INVALID_ACCESS_ERR exception." // "If command has no indeterminacy, raise an INVALID_ACCESS_ERR // exception." // "If command has no state, raise an INVALID_ACCESS_ERR exception." // "If command has no value, raise an INVALID_ACCESS_ERR exception." if (prop != "enabled" && !(prop in commands[command])) { throw "INVALID_ACCESS_ERR"; } executionStackDepth++; try { var ret = callback(); } catch(e) { executionStackDepth--; throw e; } executionStackDepth--; return ret; }
function editCommandMethod(command, prop, range, callback) { // Set up our global range magic, but only if we're the outermost function if (executionStackDepth == 0 && typeof range != "undefined") { globalRange = range; } else if (executionStackDepth == 0) { globalRange = null; globalRange = range; } // "If command is not supported, raise a NOT_SUPPORTED_ERR exception." // // We can't throw a real one, but a string will do for our purposes. if (!(command in commands)) { throw "NOT_SUPPORTED_ERR"; } // "If command has no action, raise an INVALID_ACCESS_ERR exception." // "If command has no indeterminacy, raise an INVALID_ACCESS_ERR // exception." // "If command has no state, raise an INVALID_ACCESS_ERR exception." // "If command has no value, raise an INVALID_ACCESS_ERR exception." if (prop != "enabled" && !(prop in commands[command])) { throw "INVALID_ACCESS_ERR"; } executionStackDepth++; try { var ret = callback(); } catch(e) { executionStackDepth--; throw e; } executionStackDepth--; return ret; }
JavaScript
function isEditable(node) { // This is slightly a lie, because we're excluding non-HTML elements with // contentEditable attributes. return node && !isEditingHost(node) && (node.nodeType != $_.Node.ELEMENT_NODE || node.contentEditable != "false" || jQuery(node).hasClass('aloha-table-wrapper')) && (isEditingHost(node.parentNode) || isEditable(node.parentNode)); }
function isEditable(node) { // This is slightly a lie, because we're excluding non-HTML elements with // contentEditable attributes. return node && !isEditingHost(node) && (node.nodeType != $_.Node.ELEMENT_NODE || node.contentEditable != "false" || jQuery(node).hasClass('aloha-table-wrapper')) && (isEditingHost(node.parentNode) || isEditable(node.parentNode)); }
JavaScript
function hasEditableDescendants(node) { for (var i = 0; i < node.childNodes.length; i++) { if (isEditable(node.childNodes[i]) || hasEditableDescendants(node.childNodes[i])) { return true; } } return false; }
function hasEditableDescendants(node) { for (var i = 0; i < node.childNodes.length; i++) { if (isEditable(node.childNodes[i]) || hasEditableDescendants(node.childNodes[i])) { return true; } } return false; }
JavaScript
function isCollapsedLineBreak(br) { if (!isHtmlElement(br, "br")) { return false; } // Add a zwsp after it and see if that changes the height of the nearest // non-inline parent. Note: this is not actually reliable, because the // parent might have a fixed height or something. var ref = br.parentNode; while ($_.getComputedStyle(ref).display == "inline") { ref = ref.parentNode; } var refStyle = $_( ref ).hasAttribute("style") ? ref.getAttribute("style") : null; ref.style.height = "auto"; ref.style.maxHeight = "none"; ref.style.minHeight = "0"; var space = document.createTextNode("\u200b"); var origHeight = ref.offsetHeight; if (origHeight == 0) { throw "isCollapsedLineBreak: original height is zero, bug?"; } br.parentNode.insertBefore(space, br.nextSibling); var finalHeight = ref.offsetHeight; space.parentNode.removeChild(space); if (refStyle === null) { // Without the setAttribute() line, removeAttribute() doesn't work in // Chrome 14 dev. I have no idea why. ref.setAttribute("style", ""); ref.removeAttribute("style"); } else { ref.setAttribute("style", refStyle); } // Allow some leeway in case the zwsp didn't create a whole new line, but // only made an existing line slightly higher. Firefox 6.0a2 shows this // behavior when the first line is bold. return origHeight < finalHeight - 5; }
function isCollapsedLineBreak(br) { if (!isHtmlElement(br, "br")) { return false; } // Add a zwsp after it and see if that changes the height of the nearest // non-inline parent. Note: this is not actually reliable, because the // parent might have a fixed height or something. var ref = br.parentNode; while ($_.getComputedStyle(ref).display == "inline") { ref = ref.parentNode; } var refStyle = $_( ref ).hasAttribute("style") ? ref.getAttribute("style") : null; ref.style.height = "auto"; ref.style.maxHeight = "none"; ref.style.minHeight = "0"; var space = document.createTextNode("\u200b"); var origHeight = ref.offsetHeight; if (origHeight == 0) { throw "isCollapsedLineBreak: original height is zero, bug?"; } br.parentNode.insertBefore(space, br.nextSibling); var finalHeight = ref.offsetHeight; space.parentNode.removeChild(space); if (refStyle === null) { // Without the setAttribute() line, removeAttribute() doesn't work in // Chrome 14 dev. I have no idea why. ref.setAttribute("style", ""); ref.removeAttribute("style"); } else { ref.setAttribute("style", refStyle); } // Allow some leeway in case the zwsp didn't create a whole new line, but // only made an existing line slightly higher. Firefox 6.0a2 shows this // behavior when the first line is bold. return origHeight < finalHeight - 5; }