text
stringlengths
2
1.05M
(window.webpackJsonp=window.webpackJsonp||[]).push([[146],{2984:function(t,e,n){"use strict";n.r(e),n.d(e,"icon",(function(){return c}));n(11),n(2),n(6),n(8),n(5),n(9);var r=n(0),a=n.n(r);function o(){return(o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function i(t,e){if(null==t)return{};var n,r,a=function(t,e){if(null==t)return{};var n,r,a={},o=Object.keys(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||(a[n]=t[n]);return a}(t,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}var l=function(t){var e=t.title,n=t.titleId,r=i(t,["title","titleId"]);return a.a.createElement("svg",o({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":n},r),e?a.a.createElement("title",{id:n},e):null,a.a.createElement("path",{d:"M8.13 1.229l5.5 4.47a1 1 0 01.37.777V14a1 1 0 01-1 1H2a1 1 0 01-1-1V6.476a1 1 0 01.37-.776l5.5-4.471a1 1 0 011.26 0zM13 6.476L7.5 2.005 2 6.475V14h11V6.476z"}))},c=l;l.__docgenInfo={description:"",methods:[],displayName:"EuiIconHome"}}}]); //# sourceMappingURL=icon.home-js.min.js.map
/** * COMMON WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); module.exports = options => ({ mode: options.mode, entry: options.entry, output: Object.assign( { // Compile into js/build.js path: path.resolve(process.cwd(), 'build'), publicPath: '/', }, options.output, ), // Merge with env dependent settings optimization: options.optimization, module: { rules: [ { test: /\.jsx?$/, // Transform all .js and .jsx files required somewhere with Babel exclude: /node_modules/, use: { loader: 'babel-loader', options: options.babelQuery, }, }, { // Preprocess our own .css files // This is the place to add your own loaders (e.g. sass/less etc.) // for a list of loaders, see https://webpack.js.org/loaders/#styling test: /\.css$/, exclude: /node_modules/, use: ['style-loader', 'css-loader'], }, { // Preprocess 3rd party .css files located in node_modules test: /\.css$/, include: /node_modules/, use: ['style-loader', 'css-loader'], }, { test: /\.(eot|otf|ttf|woff|woff2)$/, use: { loader: 'file-loader', options: { publicPath: '../../app/assets/fonts/', }, }, }, { test: /\.svg$/, use: [ { loader: 'svg-url-loader', options: { // Inline files smaller than 10 kB limit: 10 * 1024, noquotes: true, }, }, ], }, { test: /\.(jpg|png|gif)$/, use: [ { loader: 'url-loader', options: { // Inline files smaller than 10 kB limit: 10 * 1024, }, }, { loader: 'image-webpack-loader', options: { mozjpeg: { enabled: false, // NOTE: mozjpeg is disabled as it causes errors in some Linux environments // Try enabling it in your environment by switching the config to: // enabled: true, // progressive: true, }, gifsicle: { interlaced: false, }, optipng: { optimizationLevel: 7, }, pngquant: { quality: '65-90', speed: 4, }, }, }, ], }, { test: /\.html$/, use: 'html-loader', }, { test: /\.(mp4|webm)$/, use: { loader: 'url-loader', options: { limit: 10000, }, }, }, ], }, plugins: options.plugins.concat([ // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV` // inside your code for any environment checks; Terser will automatically // drop any unreachable code. new webpack.EnvironmentPlugin({ NODE_ENV: 'development', }), ]), resolve: { modules: ['node_modules', 'app'], extensions: ['.js', '.jsx', '.react.js'], mainFields: ['browser', 'jsnext:main', 'main'], }, devtool: options.devtool, target: 'web', // Make web variables accessible to webpack, e.g. window performance: options.performance || {}, });
const gameTypes = { OBTAIN_GAME_DATA : "OBTAIN_GAME_DATA" } export default gameTypes
import uuid from '../src/utils/uuid'; export default (spy) => { return function (documentId, pageNumber, annotation) { spy(documentId, pageNumber, annotation); annotation.class = 'Annotation'; annotation.id = uuid(); annotation.page = pageNumber; return Promise.resolve(annotation); }; }
//@target: ES6 v; for (var v of [ 0 ]){ }
/** * Worker interfacing with the Steam GC. * Provides HTTP endpoints for other workers. * */ const Steam = require('steam'); const Dota2 = require('dota2'); const async = require('async'); const express = require('express'); const compression = require('compression'); const cp = require('child_process'); const config = require('../config'); const advancedAuth = config.ENABLE_RETRIEVER_ADVANCED_AUTH ? { /* eslint-disable global-require */ redis: require('../store/redis'), crypto: require('crypto'), /* eslint-enable global-require */ pendingTwoFactorAuth: {}, pendingSteamGuardAuth: {}, } : null; const app = express(); const steamObj = {}; const launch = new Date(); const minUpTimeSeconds = 660; const maxUpTimeSeconds = 3600; const timeoutMs = 5000; const timeoutThreshold = 50; const accountsToUse = 6; const port = config.PORT || config.RETRIEVER_PORT; const matchRequestDelay = 500; const matchRequestDelayStep = 300; const matchRequestLimit = 500; let matchRequestDelayIncr = 0; let lastRequestTime; let matchRequests = 0; let matchSuccesses = 0; let profileRequests = 0; let profileSuccesses = 0; let timeouts = 0; let allReady = false; let users = config.STEAM_USER.split(','); let passes = config.STEAM_PASS.split(','); // For the latest list: https://api.steampowered.com/ISteamDirectory/GetCMList/v1/?format=json&cellid=0 Steam.servers = [{ host: '155.133.242.9', port: 27018 }, { host: '185.25.180.15', port: 27019 }, { host: '185.25.180.15', port: 27018 }, { host: '185.25.180.14', port: 27017 }, { host: '185.25.180.15', port: 27017 }, { host: '155.133.242.9', port: 27019 }, { host: '155.133.242.9', port: 27017 }, { host: '185.25.180.14', port: 27018 }, { host: '185.25.180.14', port: 27019 }, { host: '155.133.242.8', port: 27017 }, { host: '155.133.242.8', port: 27018 }, { host: '155.133.242.8', port: 27019 }, { host: '162.254.197.40', port: 27018 }, { host: '155.133.248.50', port: 27017 }, { host: '155.133.248.51', port: 27017 }, { host: '162.254.196.68', port: 27017 }, { host: '162.254.197.41', port: 27017 }, { host: '162.254.196.67', port: 27019 }, { host: '155.133.248.53', port: 27018 }, { host: '155.133.248.52', port: 27018 }, { host: '162.254.196.67', port: 27017 }, { host: '162.254.196.67', port: 27018 }, { host: '162.254.196.83', port: 27017 }, { host: '162.254.196.84', port: 27017 }, { host: '155.133.248.52', port: 27017 }, { host: '162.254.196.68', port: 27018 }, { host: '162.254.197.40', port: 27019 }, { host: '155.133.248.51', port: 27019 }, { host: '155.133.248.52', port: 27019 }, { host: '155.133.248.53', port: 27019 }, { host: '155.133.248.50', port: 27019 }, { host: '155.133.248.53', port: 27017 }, { host: '162.254.196.68', port: 27019 }, { host: '162.254.197.42', port: 27019 }, { host: '162.254.196.84', port: 27018 }, { host: '155.133.248.50', port: 27018 }, { host: '162.254.196.83', port: 27019 }, { host: '162.254.197.42', port: 27018 }, { host: '162.254.197.41', port: 27018 }, { host: '162.254.196.84', port: 27019 }, { host: '162.254.196.83', port: 27018 }, { host: '162.254.197.40', port: 27017 }, { host: '162.254.197.41', port: 27019 }, { host: '155.133.248.51', port: 27018 }, { host: '162.254.197.42', port: 27017 }, { host: '146.66.152.11', port: 27018 }, { host: '146.66.152.11', port: 27019 }, { host: '146.66.152.11', port: 27017 }, { host: '146.66.152.10', port: 27019 }, { host: '146.66.152.10', port: 27017 }, { host: '146.66.152.10', port: 27018 }, { host: '208.78.164.10', port: 27018 }, { host: '208.78.164.9', port: 27019 }, { host: '208.78.164.13', port: 27018 }, { host: '208.78.164.9', port: 27017 }, { host: '208.78.164.12', port: 27018 }, { host: '208.78.164.10', port: 27017 }, { host: '155.133.229.251', port: 27019 }, { host: '155.133.229.251', port: 27017 }, { host: '208.78.164.14', port: 27018 }, { host: '208.78.164.12', port: 27019 }, { host: '208.78.164.13', port: 27017 }, { host: '208.78.164.9', port: 27018 }, { host: '208.78.164.14', port: 27019 }, { host: '208.78.164.11', port: 27018 }, { host: '208.78.164.10', port: 27019 }, { host: '155.133.229.250', port: 27017 }, { host: '208.78.164.12', port: 27017 }, { host: '208.78.164.11', port: 27019 }, { host: '155.133.229.250', port: 27018 }, { host: '155.133.229.251', port: 27018 }, { host: '208.78.164.11', port: 27017 }, { host: '155.133.229.250', port: 27019 }, { host: '208.78.164.13', port: 27019 }, { host: '208.78.164.14', port: 27017 }, { host: '162.254.193.7', port: 27017 }, { host: '162.254.193.47', port: 27019 }, { host: '162.254.193.7', port: 27018 }, { host: '162.254.193.46', port: 27018 }, { host: '162.254.193.6', port: 27017 }]; function selfDestruct() { process.exit(0); } function getUptime() { return (new Date() - launch) / 1000; } function genStats() { const data = { matchRequests, uptime: getUptime(), numReadyAccounts: Object.keys(steamObj).length, totalAccounts: users.length, }; return data; } function shaHash(buffer) { const h = advancedAuth.crypto.createHash('sha1'); h.update(buffer); return h.digest(); } function getSentryHashKey(user) { return Buffer.from(`retriever:sentry:${user}`); } function getMMStats(idx, cb) { steamObj[idx].Dota2.requestMatchmakingStats(); steamObj[idx].Dota2.once('matchmakingStatsData', (waitTimes, searchingPlayers, disabledGroups) => { if (disabledGroups) { cb(null, disabledGroups.legacy_searching_players_by_group_source2); } else { cb('error mmstats'); } }); } function getPlayerProfile(idx, accountId, cb) { accountId = Number(accountId); const { Dota2 } = steamObj[idx]; console.log('requesting player profile %s', accountId); profileRequests += 1; Dota2.requestProfileCard(accountId, (err, profileData) => { /* enum EStatID { k_eStat_SoloRank = 1; k_eStat_PartyRank = 2; k_eStat_Wins = 3; k_eStat_Commends = 4; k_eStat_GamesPlayed = 5; k_eStat_FirstMatchDate = 6; } */ if (err) { return cb(err); } const response = { ...profileData }; profileSuccesses += 1; profileData.slots.forEach((s) => { if (s.stat && s.stat.stat_id === 1) { response.solo_competitive_rank = s.stat.stat_score; } if (s.stat && s.stat.stat_id === 2) { response.competitive_rank = s.stat.stat_score; } }); return cb(err, response); }); } function getGcMatchData(idx, matchId, cb) { const { Dota2 } = steamObj[idx]; matchRequests += 1; const timeout = setTimeout(() => { timeouts += 1; matchRequestDelayIncr += matchRequestDelayStep; }, timeoutMs); return Dota2.requestMatchDetails(Number(matchId), (err, matchData) => { matchSuccesses += 1; // Reset delay on success matchRequestDelayIncr = 0; console.log('received match %s', matchId); clearTimeout(timeout); cb(err, matchData); }); } function init() { async.each(Array.from(new Array(users.length), (v, i) => i), (i, cb) => { const client = new Steam.SteamClient(); const user = users[i]; const pass = passes[i]; const logOnDetails = { account_name: user, password: pass, }; client.steamUser = new Steam.SteamUser(client); client.steamFriends = new Steam.SteamFriends(client); client.logOnDetails = logOnDetails; client.Dota2 = new Dota2.Dota2Client(client, false); client.Dota2.on('ready', () => { console.log('acct %s ready', i); cb(); }); client.on('connected', () => { console.log('[STEAM] Trying to log on with %s,%s', user, pass); client.steamUser.logOn(logOnDetails); }); client.on('logOnResponse', (logOnResp) => { if (advancedAuth) { delete client.logOnDetails.two_factor_code; delete client.logOnDetails.auth_code; delete advancedAuth.pendingTwoFactorAuth[user]; delete advancedAuth.pendingSteamGuardAuth[user]; const isTwoFactorAuth = logOnResp.eresult === Steam.EResult.AccountLoginDeniedNeedTwoFactor; const isSteamGuard = logOnResp.eresult === Steam.EResult.AccountLogonDenied; if (isTwoFactorAuth || isSteamGuard) { console.log('[STEAM] Account %s is protected', user); if (isTwoFactorAuth) { console.log('[STEAM] Two Factor Authentication required.'); advancedAuth.pendingTwoFactorAuth[user] = client; } else { console.log('[STEAM] SteamGuard Authentication required.'); advancedAuth.pendingSteamGuardAuth[user] = client; } return; } } if (logOnResp.eresult !== Steam.EResult.OK) { // try logging on again console.error(logOnResp); client.steamUser.logOn(logOnDetails); return; } if (client && client.steamID) { console.log('[STEAM] Logged on %s', client.steamID); client.steamFriends.setPersonaName(client.steamID.toString()); steamObj[client.steamID] = client; client.Dota2.launch(); } }); client.steamUser.on('updateMachineAuth', (machineAuth, callback) => { console.log('[STEAM] Got UpdateMachineAuth for %s', user); if (advancedAuth) { const key = getSentryHashKey(user); advancedAuth.redis.hgetall(key, (err, sentries) => { const size = machineAuth.offset + machineAuth.cubtowrite; let newSentry; if (sentries && machineAuth.filename in sentries) { newSentry = sentries[machineAuth.filename]; if (size > newSentry.size) { const temp = Buffer.alloc(size); newSentry.copy(temp); newSentry = temp; } } else { newSentry = Buffer.alloc(size); } machineAuth.bytes.copy(newSentry, machineAuth.offset, 0, machineAuth.cubtowrite); advancedAuth.redis.multi() .del(key) .hset(key, machineAuth.filename, newSentry) .exec(); const sha = shaHash(newSentry); client.logOnDetails.sha_sentryfile = sha; callback({ filename: machineAuth.filename, eresult: Steam.EResult.OK, filesize: newSentry.length, sha_file: sha, getlasterror: 0, offset: machineAuth.offset, cubwrote: machineAuth.cubtowrite, otp_type: machineAuth.otp_type, otp_identifier: machineAuth.otp_identifier, }); }); } }); client.on('error', (err) => { console.error(err); if (advancedAuth && ( user in advancedAuth.pendingTwoFactorAuth || user in advancedAuth.pendingSteamGuardAuth)) { console.log('not reconnecting %s, waiting for auth...', user); client.pendingLogOn = true; } else { // console.log('reconnecting %s', user); // client.connect(); } }); if (advancedAuth) { advancedAuth.redis.hgetall(getSentryHashKey(user), (err, sentries) => { if (sentries) { Object.keys(sentries).some((k) => { if (sentries[k] && sentries[k].length > 0) { const sha = shaHash(sentries[k]); console.log('Retrieved sentry for %s: %s', user, sha.toString('hex')); logOnDetails.sha_sentryfile = sha; return true; } return false; }); } client.connect(); }); } else { client.connect(); } /* client.on('loggedOff', () => { console.log('relogging'); setTimeout(()=> { client.steamUser.logOn(logOnDetails) }, 5000); }); */ /* setInterval(() => { if (timeouts > timeoutThreshold) { client.connect(); } }, 10000); */ }, () => { allReady = true; }); } function chooseLoginInfo() { if (config.STEAM_ACCOUNT_DATA) { const accountData = cp.execSync(`curl '${config.STEAM_ACCOUNT_DATA}'`).toString().split(/\r\n|\r|\n/g); const startIndex = Math.floor((Math.random() * (accountData.length - accountsToUse))); console.log('total registered accounts: %s, startIndex: %s', accountData.length, startIndex); const accountDataToUse = accountData.slice(startIndex, startIndex + accountsToUse); users = accountDataToUse.map(a => a.split('\t')[0]); passes = accountDataToUse.map(a => a.split('\t')[1]); } } chooseLoginInfo(); init(); app.use(compression()); app.get('/healthz', (req, res) => { res.end('ok'); }); app.use((req, res, cb) => { if (config.RETRIEVER_SECRET && config.RETRIEVER_SECRET !== req.query.key) { // reject request if it doesn't have key return cb('invalid key'); } return cb(); }); if (advancedAuth) { app.get('/auth', (req, res) => { if (req.query.account) { if (req.query.two_factor) { const client = advancedAuth.pendingTwoFactorAuth[req.query.account]; if (client && client.pendingLogOn) { client.logOnDetails.two_factor_code = req.query.two_factor; delete client.logOnDetails.sha_sentryfile; client.connect(); delete client.pendingLogOn; return res.json({ result: 'success', }); } return res.status(400).json({ error: 'account not pending a two-factor authentication', }); } if (req.query.steam_guard) { const client = advancedAuth.pendingSteamGuardAuth[req.query.account]; if (client && client.pendingLogOn) { client.logOnDetails.auth_code = req.query.steam_guard; delete client.logOnDetails.sha_sentryfile; client.connect(); delete client.pendingLogOn; return res.json({ result: 'success', }); } return res.status(400).json({ error: 'account not pending a SteamGuard authentication', }); } return res.status(400).json({ error: 'missing two_factor or steam_guard parameter', }); } return res.json({ twoFactorAuth: Object.keys(advancedAuth.pendingTwoFactorAuth), steamGuardAuth: Object.keys(advancedAuth.pendingSteamGuardAuth), }); }); } app.use((req, res, cb) => { console.log( 'numReady: %s, matches: %s/%s, profiles: %s/%s, uptime: %s, matchRequestDelay: %s', Object.keys(steamObj).length, matchSuccesses, matchRequests, profileSuccesses, profileRequests, getUptime(), matchRequestDelay + matchRequestDelayIncr, ); const shouldRestart = (matchRequests > matchRequestLimit && getUptime() > minUpTimeSeconds) || getUptime() > maxUpTimeSeconds || (!allReady && getUptime() > minUpTimeSeconds) || (timeouts > timeoutThreshold && getUptime() > minUpTimeSeconds); if (shouldRestart && config.NODE_ENV !== 'development') { return selfDestruct(); } if (!allReady) { return cb('not ready'); } return cb(); }); app.get('/', (req, res, cb) => { const keys = Object.keys(steamObj); const rKey = keys[Math.floor((Math.random() * keys.length))]; if (req.query.mmstats) { return getMMStats(rKey, (err, data) => { res.locals.data = data; return cb(err); }); } if (req.query.match_id) { // Don't allow requests coming in too fast const curRequestTime = new Date(); if (lastRequestTime && (curRequestTime - lastRequestTime < (matchRequestDelay + matchRequestDelayIncr))) { return res.status(429).json({ error: 'too many requests', }); } lastRequestTime = curRequestTime; return getGcMatchData(rKey, req.query.match_id, (err, data) => { res.locals.data = data; return cb(err); }); } if (req.query.account_id) { return getPlayerProfile(rKey, req.query.account_id, (err, data) => { res.locals.data = data; return cb(err); }); } res.locals.data = genStats(); return cb(); }); app.use((req, res) => { res.json(res.locals.data); }); app.use((err, req, res) => res.status(500).json({ error: err, })); const server = app.listen(port, () => { const host = server.address().address; console.log('[RETRIEVER] listening at http://%s:%s', host, port); });
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const { Clonable, defaultContainer } = require('@nlpjs/core'); const http = require('http'); const https = require('https'); const querystring = require('querystring'); const url = require('url'); const cultures = { bn: 'bn_BD', el: 'el_GR', en: 'en_US', hi: 'hi_IN', fa: 'fa_IR', gl: 'gl_ES', pt: 'pt_BR', sv: 'sv_SE', tl: 'tl_PH', ja: 'ja_JP', ar: 'ar_AE', hy: 'hy_AM', eu: 'eu_ES', ca: 'ca_ES', cs: 'cs_CZ', da: 'da_DK', ga: 'ga_IE', ta: 'ta_IN', uk: 'uk_UA', zh: 'zh_CN', no: 'nb_NO', }; function getCulture(locale) { const result = cultures[locale]; if (result) { return result; } return locale ? `${locale}_${locale.toUpperCase()}` : 'en_US'; } class BuiltinDuckling extends Clonable { constructor(settings = {}, container = defaultContainer) { super( { settings: {}, container: settings.container || container, }, container ); this.applySettings(this.settings, settings); if (!this.settings.tag) { this.settings.tag = `builtin-duckling`; } this.registerDefault(); this.applySettings( this.settings, this.container.getConfiguration(this.settings.tag) ); this.url = url.parse(this.settings.ducklingUrl); this.client = this.url.href.startsWith('https') ? https : http; this.port = this.url.port; if (!this.port) { this.port = this.url.href.startsWith('https') ? 443 : 80; } } registerDefault() { this.container.registerConfiguration( this.settings.tag, { ducklingUrl: process.env.DUCKLING_URL || 'http://localhost:8000/parse', }, false ); } // istanbul ignore next request(utterance, language) { return new Promise((resolve, reject) => { const postData = querystring.stringify({ text: utterance, locale: getCulture(language), }); const options = { host: this.url.hostname, port: this.port, method: 'POST', path: this.url.pathname, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length, }, }; const req = this.client.request(options, res => { let result = ''; res.on('data', chunk => { result += chunk; }); res.on('end', () => { try { const obj = JSON.parse(result); resolve(obj); } catch (err) { reject(err); } }); res.on('error', err => reject(err)); }); req.on('error', err => reject(err)); req.write(postData); req.end(); }); } transformEntity(entity) { const result = { start: entity.start, end: entity.start + entity.body.length - 1, len: entity.body.length, accuracy: 0.95, sourceText: entity.body, utteranceText: entity.body, }; if (entity.dim === 'email') { result.entity = 'email'; result.resolution = { value: entity.body, }; } else if (entity.dim === 'phone-number') { result.entity = 'phonenumber'; result.resolution = { value: entity.value.value, }; } else if (entity.dim === 'url') { result.entity = 'url'; result.resolution = { value: entity.value.value, domain: entity.value.domain, }; } else if (entity.dim === 'number' || entity.dim === 'ordinal') { result.entity = entity.dim; result.resolution = { strValue: entity.value.value.toString(), value: entity.value.value, subtype: entity.value.value % 1 === 0 ? 'integer' : 'float', }; } else if (entity.dim === 'distance') { result.entity = 'dimension'; result.resolution = { strValue: entity.value.value.toString(), value: entity.value.value, unit: entity.value.unit, subtype: 'distance', }; } else if (entity.dim === 'quantity') { result.entity = 'quantity'; result.resolution = { strValue: entity.value.value.toString(), value: entity.value.value, unit: entity.value.unit, product: entity.value.product, }; } else if (entity.dim === 'temperature') { result.entity = 'temperature'; result.resolution = { strValue: entity.value.value.toString(), value: entity.value.value, unit: entity.value.unit, }; } else if (entity.dim === 'volume') { result.entity = 'dimension'; result.resolution = { strValue: entity.value.value.toString(), value: entity.value.value, unit: entity.value.unit, subtype: 'volume', }; } else if (entity.dim === 'amount-of-money') { result.entity = 'currency'; result.resolution = { strValue: entity.value.value.toString(), value: entity.value.value, unit: entity.value.unit, }; } else if (entity.dim === 'duration') { result.entity = 'duration'; result.resolution = { strValue: entity.value.normalized.value.toString(), value: entity.value.normalized.value, unit: entity.value.normalized.unit, }; } else if (entity.dim === 'time') { result.entity = 'date'; result.resolution = { value: entity.value.value, grain: entity.value.grain, values: entity.value.values, }; } return result; } transform(entities) { return entities.map(x => this.transformEntity(x)); } async findBuiltinEntities(utterance, language) { try { const result = await this.request(utterance, language); return { edges: this.transform(result), source: result }; } catch (ex) { this.logger.error(ex); return { edges: [] }; } } async extract(srcInput) { const input = srcInput; const entities = await this.findBuiltinEntities( input.text || input.utterance, input.locale ); if (!input.edges) { input.edges = []; } if (!input.sourceEntities) { input.sourceEntities = []; } if (entities.edges) { for (let i = 0; i < entities.edges.length; i += 1) { input.edges.push(entities.edges[i]); } } if (entities.source) { for (let i = 0; i < entities.source.length; i += 1) { input.sourceEntities.push(entities.source[i]); } } return input; } run(srcInput) { const input = srcInput; const locale = input.locale || 'en'; const extractor = this.container.get(`extract-builtin-${locale}`) || this; return extractor.extract(input); } } module.exports = BuiltinDuckling;
import React from 'react'; import Viewer, { Worker } from '@phuocng/react-pdf-viewer'; import '@phuocng/react-pdf-viewer/cjs/react-pdf-viewer.css'; function PdfViewer() { return ( <div className="App"> <Worker workerUrl="https://unpkg.com/pdfjs-dist@2.5.207/build/pdf.worker.min.js"> <div id="pdfviewer"> <Viewer fileUrl="https://cors-anywhere.herokuapp.com/https://onlinejudge.org/external/1/p100.pdf" /> </div> </Worker> </div> ); } export default PdfViewer;
'use strict'; /** * Root path */ exports.index = (req, res) => { res.json('Under Development'); };
const File = require('gulp-factory').gulpUtil.File; module.exports = function(content, path) { content = content || ''; path = path || ''; return new File({ path: path, contents: new Buffer(content) }); };
import React from 'react'; import { Typography, Container, Link } from '@material-ui/core'; import preval from 'preval.macro'; import 'prismjs/themes/prism-okaidia.css'; import { makeStyles } from '@material-ui/styles'; import Demo from './Demo'; import BasicUsage from './demos/BasicUsage'; import Code from './Code'; import Heading from './Heading'; import { GITHUB_BLOB_URL } from './constants'; const SPACE = ' '; const PROPS = [ { name: 'closedBackLayerHeight', type: 'number', default_: '56', description: 'The height of the back layer when it is collapsed.', }, { name: 'openBackLayerHeight', type: 'number', default_: '300', description: 'The height of the back layer when it is expanded.', }, { name: 'frontLayer', type: 'node', default_: '', description: 'The contents of the front layer.', }, { name: 'backLayer', type: 'node', default_: '', description: 'The contents of the back layer.' }, { name: 'backLayerOpen', type: 'bool', default_: 'true', description: 'Whether or not the back layer is open.', }, { name: 'onFrontLayerUnfix', type: 'func', default_: '', description: 'Callback fired when a swipe starts.', }, { name: 'onFrontLayerFix', type: 'func', default_: '', description: 'Callback fired when a swipe and the subsequent animation ends.', }, { name: 'onBackLayerOpen', type: 'func (required)', default_: '', description: 'Callback fired when the back layer requires to be opened.', }, { name: 'onBackLayerClose', type: 'func (required)', default_: '', description: 'Callback fired when the back layer requires to be closed.', }, { name: 'classes', type: 'object', default_: '', description: 'Override or extend the styles applied to the component.', }, ]; const useStyles = makeStyles(theme => ({ demo: { marginBottom: theme.spacing(2), }, code: { marginBottom: theme.spacing(2), }, table: { overflowX: 'auto', width: '100%', display: 'block', borderSpacing: 0, borderCollapse: 'collapse', '& th,td': { color: theme.palette.text.primary, padding: theme.spacing(2), fontSize: '14px', whiteSpace: 'pre-wrap', borderBottom: '1px solid rgba(0, 0, 0, 0.12)', }, '& th': { fontWeight: 500, lineHeight: '1.5rem', }, '& td': { lineHeight: '1.43', }, }, })); function Main() { const classes = useStyles(); return ( <Container> <Heading variant="h4">Introduction</Heading> <Typography gutterBottom> Material-ish {SPACE} <Link href="https://material.io/components/backdrop/" target="_blank"> Backdrop </Link> {SPACE} react component that is swipeable. An extension to the awesome {SPACE} <Link href="https://material-ui.com" target="_blank"> Material-UI </Link> {SPACE} framework. </Typography> <Demo code={preval` module.exports = require( './preprocessors/processCode' )( './doc/demos/BasicUsage.js' ); `} demo={<BasicUsage />} githubUrl={`${GITHUB_BLOB_URL}doc/demos/BasicUsage.js`} className={classes.demo} /> <Heading variant="h4">Installing</Heading> <Code code="$ npm install material-ui-swipeable-backdrop" className={classes.code} /> <Typography gutterBottom> Also, this package depends on the following packages. You have to install them your self. </Typography> <ul> <Typography component="li"> <Link href="https://www.npmjs.com/package/@material-ui/core">@material-ui/core</Link> </Typography> <Typography component="li"> <Link href="https://www.npmjs.com/package/@material-ui/styles">@material-ui/styles</Link> </Typography> </ul> <Heading variant="h4">API</Heading> <Heading variant="h5">Backdrop</Heading> <Heading variant="h6">Props</Heading> <table className={classes.table}> <thead> <tr> <th align="left">Name</th> <th align="left">Type</th> <th align="left">Default</th> <th align="left">Description</th> </tr> </thead> <tbody> {PROPS.map(({ name, type, default_, description }) => ( <tr> <td> <code>{name}</code> </td> <td> <code>{type}</code> </td> <td> <code>{default_}</code> </td> <td>{description}</td> </tr> ))} </tbody> </table> <Heading variant="h4">Why Material&quot;ish&quot;?</Heading> <Typography gutterBottom> This component is not strictly compliant with the Material Design specification because the {SPACE} spec explicitly requires backdrops not to be swipeable. Although my assumption is that {SPACE} backdrops being swipeable won&apos;t confuse users in most cases, it&apos; up to you whether {SPACE} to stick to the spec or deviate a little bit from it <span role="img" aria-label="emoji"> 😉 </span> . </Typography> </Container> ); } Main.defaultProps = {}; Main.propTypes = {}; export default Main;
/** * @license AngularJS v1.3.10 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function (window, angular, undefined) { 'use strict'; var $sanitizeMinErr = angular.$$minErr('$sanitize'); /** * @ngdoc module * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ /** * @ngdoc service * @name $sanitize * @kind function * * @description * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. The input may also contain SVG markup. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. * * @param {string} html HTML input. * @returns {string} Sanitized HTML. * * @example <example module="sanitizeExample" deps="angular-sanitize.js"> <file name="index.html"> <script> angular.module('sanitizeExample', ['ngSanitize']) .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </file> <file name="protractor.js" type="protractor"> it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getInnerHtml()). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('new <b>text</b>'); expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( 'new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </file> </example> */ function $SanitizeProvider() { this.$get = ['$$sanitizeUri', function ($$sanitizeUri) { return function (html) { if (typeof arguments[1] != 'undefined') { arguments[1].version = 'taSanitize'; } var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function (uri, isImage) { return !/^unsafe/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, angular.noop); writer.chars(chars); return buf.join(''); } // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/, END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\//, COMMENT_REGEXP = /<!--(.*?)-->/g, SINGLE_COMMENT_REGEXP = /(^<!--.*?-->)/, DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g, WHITE_SPACE_REGEXP = /^(\s+)/; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr,input"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); // SVG Elements // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," + "desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," + "line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," + "stop,svg,switch,text,title,tspan,use"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements, svgElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href"); var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'id,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,target,title,type,' + 'valign,value,vspace,width'); // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' + 'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' + 'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' + 'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' + 'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' + 'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' + 'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' + 'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' + 'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' + 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' + 'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' + 'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' + 'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' + 'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' + 'zoomAndPan'); var validAttrs = angular.extend({}, uriAttrs, svgAttrs, htmlAttrs); function makeMap(str) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) obj[items[i]] = true; return obj; } /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser(html, handler) { if (typeof html !== 'string') { if (html === null || typeof html === 'undefined') { html = ''; } else { html = '' + html; } } var index, chars, match, stack = [], last = html, text; stack.last = function () { return stack[stack.length - 1]; }; while (html) { text = ''; chars = true; // Make sure we're not in a script or style element if (!stack.last() || !specialElements[stack.last()]) { // White space if (WHITE_SPACE_REGEXP.test(html)) { match = html.match(WHITE_SPACE_REGEXP); if (match) { var mat = match[0]; if (handler.whitespace) handler.whitespace(match[0]); html = html.replace(match[0], ''); chars = false; } //Comment } else if (SINGLE_COMMENT_REGEXP.test(html)) { match = html.match(SINGLE_COMMENT_REGEXP); if (match) { if (handler.comment) handler.comment(match[1]); html = html.replace(match[0], ''); chars = false; } // DOCTYPE } else if (DOCTYPE_REGEXP.test(html)) { match = html.match(DOCTYPE_REGEXP); if (match) { html = html.replace(match[0], ''); chars = false; } // end tag } else if (BEGING_END_TAGE_REGEXP.test(html)) { match = html.match(END_TAG_REGEXP); if (match) { html = html.substring(match[0].length); match[0].replace(END_TAG_REGEXP, parseEndTag); chars = false; } // start tag } else if (BEGIN_TAG_REGEXP.test(html)) { match = html.match(START_TAG_REGEXP); if (match) { // We only have a valid start-tag if there is a '>'. if (match[4]) { html = html.substring(match[0].length); match[0].replace(START_TAG_REGEXP, parseStartTag); } chars = false; } else { // no ending tag found --- this piece should be encoded as an entity. text += '<'; html = html.substring(1); } } if (chars) { index = html.indexOf("<"); text += index < 0 ? html : html.substring(0, index); html = index < 0 ? "" : html.substring(index); if (handler.chars) handler.chars(decodeEntities(text)); } } else { html = html.replace(new RegExp("([^]*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function (all, text) { text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars(decodeEntities(text)); return ""; }); parseEndTag("", stack.last()); } if (html == last) { throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + "of html: {0}", html); } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag(tag, tagName, rest, unary) { tagName = angular.lowercase(tagName); if (blockElements[tagName]) { while (stack.last() && inlineElements[stack.last()]) { parseEndTag("", stack.last()); } } if (optionalEndTagElements[tagName] && stack.last() == tagName) { parseEndTag("", tagName); } unary = voidElements[tagName] || !!unary; if (!unary) stack.push(tagName); var attrs = {}; rest.replace(ATTR_REGEXP, function (match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { var value = doubleQuotedValue || singleQuotedValue || unquotedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start(tagName, attrs, unary); } function parseEndTag(tag, tagName) { var pos = 0, i; tagName = angular.lowercase(tagName); if (tagName) // Find the closest opened tag of the same type for (pos = stack.length - 1; pos >= 0; pos--) if (stack[pos] == tagName) break; if (pos >= 0) { // Close all the open elements, up the stack for (i = stack.length - 1; i >= pos; i--) if (handler.end) handler.end(stack[i]); // Remove the open elements from the stack stack.length = pos; } } } var hiddenPre = document.createElement("pre"); var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ function decodeEntities(value) { if (!value) { return ''; } // Note: IE8 does not preserve spaces at the start/end of innerHTML // so we must capture them and reattach them afterward var parts = spaceRe.exec(value); var spaceBefore = parts[1]; var spaceAfter = parts[3]; var content = parts[2]; if (content) { hiddenPre.innerHTML = content.replace(/</g, "&lt;"); // innerText depends on styling as it doesn't display hidden elements. // Therefore, it's better to use textContent not to cause unnecessary // reflows. However, IE<9 don't support textContent so the innerText // fallback is necessary. content = 'textContent' in hiddenPre ? hiddenPre.textContent : hiddenPre.innerText; } return spaceBefore + content + spaceAfter; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value.replace(/&/g, '&amp;').replace(SURROGATE_PAIR_REGEXP, function (value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }).replace(NON_ALPHANUMERIC_REGEXP, function (value) { // unsafe chars are: \u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff from jslint.com/lint.html // decimal values are: 0-31, 127-159, 173, 1536-1540, 1807, 6068, 6069, 8204-8207, 8232-8239, 8288-8303, 65279, 65520-65535 var c = value.charCodeAt(0); // if unsafe character encode if (c <= 159 || c == 173 || (c >= 1536 && c <= 1540) || c == 1807 || c == 6068 || c == 6069 || (c >= 8204 && c <= 8207) || (c >= 8232 && c <= 8239) || (c >= 8288 && c <= 8303) || c == 65279 || (c >= 65520 && c <= 65535)) return '&#' + c + ';'; return value; // avoids multilingual issues }).replace(/</g, '&lt;').replace(/>/g, '&gt;'); } var trim = (function () { // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn't have it... :-( // TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function (value) { return angular.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; }; } return function (value) { return angular.isString(value) ? value.trim() : value; }; })(); // Custom logic for accepting certain style options only - textAngular // Currently allows only the color, background-color, text-align, float, width and height attributes // all other attributes should be easily done through classes. function validStyles(styleAttr) { var result = ''; var styleArray = styleAttr.split(';'); angular.forEach(styleArray, function (value) { var v = value.split(':'); if (v.length == 2) { var key = trim(angular.lowercase(v[0])); var value = trim(angular.lowercase(v[1])); if ( (key === 'color' || key === 'background-color') && ( value.match(/^rgb\([0-9%,\. ]*\)$/i) || value.match(/^rgba\([0-9%,\. ]*\)$/i) || value.match(/^hsl\([0-9%,\. ]*\)$/i) || value.match(/^hsla\([0-9%,\. ]*\)$/i) || value.match(/^#[0-9a-f]{3,6}$/i) || value.match(/^[a-z]*$/i) ) || key === 'text-align' && ( value === 'left' || value === 'right' || value === 'center' || value === 'justify' ) || key === 'text-decoration' && ( value === 'underline' || value === 'line-through' ) || key === 'font-weight' && ( value === 'bold' ) || key === 'font-style' && ( value === 'italic' ) || key === 'float' && ( value === 'left' || value === 'right' || value === 'none' ) || key === 'vertical-align' && ( value === 'baseline' || value === 'sub' || value === 'super' || value === 'test-top' || value === 'text-bottom' || value === 'middle' || value === 'top' || value === 'bottom' || value.match(/[0-9]*(px|em)/) || value.match(/[0-9]+?%/) ) || key === 'font-size' && ( value === 'xx-small' || value === 'x-small' || value === 'small' || value === 'medium' || value === 'large' || value === 'x-large' || value === 'xx-large' || value === 'larger' || value === 'smaller' || value.match(/[0-9]*\.?[0-9]*(px|em|rem|mm|q|cm|in|pt|pc|%)/) ) || (key === 'width' || key === 'height') && ( value.match(/[0-9\.]*(px|em|rem|%)/) ) || // Reference #520 (key === 'direction' && value.match(/^ltr|rtl|initial|inherit$/)) ) result += key + ': ' + value + ';'; } }); return result; } // this function is used to manually allow specific attributes on specific tags with certain prerequisites function validCustomTag(tag, attrs, lkey, value) { // catch the div placeholder for the iframe replacement if (tag === 'img' && attrs['ta-insert-video']) { if (lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditable' && value === 'false')) return true; } return false; } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf, uriValidator) { var ignore = false; var out = angular.bind(buf, buf.push); return { start: function (tag, attrs, unary) { tag = angular.lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] === true) { out('<'); out(tag); angular.forEach(attrs, function (value, key) { var lkey = angular.lowercase(key); var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); if ((lkey === 'style' && (value = validStyles(value)) !== '') || validCustomTag(tag, attrs, lkey, value) || validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, comment: function (com) { out(com); }, whitespace: function (ws) { out(encodeEntities(ws)); }, end: function (tag) { tag = angular.lowercase(tag); if (!ignore && validElements[tag] === true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function (chars) { if (!ignore) { out(encodeEntities(chars)); } } }; } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); /* global sanitizeText: false */ /** * @ngdoc filter * @name linky * @kind function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. * @returns {string} Html-linkified text. * * @usage <span ng-bind-html="linky_expression | linky"></span> * * @example <example module="linkyExample" deps="angular-sanitize.js"> <file name="index.html"> <script> angular.module('linkyExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.snippet = 'Pretty text with some links:\n'+ 'http://angularjs.org/,\n'+ 'mailto:us@somewhere.org,\n'+ 'another@somewhere.org,\n'+ 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithTarget = 'http://angularjs.org/'; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="linky-target"> <td>linky target</td> <td> <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </file> <file name="protractor.js" type="protractor"> it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('new http://link.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); </file> </example> */ angular.module('ngSanitize').filter('linky', ['$sanitize', function ($sanitize) { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/, MAILTO_REGEXP = /^mailto:/; return function (text, target) { if (!text) return text; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/www/mailto then assume mailto if (!match[2] && !match[4]) { url = (match[3] ? 'http://' : 'mailto:') + url; } i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { html.push('<a '); if (angular.isDefined(target)) { html.push('target="', target, '" '); } html.push('href="', url.replace(/"/g, '&quot;'), '">'); addText(text); html.push('</a>'); } }; }]); })(window, window.angular);
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Because AdSense and DoubleClick are both operated by Google and their A4A // implementations share some behavior in common, part of the logic for this // implementation is located in the ads/google/a4a directory rather than here. // Most other ad networks will want to put their A4A code entirely in the // extensions/amp-ad-network-${NETWORK_NAME}-impl directory. import {AdsenseSharedState} from './adsense-shared-state'; import {AmpA4A} from '../../amp-a4a/0.1/amp-a4a'; import {CONSENT_POLICY_STATE} from '../../../src/consent-state'; import {FIE_CSS_CLEANUP_EXP} from '../../../src/friendly-iframe-embed'; import {Navigation} from '../../../src/service/navigation'; import { QQID_HEADER, SANDBOX_HEADER, ValidAdContainerTypes, addCsiSignalsToAmpAnalyticsConfig, additionalDimensions, extractAmpAnalyticsConfig, getCsiAmpAnalyticsConfig, getCsiAmpAnalyticsVariables, getEnclosingContainerTypes, getIdentityToken, googleAdUrl, isCdnProxy, isReportingEnabled, maybeAppendErrorParameter, } from '../../../ads/google/a4a/utils'; import {ResponsiveState} from './responsive-state'; import {Services} from '../../../src/services'; import { addExperimentIdToElement, isInManualExperiment, } from '../../../ads/google/a4a/traffic-experiments'; import {computedStyle, setStyles} from '../../../src/style'; import {dev, devAssert, user} from '../../../src/log'; import {domFingerprintPlain} from '../../../src/utils/dom-fingerprint'; import {getAmpAdRenderOutsideViewport} from '../../amp-ad/0.1/concurrent-load'; import {getData} from '../../../src/event-helper'; import {getDefaultBootstrapBaseUrl} from '../../../src/3p-frame'; import { getExperimentBranch, randomlySelectUnsetExperiments, } from '../../../src/experiments'; import {getMode} from '../../../src/mode'; import {insertAnalyticsElement} from '../../../src/extension-analytics'; import {removeElement} from '../../../src/dom'; import {stringHash32} from '../../../src/string'; import {utf8Decode} from '../../../src/utils/bytes'; /** @const {string} */ const ADSENSE_BASE_URL = 'https://googleads.g.doubleclick.net/pagead/ads'; /** @const {string} */ const TAG = 'amp-ad-network-adsense-impl'; /** * Shared state for AdSense ad slots. This is used primarily for ad request url * parameters that depend on previous slots. * @const {!AdsenseSharedState} */ const sharedState = new AdsenseSharedState(); /** @visibleForTesting */ export function resetSharedState() { sharedState.reset(); } /** @type {string} */ const FORMAT_EXP = 'as-use-attr-for-format'; /** @final */ export class AmpAdNetworkAdsenseImpl extends AmpA4A { /** * @param {!Element} element */ constructor(element) { super(element); /** * A unique identifier for this slot. * Not initialized until getAdUrl() is called; updated upon each invocation * of getAdUrl(). * @private {?string} */ this.uniqueSlotId_ = null; /** * Config to generate amp-analytics element for active view reporting. * @type {?JsonObject} * @private */ this.ampAnalyticsConfig_ = null; /** @private {!../../../src/service/extensions-impl.Extensions} */ this.extensions_ = Services.extensionsFor(this.win); /** @private {?({width, height}|../../../src/layout-rect.LayoutRectDef)} */ this.size_ = null; /** * amp-analytics element generated based on this.ampAnalyticsConfig_ * @private {?Element} */ this.ampAnalyticsElement_ = null; /** @private {?string} */ this.qqid_ = null; /** @private {?ResponsiveState}. */ this.responsiveState_ = ResponsiveState.createIfResponsive(element); /** @private {?Promise<!../../../ads/google/a4a/utils.IdentityToken>} */ this.identityTokenPromise_ = null; /** * @private {?boolean} whether preferential rendered AMP creative, null * indicates no creative render. */ this.isAmpCreative_ = null; /** @private {number} slot index specific to google inventory */ this.ifi_ = 0; /** * Whether or not the iframe containing the ad should be sandboxed via the * "sandbox" attribute. * @private {boolean} */ this.shouldSandbox_ = false; } /** @override */ isValidElement() { /** * isValidElement used to also check that we are in a valid A4A environment, * however this is not necessary as that is checked by adsenseIsA4AEnabled, * which is always called as part of the upgrade path from an amp-ad element * to an amp-ad-adsense element. Thus, if we are an amp-ad, we can be sure * that it has been verified. */ if ( this.responsiveState_ != null && !this.responsiveState_.isValidElement() ) { return false; } if (!this.element.getAttribute('data-ad-client')) { return false; } return this.isAmpAdElement(); } /** @override */ delayAdRequestEnabled() { return getAmpAdRenderOutsideViewport(this.element) || 3; } /** @override @return {!Promise|undefined}. */ buildCallback() { super.buildCallback(); this.identityTokenPromise_ = this.getAmpDoc() .whenFirstVisible() .then(() => getIdentityToken(this.win, this.getAmpDoc(), super.getConsentPolicy()) ); return ResponsiveState.maybeUpgradeToResponsive( this.element, this.getAdClientId_() ).then(state => { if (state != null) { this.responsiveState_ = state; } if (this.responsiveState_ != null) { return this.responsiveState_.attemptChangeSize(); } // This should happen last, as some diversion criteria rely on some of the // preceding logic (specifically responsive logic). this.divertExperiments(); this.maybeAddSinglePassExperiment(); }); } /** @override */ getConsentPolicy() { // Ensure that build is not blocked by need for consent (delay will occur // prior to ad URL construction). return null; } /** * Selects into experiments based on url fragment and/or page level diversion. * @visibleForTesting */ divertExperiments() { const experimentInfoMap = /** @type {!Object<string, !../../../src/experiments.ExperimentInfo>} */ ({ [FORMAT_EXP]: { isTrafficEligible: () => !this.responsiveState_ && Number(this.element.getAttribute('width')) > 0 && Number(this.element.getAttribute('height')) > 0, branches: ['21062003', '21062004'], }, [[FIE_CSS_CLEANUP_EXP.branch]]: { isTrafficEligible: () => true, branches: [ [FIE_CSS_CLEANUP_EXP.control], [FIE_CSS_CLEANUP_EXP.experiment], ], }, }); const setExps = randomlySelectUnsetExperiments(this.win, experimentInfoMap); Object.keys(setExps).forEach(expName => addExperimentIdToElement(setExps[expName], this.element) ); } /** * @return {string} ad client ID for the current ad unit. * @private */ getAdClientId_() { const adClientId = ( this.element.getAttribute('data-ad-client') || '' ).toLowerCase(); if (!/^ca-/i.test(adClientId)) { return `ca-${adClientId}`; } return adClientId; } /** @override */ getAdUrl(consentState) { if ( consentState == CONSENT_POLICY_STATE.UNKNOWN && this.element.getAttribute('data-npa-on-unknown-consent') != 'true' ) { user().info(TAG, 'Ad request suppressed due to unknown consent'); return Promise.resolve(''); } // TODO: Check for required and allowed parameters. Probably use // validateData, from 3p/3p/js, after moving it someplace common. const startTime = Date.now(); const global = this.win; const adClientId = this.getAdClientId_(); const adTestOn = this.element.getAttribute('data-adtest') || isInManualExperiment(this.element); const width = Number(this.element.getAttribute('width')); const height = Number(this.element.getAttribute('height')); this.size_ = getExperimentBranch(this.win, FORMAT_EXP) == '21062004' ? {width, height} : this.getIntersectionElementLayoutBox(); const sizeToSend = this.isSinglePageStoryAd ? {width: 1, height: 1} : this.size_; const format = `${sizeToSend.width}x${sizeToSend.height}`; const slotId = this.element.getAttribute('data-amp-slot-index'); // data-amp-slot-index is set by the upgradeCallback method of amp-ad. // TODO(bcassels): Uncomment the assertion, fixing the tests. // But not all tests arrange to call upgradeCallback. // devAssert(slotId != undefined); const adk = this.adKey_(format); this.uniqueSlotId_ = slotId + adk; const slotname = this.element.getAttribute('data-ad-slot'); const sharedStateParams = sharedState.addNewSlot( format, this.uniqueSlotId_, adClientId, slotname ); const viewportSize = this.getViewport().getSize(); if (!this.ifi_) { this.win['ampAdGoogleIfiCounter'] = this.win['ampAdGoogleIfiCounter'] || 1; this.ifi_ = this.win['ampAdGoogleIfiCounter']++; } const enclosingContainers = getEnclosingContainerTypes(this.element); const pfx = enclosingContainers.includes( ValidAdContainerTypes['AMP-FX-FLYING-CARPET'] ) || enclosingContainers.includes(ValidAdContainerTypes['AMP-STICKY-AD']); const parameters = { 'client': adClientId, 'format': format, 'w': sizeToSend.width, 'h': sizeToSend.height, 'iu': slotname, 'npa': consentState == CONSENT_POLICY_STATE.INSUFFICIENT || consentState == CONSENT_POLICY_STATE.UNKNOWN ? 1 : null, 'adtest': adTestOn ? 'on' : null, 'adk': adk, 'output': 'html', 'bc': global.SVGElement && global.document.createElementNS ? '1' : null, 'ctypes': this.getCtypes_(), 'host': this.element.getAttribute('data-ad-host'), 'hl': this.element.getAttribute('data-language'), 'to': this.element.getAttribute('data-tag-origin'), 'pv': sharedStateParams.pv, 'channel': this.element.getAttribute('data-ad-channel'), 'wgl': global['WebGLRenderingContext'] ? '1' : '0', 'asnt': this.sentinel, 'dff': computedStyle(this.win, this.element)['font-family'], 'prev_fmts': sharedStateParams.prevFmts || null, 'prev_slotnames': sharedStateParams.prevSlotnames || null, 'brdim': additionalDimensions(this.win, viewportSize), 'ifi': this.ifi_, 'rc': this.fromResumeCallback ? 1 : null, 'rafmt': this.responsiveState_ != null ? this.responsiveState_.getRafmtParam() : null, 'pfx': pfx ? '1' : '0', 'aanf': /^(true|false)$/i.test(this.element.getAttribute('data-no-fill')) ? this.element.getAttribute('data-no-fill') : null, // Matched content specific fields. 'crui': this.element.getAttribute('data-matched-content-ui-type'), 'cr_row': this.element.getAttribute('data-matched-content-rows-num'), 'cr_col': this.element.getAttribute('data-matched-content-columns-num'), // Package code (also known as URL group) that was used to // create ad. 'pwprc': this.element.getAttribute('data-package'), 'spsa': this.isSinglePageStoryAd ? `${viewportSize.width}x${viewportSize.height}` : null, }; const experimentIds = []; const identityPromise = Services.timerFor(this.win) .timeoutPromise(1000, this.identityTokenPromise_) .catch(unusedErr => { // On error/timeout, proceed. return /**@type {!../../../ads/google/a4a/utils.IdentityToken}*/ ({}); }); return identityPromise.then(identity => { return googleAdUrl( this, ADSENSE_BASE_URL, startTime, Object.assign( { 'adsid': identity.token || null, 'jar': identity.jar || null, 'pucrd': identity.pucrd || null, }, parameters ), experimentIds ); }); } /** @override */ onNetworkFailure(error, adUrl) { dev().info(TAG, 'network error, attempt adding of error parameter', error); return {adUrl: maybeAppendErrorParameter(adUrl, 'n')}; } /** @override */ maybeValidateAmpCreative(bytes, headers) { if (headers.get('AMP-Verification-Checksum-Algorithm') !== 'djb2a-32') { return super.maybeValidateAmpCreative(bytes, headers); } const checksum = headers.get('AMP-Verification-Checksum'); return Promise.resolve( checksum && stringHash32(utf8Decode(bytes)) == checksum ? bytes : null ); } /** @override */ extractSize(responseHeaders) { this.ampAnalyticsConfig_ = extractAmpAnalyticsConfig(this, responseHeaders); this.qqid_ = responseHeaders.get(QQID_HEADER); this.shouldSandbox_ = responseHeaders.get(SANDBOX_HEADER) == 'true'; if (this.ampAnalyticsConfig_) { // Load amp-analytics extensions this.extensions_./*OK*/ installExtensionForDoc( this.getAmpDoc(), 'amp-analytics' ); } return this.size_; } /** * @param {string} format * @return {string} The ad unit hash key string. * @private */ adKey_(format) { const {element} = this; const slot = element.getAttribute('data-ad-slot') || ''; const string = `${slot}:${format}:${domFingerprintPlain(element)}`; return stringHash32(string); } /** * @return {?string} * @private */ getCtypes_() { if (!getMode().localDev) { return null; } const ctypesReMatch = /[?&]force_a4a_ctypes=([^&]+)/.exec( this.win.location.search ); // If the RE passes, then length is necessarily > 1. if (ctypesReMatch) { return ctypesReMatch[1]; } return null; } /** @override */ isXhrAllowed() { return isCdnProxy(this.win); } /** @override */ sandboxHTMLCreativeFrame() { return this.shouldSandbox_; } /** @override */ onCreativeRender(creativeMetaData) { super.onCreativeRender(creativeMetaData); if (this.iframe != null) { ResponsiveState.maybeAttachSettingsListener( this.element, this.iframe, this.getAdClientId_() ); } this.isAmpCreative_ = !!creativeMetaData; if ( creativeMetaData && !creativeMetaData.customElementExtensions.includes('amp-ad-exit') ) { // Capture phase click handlers on the ad if amp-ad-exit not present // (assume it will handle capture). devAssert(this.iframe); Navigation.installAnchorClickInterceptor( this.getAmpDoc(), devAssert(this.iframe.contentWindow) ); } if (this.ampAnalyticsConfig_) { devAssert(!this.ampAnalyticsElement_); if (isReportingEnabled(this)) { addCsiSignalsToAmpAnalyticsConfig( this.win, this.element, this.ampAnalyticsConfig_, this.qqid_, !!creativeMetaData ); } this.ampAnalyticsElement_ = insertAnalyticsElement( this.element, this.ampAnalyticsConfig_, /*loadAnalytics*/ true, !!this.postAdResponseExperimentFeatures['avr_disable_immediate'] ); } setStyles(dev().assertElement(this.iframe), { width: `${this.size_.width}px`, height: `${this.size_.height}px`, }); if (this.qqid_) { this.element.setAttribute('data-google-query-id', this.qqid_); } dev().assertElement(this.iframe).id = `google_ads_iframe_${this.ifi_}`; } /** @override */ unlayoutCallback() { if (this.isAmpCreative_) { // Allow AMP creatives to remain in case SERP viewer swipe back. return false; } const superResult = super.unlayoutCallback(); this.element.setAttribute( 'data-amp-slot-index', this.win.ampAdSlotIdCounter++ ); if (this.uniqueSlotId_) { sharedState.removeSlot(this.uniqueSlotId_); } if (this.ampAnalyticsElement_) { removeElement(this.ampAnalyticsElement_); this.ampAnalyticsElement_ = null; } this.ampAnalyticsConfig_ = null; this.qqid_ = null; this.isAmpCreative_ = null; this.shouldSandbox_ = false; return superResult; } /** @override */ onLayoutMeasure() { super.onLayoutMeasure(); this.responsiveState_ && this.responsiveState_.alignToViewport(); } /** @override */ getPreconnectUrls() { this.preconnect.preload(getDefaultBootstrapBaseUrl(this.win, 'nameframe')); return ['https://googleads.g.doubleclick.net']; } /** @override */ getA4aAnalyticsVars(analyticsTrigger) { return getCsiAmpAnalyticsVariables(analyticsTrigger, this, this.qqid_); } /** @override */ getA4aAnalyticsConfig() { return getCsiAmpAnalyticsConfig(); } /** @override */ letCreativeTriggerRenderStart() { if ( this.element && this.element.parentElement && this.element.parentElement.tagName == 'AMP-STICKY-AD' ) { const stickyMsgListener = event => { if ( getData(event) == 'fill_sticky' && event['source'] == this.iframe.contentWindow ) { this.renderStarted(); this.iframe.setAttribute('visible', ''); this.win.removeEventListener('message', stickyMsgListener); } }; this.win.addEventListener('message', stickyMsgListener); return true; } return false; } } AMP.extension(TAG, '0.1', AMP => { AMP.registerElement(TAG, AmpAdNetworkAdsenseImpl); });
describe('Iframe Builder', function () { it('should build', function () { const iframe = createDocElement('iframe'); iframe.src = "#example"; new BuilderTest(new IframeBuilder("#example")).toEqualNode(iframe); }) it('should build using all methods', function () { const iframe = createDocElement('iframe'); iframe.src = "#example"; iframe.allow = 'autoplay camera magnetometer'; iframe.referrerPolicy = 'no-referrer'; iframe.sandbox = 'allow-downloads allow-modals allow-popups'; new BuilderTest( new IframeBuilder("#example") .allow('autoplay camera magnetometer') .referrerPolicy('no-referrer') .sandbox('allow-downloads allow-modals allow-popups') ).toEqualNode(iframe); }) })
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['da']={"editor":"Rich Text Editor","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"Tryk ALT 0 for hjælp","browseServer":"Gennemse...","url":"URL","protocol":"Protokol","upload":"Upload","uploadSubmit":"Upload","image":"Indsæt billede","flash":"Indsæt Flash","form":"Indsæt formular","checkbox":"Indsæt afkrydsningsfelt","radio":"Indsæt alternativknap","textField":"Indsæt tekstfelt","textarea":"Indsæt tekstboks","hiddenField":"Indsæt skjult felt","button":"Indsæt knap","select":"Indsæt liste","imageButton":"Indsæt billedknap","notSet":"<intet valgt>","id":"Id","name":"Navn","langDir":"Tekstretning","langDirLtr":"Fra venstre mod højre (LTR)","langDirRtl":"Fra højre mod venstre (RTL)","langCode":"Sprogkode","longDescr":"Udvidet beskrivelse","cssClass":"Typografiark (CSS)","advisoryTitle":"Titel","cssStyle":"Typografi (CSS)","ok":"OK","cancel":"Annullér","close":"Luk","preview":"Forhåndsvisning","resize":"Træk for at skalere","generalTab":"Generelt","advancedTab":"Avanceret","validateNumberFailed":"Værdien er ikke et tal.","confirmNewPage":"Alt indhold, der ikke er blevet gemt, vil gå tabt. Er du sikker på, at du vil indlæse en ny side?","confirmCancel":"Nogle af indstillingerne er blevet ændret. Er du sikker på, at du vil lukke vinduet?","options":"Vis muligheder","target":"Mål","targetNew":"Nyt vindue (_blank)","targetTop":"Øverste vindue (_top)","targetSelf":"Samme vindue (_self)","targetParent":"Samme vindue (_parent)","langDirLTR":"Venstre til højre (LTR)","langDirRTL":"Højre til venstre (RTL)","styles":"Style","cssClasses":"Stylesheetklasser","width":"Bredde","height":"Højde","align":"Justering","alignLeft":"Venstre","alignRight":"Højre","alignCenter":"Centreret","alignJustify":"Lige margener","alignTop":"Øverst","alignMiddle":"Centreret","alignBottom":"Nederst","alignNone":"Ingen","invalidValue":"Ugyldig værdi.","invalidHeight":"Højde skal være et tal.","invalidWidth":"Bredde skal være et tal.","invalidCssLength":"Værdien specificeret for \"%1\" feltet skal være et positivt nummer med eller uden en CSS måleenhed (px, %, in, cm, mm, em, ex, pt, eller pc).","invalidHtmlLength":"Værdien specificeret for \"%1\" feltet skal være et positivt nummer med eller uden en CSS måleenhed (px eller %).","invalidInlineStyle":"Værdien specificeret for inline style skal indeholde en eller flere elementer med et format som \"name:value\", separeret af semikoloner","cssLengthTooltip":"Indsæt en numerisk værdi i pixel eller nummer med en gyldig CSS værdi (px, %, in, cm, mm, em, ex, pt, eller pc).","unavailable":"%1<span class=\"cke_accessibility\">, ikke tilgængelig</span>","keyboard":{"8":"Backspace","13":"Retur","16":"Shift","17":"Ctrl","18":"Alt","32":"Mellemrum","35":"End","36":"Home","46":"Slet","224":"Command"},"keyboardShortcut":"Tastatur genvej"},"about":{"copy":"Copyright &copy; $1. Alle rettigheder forbeholdes.","dlgTitle":"Om CKEditor","help":"Se $1 for at få hjælp.","moreInfo":"For informationer omkring licens, se venligst vores hjemmeside (på engelsk):","title":"Om CKEditor","userGuide":"CKEditor-brugermanual"},"clipboard":{"copy":"Kopiér","copyError":"Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Brug i stedet tastaturet til at kopiere teksten (Ctrl/Cmd+C).","cut":"Klip","cutError":"Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Brug i stedet tastaturet til at klippe teksten (Ctrl/Cmd+X).","paste":"Indsæt","pasteArea":"Indsæt område","pasteMsg":"Indsæt i feltet herunder (<STRONG>Ctrl/Cmd+V</STRONG>) og klik på <STRONG>OK</STRONG>.","securityMsg":"Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Du skal indsætte udklipsholderens indhold i dette vindue igen.","title":"Indsæt"},"base64image":{"alt":"Alternativ tekst","lockRatio":"Lås størrelsesforhold","vSpace":"Lodret margen","hSpace":"Vandret margen","border":"Ramme"},"basicstyles":{"bold":"Fed","italic":"Kursiv","strike":"Gennemstreget","subscript":"Sænket skrift","superscript":"Hævet skrift","underline":"Understreget"},"bidi":{"ltr":"Tekstretning fra venstre til højre","rtl":"Tekstretning fra højre til venstre"},"blockquote":{"toolbar":"Blokcitat"},"button":{"selectedLabel":"%1 (Valgt)"},"colorbutton":{"auto":"Automatisk","bgColorTitle":"Baggrundsfarve","colors":{"000":"Sort","800000":"Mørkerød","8B4513":"Mørk orange","2F4F4F":"Dark Slate Grå","008080":"Teal","000080":"Navy","4B0082":"Indigo","696969":"Mørkegrå","B22222":"Scarlet / Rød","A52A2A":"Brun","DAA520":"Guld","006400":"Mørkegrøn","40E0D0":"Tyrkis","0000CD":"Mellemblå","800080":"Lilla","808080":"Grå","F00":"Rød","FF8C00":"Mørk orange","FFD700":"Guld","008000":"Grøn","0FF":"Cyan","00F":"Blå","EE82EE":"Violet","A9A9A9":"Matgrå","FFA07A":"Laksefarve","FFA500":"Orange","FFFF00":"Gul","00FF00":"Lime","AFEEEE":"Mat tyrkis","ADD8E6":"Lyseblå","DDA0DD":"Plum","D3D3D3":"Lysegrå","FFF0F5":"Lavender Blush","FAEBD7":"Antikhvid","FFFFE0":"Lysegul","F0FFF0":"Gul / Beige","F0FFFF":"Himmeblå","F0F8FF":"Alice blue","E6E6FA":"Lavendel","FFF":"Hvid","1ABC9C":"Strong Cyan","2ECC71":"Emerald","3498DB":"Bright Blue","9B59B6":"Amethyst","4E5F70":"Grayish Blue","F1C40F":"Vivid Yellow","16A085":"Dark Cyan","27AE60":"Dark Emerald","2980B9":"Strong Blue","8E44AD":"Dark Violet","2C3E50":"Desaturated Blue","F39C12":"Orange","E67E22":"Carrot","E74C3C":"Pale Red","ECF0F1":"Bright Silver","95A5A6":"Light Grayish Cyan","DDD":"Light Gray","D35400":"Pumpkin","C0392B":"Strong Red","BDC3C7":"Silver","7F8C8D":"Grayish Cyan","999":"Dark Gray"},"more":"Flere farver...","panelTitle":"Farver","textColorTitle":"Tekstfarve"},"font":{"fontSize":{"label":"Skriftstørrelse","voiceLabel":"Skriftstørrelse","panelTitle":"Skriftstørrelse"},"label":"Skrifttype","panelTitle":"Skrifttype","voiceLabel":"Skrifttype"},"image":{"alt":"Alternativ tekst","border":"Ramme","btnUpload":"Upload fil til serveren","button2Img":"Vil du lave billedknappen om til et almindeligt billede?","hSpace":"Vandret margen","img2Button":"Vil du lave billedet om til en billedknap?","infoTab":"Generelt","linkTab":"Hyperlink","lockRatio":"Lås størrelsesforhold","menu":"Egenskaber for billede","resetSize":"Nulstil størrelse","title":"Egenskaber for billede","titleButton":"Egenskaber for billedknap","upload":"Upload","urlMissing":"Kilde på billed-URL mangler","vSpace":"Lodret margen","validateBorder":"Kant skal være et helt nummer.","validateHSpace":"HSpace skal være et helt nummer.","validateVSpace":"VSpace skal være et helt nummer."},"widget":{"move":"Klik og træk for at flytte","label":"%1 widget"},"image2":{"alt":"Alternativ tekst","btnUpload":"Upload fil til serveren","captioned":"Tekstet billede","captionPlaceholder":"Tekst","infoTab":"Generelt","lockRatio":"Lås størrelsesforhold","menu":"Egenskaber for billede","pathName":"billede","pathNameCaption":"tekst","resetSize":"Nulstil størrelse","resizer":"Klik og træk for at ændre størrelsen","title":"Egenskaber for billede","uploadTab":"Upload","urlMissing":"Kilde på billed-URL mangler","altMissing":"Alternative text is missing."},"indent":{"indent":"Forøg indrykning","outdent":"Formindsk indrykning"},"fakeobjects":{"anchor":"Anker","flash":"Flashanimation","hiddenfield":"Skjult felt","iframe":"Iframe","unknown":"Ukendt objekt"},"link":{"acccessKey":"Genvejstast","advanced":"Avanceret","advisoryContentType":"Indholdstype","advisoryTitle":"Titel","anchor":{"toolbar":"Indsæt/redigér bogmærke","menu":"Egenskaber for bogmærke","title":"Egenskaber for bogmærke","name":"Bogmærkenavn","errorName":"Indtast bogmærkenavn","remove":"Fjern bogmærke"},"anchorId":"Efter element-Id","anchorName":"Efter ankernavn","charset":"Tegnsæt","cssClasses":"Typografiark","download":"Force Download","displayText":"Display Text","emailAddress":"E-mailadresse","emailBody":"Besked","emailSubject":"Emne","id":"Id","info":"Generelt","langCode":"Tekstretning","langDir":"Tekstretning","langDirLTR":"Fra venstre mod højre (LTR)","langDirRTL":"Fra højre mod venstre (RTL)","menu":"Redigér hyperlink","name":"Navn","noAnchors":"(Ingen bogmærker i dokumentet)","noEmail":"Indtast e-mailadresse!","noUrl":"Indtast hyperlink-URL!","other":"<anden>","popupDependent":"Koblet/dependent (Netscape)","popupFeatures":"Egenskaber for popup","popupFullScreen":"Fuld skærm (IE)","popupLeft":"Position fra venstre","popupLocationBar":"Adresselinje","popupMenuBar":"Menulinje","popupResizable":"Justérbar","popupScrollBars":"Scrollbar","popupStatusBar":"Statuslinje","popupToolbar":"Værktøjslinje","popupTop":"Position fra toppen","rel":"Relation","selectAnchor":"Vælg et anker","styles":"Typografi","tabIndex":"Tabulatorindeks","target":"Mål","targetFrame":"<ramme>","targetFrameName":"Destinationsvinduets navn","targetPopup":"<popup vindue>","targetPopupName":"Popupvinduets navn","title":"Egenskaber for hyperlink","toAnchor":"Bogmærke på denne side","toEmail":"E-mail","toUrl":"URL","toolbar":"Indsæt/redigér hyperlink","type":"Type","unlink":"Fjern hyperlink","upload":"Upload"},"list":{"bulletedlist":"Punktopstilling","numberedlist":"Talopstilling"},"maximize":{"maximize":"Maksimér","minimize":"Minimér"},"table":{"border":"Rammebredde","caption":"Titel","cell":{"menu":"Celle","insertBefore":"Indsæt celle før","insertAfter":"Indsæt celle efter","deleteCell":"Slet celle","merge":"Flet celler","mergeRight":"Flet til højre","mergeDown":"Flet nedad","splitHorizontal":"Del celle vandret","splitVertical":"Del celle lodret","title":"Celleegenskaber","cellType":"Celletype","rowSpan":"Række span (rows span)","colSpan":"Kolonne span (columns span)","wordWrap":"Tekstombrydning","hAlign":"Vandret justering","vAlign":"Lodret justering","alignBaseline":"Grundlinje","bgColor":"Baggrundsfarve","borderColor":"Rammefarve","data":"Data","header":"Hoved","yes":"Ja","no":"Nej","invalidWidth":"Cellebredde skal være et tal.","invalidHeight":"Cellehøjde skal være et tal.","invalidRowSpan":"Række span skal være et heltal.","invalidColSpan":"Kolonne span skal være et heltal.","chooseColor":"Vælg"},"cellPad":"Cellemargen","cellSpace":"Celleafstand","column":{"menu":"Kolonne","insertBefore":"Indsæt kolonne før","insertAfter":"Indsæt kolonne efter","deleteColumn":"Slet kolonne"},"columns":"Kolonner","deleteTable":"Slet tabel","headers":"Hoved","headersBoth":"Begge","headersColumn":"Første kolonne","headersNone":"Ingen","headersRow":"Første række","invalidBorder":"Rammetykkelse skal være et tal.","invalidCellPadding":"Cellemargen skal være et tal.","invalidCellSpacing":"Celleafstand skal være et tal.","invalidCols":"Antallet af kolonner skal være større end 0.","invalidHeight":"Tabelhøjde skal være et tal.","invalidRows":"Antallet af rækker skal være større end 0.","invalidWidth":"Tabelbredde skal være et tal.","menu":"Egenskaber for tabel","row":{"menu":"Række","insertBefore":"Indsæt række før","insertAfter":"Indsæt række efter","deleteRow":"Slet række"},"rows":"Rækker","summary":"Resumé","title":"Egenskaber for tabel","toolbar":"Tabel","widthPc":"procent","widthPx":"pixels","widthUnit":"Bredde på enhed"},"quicktable":{"more":"Flere..."},"removeformat":{"toolbar":"Fjern formatering"},"sourcearea":{"toolbar":"Kilde"},"toolbar":{"toolbarCollapse":"Sammenklap værktøjslinje","toolbarExpand":"Udvid værktøjslinje","toolbarGroups":{"document":"Dokument","clipboard":"Udklipsholder/Fortryd","editing":"Redigering","forms":"Formularer","basicstyles":"Basis styles","paragraph":"Paragraf","links":"Links","insert":"Indsæt","styles":"Typografier","colors":"Farver","tools":"Værktøjer"},"toolbars":"Editors værktøjslinjer"},"undo":{"redo":"Annullér fortryd","undo":"Fortryd"},"colordialog":{"clear":"Nulstil","highlight":"Markér","options":"Farvemuligheder","selected":"Valgt farve","title":"Vælg farve"}};
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utilities for manipulating the browser's Document Object Model * Inspiration taken *heavily* from mochikit (http://mochikit.com/). * * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer * to a different document object. This is useful if you are working with * frames or multiple windows. * */ // TODO(user): Rename/refactor getTextContent and getRawTextContent. The problem // is that getTextContent should mimic the DOM3 textContent. We should add a // getInnerText (or getText) which tries to return the visible text, innerText. goog.provide('goog.dom'); goog.provide('goog.dom.DomHelper'); goog.provide('goog.dom.NodeType'); goog.require('goog.array'); goog.require('goog.dom.BrowserFeature'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classes'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Size'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.userAgent'); /** * @define {boolean} Whether we know at compile time that the browser is in * quirks mode. */ goog.dom.ASSUME_QUIRKS_MODE = false; /** * @define {boolean} Whether we know at compile time that the browser is in * standards compliance mode. */ goog.dom.ASSUME_STANDARDS_MODE = false; /** * Whether we know the compatibility mode at compile time. * @type {boolean} * @private */ goog.dom.COMPAT_MODE_KNOWN_ = goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE; /** * Enumeration for DOM node types (for reference) * @enum {number} */ goog.dom.NodeType = { ELEMENT: 1, ATTRIBUTE: 2, TEXT: 3, CDATA_SECTION: 4, ENTITY_REFERENCE: 5, ENTITY: 6, PROCESSING_INSTRUCTION: 7, COMMENT: 8, DOCUMENT: 9, DOCUMENT_TYPE: 10, DOCUMENT_FRAGMENT: 11, NOTATION: 12 }; /** * Gets the DomHelper object for the document where the element resides. * @param {Node|Window=} opt_element If present, gets the DomHelper for this * element. * @return {!goog.dom.DomHelper} The DomHelper. */ goog.dom.getDomHelper = function(opt_element) { return opt_element ? new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) : (goog.dom.defaultDomHelper_ || (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper())); }; /** * Cached default DOM helper. * @type {goog.dom.DomHelper} * @private */ goog.dom.defaultDomHelper_; /** * Gets the document object being used by the dom library. * @return {!Document} Document object. */ goog.dom.getDocument = function() { return document; }; /** * Alias for getElementById. If a DOM node is passed in then we just return * that. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. */ goog.dom.getElement = function(element) { return goog.isString(element) ? document.getElementById(element) : element; }; /** * Alias for getElement. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. * @deprecated Use {@link goog.dom.getElement} instead. */ goog.dom.$ = goog.dom.getElement; /** * Looks up elements by both tag and class name, using browser native functions * ({@code querySelectorAll}, {@code getElementsByTagName} or * {@code getElementsByClassName}) where possible. This function * is a useful, if limited, way of collecting a list of DOM elements * with certain characteristics. {@code goog.dom.query} offers a * more powerful and general solution which allows matching on CSS3 * selector expressions, but at increased cost in code size. If all you * need is particular tags belonging to a single class, this function * is fast and sleek. * * @see {goog.dom.query} * * @param {?string=} opt_tag Element tag name. * @param {?string=} opt_class Optional class name. * @param {Document|Element=} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). */ goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) { return goog.dom.getElementsByTagNameAndClass_(document, opt_tag, opt_class, opt_el); }; /** * Returns an array of all the elements with the provided className. * @see {goog.dom.query} * @param {!string} className the name of the class to look for. * @param {Document|Element=} opt_el Optional element to look in. * @return { {length: number} } The items found with the class name provided. */ goog.dom.getElementsByClass = function(className, opt_el) { var parent = opt_el || document; if (goog.dom.canUseQuerySelector_(parent)) { return parent.querySelectorAll('.' + className); } else if (parent.getElementsByClassName) { return parent.getElementsByClassName(className); } return goog.dom.getElementsByTagNameAndClass_( document, '*', className, opt_el); }; /** * Returns the first element with the provided className. * @see {goog.dom.query} * @param {!string} className the name of the class to look for. * @param {Element|Document=} opt_el Optional element to look in. * @return {Element} The first item with the class name provided. */ goog.dom.getElementByClass = function(className, opt_el) { var parent = opt_el || document; var retVal = null; if (goog.dom.canUseQuerySelector_(parent)) { retVal = parent.querySelector('.' + className); } else { retVal = goog.dom.getElementsByClass(className, opt_el)[0]; } return retVal || null; }; /** * Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and * fast W3C Selectors API. However, the version of WebKit that shipped with * Safari 3.1 and Chrome has a bug where it will not correctly match mixed- * case class name selectors in quirks mode. * @param {!Element|Document} parent The parent document object. * @return {boolean} whether or not we can use parent.querySelector* APIs. * @private */ goog.dom.canUseQuerySelector_ = function(parent) { return parent.querySelectorAll && parent.querySelector && (!goog.userAgent.WEBKIT || goog.dom.isCss1CompatMode_(document) || goog.userAgent.isVersion('528')); }; /** * Helper for {@code getElementsByTagNameAndClass}. * @param {!Document} doc The document to get the elements in. * @param {?string=} opt_tag Element tag name. * @param {?string=} opt_class Optional class name. * @param {Document|Element=} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). * @private */ goog.dom.getElementsByTagNameAndClass_ = function(doc, opt_tag, opt_class, opt_el) { var parent = opt_el || doc; var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toUpperCase() : ''; if (goog.dom.canUseQuerySelector_(parent) && (tagName || opt_class)) { var query = tagName + (opt_class ? '.' + opt_class : ''); return parent.querySelectorAll(query); } // Use the native getElementsByClassName if available, under the assumption // that even when the tag name is specified, there will be fewer elements to // filter through when going by class than by tag name if (opt_class && parent.getElementsByClassName) { var els = parent.getElementsByClassName(opt_class); if (tagName) { var arrayLike = {}; var len = 0; // Filter for specific tags if requested. for (var i = 0, el; el = els[i]; i++) { if (tagName == el.nodeName) { arrayLike[len++] = el; } } arrayLike.length = len; return arrayLike; } else { return els; } } var els = parent.getElementsByTagName(tagName || '*'); if (opt_class) { var arrayLike = {}; var len = 0; for (var i = 0, el; el = els[i]; i++) { var className = el.className; // Check if className has a split function since SVG className does not. if (typeof className.split == 'function' && goog.array.contains(className.split(/\s+/), opt_class)) { arrayLike[len++] = el; } } arrayLike.length = len; return arrayLike; } else { return els; } }; /** * Alias for {@code getElementsByTagNameAndClass}. * @param {?string=} opt_tag Element tag name. * @param {?string=} opt_class Optional class name. * @param {Element=} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). * @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead. */ goog.dom.$$ = goog.dom.getElementsByTagNameAndClass; /** * Sets multiple properties on a node. * @param {Element} element DOM node to set properties on. * @param {Object} properties Hash of property:value pairs. */ goog.dom.setProperties = function(element, properties) { goog.object.forEach(properties, function(val, key) { if (key == 'style') { element.style.cssText = val; } else if (key == 'class') { element.className = val; } else if (key == 'for') { element.htmlFor = val; } else if (key in goog.dom.DIRECT_ATTRIBUTE_MAP_) { element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val); } else { element[key] = val; } }); }; /** * Map of attributes that should be set using * element.setAttribute(key, val) instead of element[key] = val. Used * by goog.dom.setProperties. * * @type {Object} * @private */ goog.dom.DIRECT_ATTRIBUTE_MAP_ = { 'cellpadding': 'cellPadding', 'cellspacing': 'cellSpacing', 'colspan': 'colSpan', 'rowspan': 'rowSpan', 'valign': 'vAlign', 'height': 'height', 'width': 'width', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'maxlength': 'maxLength', 'type': 'type' }; /** * Gets the dimensions of the viewport. * * Gecko Standards mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Width of viewport including scrollbar. * body.clientWidth Width of body element. * * docEl.clientHeight Height of viewport excluding scrollbar. * win.innerHeight Height of viewport including scrollbar. * body.clientHeight Height of document. * * Gecko Backwards compatible mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Width of viewport including scrollbar. * body.clientWidth Width of viewport excluding scrollbar. * * docEl.clientHeight Height of document. * win.innerHeight Height of viewport including scrollbar. * body.clientHeight Height of viewport excluding scrollbar. * * IE6/7 Standards mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Undefined. * body.clientWidth Width of body element. * * docEl.clientHeight Height of viewport excluding scrollbar. * win.innerHeight Undefined. * body.clientHeight Height of document element. * * IE5 + IE6/7 Backwards compatible mode: * docEl.clientWidth 0. * win.innerWidth Undefined. * body.clientWidth Width of viewport excluding scrollbar. * * docEl.clientHeight 0. * win.innerHeight Undefined. * body.clientHeight Height of viewport excluding scrollbar. * * Opera 9 Standards and backwards compatible mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Width of viewport including scrollbar. * body.clientWidth Width of viewport excluding scrollbar. * * docEl.clientHeight Height of document. * win.innerHeight Height of viewport including scrollbar. * body.clientHeight Height of viewport excluding scrollbar. * * WebKit: * Safari 2 * docEl.clientHeight Same as scrollHeight. * docEl.clientWidth Same as innerWidth. * win.innerWidth Width of viewport excluding scrollbar. * win.innerHeight Height of the viewport including scrollbar. * frame.innerHeight Height of the viewport exluding scrollbar. * * Safari 3 (tested in 522) * * docEl.clientWidth Width of viewport excluding scrollbar. * docEl.clientHeight Height of viewport excluding scrollbar in strict mode. * body.clientHeight Height of viewport excluding scrollbar in quirks mode. * * @param {Window=} opt_window Optional window element to test. * @return {!goog.math.Size} Object with values 'width' and 'height'. */ goog.dom.getViewportSize = function(opt_window) { // TODO(user): This should not take an argument return goog.dom.getViewportSize_(opt_window || window); }; /** * Helper for {@code getViewportSize}. * @param {Window} win The window to get the view port size for. * @return {!goog.math.Size} Object with values 'width' and 'height'. * @private */ goog.dom.getViewportSize_ = function(win) { var doc = win.document; if (goog.userAgent.WEBKIT && !goog.userAgent.isVersion('500') && !goog.userAgent.MOBILE) { // TODO(user): Sometimes we get something that isn't a valid window // object. In this case we just revert to the current window. We need to // figure out when this happens and find a real fix for it. // See the comments on goog.dom.getWindow. if (typeof win.innerHeight == 'undefined') { win = window; } var innerHeight = win.innerHeight; var scrollHeight = win.document.documentElement.scrollHeight; if (win == win.top) { if (scrollHeight < innerHeight) { innerHeight -= 15; // Scrollbars are 15px wide on Mac } } return new goog.math.Size(win.innerWidth, innerHeight); } var readsFromDocumentElement = goog.dom.isCss1CompatMode_(doc); if (goog.userAgent.OPERA && !goog.userAgent.isVersion('9.50')) { // Older versions of Opera used to read from document.body, but this // changed with 9.5. readsFromDocumentElement = false; } var el = readsFromDocumentElement ? doc.documentElement : doc.body; return new goog.math.Size(el.clientWidth, el.clientHeight); }; /** * Calculates the height of the document. * * @return {number} The height of the current document. */ goog.dom.getDocumentHeight = function() { return goog.dom.getDocumentHeight_(window); }; /** * Calculates the height of the document of the given window. * * Function code copied from the opensocial gadget api: * gadgets.window.adjustHeight(opt_height) * * @private * @param {Window} win The window whose document height to retrieve. * @return {number} The height of the document of the given window. */ goog.dom.getDocumentHeight_ = function(win) { // NOTE(user): This method will return the window size rather than the document // size in webkit quirks mode. var doc = win.document; var height = 0; if (doc) { // Calculating inner content height is hard and different between // browsers rendering in Strict vs. Quirks mode. We use a combination of // three properties within document.body and document.documentElement: // - scrollHeight // - offsetHeight // - clientHeight // These values differ significantly between browsers and rendering modes. // But there are patterns. It just takes a lot of time and persistence // to figure out. // Get the height of the viewport var vh = goog.dom.getViewportSize_(win).height; var body = doc.body; var docEl = doc.documentElement; if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) { // In Strict mode: // The inner content height is contained in either: // document.documentElement.scrollHeight // document.documentElement.offsetHeight // Based on studying the values output by different browsers, // use the value that's NOT equal to the viewport height found above. height = docEl.scrollHeight != vh ? docEl.scrollHeight : docEl.offsetHeight; } else { // In Quirks mode: // documentElement.clientHeight is equal to documentElement.offsetHeight // except in IE. In most browsers, document.documentElement can be used // to calculate the inner content height. // However, in other browsers (e.g. IE), document.body must be used // instead. How do we know which one to use? // If document.documentElement.clientHeight does NOT equal // document.documentElement.offsetHeight, then use document.body. var sh = docEl.scrollHeight; var oh = docEl.offsetHeight; if (docEl.clientHeight != oh) { sh = body.scrollHeight; oh = body.offsetHeight; } // Detect whether the inner content height is bigger or smaller // than the bounding box (viewport). If bigger, take the larger // value. If smaller, take the smaller value. if (sh > vh) { // Content is larger height = sh > oh ? sh : oh; } else { // Content is smaller height = sh < oh ? sh : oh; } } } return height; }; /** * Gets the page scroll distance as a coordinate object. * * @param {Window=} opt_window Optional window element to test. * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. * @deprecated Use {@link goog.dom.getDocumentScroll} instead. */ goog.dom.getPageScroll = function(opt_window) { var win = opt_window || goog.global || window; return goog.dom.getDomHelper(win.document).getDocumentScroll(); }; /** * Gets the document scroll distance as a coordinate object. * * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. */ goog.dom.getDocumentScroll = function() { return goog.dom.getDocumentScroll_(document); }; /** * Helper for {@code getDocumentScroll}. * * @param {!Document} doc The document to get the scroll for. * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. * @private */ goog.dom.getDocumentScroll_ = function(doc) { var el = goog.dom.getDocumentScrollElement_(doc); return new goog.math.Coordinate(el.scrollLeft, el.scrollTop); }; /** * Gets the document scroll element. * @return {Element} Scrolling element. */ goog.dom.getDocumentScrollElement = function() { return goog.dom.getDocumentScrollElement_(document); }; /** * Helper for {@code getDocumentScrollElement}. * @param {!Document} doc The document to get the scroll element for. * @return {Element} Scrolling element. * @private */ goog.dom.getDocumentScrollElement_ = function(doc) { // Safari (2 and 3) needs body.scrollLeft in both quirks mode and strict mode. return !goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body; }; /** * Gets the window object associated with the given document. * * @param {Document=} opt_doc Document object to get window for. * @return {Window} The window associated with the given document. */ goog.dom.getWindow = function(opt_doc) { // TODO(user): This should not take an argument. return opt_doc ? goog.dom.getWindow_(opt_doc) : window; }; /** * Helper for {@code getWindow}. * * @param {!Document} doc Document object to get window for. * @return {!Window} The window associated with the given document. * @private */ goog.dom.getWindow_ = function(doc) { return doc.parentWindow || doc.defaultView; }; /** * Returns a dom node with a set of attributes. This function accepts varargs * for subsequent nodes to be added. Subsequent nodes will be added to the * first node as childNodes. * * So: * <code>createDom('div', null, createDom('p'), createDom('p'));</code> * would return a div with two child paragraphs * * @param {string} tagName Tag to create. * @param {Object|Array.<string>|string=} opt_attributes If object, then a map * of name-value pairs for attributes. If a string, then this is the * className of the new element. If an array, the elements will be joined * together as the className of the new element. * @param {...Object|string|Array|NodeList} var_args Further DOM nodes or * strings for text nodes. If one of the var_args is an array or NodeList,i * its elements will be added as childNodes instead. * @return {!Element} Reference to a DOM node. */ goog.dom.createDom = function(tagName, opt_attributes, var_args) { return goog.dom.createDom_(document, arguments); }; /** * Helper for {@code createDom}. * @param {!Document} doc The document to create the DOM in. * @param {!Arguments} args Argument object passed from the callers. See * {@code goog.dom.createDom} for details. * @return {!Element} Reference to a DOM node. * @private */ goog.dom.createDom_ = function(doc, args) { var tagName = args[0]; var attributes = args[1]; // Internet Explorer is dumb: http://msdn.microsoft.com/workshop/author/ // dhtml/reference/properties/name_2.asp // Also does not allow setting of 'type' attribute on 'input' or 'button'. if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes && (attributes.name || attributes.type)) { var tagNameArr = ['<', tagName]; if (attributes.name) { tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name), '"'); } if (attributes.type) { tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type), '"'); // Clone attributes map to remove 'type' without mutating the input. var clone = {}; goog.object.extend(clone, attributes); attributes = clone; delete attributes.type; } tagNameArr.push('>'); tagName = tagNameArr.join(''); } var element = doc.createElement(tagName); if (attributes) { if (goog.isString(attributes)) { element.className = attributes; } else if (goog.isArray(attributes)) { goog.dom.classes.add.apply(null, [element].concat(attributes)); } else { goog.dom.setProperties(element, attributes); } } if (args.length > 2) { goog.dom.append_(doc, element, args, 2); } return element; }; /** * Appends a node with text or other nodes. * @param {!Document} doc The document to create new nodes in. * @param {!Node} parent The node to append nodes to. * @param {!Arguments} args The values to add. See {@code goog.dom.append}. * @param {number} startIndex The index of the array to start from. * @private */ goog.dom.append_ = function(doc, parent, args, startIndex) { function childHandler(child) { // TODO(user): More coercion, ala MochiKit? if (child) { parent.appendChild(goog.isString(child) ? doc.createTextNode(child) : child); } } for (var i = startIndex; i < args.length; i++) { var arg = args[i]; // TODO(user): Fix isArrayLike to return false for a text node. if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) { // If the argument is a node list, not a real array, use a clone, // because forEach can't be used to mutate a NodeList. goog.array.forEach(goog.dom.isNodeList(arg) ? goog.array.clone(arg) : arg, childHandler); } else { childHandler(arg); } } }; /** * Alias for {@code createDom}. * @param {string} tagName Tag to create. * @param {string|Object=} opt_attributes If object, then a map of name-value * pairs for attributes. If a string, then this is the className of the new * element. * @param {...Object|string|Array|NodeList} var_args Further DOM nodes or * strings for text nodes. If one of the var_args is an array, its * children will be added as childNodes instead. * @return {!Element} Reference to a DOM node. * @deprecated Use {@link goog.dom.createDom} instead. */ goog.dom.$dom = goog.dom.createDom; /** * Creates a new element. * @param {string} name Tag name. * @return {!Element} The new element. */ goog.dom.createElement = function(name) { return document.createElement(name); }; /** * Creates a new text node. * @param {string} content Content. * @return {!Text} The new text node. */ goog.dom.createTextNode = function(content) { return document.createTextNode(content); }; /** * Create a table. * @param {number} rows The number of rows in the table. Must be >= 1. * @param {number} columns The number of columns in the table. Must be >= 1. * @param {boolean=} opt_fillWithNbsp If true, fills table entries with nsbps. * @return {!Element} The created table. */ goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) { return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp); }; /** * Create a table. * @param {!Document} doc Document object to use to create the table. * @param {number} rows The number of rows in the table. Must be >= 1. * @param {number} columns The number of columns in the table. Must be >= 1. * @param {boolean} fillWithNbsp If true, fills table entries with nsbps. * @return {!Element} The created table. * @private */ goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) { var rowHtml = ['<tr>']; for (var i = 0; i < columns; i++) { rowHtml.push(fillWithNbsp ? '<td>&nbsp;</td>' : '<td></td>'); } rowHtml.push('</tr>'); rowHtml = rowHtml.join(''); var totalHtml = ['<table>']; for (i = 0; i < rows; i++) { totalHtml.push(rowHtml); } totalHtml.push('</table>'); var elem = doc.createElement(goog.dom.TagName.DIV); elem.innerHTML = totalHtml.join(''); return /** @type {!Element} */ (elem.removeChild(elem.firstChild)); }; /** * Converts an HTML string into a document fragment. * * @param {string} htmlString The HTML string to convert. * @return {!Node} The resulting document fragment. */ goog.dom.htmlToDocumentFragment = function(htmlString) { return goog.dom.htmlToDocumentFragment_(document, htmlString); }; /** * Helper for {@code htmlToDocumentFragment}. * * @param {!Document} doc The document. * @param {string} htmlString The HTML string to convert. * @return {!Node} The resulting document fragment. * @private */ goog.dom.htmlToDocumentFragment_ = function(doc, htmlString) { var tempDiv = doc.createElement('div'); if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) { tempDiv.innerHTML = '<br>' + htmlString; tempDiv.removeChild(tempDiv.firstChild); } else { tempDiv.innerHTML = htmlString; } if (tempDiv.childNodes.length == 1) { return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild)); } else { var fragment = doc.createDocumentFragment(); while (tempDiv.firstChild) { fragment.appendChild(tempDiv.firstChild); } return fragment; } }; /** * Returns the compatMode of the document. * @return {string} The result is either CSS1Compat or BackCompat. * @deprecated use goog.dom.isCss1CompatMode instead. */ goog.dom.getCompatMode = function() { return goog.dom.isCss1CompatMode() ? 'CSS1Compat' : 'BackCompat'; }; /** * Returns true if the browser is in "CSS1-compatible" (standards-compliant) * mode, false otherwise. * @return {boolean} True if in CSS1-compatible mode. */ goog.dom.isCss1CompatMode = function() { return goog.dom.isCss1CompatMode_(document); }; /** * Returns true if the browser is in "CSS1-compatible" (standards-compliant) * mode, false otherwise. * @param {Document} doc The document to check. * @return {boolean} True if in CSS1-compatible mode. * @private */ goog.dom.isCss1CompatMode_ = function(doc) { if (goog.dom.COMPAT_MODE_KNOWN_) { return goog.dom.ASSUME_STANDARDS_MODE; } return doc.compatMode == 'CSS1Compat'; }; /** * Determines if the given node can contain children, intended to be used for * HTML generation. * * IE natively supports node.canHaveChildren but has inconsistent behavior. * Prior to IE8 the base tag allows children and in IE9 all nodes return true * for canHaveChildren. * * In practice all non-IE browsers allow you to add children to any node, but * the behavior is inconsistent: * * <pre> * var a = document.createElement('br'); * a.appendChild(document.createTextNode('foo')); * a.appendChild(document.createTextNode('bar')); * console.log(a.childNodes.length); // 2 * console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar" * </pre> * * TODO(user): Rename shouldAllowChildren() ? * * @param {Node} node The node to check. * @return {boolean} Whether the node can contain children. */ goog.dom.canHaveChildren = function(node) { if (node.nodeType != goog.dom.NodeType.ELEMENT) { return false; } switch (node.tagName) { case goog.dom.TagName.APPLET: case goog.dom.TagName.AREA: case goog.dom.TagName.BASE: case goog.dom.TagName.BR: case goog.dom.TagName.COL: case goog.dom.TagName.FRAME: case goog.dom.TagName.HR: case goog.dom.TagName.IMG: case goog.dom.TagName.INPUT: case goog.dom.TagName.IFRAME: case goog.dom.TagName.ISINDEX: case goog.dom.TagName.LINK: case goog.dom.TagName.NOFRAMES: case goog.dom.TagName.NOSCRIPT: case goog.dom.TagName.META: case goog.dom.TagName.OBJECT: case goog.dom.TagName.PARAM: case goog.dom.TagName.SCRIPT: case goog.dom.TagName.STYLE: return false; } return true; }; /** * Appends a child to a node. * @param {Node} parent Parent. * @param {Node} child Child. */ goog.dom.appendChild = function(parent, child) { parent.appendChild(child); }; /** * Appends a node with text or other nodes. * @param {!Node} parent The node to append nodes to. * @param {...goog.dom.Appendable} var_args The things to append to the node. * If this is a Node it is appended as is. * If this is a string then a text node is appended. * If this is an array like object then fields 0 to length - 1 are appended. */ goog.dom.append = function(parent, var_args) { goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1); }; /** * Removes all the child nodes on a DOM node. * @param {Node} node Node to remove children from. */ goog.dom.removeChildren = function(node) { // Note: Iterations over live collections can be slow, this is the fastest // we could find. The double parenthesis are used to prevent JsCompiler and // strict warnings. var child; while ((child = node.firstChild)) { node.removeChild(child); } }; /** * Inserts a new node before an existing reference node (i.e. as the previous * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert before. */ goog.dom.insertSiblingBefore = function(newNode, refNode) { if (refNode.parentNode) { refNode.parentNode.insertBefore(newNode, refNode); } }; /** * Inserts a new node after an existing reference node (i.e. as the next * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert after. */ goog.dom.insertSiblingAfter = function(newNode, refNode) { if (refNode.parentNode) { refNode.parentNode.insertBefore(newNode, refNode.nextSibling); } }; /** * Removes a node from its parent. * @param {Node} node The node to remove. * @return {Node} The node removed if removed; else, null. */ goog.dom.removeNode = function(node) { return node && node.parentNode ? node.parentNode.removeChild(node) : null; }; /** * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no * parent. * @param {Node} newNode Node to insert. * @param {Node} oldNode Node to replace. */ goog.dom.replaceNode = function(newNode, oldNode) { var parent = oldNode.parentNode; if (parent) { parent.replaceChild(newNode, oldNode); } }; /** * Flattens an element. That is, removes it and replace it with its children. * Does nothing if the element is not in the document. * @param {Element} element The element to flatten. * @return {Element|undefined} The original element, detached from the document * tree, sans children; or undefined, if the element was not in the * document to begin with. */ goog.dom.flattenElement = function(element) { var child, parent = element.parentNode; if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) { // Use IE DOM method (supported by Opera too) if available if (element.removeNode) { return /** @type {Element} */ (element.removeNode(false)); } else { // Move all children of the original node up one level. while ((child = element.firstChild)) { parent.insertBefore(child, element); } // Detach the original element. return /** @type {Element} */ (goog.dom.removeNode(element)); } } }; /** * Returns the first child node that is an element. * @param {Node} node The node to get the first child element of. * @return {Element} The first child node of {@code node} that is an element. */ goog.dom.getFirstElementChild = function(node) { return goog.dom.getNextElementNode_(node.firstChild, true); }; /** * Returns the last child node that is an element. * @param {Node} node The node to get the last child element of. * @return {Element} The last child node of {@code node} that is an element. */ goog.dom.getLastElementChild = function(node) { return goog.dom.getNextElementNode_(node.lastChild, false); }; /** * Returns the first next sibling that is an element. * @param {Node} node The node to get the next sibling element of. * @return {Element} The next sibling of {@code node} that is an element. */ goog.dom.getNextElementSibling = function(node) { return goog.dom.getNextElementNode_(node.nextSibling, true); }; /** * Returns the first previous sibling that is an element. * @param {Node} node The node to get the previous sibling element of. * @return {Element} The first previous sibling of {@code node} that is * an element. */ goog.dom.getPreviousElementSibling = function(node) { return goog.dom.getNextElementNode_(node.previousSibling, false); }; /** * Returns the first node that is an element in the specified direction, * starting with {@code node}. * @param {Node} node The node to get the next element from. * @param {boolean} forward Whether to look forwards or backwards. * @return {Element} The first element. * @private */ goog.dom.getNextElementNode_ = function(node, forward) { while (node && node.nodeType != goog.dom.NodeType.ELEMENT) { node = forward ? node.nextSibling : node.previousSibling; } return /** @type {Element} */ (node); }; /** * Returns the next node in source order from the given node. * @param {Node} node The node. * @return {Node} The next node in the DOM tree, or null if this was the last * node. */ goog.dom.getNextNode = function(node) { if (!node) { return null; } if (node.firstChild) { return node.firstChild; } while (node && !node.nextSibling) { node = node.parentNode; } return node ? node.nextSibling : null; }; /** * Returns the previous node in source order from the given node. * @param {Node} node The node. * @return {Node} The previous node in the DOM tree, or null if this was the * first node. */ goog.dom.getPreviousNode = function(node) { if (!node) { return null; } if (!node.previousSibling) { return node.parentNode; } node = node.previousSibling; while (node && node.lastChild) { node = node.lastChild; } return node; }; /** * Whether the object looks like a DOM node. * @param {*} obj The object being tested for node likeness. * @return {boolean} Whether the object looks like a DOM node. */ goog.dom.isNodeLike = function(obj) { return goog.isObject(obj) && obj.nodeType > 0; }; /** * Whether a node contains another node. * @param {Node} parent The node that should contain the other node. * @param {Node} descendant The node to test presence of. * @return {boolean} Whether the parent node contains the descendent node. */ goog.dom.contains = function(parent, descendant) { // We use browser specific methods for this if available since it is faster // that way. // IE DOM if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) { return parent == descendant || parent.contains(descendant); } // W3C DOM Level 3 if (typeof parent.compareDocumentPosition != 'undefined') { return parent == descendant || Boolean(parent.compareDocumentPosition(descendant) & 16); } // W3C DOM Level 1 while (descendant && parent != descendant) { descendant = descendant.parentNode; } return descendant == parent; }; /** * Compares the document order of two nodes, returning 0 if they are the same * node, a negative number if node1 is before node2, and a positive number if * node2 is before node1. Note that we compare the order the tags appear in the * document so in the tree <b><i>text</i></b> the B node is considered to be * before the I node. * * @param {Node} node1 The first node to compare. * @param {Node} node2 The second node to compare. * @return {number} 0 if the nodes are the same node, a negative number if node1 * is before node2, and a positive number if node2 is before node1. */ goog.dom.compareNodeOrder = function(node1, node2) { // Fall out quickly for equality. if (node1 == node2) { return 0; } // Use compareDocumentPosition where available if (node1.compareDocumentPosition) { // 4 is the bitmask for FOLLOWS. return node1.compareDocumentPosition(node2) & 2 ? 1 : -1; } // Process in IE using sourceIndex - we check to see if the first node has // a source index or if its parent has one. if ('sourceIndex' in node1 || (node1.parentNode && 'sourceIndex' in node1.parentNode)) { var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT; var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT; if (isElement1 && isElement2) { return node1.sourceIndex - node2.sourceIndex; } else { var parent1 = node1.parentNode; var parent2 = node2.parentNode; if (parent1 == parent2) { return goog.dom.compareSiblingOrder_(node1, node2); } if (!isElement1 && goog.dom.contains(parent1, node2)) { return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2); } if (!isElement2 && goog.dom.contains(parent2, node1)) { return goog.dom.compareParentsDescendantNodeIe_(node2, node1); } return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) - (isElement2 ? node2.sourceIndex : parent2.sourceIndex); } } // For Safari, we compare ranges. var doc = goog.dom.getOwnerDocument(node1); var range1, range2; range1 = doc.createRange(); range1.selectNode(node1); range1.collapse(true); range2 = doc.createRange(); range2.selectNode(node2); range2.collapse(true); return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END, range2); }; /** * Utility function to compare the position of two nodes, when * {@code textNode}'s parent is an ancestor of {@code node}. If this entry * condition is not met, this function will attempt to reference a null object. * @param {Node} textNode The textNode to compare. * @param {Node} node The node to compare. * @return {number} -1 if node is before textNode, +1 otherwise. * @private */ goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) { var parent = textNode.parentNode; if (parent == node) { // If textNode is a child of node, then node comes first. return -1; } var sibling = node; while (sibling.parentNode != parent) { sibling = sibling.parentNode; } return goog.dom.compareSiblingOrder_(sibling, textNode); }; /** * Utility function to compare the position of two nodes known to be non-equal * siblings. * @param {Node} node1 The first node to compare. * @param {Node} node2 The second node to compare. * @return {number} -1 if node1 is before node2, +1 otherwise. * @private */ goog.dom.compareSiblingOrder_ = function(node1, node2) { var s = node2; while ((s = s.previousSibling)) { if (s == node1) { // We just found node1 before node2. return -1; } } // Since we didn't find it, node1 must be after node2. return 1; }; /** * Find the deepest common ancestor of the given nodes. * @param {...Node} var_args The nodes to find a common ancestor of. * @return {Node} The common ancestor of the nodes, or null if there is none. * null will only be returned if two or more of the nodes are from different * documents. */ goog.dom.findCommonAncestor = function(var_args) { var i, count = arguments.length; if (!count) { return null; } else if (count == 1) { return arguments[0]; } var paths = []; var minLength = Infinity; for (i = 0; i < count; i++) { // Compute the list of ancestors. var ancestors = []; var node = arguments[i]; while (node) { ancestors.unshift(node); node = node.parentNode; } // Save the list for comparison. paths.push(ancestors); minLength = Math.min(minLength, ancestors.length); } var output = null; for (i = 0; i < minLength; i++) { var first = paths[0][i]; for (var j = 1; j < count; j++) { if (first != paths[j][i]) { return output; } } output = first; } return output; }; /** * Returns the owner document for a node. * @param {Node|Window} node The node to get the document for. * @return {!Document} The document owning the node. */ goog.dom.getOwnerDocument = function(node) { // TODO(user): Remove IE5 code. // IE5 uses document instead of ownerDocument return /** @type {!Document} */ ( node.nodeType == goog.dom.NodeType.DOCUMENT ? node : node.ownerDocument || node.document); }; /** * Cross-browser function for getting the document element of a frame or iframe. * @param {Element} frame Frame element. * @return {!Document} The frame content document. */ goog.dom.getFrameContentDocument = function(frame) { var doc; if (goog.userAgent.WEBKIT) { doc = (frame.document || frame.contentWindow.document); } else { doc = (frame.contentDocument || frame.contentWindow.document); } return doc; }; /** * Cross-browser function for getting the window of a frame or iframe. * @param {HTMLIFrameElement|HTMLFrameElement} frame Frame element. * @return {Window} The window associated with the given frame. */ goog.dom.getFrameContentWindow = function(frame) { return frame.contentWindow || goog.dom.getWindow_(goog.dom.getFrameContentDocument(frame)); }; /** * Cross-browser function for setting the text content of an element. * @param {Element} element The element to change the text content of. * @param {string} text The string that should replace the current element * content. */ goog.dom.setTextContent = function(element, text) { if ('textContent' in element) { element.textContent = text; } else if (element.firstChild && element.firstChild.nodeType == goog.dom.NodeType.TEXT) { // If the first child is a text node we just change its data and remove the // rest of the children. while (element.lastChild != element.firstChild) { element.removeChild(element.lastChild); } element.firstChild.data = text; } else { goog.dom.removeChildren(element); var doc = goog.dom.getOwnerDocument(element); element.appendChild(doc.createTextNode(text)); } }; /** * Gets the outerHTML of a node, which islike innerHTML, except that it * actually contains the HTML of the node itself. * @param {Element} element The element to get the HTML of. * @return {string} The outerHTML of the given element. */ goog.dom.getOuterHtml = function(element) { // IE, Opera and WebKit all have outerHTML. if ('outerHTML' in element) { return element.outerHTML; } else { var doc = goog.dom.getOwnerDocument(element); var div = doc.createElement('div'); div.appendChild(element.cloneNode(true)); return div.innerHTML; } }; /** * Finds the first descendant node that matches the filter function, using * a depth first search. This function offers the most general purpose way * of finding a matching element. You may also wish to consider * {@code goog.dom.query} which can express many matching criteria using * CSS selector expressions. These expressions often result in a more * compact representation of the desired result. * @see goog.dom.query * * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {Node|undefined} The found node or undefined if none is found. */ goog.dom.findNode = function(root, p) { var rv = []; var found = goog.dom.findNodes_(root, p, rv, true); return found ? rv[0] : undefined; }; /** * Finds all the descendant nodes that match the filter function, using a * a depth first search. This function offers the most general-purpose way * of finding a set of matching elements. You may also wish to consider * {@code goog.dom.query} which can express many matching criteria using * CSS selector expressions. These expressions often result in a more * compact representation of the desired result. * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {Array.<Node>} The found nodes or an empty array if none are found. */ goog.dom.findNodes = function(root, p) { var rv = []; goog.dom.findNodes_(root, p, rv, false); return rv; }; /** * Finds the first or all the descendant nodes that match the filter function, * using a depth first search. * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @param {Array.<Node>} rv The found nodes are added to this array. * @param {boolean} findOne If true we exit after the first found node. * @return {boolean} Whether the search is complete or not. True in case findOne * is true and the node is found. False otherwise. * @private */ goog.dom.findNodes_ = function(root, p, rv, findOne) { if (root != null) { for (var i = 0, child; child = root.childNodes[i]; i++) { if (p(child)) { rv.push(child); if (findOne) { return true; } } if (goog.dom.findNodes_(child, p, rv, findOne)) { return true; } } } return false; }; /** * Map of tags whose content to ignore when calculating text length. * @type {Object} * @private */ goog.dom.TAGS_TO_IGNORE_ = { 'SCRIPT': 1, 'STYLE': 1, 'HEAD': 1, 'IFRAME': 1, 'OBJECT': 1 }; /** * Map of tags which have predefined values with regard to whitespace. * @type {Object} * @private */ goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'}; /** * Returns true if the element has a tab index that allows it to receive * keyboard focus (tabIndex >= 0), false otherwise. Note that form elements * natively support keyboard focus, even if they have no tab index. * @param {Element} element Element to check. * @return {boolean} Whether the element has a tab index that allows keyboard * focus. * @see http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ */ goog.dom.isFocusableTabIndex = function(element) { // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(), // which returns an object with a 'specified' property if tabIndex is // specified. This works on other browsers, too. var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase! if (attrNode && attrNode.specified) { var index = element.tabIndex; return goog.isNumber(index) && index >= 0; } return false; }; /** * Enables or disables keyboard focus support on the element via its tab index. * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true * (or elements that natively support keyboard focus, like form elements) can * receive keyboard focus. See http://go/tabindex for more info. * @param {Element} element Element whose tab index is to be changed. * @param {boolean} enable Whether to set or remove a tab index on the element * that supports keyboard focus. */ goog.dom.setFocusableTabIndex = function(element, enable) { if (enable) { element.tabIndex = 0; } else { element.removeAttribute('tabIndex'); // Must be camelCase! } }; /** * Returns the text content of the current node, without markup and invisible * symbols. New lines are stripped and whitespace is collapsed, * such that each character would be visible. * * In browsers that support it, innerText is used. Other browsers attempt to * simulate it via node traversal. Line breaks are canonicalized in IE. * * @param {Node} node The node from which we are getting content. * @return {string} The text content. */ goog.dom.getTextContent = function(node) { var textContent; // Note(user): IE9, Opera, and Safara 3 support innerText but they include // text nodes in script tags. So we revert to use a user agent test here. if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && ('innerText' in node)) { textContent = goog.string.canonicalizeNewlines(node.innerText); // Unfortunately .innerText() returns text with &shy; symbols // We need to filter it out and then remove duplicate whitespaces } else { var buf = []; goog.dom.getTextContent_(node, buf, true); textContent = buf.join(''); } // Strip &shy; entities. goog.format.insertWordBreaks inserts them in Opera. textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, ''); // Skip this replacement on IE, which automatically turns &nbsp; into ' ' // and / +/ into ' ' when reading innerText. if (!goog.userAgent.IE) { textContent = textContent.replace(/ +/g, ' '); } if (textContent != ' ') { textContent = textContent.replace(/^\s*/, ''); } return textContent; }; /** * Returns the text content of the current node, without markup. * * Unlike {@code getTextContent} this method does not collapse whitespaces * or normalize lines breaks. * * @param {Node} node The node from which we are getting content. * @return {string} The raw text content. */ goog.dom.getRawTextContent = function(node) { var buf = []; goog.dom.getTextContent_(node, buf, false); return buf.join(''); }; /** * Recursive support function for text content retrieval. * * @param {Node} node The node from which we are getting content. * @param {Array} buf string buffer. * @param {boolean} normalizeWhitespace Whether to normalize whitespace. * @private */ goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) { if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) { // ignore certain tags } else if (node.nodeType == goog.dom.NodeType.TEXT) { if (normalizeWhitespace) { buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, '')); } else { buf.push(node.nodeValue); } } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) { buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]); } else { var child = node.firstChild; while (child) { goog.dom.getTextContent_(child, buf, normalizeWhitespace); child = child.nextSibling; } } }; /** * Returns the text length of the text contained in a node, without markup. This * is equivalent to the selection length if the node was selected, or the number * of cursor movements to traverse the node. Images & BRs take one space. New * lines are ignored. * * @param {Node} node The node whose text content length is being calculated. * @return {number} The length of {@code node}'s text content. */ goog.dom.getNodeTextLength = function(node) { return goog.dom.getTextContent(node).length; }; /** * Returns the text offset of a node relative to one of its ancestors. The text * length is the same as the length calculated by goog.dom.getNodeTextLength. * * @param {Node} node The node whose offset is being calculated. * @param {Node=} opt_offsetParent The node relative to which the offset will * be calculated. Defaults to the node's owner document's body. * @return {number} The text offset. */ goog.dom.getNodeTextOffset = function(node, opt_offsetParent) { var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body; var buf = []; while (node && node != root) { var cur = node; while ((cur = cur.previousSibling)) { buf.unshift(goog.dom.getTextContent(cur)); } node = node.parentNode; } // Trim left to deal with FF cases when there might be line breaks and empty // nodes at the front of the text return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length; }; /** * Returns the node at a given offset in a parent node. If an object is * provided for the optional third parameter, the node and the remainder of the * offset will stored as properties of this object. * @param {Node} parent The parent node. * @param {number} offset The offset into the parent node. * @param {Object=} opt_result Object to be used to store the return value. The * return value will be stored in the form {node: Node, remainder: number} * if this object is provided. * @return {Node} The node at the given offset. */ goog.dom.getNodeAtOffset = function(parent, offset, opt_result) { var stack = [parent], pos = 0, cur; while (stack.length > 0 && pos < offset) { cur = stack.pop(); if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) { // ignore certain tags } else if (cur.nodeType == goog.dom.NodeType.TEXT) { var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' '); pos += text.length; } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) { pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length; } else { for (var i = cur.childNodes.length - 1; i >= 0; i--) { stack.push(cur.childNodes[i]); } } } if (goog.isObject(opt_result)) { opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0; opt_result.node = cur; } return cur; }; /** * Returns true if the object is a {@code NodeList}. To qualify as a NodeList, * the object must have a numeric length property and an item function (which * has type 'string' on IE for some reason). * @param {Object} val Object to test. * @return {boolean} Whether the object is a NodeList. */ goog.dom.isNodeList = function(val) { // TODO(user): Now the isNodeList is part of goog.dom we can use // goog.userAgent to make this simpler. // A NodeList must have a length property of type 'number' on all platforms. if (val && typeof val.length == 'number') { // A NodeList is an object everywhere except Safari, where it's a function. if (goog.isObject(val)) { // A NodeList must have an item function (on non-IE platforms) or an item // property of type 'string' (on IE). return typeof val.item == 'function' || typeof val.item == 'string'; } else if (goog.isFunction(val)) { // On Safari, a NodeList is a function with an item property that is also // a function. return typeof val.item == 'function'; } } // Not a NodeList. return false; }; /** * Walks up the DOM hierarchy returning the first ancestor that has the passed * tag name and/or class name. If the passed element matches the specified * criteria, the element itself is returned. * @param {Node} element The DOM node to start with. * @param {?string=} opt_tag The tag name to match (or null/undefined to match * any node regardless of tag name). Must be uppercase (goog.dom.TagName). * @param {?string=} opt_class The class name to match (or null/undefined to * match any node regardless of class name). * @return {Node} The first ancestor that matches the passed criteria, or * null if none match. */ goog.dom.getAncestorByTagNameAndClass = function(element, opt_tag, opt_class) { var tagName = opt_tag ? opt_tag.toUpperCase() : null; return goog.dom.getAncestor(element, function(node) { return (!tagName || node.nodeName == tagName) && (!opt_class || goog.dom.classes.has(node, opt_class)); }, true); }; /** * Walks up the DOM hierarchy returning the first ancestor that has the passed * class name. If the passed element matches the specified criteria, the * element itself is returned. * @param {Node} element The DOM node to start with. * @param {?string=} opt_class The class name to match (or null/undefined to * match any node regardless of class name). * @return {Node} The first ancestor that matches the passed criteria, or * null if none match. */ goog.dom.getAncestorByClass = function(element, opt_class) { return goog.dom.getAncestorByTagNameAndClass(element, null, opt_class); }; /** * Walks up the DOM hierarchy returning the first ancestor that passes the * matcher function. * @param {Node} element The DOM node to start with. * @param {function(Node) : boolean} matcher A function that returns true if the * passed node matches the desired criteria. * @param {boolean=} opt_includeNode If true, the node itself is included in * the search (the first call to the matcher will pass startElement as * the node to test). * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the * dom. * @return {Node} DOM node that matched the matcher, or null if there was * no match. */ goog.dom.getAncestor = function( element, matcher, opt_includeNode, opt_maxSearchSteps) { if (!opt_includeNode) { element = element.parentNode; } var ignoreSearchSteps = opt_maxSearchSteps == null; var steps = 0; while (element && (ignoreSearchSteps || steps <= opt_maxSearchSteps)) { if (matcher(element)) { return element; } element = element.parentNode; steps++; } // Reached the root of the DOM without a match return null; }; /** * Create an instance of a DOM helper with a new document object. * @param {Document=} opt_document Document object to associate with this * DOM helper. * @constructor */ goog.dom.DomHelper = function(opt_document) { /** * Reference to the document object to use * @type {!Document} * @private */ this.document_ = opt_document || goog.global.document || document; }; /** * Gets the dom helper object for the document where the element resides. * @param {Node=} opt_node If present, gets the DomHelper for this node. * @return {!goog.dom.DomHelper} The DomHelper. */ goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper; /** * Sets the document object. * @param {!Document} document Document object. */ goog.dom.DomHelper.prototype.setDocument = function(document) { this.document_ = document; }; /** * Gets the document object being used by the dom library. * @return {!Document} Document object. */ goog.dom.DomHelper.prototype.getDocument = function() { return this.document_; }; /** * Alias for {@code getElementById}. If a DOM node is passed in then we just * return that. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. */ goog.dom.DomHelper.prototype.getElement = function(element) { if (goog.isString(element)) { return this.document_.getElementById(element); } else { return element; } }; /** * Alias for {@code getElement}. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead. */ goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement; /** * Looks up elements by both tag and class name, using browser native functions * ({@code querySelectorAll}, {@code getElementsByTagName} or * {@code getElementsByClassName}) where possible. The returned array is a live * NodeList or a static list depending on the code path taken. * * @see goog.dom.query * * @param {?string=} opt_tag Element tag name or * for all tags. * @param {?string=} opt_class Optional class name. * @param {Document|Element=} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). */ goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) { return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag, opt_class, opt_el); }; /** * Returns an array of all the elements with the provided className. * @see {goog.dom.query} * @param {!string} className the name of the class to look for. * @param {Element|Document=} opt_el Optional element to look in. * @return { {length: number} } The items found with the class name provided. */ goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) { var doc = opt_el || this.document_; return goog.dom.getElementsByClass(className, doc); }; /** * Returns the first element we find matching the provided class name. * @see {goog.dom.query} * @param {!string} className the name of the class to look for. * @param {Element|Document=} opt_el Optional element to look in. * @return {Element} The first item found with the class name provided. */ goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) { var doc = opt_el || this.document_; return goog.dom.getElementByClass(className, doc); }; /** * Alias for {@code getElementsByTagNameAndClass}. * @deprecated Use DomHelper getElementsByTagNameAndClass. * @see goog.dom.query * * @param {?string=} opt_tag Element tag name. * @param {?string=} opt_class Optional class name. * @param {Element=} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). */ goog.dom.DomHelper.prototype.$$ = goog.dom.DomHelper.prototype.getElementsByTagNameAndClass; /** * Sets a number of properties on a node. * @param {Element} element DOM node to set properties on. * @param {Object} properties Hash of property:value pairs. */ goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties; /** * Gets the dimensions of the viewport. * @param {Window=} opt_window Optional window element to test. Defaults to * the window of the Dom Helper. * @return {!goog.math.Size} Object with values 'width' and 'height'. */ goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) { // TODO(user): This should not take an argument. That breaks the rule of a // a DomHelper representing a single frame/window/document. return goog.dom.getViewportSize(opt_window || this.getWindow()); }; /** * Calculates the height of the document. * * @return {number} The height of the document. */ goog.dom.DomHelper.prototype.getDocumentHeight = function() { return goog.dom.getDocumentHeight_(this.getWindow()); }; /** * Typedef for use with goog.dom.createDom and goog.dom.append. * @typedef {Object|string|Array|NodeList} */ goog.dom.Appendable; /** * Returns a dom node with a set of attributes. This function accepts varargs * for subsequent nodes to be added. Subsequent nodes will be added to the * first node as childNodes. * * So: * <code>createDom('div', null, createDom('p'), createDom('p'));</code> * would return a div with two child paragraphs * * An easy way to move all child nodes of an existing element to a new parent * element is: * <code>createDom('div', null, oldElement.childNodes);</code> * which will remove all child nodes from the old element and add them as * child nodes of the new DIV. * * @param {string} tagName Tag to create. * @param {Object|string=} opt_attributes If object, then a map of name-value * pairs for attributes. If a string, then this is the className of the new * element. * @param {...goog.dom.Appendable} var_args Further DOM nodes or * strings for text nodes. If one of the var_args is an array or * NodeList, its elements will be added as childNodes instead. * @return {!Element} Reference to a DOM node. */ goog.dom.DomHelper.prototype.createDom = function(tagName, opt_attributes, var_args) { return goog.dom.createDom_(this.document_, arguments); }; /** * Alias for {@code createDom}. * @param {string} tagName Tag to create. * @param {Object|string=} opt_attributes If object, then a map of name-value * pairs for attributes. If a string, then this is the className of the new * element. * @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for * text nodes. If one of the var_args is an array, its children will be * added as childNodes instead. * @return {!Element} Reference to a DOM node. * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead. */ goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom; /** * Creates a new element. * @param {string} name Tag name. * @return {!Element} The new element. */ goog.dom.DomHelper.prototype.createElement = function(name) { return this.document_.createElement(name); }; /** * Creates a new text node. * @param {string} content Content. * @return {!Text} The new text node. */ goog.dom.DomHelper.prototype.createTextNode = function(content) { return this.document_.createTextNode(content); }; /** * Create a table. * @param {number} rows The number of rows in the table. Must be >= 1. * @param {number} columns The number of columns in the table. Must be >= 1. * @param {boolean=} opt_fillWithNbsp If true, fills table entries with nsbps. * @return {!Element} The created table. */ goog.dom.DomHelper.prototype.createTable = function(rows, columns, opt_fillWithNbsp) { return goog.dom.createTable_(this.document_, rows, columns, !!opt_fillWithNbsp); }; /** * Converts an HTML string into a node or a document fragment. A single Node * is used if the {@code htmlString} only generates a single node. If the * {@code htmlString} generates multiple nodes then these are put inside a * {@code DocumentFragment}. * * @param {string} htmlString The HTML string to convert. * @return {!Node} The resulting node. */ goog.dom.DomHelper.prototype.htmlToDocumentFragment = function(htmlString) { return goog.dom.htmlToDocumentFragment_(this.document_, htmlString); }; /** * Returns the compatMode of the document. * @return {string} The result is either CSS1Compat or BackCompat. * @deprecated use goog.dom.DomHelper.prototype.isCss1CompatMode instead. */ goog.dom.DomHelper.prototype.getCompatMode = function() { return this.isCss1CompatMode() ? 'CSS1Compat' : 'BackCompat'; }; /** * Returns true if the browser is in "CSS1-compatible" (standards-compliant) * mode, false otherwise. * @return {boolean} True if in CSS1-compatible mode. */ goog.dom.DomHelper.prototype.isCss1CompatMode = function() { return goog.dom.isCss1CompatMode_(this.document_); }; /** * Gets the window object associated with the document. * @return {!Window} The window associated with the given document. */ goog.dom.DomHelper.prototype.getWindow = function() { return goog.dom.getWindow_(this.document_); }; /** * Gets the document scroll element. * @return {Element} Scrolling element. */ goog.dom.DomHelper.prototype.getDocumentScrollElement = function() { return goog.dom.getDocumentScrollElement_(this.document_); }; /** * Gets the document scroll distance as a coordinate object. * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'. */ goog.dom.DomHelper.prototype.getDocumentScroll = function() { return goog.dom.getDocumentScroll_(this.document_); }; /** * Appends a child to a node. * @param {Node} parent Parent. * @param {Node} child Child. */ goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild; /** * Appends a node with text or other nodes. * @param {!Node} parent The node to append nodes to. * @param {...goog.dom.Appendable} var_args The things to append to the node. * If this is a Node it is appended as is. * If this is a string then a text node is appended. * If this is an array like object then fields 0 to length - 1 are appended. */ goog.dom.DomHelper.prototype.append = goog.dom.append; /** * Removes all the child nodes on a DOM node. * @param {Node} node Node to remove children from. */ goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren; /** * Inserts a new node before an existing reference node (i.e., as the previous * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert before. */ goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore; /** * Inserts a new node after an existing reference node (i.e., as the next * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert after. */ goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter; /** * Removes a node from its parent. * @param {Node} node The node to remove. * @return {Node} The node removed if removed; else, null. */ goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode; /** * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no * parent. * @param {Node} newNode Node to insert. * @param {Node} oldNode Node to replace. */ goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode; /** * Flattens an element. That is, removes it and replace it with its children. * @param {Element} element The element to flatten. * @return {Element|undefined} The original element, detached from the document * tree, sans children, or undefined if the element was already not in the * document. */ goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement; /** * Returns the first child node that is an element. * @param {Node} node The node to get the first child element of. * @return {Element} The first child node of {@code node} that is an element. */ goog.dom.DomHelper.prototype.getFirstElementChild = goog.dom.getFirstElementChild; /** * Returns the last child node that is an element. * @param {Node} node The node to get the last child element of. * @return {Element} The last child node of {@code node} that is an element. */ goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild; /** * Returns the first next sibling that is an element. * @param {Node} node The node to get the next sibling element of. * @return {Element} The next sibling of {@code node} that is an element. */ goog.dom.DomHelper.prototype.getNextElementSibling = goog.dom.getNextElementSibling; /** * Returns the first previous sibling that is an element. * @param {Node} node The node to get the previous sibling element of. * @return {Element} The first previous sibling of {@code node} that is * an element. */ goog.dom.DomHelper.prototype.getPreviousElementSibling = goog.dom.getPreviousElementSibling; /** * Returns the next node in source order from the given node. * @param {Node} node The node. * @return {Node} The next node in the DOM tree, or null if this was the last * node. */ goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode; /** * Returns the previous node in source order from the given node. * @param {Node} node The node. * @return {Node} The previous node in the DOM tree, or null if this was the * first node. */ goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode; /** * Whether the object looks like a DOM node. * @param {*} obj The object being tested for node likeness. * @return {boolean} Whether the object looks like a DOM node. */ goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike; /** * Whether a node contains another node. * @param {Node} parent The node that should contain the other node. * @param {Node} descendant The node to test presence of. * @return {boolean} Whether the parent node contains the descendent node. */ goog.dom.DomHelper.prototype.contains = goog.dom.contains; /** * Returns the owner document for a node. * @param {Node} node The node to get the document for. * @return {!Document} The document owning the node. */ goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument; /** * Cross browser function for getting the document element of an iframe. * @param {HTMLIFrameElement|HTMLFrameElement} iframe Iframe element. * @return {!HTMLDocument} The frame content document. */ goog.dom.DomHelper.prototype.getFrameContentDocument = goog.dom.getFrameContentDocument; /** * Cross browser function for getting the window of a frame or iframe. * @param {HTMLIFrameElement|HTMLFrameElement} frame Frame element. * @return {Window} The window associated with the given frame. */ goog.dom.DomHelper.prototype.getFrameContentWindow = goog.dom.getFrameContentWindow; /** * Cross browser function for setting the text content of an element. * @param {Element} element The element to change the text content of. * @param {string} text The string that should replace the current element * content with. */ goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent; /** * Finds the first descendant node that matches the filter function. This does * a depth first search. * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {(Node, undefined)} The found node or undefined if none is found. */ goog.dom.DomHelper.prototype.findNode = goog.dom.findNode; /** * Finds all the descendant nodes that matches the filter function. This does a * depth first search. * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {Array.<Node>} The found nodes or an empty array if none are found. */ goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes; /** * Returns the text contents of the current node, without markup. New lines are * stripped and whitespace is collapsed, such that each character would be * visible. * * In browsers that support it, innerText is used. Other browsers attempt to * simulate it via node traversal. Line breaks are canonicalized in IE. * * @param {Node} node The node from which we are getting content. * @return {string} The text content. */ goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent; /** * Returns the text length of the text contained in a node, without markup. This * is equivalent to the selection length if the node was selected, or the number * of cursor movements to traverse the node. Images & BRs take one space. New * lines are ignored. * * @param {Node} node The node whose text content length is being calculated. * @return {number} The length of {@code node}'s text content. */ goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength; /** * Returns the text offset of a node relative to one of its ancestors. The text * length is the same as the length calculated by * {@code goog.dom.getNodeTextLength}. * * @param {Node} node The node whose offset is being calculated. * @param {Node=} opt_offsetParent Defaults to the node's owner document's body. * @return {number} The text offset. */ goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset; /** * Walks up the DOM hierarchy returning the first ancestor that has the passed * tag name and/or class name. If the passed element matches the specified * criteria, the element itself is returned. * @param {Node} element The DOM node to start with. * @param {?string=} opt_tag The tag name to match (or null/undefined to match * any node regardless of tag name). Must be uppercase (goog.dom.TagName). * @param {?string=} opt_class The class name to match (or null/undefined to * match any node regardless of class name). * @return {Node} The first ancestor that matches the passed criteria, or * null if none match. */ goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass = goog.dom.getAncestorByTagNameAndClass; /** * Walks up the DOM hierarchy returning the first ancestor that passes the * matcher function. * @param {Node} element The DOM node to start with. * @param {function(Node) : boolean} matcher A function that returns true if the * passed node matches the desired criteria. * @param {boolean=} opt_includeNode If true, the node itself is included in * the search (the first call to the matcher will pass startElement as * the node to test). * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the * dom. * @return {Node} DOM node that matched the matcher, or null if there was * no match. */ goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;
import React from 'react' export function createFixture(Definition, universe, startChannel) { return class FixtureWrapper extends React.Component { render() { return ( <Definition universe={universe} start={startChannel} {... this.props} /> ) } } }
/* * ! OpenUI5 * (c) Copyright 2009-2020 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.P13nColumnsItem. sap.ui.define([ './library', 'sap/ui/core/Item' ], function(library, Item) { "use strict"; /** * Constructor for a new P13nColumnsItem. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] initial settings for the new control * @class Type for <code>columnsItems</code> aggregation in <code>P13nColumnsPanel</code> control. * @extends sap.ui.core.Item * @version 1.84.11 * @constructor * @author SAP SE * @public * @since 1.26.0 * @alias sap.m.P13nColumnsItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var P13nColumnsItem = Item.extend("sap.m.P13nColumnsItem", /** @lends sap.m.P13nColumnsItem.prototype */ { metadata: { library: "sap.m", properties: { /** * This property contains the unique table column key * * @since 1.26.0 */ columnKey: { type: "string", group: "Misc" }, // don't set a default value /** * This property contains the index of a table column * * @since 1.26.0 */ index: { type: "int", group: "Appearance" }, // don't set a default value /** * This property decides whether a <code>P13nColumnsItem</code> is visible * * @since 1.26.0 */ visible: { type: "boolean", group: "Appearance" }, // don't set a default value /** * This property contains the with of a table column. * * @since 1.26.0 */ width: { type: "string", group: "Misc" }, // don't set a default value /** * This property contains the total flag of a table column. * * @since 1.26.0 */ total: { type: "boolean" } } } }); return P13nColumnsItem; });
import el from './dom.js'; import * as api from './data.js'; window.addEventListener('load', () => { const btnLoad = document.querySelector('#loadBooks'); btnLoad.addEventListener('click', displayBook); const tableBody = document.querySelector('table tbody'); const createBtn = document.querySelector('form > button'); const input = { title: document.querySelector('#title'), author: document.querySelector('#author'), isbn: document.querySelector('#isbn') } createBtn.addEventListener('click', createBook); async function createBook(ev) { ev.preventDefault(); if (validateInput(input) == false) { alert(`All fields are required!`); return; } const book = { title: input.title.value, author: input.author.value, isbn: input.isbn.value } try { toggleInput(true, ...Object.values(input), createBtn); const created = await api.createBook(book); tableBody.appendChild(renderBook(created)); Object.entries(input).forEach(([k, v]) => v.value = ''); } catch (err) { alert(err); } finally { toggleInput(false, ...Object.values(input), createBtn); } } function toggleInput(active, ...list) { list.forEach(e => { if (active) { e.setAttribute('disabled', true); } else { e.removeAttribute('disabled'); } }); } function validateInput(input) { let valid = true; Object.entries(input).forEach(([k, v]) => { if (v === undefined || v.value.length === 0) { v.classList.add('inputError'); valid = false; } else { v.classList.remove('inputError'); } }); return valid; } async function displayBook() { btnLoad.setAttribute('disabled', true); tableBody.innerHTML = '<tr><td colspan="4">Loading...</td><tr>'; const books = await api.getBooks(); tableBody.innerHTML = ''; books .sort((a, b) => a.author.localeCompare(b.author)) .forEach(b => tableBody.appendChild(renderBook(b))); btnLoad.removeAttribute('disabled'); } function renderBook(book) { const deleteBtn = el('button', 'Delete'); deleteBtn.addEventListener('click', deleteBook) const editBtn = el('button', 'Edit'); editBtn.addEventListener('click', toggleEditor) const element = el('tr', [ el('td', book.title), el('td', book.author), el('td', book.isbn), el('td', [ editBtn, deleteBtn ]) ]); function toggleEditor() { const confirmBtn = el('button', 'Save'); const cancelBtn = el('button', 'Cancel'); cancelBtn.addEventListener('click', () => { tableBody.replaceChild(element, editor); }); confirmBtn.addEventListener('click', async () => { if (validateInput(edit) == false) { alert(`All fields are required!`); return; } const editedBook = { objectId: book.objectId, title: edit.title.value, author: edit.author.value, isbn: edit.isbn.value } try { toggleInput(true, ...Object.values(edit), confirmBtn, cancelBtn); const updatedBook = await api.updateBook(editedBook); console.log(updatedBook); if (updatedBook.code === 1012) { throw new Error(`${updatedBook.message}: ${book.title}`); } tableBody.replaceChild(renderBook(updatedBook), editor); } catch (err) { alert(err.message); toggleInput(false, ...Object.values(edit), confirmBtn, cancelBtn); } }); const edit = { title: el('input', null, { type: 'text', value: book.title }), author: el('input', null, { type: 'text', value: book.author }), isbn: el('input', null, { type: 'text', value: book.isbn }), } const editor = el('tr', [ el('td', edit.title), el('td', edit.author), el('td', edit.isbn), el('td', [ confirmBtn, cancelBtn ]) ]); tableBody.replaceChild(editor, element); } async function deleteBook() { try { deleteBtn.setAttribute('disabled', true); deleteBtn.disable = true; deleteBtn.textContent = 'Please wait...' let result = await api.deleteBook(book.objectId); if (result.code === 1014) { throw new Error(`${result.message} The book "${book.title}" is protected.`); } element.remove(); } catch (err) { deleteBtn.removeAttribute('disabled'); deleteBtn.textContent = 'Delete' alert(err); } } return element; } })
export default function prep(stats, grad) { if (!stats) return grad; return stats.map((y, i) => y / (grad[i] || 1)); }
const inquirer = require("inquirer"); const fs = require("fs"); const generateMarkdown = require("./generateMarkdown.js"); require('dotenv').config(); const questions = [ { type: 'input', name: 'username', message: "GitHub Username: ", validate: function(name){ return name !== ''; } }, { type: 'input', name: 'repo', message: "Repo: ", validate: function(name){ return name !== ''; } }, { type: 'input', name: 'title', message: "Title: ", validate: function(name){ return name !== ''; } }, { type: 'editor', name: 'description', message: "Description: " }, { type: 'list', name: 'table', message: "Table of Contents? ", choices: ['Yes', 'No'] }, { type: 'editor', name: 'installation', message: "Installation: " }, { type: 'editor', name: 'usage', message: "Usage: " }, { type: 'editor', name: 'tests', message: 'Tests: ' }, { type: 'editor', name: 'questions', message: 'Questions? Who to contact?: ' }, { type: 'editor', name: 'contributing', message: "Contributing. How can others help?: " }, { type: 'input', name: 'contributors', message: "Contributors (Github Usernames, comma separated): " }, { type: 'editor', name: 'license', message: 'License: ' } ]; function writeToFile(dirName, data) { fs.mkdirSync(`${process.cwd()}/readmes/${dirName}`, {recursive: true}, (error) => { if(error){console.log(error)} }); fs.writeFileSync(`${process.cwd()}/readmes/${dirName}/README.md`, data); console.log(`\nREADME is complete.\nIt is located: ${process.cwd()}/readmes/${dirName}/README.md`); } async function askQuestions(questions){ inquirer.prompt(questions).then(async (answers) => { let marked = await generateMarkdown(answers); writeToFile(`${answers.repo}`, marked); }); } function init() { askQuestions(questions); } init();
import React,{PropTypes} from 'react' ; import {Link,IndexLink} from 'react-router' ; const NavLink = (props)=>{ const isIndex = props.isIndex || false; return isIndex?<IndexLink activeClassName = "nav-active" {...props}/> : <Link activeClassName = "nav-active" {...props}/> }; export default NavLink ;
const i18n = require('../i18n'); test('i18n', () => { expect(i18n).toHaveProperty('zh-cn'); expect(i18n).toHaveProperty('en'); });
import React, { Component } from 'react' import Monster from './Monster' import bride from '../images/bride.jpg' import nosferatu from '../images/nosferatu.jpg' import wolfman from '../images/wolfman.jpg' export class NotableMonsters extends Component { render() { const monsters = [ { name: 'Wolfman', url: wolfman }, { name: 'Nosferatu', url: nosferatu }, { name: 'Bride of Frankenstein', url: bride }, ] return ( <section class="notable-monsters"> <header>Notable Others</header> <ul> {monsters.map(mon => { return <Monster monsterName={mon.name} imageUrl={mon.url} /> })} {/* <Monster monsterName="Wolfman" imageUrl={wolfman} /> <Monster monsterName="Nosferatu" imageUrl={nosferatu} /> <Monster imageUrl={bride} monsterName="Bride of Frankenstein" /> */} </ul> </section> ) } } export default NotableMonsters
/** * @class Ext.sparkline.Base */ Ext.define('Ext.override.sparkline.Base', { override: 'Ext.sparkline.Base', statics: { constructTip: function() { return new Ext.tip['ToolTip']({ id: 'sparklines-tooltip', showDelay: 0, dismissDelay: 0, hideDelay: 400 }); } }, onMouseMove: function (e) { this.getSharedTooltip().triggerEvent = e; this.callParent([e]); }, onMouseLeave: function(e) { this.callParent([e]); this.getSharedTooltip().target = null; }, privates: { hideTip: function() { var tip = this.getSharedTooltip(); tip.target = null; tip.hide(); }, showTip: function() { var tip = this.getSharedTooltip(); tip.target = this.el; tip.onTargetOver(tip.triggerEvent); } } });
import React, { Component } from 'react'; import * as PropTypes from 'prop-types'; import { Formik, Form, Field } from 'formik'; import { withStyles } from '@material-ui/core/styles'; import Drawer from '@material-ui/core/Drawer'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import Fab from '@material-ui/core/Fab'; import { Add, Close } from '@material-ui/icons'; import { compose, pluck, sortBy, toLower, prop, pipe, map, assoc, filter, includes, dissoc, toPairs, fromPairs, propOr, } from 'ramda'; import * as Yup from 'yup'; import graphql from 'babel-plugin-relay/macro'; import { ConnectionHandler } from 'relay-runtime'; import DialogTitle from '@material-ui/core/DialogTitle'; import DialogContent from '@material-ui/core/DialogContent'; import Dialog from '@material-ui/core/Dialog'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import inject18n from '../../../../components/i18n'; import { commitMutation, QueryRenderer } from '../../../../relay/environment'; import TextField from '../../../../components/TextField'; import SwitchField from '../../../../components/SwitchField'; import CreatedByField from '../../common/form/CreatedByField'; import ObjectLabelField from '../../common/form/ObjectLabelField'; import ObjectMarkingField from '../../common/form/ObjectMarkingField'; import { stixCyberObservablesLinesAttributesQuery, stixCyberObservablesLinesSubTypesQuery, } from './StixCyberObservablesLines'; import DatePickerField from '../../../../components/DatePickerField'; import { parse } from '../../../../utils/Time'; import MarkDownField from '../../../../components/MarkDownField'; export const ignoredAttributes = [ 'internal_id', 'standard_id', 'x_opencti_description', 'x_opencti_stix_ids', 'entity_type', 'spec_version', 'extensions', 'created', 'modified', 'created_at', 'x_opencti_score', 'updated_at', 'observable_value', ]; export const dateAttributes = [ 'ctime', 'mtime', 'atime', 'attribute_date', 'validity_not_before', 'validity_not_after', 'start', 'end', 'created_time', 'modified_time', 'account_created', 'account_expires', 'credential_last_changed', 'account_first_login', 'account_last_login', ]; export const numberAttributes = [ 'number', 'src_port', 'dst_port', 'src_byte_count', 'dst_byte_count', 'src_packets', 'dst_packets', 'pid', 'size', 'number_of_subkeys', 'subject_public_key_exponent', ]; export const booleanAttributes = [ 'is_self_signed', 'is_multipart', 'is_hidden', 'is_active', 'is_disabled', 'is_privileged', 'is_service_account', 'can_escalate_privs', ]; export const multipleAttributes = ['x_opencti_additional_names']; const styles = (theme) => ({ drawerPaper: { minHeight: '100vh', width: '50%', position: 'fixed', backgroundColor: theme.palette.navAlt.background, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), padding: 0, }, createButton: { position: 'fixed', bottom: 30, right: 280, transition: theme.transitions.create('right', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }, createButtonExports: { position: 'fixed', bottom: 30, right: 590, transition: theme.transitions.create('right', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.leavingScreen, }), }, createButtonContextual: { position: 'fixed', bottom: 30, right: 30, zIndex: 2000, }, createButtonContextualSpeedDial: { position: 'fixed', bottom: 90, right: 30, zIndex: 2000, }, buttons: { marginTop: 20, textAlign: 'right', }, button: { marginLeft: theme.spacing(2), }, header: { backgroundColor: theme.palette.navAlt.backgroundHeader, padding: '20px 20px 20px 60px', }, closeButton: { position: 'absolute', top: 12, left: 5, }, importButton: { position: 'absolute', top: 15, right: 20, }, container: { padding: '10px 20px 20px 20px', }, }); const stixCyberObservableMutation = graphql` mutation StixCyberObservableCreationMutation( $type: String! $x_opencti_score: Int $x_opencti_description: String $createIndicator: Boolean $createdBy: String $objectMarking: [String] $objectLabel: [String] $externalReferences: [String] $AutonomousSystem: AutonomousSystemAddInput $Directory: DirectoryAddInput $DomainName: DomainNameAddInput $EmailAddr: EmailAddrAddInput $EmailMessage: EmailMessageAddInput $EmailMimePartType: EmailMimePartTypeAddInput $Artifact: ArtifactAddInput $StixFile: StixFileAddInput $X509Certificate: X509CertificateAddInput $IPv4Addr: IPv4AddrAddInput $IPv6Addr: IPv6AddrAddInput $MacAddr: MacAddrAddInput $Mutex: MutexAddInput $NetworkTraffic: NetworkTrafficAddInput $Process: ProcessAddInput $Software: SoftwareAddInput $Url: UrlAddInput $UserAccount: UserAccountAddInput $WindowsRegistryKey: WindowsRegistryKeyAddInput $WindowsRegistryValueType: WindowsRegistryValueTypeAddInput $X509V3ExtensionsType: X509V3ExtensionsTypeAddInput $XOpenCTICryptographicKey: XOpenCTICryptographicKeyAddInput $XOpenCTICryptocurrencyWallet: XOpenCTICryptocurrencyWalletAddInput $XOpenCTIText: XOpenCTITextAddInput $XOpenCTIUserAgent: XOpenCTIUserAgentAddInput ) { stixCyberObservableAdd( type: $type x_opencti_score: $x_opencti_score x_opencti_description: $x_opencti_description createIndicator: $createIndicator createdBy: $createdBy objectMarking: $objectMarking objectLabel: $objectLabel externalReferences: $externalReferences AutonomousSystem: $AutonomousSystem Directory: $Directory DomainName: $DomainName EmailAddr: $EmailAddr EmailMessage: $EmailMessage EmailMimePartType: $EmailMimePartType Artifact: $Artifact StixFile: $StixFile X509Certificate: $X509Certificate IPv4Addr: $IPv4Addr IPv6Addr: $IPv6Addr MacAddr: $MacAddr Mutex: $Mutex NetworkTraffic: $NetworkTraffic Process: $Process Software: $Software Url: $Url UserAccount: $UserAccount WindowsRegistryKey: $WindowsRegistryKey WindowsRegistryValueType: $WindowsRegistryValueType X509V3ExtensionsType: $X509V3ExtensionsType XOpenCTICryptographicKey: $XOpenCTICryptographicKey XOpenCTICryptocurrencyWallet: $XOpenCTICryptocurrencyWallet XOpenCTIText: $XOpenCTIText XOpenCTIUserAgent: $XOpenCTIUserAgent ) { id entity_type observable_value x_opencti_description created_at createdBy { ... on Identity { id name entity_type } } objectMarking { edges { node { id definition } } } objectLabel { edges { node { id value color } } } } } `; const stixCyberObservableValidation = (t) => Yup.object().shape({ x_opencti_score: Yup.number().required(t('This field is required')), x_opencti_description: Yup.string(), createIndicator: Yup.boolean(), }); const sharedUpdater = ( store, userId, paginationKey, paginationOptions, newEdge, ) => { const userProxy = store.get(userId); const conn = ConnectionHandler.getConnection( userProxy, paginationKey, paginationOptions, ); ConnectionHandler.insertEdgeBefore(conn, newEdge); }; class StixCyberObservableCreation extends Component { constructor(props) { super(props); this.state = { open: false, type: null }; } handleOpen() { this.setState({ open: true }); } handleClose() { this.setState({ open: false, type: null }); } selectType(type) { this.setState({ type }); } onSubmit(values, { setSubmitting, resetForm }) { let adaptedValues = values; // Potential dicts if ( adaptedValues.hashes_MD5 || adaptedValues['hashes_SHA-1'] || adaptedValues['hashes_SHA-256'] || adaptedValues['hashes_SHA-512'] ) { adaptedValues.hashes = []; if (adaptedValues.hashes_MD5.length > 0) { adaptedValues.hashes.push({ algorithm: 'MD5', hash: adaptedValues.hashes_MD5, }); } if (adaptedValues['hashes_SHA-1'].length > 0) { adaptedValues.hashes.push({ algorithm: 'SHA-1', hash: adaptedValues['hashes_SHA-1'], }); } if (adaptedValues['hashes_SHA-256'].length > 0) { adaptedValues.hashes.push({ algorithm: 'SHA-256', hash: adaptedValues['hashes_SHA-256'], }); } if (adaptedValues['hashes_SHA-512'].length > 0) { adaptedValues.hashes.push({ algorithm: 'SHA-512', hash: adaptedValues['hashes_SHA-512'], }); } } adaptedValues = pipe( dissoc('x_opencti_description'), dissoc('x_opencti_score'), dissoc('createdBy'), dissoc('objectMarking'), dissoc('objectLabel'), dissoc('createIndicator'), dissoc('hashes_MD5'), dissoc('hashes_SHA-1'), dissoc('hashes_SHA-256'), dissoc('hashes_SHA-512'), toPairs, map((n) => (includes(n[0], dateAttributes) ? [n[0], n[1] ? parse(n[1]).format() : null] : n)), map((n) => (includes(n[0], numberAttributes) ? [n[0], n[1] ? parseInt(n[1], 10) : null] : n)), map((n) => (includes(n[0], multipleAttributes) ? [n[0], n[1] ? n[1].split(',') : null] : n)), fromPairs, )(adaptedValues); const finalValues = { type: this.state.type, x_opencti_description: values.x_opencti_description.length > 0 ? values.x_opencti_description : null, x_opencti_score: parseInt(values.x_opencti_score, 10), createdBy: propOr(null, 'value', values.createdBy), objectMarking: pluck('value', values.objectMarking), objectLabel: pluck('value', values.objectLabel), createIndicator: values.createIndicator, [this.state.type.replace(/(?:^|-|_)(\w)/g, (matches, letter) => letter.toUpperCase())]: adaptedValues, }; commitMutation({ mutation: stixCyberObservableMutation, variables: finalValues, updater: (store) => { const payload = store.getRootField('stixCyberObservableAdd'); const newEdge = payload.setLinkedRecord(payload, 'node'); // Creation of the pagination container. const container = store.getRoot(); sharedUpdater( store, container.getDataID(), this.props.paginationKey, this.props.paginationOptions, newEdge, ); }, setSubmitting, onCompleted: () => { setSubmitting(false); resetForm(); this.handleClose(); }, }); } onReset() { this.handleClose(); } renderList() { const { t } = this.props; return ( <QueryRenderer query={stixCyberObservablesLinesSubTypesQuery} variables={{ type: 'Stix-Cyber-Observable' }} render={({ props }) => { if (props && props.subTypes) { const subTypesEdges = props.subTypes.edges; const sortByLabel = sortBy(compose(toLower, prop('tlabel'))); const translatedOrderedList = pipe( map((n) => n.node), map((n) => assoc('tlabel', t(`entity_${n.label}`), n)), sortByLabel, )(subTypesEdges); return ( <List> {translatedOrderedList.map((subType) => ( <ListItem key={subType.label} divider={true} button={true} dense={true} onClick={this.selectType.bind(this, subType.label)} > <ListItemText primary={subType.tlabel} /> </ListItem> ))} </List> ); } return <div />; }} /> ); } renderForm() { const { type } = this.state; const { classes, t } = this.props; return ( <QueryRenderer query={stixCyberObservablesLinesAttributesQuery} variables={{ elementType: type }} render={({ props }) => { if (props && props.attributes) { const initialValues = { x_opencti_description: '', x_opencti_score: 50, createdBy: '', objectMarking: [], objectLabel: [], createIndicator: false, }; const attributes = pipe( map((n) => n.node), filter( (n) => !includes(n.value, ignoredAttributes) && !n.value.startsWith('i_'), ), )(props.attributes.edges); for (const attribute of attributes) { if (includes(attribute.value, dateAttributes)) { initialValues[attribute.value] = null; } else if (includes(attribute.value, booleanAttributes)) { initialValues[attribute.value] = false; } else if (attribute.value === 'hashes') { initialValues.hashes_MD5 = ''; initialValues['hashes_SHA-1'] = ''; initialValues['hashes_SHA-256'] = ''; initialValues['hashes_SHA-512'] = ''; } else { initialValues[attribute.value] = ''; } } return ( <Formik initialValues={initialValues} validationSchema={stixCyberObservableValidation(t)} onSubmit={this.onSubmit.bind(this)} onReset={this.onReset.bind(this)} > {({ submitForm, handleReset, isSubmitting, setFieldValue, values, }) => ( <Form style={{ margin: '20px 0 20px 0' }}> <div> <Field component={TextField} name="x_opencti_score" label={t('Score')} fullWidth={true} type="number" /> <Field component={MarkDownField} name="x_opencti_description" label={t('Description')} fullWidth={true} multiline={true} rows="4" style={{ marginTop: 20 }} /> {attributes.map((attribute) => { if (attribute.value === 'hashes') { return ( <div key={attribute.value}> <Field component={TextField} key={attribute.value} name="hashes_MD5" label="hash_md5" fullWidth={true} style={{ marginTop: 20 }} /> <Field component={TextField} key={attribute.value} name="hashes_SHA-1" label="hash_sha-1" fullWidth={true} style={{ marginTop: 20 }} /> <Field component={TextField} key={attribute.value} name="hashes_SHA-256" label="hash_sha-256" fullWidth={true} style={{ marginTop: 20 }} /> </div> ); } if (includes(attribute.value, dateAttributes)) { return ( <Field component={DatePickerField} key={attribute.value} name={attribute.value} label={attribute.value} invalidDateMessage={t( 'The value must be a date (YYYY-MM-DD)', )} fullWidth={true} style={{ marginTop: 20 }} /> ); } if (includes(attribute.value, numberAttributes)) { return ( <Field component={TextField} key={attribute.value} name={attribute.value} label={attribute.value} fullWidth={true} type="number" style={{ marginTop: 20 }} /> ); } if (includes(attribute.value, booleanAttributes)) { return ( <Field component={SwitchField} type="checkbox" key={attribute.value} name={attribute.value} label={attribute.value} containerstyle={{ marginTop: 20 }} /> ); } return ( <Field component={TextField} key={attribute.value} name={attribute.value} label={attribute.value} fullWidth={true} style={{ marginTop: 20 }} /> ); })} </div> <CreatedByField name="createdBy" style={{ marginTop: 20, width: '100%' }} setFieldValue={setFieldValue} /> <ObjectLabelField name="objectLabel" style={{ marginTop: 20, width: '100%' }} setFieldValue={setFieldValue} values={values.objectLabel} /> <ObjectMarkingField name="objectMarking" style={{ marginTop: 20, width: '100%' }} /> <Field component={SwitchField} type="checkbox" name="createIndicator" label={t('Create an indicator from this observable')} containerstyle={{ marginTop: 20 }} /> <div className={classes.buttons}> <Button variant="contained" onClick={handleReset} disabled={isSubmitting} classes={{ root: classes.button }} > {t('Cancel')} </Button> <Button variant="contained" color="primary" onClick={submitForm} disabled={isSubmitting} classes={{ root: classes.button }} > {t('Create')} </Button> </div> </Form> )} </Formik> ); } return <div />; }} /> ); } renderClassic() { const { type } = this.state; const { t, classes, openExports } = this.props; return ( <div> <Fab onClick={this.handleOpen.bind(this)} color="secondary" aria-label="Add" className={ openExports ? classes.createButtonExports : classes.createButton } > <Add /> </Fab> <Drawer open={this.state.open} anchor="right" classes={{ paper: classes.drawerPaper }} onClose={this.handleClose.bind(this)} > <div className={classes.header}> <IconButton aria-label="Close" className={classes.closeButton} onClick={this.handleClose.bind(this)} > <Close fontSize="small" /> </IconButton> <Typography variant="h6">{t('Create an observable')}</Typography> </div> <div className={classes.container}> {!type ? this.renderList() : this.renderForm()} </div> </Drawer> </div> ); } renderContextual() { const { type } = this.state; const { t, classes, display } = this.props; return ( <div style={{ display: display ? 'block' : 'none' }}> <Fab onClick={this.handleOpen.bind(this)} color="secondary" aria-label="Add" className={classes.createButtonContextual} > <Add /> </Fab> <Dialog open={this.state.open} onClose={this.handleClose.bind(this)} fullWidth={true} > <DialogTitle>{t('Create an observable')}</DialogTitle> <DialogContent style={{ paddingTop: 0 }}> {!type ? this.renderList() : this.renderForm()} </DialogContent> </Dialog> </div> ); } render() { const { contextual } = this.props; if (contextual) { return this.renderContextual(); } return this.renderClassic(); } } StixCyberObservableCreation.propTypes = { paginationKey: PropTypes.string, paginationOptions: PropTypes.object, classes: PropTypes.object, theme: PropTypes.object, t: PropTypes.func, contextual: PropTypes.bool, display: PropTypes.bool, inputValue: PropTypes.string, openExports: PropTypes.bool, }; export default compose( inject18n, withStyles(styles, { withTheme: true }), )(StixCyberObservableCreation);
import { Injectable } from '@angular/core'; import { AdalService } from 'adal-angular4'; import { StorageService } from './storage.service'; import { NswhpAuthService } from '../nswhpauth.service'; import * as i0 from "@angular/core"; import * as i1 from "adal-angular4/index"; import * as i2 from "./storage.service"; import * as i3 from "../nswhpauth.service"; export class AadService { constructor(adalService, storage, nswhpAuthService) { this.adalService = adalService; this.storage = storage; this.nswhpAuthService = nswhpAuthService; this.adalConfigs = this.nswhpAuthService.nswhpAuthOptions.adalConfig; } /** Takes an integer and returns true if it is in a valid range for the config array */ isValidAdalConfigIndex(index) { return index !== null && index >= 0 && index < this.adalConfigs.length; } /** * initialises the Adal service with the config specified by configIndex * @param configIndex - Determines which config will be selected, used as an index on `this.adalConfigs` * @example * if (aadService.isValidAdalConfigIndex(index)) { * intialiseAdalServiceWithConfig(index); * } */ initialiseAdalServiceWithConfig(configIndex) { if (!this.isValidAdalConfigIndex(configIndex)) { throw new Error('ConfigIndex out of bounds. Consider checking with the isValidAdalConfigIndex helper method before calling.'); } console.debug(`Initialising adal4Service with config index: ` + configIndex); const config = this.adalConfigs[configIndex]; console.debug(`Adal config: `); console.debug('- tenant: ' + config.tenant); console.debug('- clientId: ' + config.clientId); this.adalService.init(this.adalConfigs[configIndex]); console.debug('>>>>>>> Actual config after init:'); console.debug(this.adalService.config); } /** * Each AD token contains its tenant. Given a token, the tenant can be * extracted and passed into getConfigIndexByTenant which will return the * config index for that tenant */ getConfigIndexByTenant(tenant) { if (tenant === this.adalConfigs[0].tenant) { return 0; } throw Error(`Unknown tenant passed in: ${tenant}`); } handleWindowCallbackFromAzureLogin() { this.adalService.handleWindowCallback(); } loginToAzure() { // Whenever the user gets a new AAD token we clear any existing VIP token // TODO: Why do we need to clear the VIP token, does this really make sense? this.storage.clearVipToken(); this.storage.clearTransactionId(); this.adalService.login(); } logoutOfAzure() { // Delete the user's Azure instance selection when they logout this.storage.clearAzureInstance(); this.adalService.logOut(); } retrieveAadToken() { return this.adalService.userInfo.token; } } AadService.AZURE_AD_INSTANCE = 0; AadService.AZURE_B2C_INSTANCE = 1; // Not used because the app only supports Health AD Logins. AadService.ɵprov = i0.ɵɵdefineInjectable({ factory: function AadService_Factory() { return new AadService(i0.ɵɵinject(i1.AdalService), i0.ɵɵinject(i2.StorageService), i0.ɵɵinject(i3.NswhpAuthService)); }, token: AadService, providedIn: "root" }); AadService.decorators = [ { type: Injectable, args: [{ providedIn: 'root' },] } ]; AadService.ctorParameters = () => [ { type: AdalService }, { type: StorageService }, { type: NswhpAuthService } ]; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYWFkLnNlcnZpY2UuanMiLCJzb3VyY2VSb290IjoiQzovUHJvamVjdHMvbnN3aHBhdXRoLW1vZHVsZS9wcm9qZWN0cy9uc3docGF1dGgvc3JjLyIsInNvdXJjZXMiOlsibGliL3NlcnZpY2VzL2FhZC5zZXJ2aWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxVQUFVLEVBQUUsTUFBTSxlQUFlLENBQUM7QUFDM0MsT0FBTyxFQUFFLFdBQVcsRUFBRSxNQUFNLGVBQWUsQ0FBQztBQUM1QyxPQUFPLEVBQUUsY0FBYyxFQUFFLE1BQU0sbUJBQW1CLENBQUM7QUFDbkQsT0FBTyxFQUFFLGdCQUFnQixFQUFFLE1BQU0sc0JBQXNCLENBQUM7Ozs7O0FBS3hELE1BQU0sT0FBTyxVQUFVO0lBY3JCLFlBQ1UsV0FBd0IsRUFDeEIsT0FBdUIsRUFDdkIsZ0JBQWtDO1FBRmxDLGdCQUFXLEdBQVgsV0FBVyxDQUFhO1FBQ3hCLFlBQU8sR0FBUCxPQUFPLENBQWdCO1FBQ3ZCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBa0I7UUFFMUMsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLENBQUMsZ0JBQWdCLENBQUMsZ0JBQWdCLENBQUMsVUFBVSxDQUFDO0lBQ3ZFLENBQUM7SUFYRCx1RkFBdUY7SUFDaEYsc0JBQXNCLENBQUMsS0FBYTtRQUN6QyxPQUFPLEtBQUssS0FBSyxJQUFJLElBQUksS0FBSyxJQUFJLENBQUMsSUFBSSxLQUFLLEdBQUcsSUFBSSxDQUFDLFdBQVcsQ0FBQyxNQUFNLENBQUM7SUFDekUsQ0FBQztJQVVEOzs7Ozs7O09BT0c7SUFDSSwrQkFBK0IsQ0FBQyxXQUFtQjtRQUN4RCxJQUFJLENBQUMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLFdBQVcsQ0FBQyxFQUFFO1lBQzdDLE1BQU0sSUFBSSxLQUFLLENBQUMsNEdBQTRHLENBQUMsQ0FBQztTQUMvSDtRQUVELE9BQU8sQ0FBQyxLQUFLLENBQUMsK0NBQStDLEdBQUcsV0FBVyxDQUFDLENBQUM7UUFFN0UsTUFBTSxNQUFNLEdBQUcsSUFBSSxDQUFDLFdBQVcsQ0FBQyxXQUFXLENBQUMsQ0FBQztRQUM3QyxPQUFPLENBQUMsS0FBSyxDQUFDLGVBQWUsQ0FBQyxDQUFDO1FBQy9CLE9BQU8sQ0FBQyxLQUFLLENBQUMsWUFBWSxHQUFHLE1BQU0sQ0FBQyxNQUFNLENBQUMsQ0FBQztRQUM1QyxPQUFPLENBQUMsS0FBSyxDQUFDLGNBQWMsR0FBRyxNQUFNLENBQUMsUUFBUSxDQUFDLENBQUM7UUFFaEQsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxXQUFXLENBQUMsQ0FBQyxDQUFDO1FBRXJELE9BQU8sQ0FBQyxLQUFLLENBQUMsbUNBQW1DLENBQUMsQ0FBQztRQUNuRCxPQUFPLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxXQUFXLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDekMsQ0FBQztJQUVEOzs7O09BSUc7SUFDSSxzQkFBc0IsQ0FBQyxNQUFjO1FBQzFDLElBQUksTUFBTSxLQUFLLElBQUksQ0FBQyxXQUFXLENBQUMsQ0FBQyxDQUFDLENBQUMsTUFBTSxFQUFFO1lBQ3pDLE9BQU8sQ0FBQyxDQUFDO1NBQ1Y7UUFFRCxNQUFNLEtBQUssQ0FBQyw2QkFBNkIsTUFBTSxFQUFFLENBQUMsQ0FBQztJQUNyRCxDQUFDO0lBRU0sa0NBQWtDO1FBQ3ZDLElBQUksQ0FBQyxXQUFXLENBQUMsb0JBQW9CLEVBQUUsQ0FBQztJQUMxQyxDQUFDO0lBRU0sWUFBWTtRQUNqQix5RUFBeUU7UUFDekUsNEVBQTRFO1FBQzVFLElBQUksQ0FBQyxPQUFPLENBQUMsYUFBYSxFQUFFLENBQUM7UUFDN0IsSUFBSSxDQUFDLE9BQU8sQ0FBQyxrQkFBa0IsRUFBRSxDQUFDO1FBRWxDLElBQUksQ0FBQyxXQUFXLENBQUMsS0FBSyxFQUFFLENBQUM7SUFDM0IsQ0FBQztJQUVNLGFBQWE7UUFDbEIsOERBQThEO1FBQzlELElBQUksQ0FBQyxPQUFPLENBQUMsa0JBQWtCLEVBQUUsQ0FBQztRQUVsQyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sRUFBRSxDQUFDO0lBQzVCLENBQUM7SUFFTSxnQkFBZ0I7UUFDckIsT0FBTyxJQUFJLENBQUMsV0FBVyxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUM7SUFDekMsQ0FBQzs7QUFsRmUsNEJBQWlCLEdBQUcsQ0FBQyxDQUFDO0FBQ3RCLDZCQUFrQixHQUFHLENBQUMsQ0FBQyxDQUFDLDJEQUEyRDs7O1lBTHBHLFVBQVUsU0FBQztnQkFDVixVQUFVLEVBQUUsTUFBTTthQUNuQjs7O1lBTlEsV0FBVztZQUNYLGNBQWM7WUFDZCxnQkFBZ0IiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBJbmplY3RhYmxlIH0gZnJvbSAnQGFuZ3VsYXIvY29yZSc7XHJcbmltcG9ydCB7IEFkYWxTZXJ2aWNlIH0gZnJvbSAnYWRhbC1hbmd1bGFyNCc7XHJcbmltcG9ydCB7IFN0b3JhZ2VTZXJ2aWNlIH0gZnJvbSAnLi9zdG9yYWdlLnNlcnZpY2UnO1xyXG5pbXBvcnQgeyBOc3docEF1dGhTZXJ2aWNlIH0gZnJvbSAnLi4vbnN3aHBhdXRoLnNlcnZpY2UnO1xyXG5cclxuQEluamVjdGFibGUoe1xyXG4gIHByb3ZpZGVkSW46ICdyb290J1xyXG59KVxyXG5leHBvcnQgY2xhc3MgQWFkU2VydmljZSB7XHJcbiAgc3RhdGljIHJlYWRvbmx5IEFaVVJFX0FEX0lOU1RBTkNFID0gMDtcclxuICBzdGF0aWMgcmVhZG9ubHkgQVpVUkVfQjJDX0lOU1RBTkNFID0gMTsgLy8gTm90IHVzZWQgYmVjYXVzZSB0aGUgYXBwIG9ubHkgc3VwcG9ydHMgSGVhbHRoIEFEIExvZ2lucy5cclxuXHJcbiAgLyoqIFRoZSBpbmRleCBvZiB0aGUgYWRhbENvbmZpZyB0byB1c2Ugc2V0IGJ5IGNsaWNraW5nIHRoZSBsb2dpbiBidXR0b25zIG9yIHRocm91Z2ggdGhlIHJvdXRlIHBhcmFtZXRlciAqL1xyXG4gIHB1YmxpYyBjb25maWdJbmRleDogbnVtYmVyO1xyXG4gIC8vIEFkYWwgY29uZmlnc1xyXG4gIHByaXZhdGUgYWRhbENvbmZpZ3M6IGFkYWwuQ29uZmlnW107XHJcblxyXG4gIC8qKiBUYWtlcyBhbiBpbnRlZ2VyIGFuZCByZXR1cm5zIHRydWUgaWYgaXQgaXMgaW4gYSB2YWxpZCByYW5nZSBmb3IgdGhlIGNvbmZpZyBhcnJheSAqL1xyXG4gIHB1YmxpYyBpc1ZhbGlkQWRhbENvbmZpZ0luZGV4KGluZGV4OiBudW1iZXIpIHtcclxuICAgIHJldHVybiBpbmRleCAhPT0gbnVsbCAmJiBpbmRleCA+PSAwICYmIGluZGV4IDwgdGhpcy5hZGFsQ29uZmlncy5sZW5ndGg7XHJcbiAgfVxyXG5cclxuICBjb25zdHJ1Y3RvcihcclxuICAgIHByaXZhdGUgYWRhbFNlcnZpY2U6IEFkYWxTZXJ2aWNlLFxyXG4gICAgcHJpdmF0ZSBzdG9yYWdlOiBTdG9yYWdlU2VydmljZSxcclxuICAgIHByaXZhdGUgbnN3aHBBdXRoU2VydmljZTogTnN3aHBBdXRoU2VydmljZVxyXG4gICkge1xyXG4gICAgdGhpcy5hZGFsQ29uZmlncyA9IHRoaXMubnN3aHBBdXRoU2VydmljZS5uc3docEF1dGhPcHRpb25zLmFkYWxDb25maWc7XHJcbiAgfVxyXG5cclxuICAvKipcclxuICAgKiBpbml0aWFsaXNlcyB0aGUgQWRhbCBzZXJ2aWNlIHdpdGggdGhlIGNvbmZpZyBzcGVjaWZpZWQgYnkgY29uZmlnSW5kZXhcclxuICAgKiBAcGFyYW0gY29uZmlnSW5kZXggLSBEZXRlcm1pbmVzIHdoaWNoIGNvbmZpZyB3aWxsIGJlIHNlbGVjdGVkLCB1c2VkIGFzIGFuIGluZGV4IG9uIGB0aGlzLmFkYWxDb25maWdzYFxyXG4gICAqIEBleGFtcGxlXHJcbiAgICogaWYgKGFhZFNlcnZpY2UuaXNWYWxpZEFkYWxDb25maWdJbmRleChpbmRleCkpIHtcclxuICAgKiAgICAgaW50aWFsaXNlQWRhbFNlcnZpY2VXaXRoQ29uZmlnKGluZGV4KTtcclxuICAgKiB9XHJcbiAgICovXHJcbiAgcHVibGljIGluaXRpYWxpc2VBZGFsU2VydmljZVdpdGhDb25maWcoY29uZmlnSW5kZXg6IG51bWJlcikge1xyXG4gICAgaWYgKCF0aGlzLmlzVmFsaWRBZGFsQ29uZmlnSW5kZXgoY29uZmlnSW5kZXgpKSB7XHJcbiAgICAgIHRocm93IG5ldyBFcnJvcignQ29uZmlnSW5kZXggb3V0IG9mIGJvdW5kcy4gQ29uc2lkZXIgY2hlY2tpbmcgd2l0aCB0aGUgaXNWYWxpZEFkYWxDb25maWdJbmRleCBoZWxwZXIgbWV0aG9kIGJlZm9yZSBjYWxsaW5nLicpO1xyXG4gICAgfVxyXG5cclxuICAgIGNvbnNvbGUuZGVidWcoYEluaXRpYWxpc2luZyBhZGFsNFNlcnZpY2Ugd2l0aCBjb25maWcgaW5kZXg6IGAgKyBjb25maWdJbmRleCk7XHJcblxyXG4gICAgY29uc3QgY29uZmlnID0gdGhpcy5hZGFsQ29uZmlnc1tjb25maWdJbmRleF07XHJcbiAgICBjb25zb2xlLmRlYnVnKGBBZGFsIGNvbmZpZzogYCk7XHJcbiAgICBjb25zb2xlLmRlYnVnKCctIHRlbmFudDogJyArIGNvbmZpZy50ZW5hbnQpO1xyXG4gICAgY29uc29sZS5kZWJ1ZygnLSBjbGllbnRJZDogJyArIGNvbmZpZy5jbGllbnRJZCk7XHJcblxyXG4gICAgdGhpcy5hZGFsU2VydmljZS5pbml0KHRoaXMuYWRhbENvbmZpZ3NbY29uZmlnSW5kZXhdKTtcclxuXHJcbiAgICBjb25zb2xlLmRlYnVnKCc+Pj4+Pj4+IEFjdHVhbCBjb25maWcgYWZ0ZXIgaW5pdDonKTtcclxuICAgIGNvbnNvbGUuZGVidWcodGhpcy5hZGFsU2VydmljZS5jb25maWcpO1xyXG4gIH1cclxuXHJcbiAgLyoqXHJcbiAgICogRWFjaCBBRCB0b2tlbiBjb250YWlucyBpdHMgdGVuYW50LiBHaXZlbiBhIHRva2VuLCB0aGUgdGVuYW50IGNhbiBiZVxyXG4gICAqIGV4dHJhY3RlZCBhbmQgcGFzc2VkIGludG8gZ2V0Q29uZmlnSW5kZXhCeVRlbmFudCB3aGljaCB3aWxsIHJldHVybiB0aGVcclxuICAgKiBjb25maWcgaW5kZXggZm9yIHRoYXQgdGVuYW50XHJcbiAgICovXHJcbiAgcHVibGljIGdldENvbmZpZ0luZGV4QnlUZW5hbnQodGVuYW50OiBzdHJpbmcpIHtcclxuICAgIGlmICh0ZW5hbnQgPT09IHRoaXMuYWRhbENvbmZpZ3NbMF0udGVuYW50KSB7XHJcbiAgICAgIHJldHVybiAwO1xyXG4gICAgfVxyXG5cclxuICAgIHRocm93IEVycm9yKGBVbmtub3duIHRlbmFudCBwYXNzZWQgaW46ICR7dGVuYW50fWApO1xyXG4gIH1cclxuXHJcbiAgcHVibGljIGhhbmRsZVdpbmRvd0NhbGxiYWNrRnJvbUF6dXJlTG9naW4oKSB7XHJcbiAgICB0aGlzLmFkYWxTZXJ2aWNlLmhhbmRsZVdpbmRvd0NhbGxiYWNrKCk7XHJcbiAgfVxyXG5cclxuICBwdWJsaWMgbG9naW5Ub0F6dXJlKCkge1xyXG4gICAgLy8gV2hlbmV2ZXIgdGhlIHVzZXIgZ2V0cyBhIG5ldyBBQUQgdG9rZW4gd2UgY2xlYXIgYW55IGV4aXN0aW5nIFZJUCB0b2tlblxyXG4gICAgLy8gVE9ETzogV2h5IGRvIHdlIG5lZWQgdG8gY2xlYXIgdGhlIFZJUCB0b2tlbiwgZG9lcyB0aGlzIHJlYWxseSBtYWtlIHNlbnNlP1xyXG4gICAgdGhpcy5zdG9yYWdlLmNsZWFyVmlwVG9rZW4oKTtcclxuICAgIHRoaXMuc3RvcmFnZS5jbGVhclRyYW5zYWN0aW9uSWQoKTtcclxuXHJcbiAgICB0aGlzLmFkYWxTZXJ2aWNlLmxvZ2luKCk7XHJcbiAgfVxyXG5cclxuICBwdWJsaWMgbG9nb3V0T2ZBenVyZSgpIHtcclxuICAgIC8vIERlbGV0ZSB0aGUgdXNlcidzIEF6dXJlIGluc3RhbmNlIHNlbGVjdGlvbiB3aGVuIHRoZXkgbG9nb3V0XHJcbiAgICB0aGlzLnN0b3JhZ2UuY2xlYXJBenVyZUluc3RhbmNlKCk7XHJcblxyXG4gICAgdGhpcy5hZGFsU2VydmljZS5sb2dPdXQoKTtcclxuICB9XHJcblxyXG4gIHB1YmxpYyByZXRyaWV2ZUFhZFRva2VuKCk6IHN0cmluZyB7XHJcbiAgICByZXR1cm4gdGhpcy5hZGFsU2VydmljZS51c2VySW5mby50b2tlbjtcclxuICB9XHJcbn1cclxuIl19
/** * This widget shows a list of folders under a given parent. * Initialize this with a "parentType" and "parentId" value, which will * be passed to the folder GET endpoint. */ girder.views.FolderListWidget = Backbone.View.extend({ events: { 'click a.g-folder-list-link': function (event) { var cid = $(event.currentTarget).attr('g-folder-cid'); this.trigger('g:folderClicked', this.collection.get(cid)); }, 'click a.g-show-more-folders': function () { this.collection.fetchNextPage(); } }, initialize: function (settings) { this.checked = []; this.collection = new girder.collections.FolderCollection(); this.collection.append = true; // Append, don't replace pages this.collection.on('g:changed', function () { this.render(); this.trigger('g:changed'); }, this).fetch({ parentType: settings.parentType || 'folder', parentId: settings.parentId }); }, render: function () { this.checked = []; this.$el.html(jade.templates.folderList({ folders: this.collection.models, hasMore: this.collection.hasNextPage() })); var view = this; this.$('.g-list-checkbox').unbind('change').change(function () { var cid = $(this).attr('g-folder-cid'); if (this.checked) { view.checked.push(cid); } else { var idx = view.checked.indexOf(cid); if (idx !== -1) { view.checked.splice(idx, 1); } } view.trigger('g:checkboxesChanged'); }); return this; }, /** * Insert a folder into the collection and re-render it. */ insertFolder: function (folder) { this.collection.add(folder); this.trigger('g:changed'); this.render(); }, /** * Set all folder checkboxes to a certain checked state. The event * g:checkboxesChanged is triggered once after checking/unchecking everything. * @param {bool} checked The checked state. */ checkAll: function (checked) { this.$('.g-list-checkbox').prop('checked', checked); this.checked = []; if (checked) { _.each(this.collection.models, function (model) { this.checked.push(model.cid); }, this); } this.trigger('g:checkboxesChanged'); } });
import React from 'react'; import PropTypes from 'prop-types'; const ProductName = ({ className, style, name }) => ( <div className={className} style={style}> {name} </div> ); ProductName.propTypes = { style: PropTypes.object, className: PropTypes.string, name: PropTypes.string.isRequired }; ProductName.defaultProps = { style: {}, className: '' }; export default ProductName;
!function(){"use strict";var e,v={},g={};function n(e){var a=g[e];if(void 0!==a)return a.exports;var t=g[e]={id:e,loaded:!1,exports:{}};return v[e].call(t.exports,t,t.exports,n),t.loaded=!0,t.exports}n.m=v,e=[],n.O=function(a,t,u,f){if(!t){var r=1/0;for(i=0;i<e.length;i++){t=e[i][0],u=e[i][1],f=e[i][2];for(var s=!0,o=0;o<t.length;o++)(!1&f||r>=f)&&Object.keys(n.O).every(function(b){return n.O[b](t[o])})?t.splice(o--,1):(s=!1,f<r&&(r=f));if(s){e.splice(i--,1);var l=u();void 0!==l&&(a=l)}}return a}f=f||0;for(var i=e.length;i>0&&e[i-1][2]>f;i--)e[i]=e[i-1];e[i]=[t,u,f]},n.n=function(e){var a=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(a,{a:a}),a},n.d=function(e,a){for(var t in a)n.o(a,t)&&!n.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:a[t]})},n.f={},n.e=function(e){return Promise.all(Object.keys(n.f).reduce(function(a,t){return n.f[t](e,a),a},[]))},n.u=function(e){return e+".56192c94389c54848b7b.js"},n.miniCssF=function(e){return"styles.00529db46248ef918aa8.css"},n.o=function(e,a){return Object.prototype.hasOwnProperty.call(e,a)},function(){var e={},a="bip39-ng-app:";n.l=function(t,u,f,i){if(e[t])e[t].push(u);else{var r,s;if(void 0!==f)for(var o=document.getElementsByTagName("script"),l=0;l<o.length;l++){var c=o[l];if(c.getAttribute("src")==t||c.getAttribute("data-webpack")==a+f){r=c;break}}r||(s=!0,(r=document.createElement("script")).charset="utf-8",r.timeout=120,n.nc&&r.setAttribute("nonce",n.nc),r.setAttribute("data-webpack",a+f),r.src=n.tu(t)),e[t]=[u];var d=function(_,b){r.onerror=r.onload=null,clearTimeout(p);var h=e[t];if(delete e[t],r.parentNode&&r.parentNode.removeChild(r),h&&h.forEach(function(m){return m(b)}),_)return _(b)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:r}),12e4);r.onerror=d.bind(null,r.onerror),r.onload=d.bind(null,r.onload),s&&document.head.appendChild(r)}}}(),n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=function(e){return e.paths=[],e.children||(e.children=[]),e},function(){var e;n.tu=function(a){return void 0===e&&(e={createScriptURL:function(t){return t}},"undefined"!=typeof trustedTypes&&trustedTypes.createPolicy&&(e=trustedTypes.createPolicy("angular#bundler",e))),e.createScriptURL(a)}}(),n.p="",function(){var e={666:0};n.f.j=function(u,f){var i=n.o(e,u)?e[u]:void 0;if(0!==i)if(i)f.push(i[2]);else if(666!=u){var r=new Promise(function(c,d){i=e[u]=[c,d]});f.push(i[2]=r);var s=n.p+n.u(u),o=new Error;n.l(s,function(c){if(n.o(e,u)&&(0!==(i=e[u])&&(e[u]=void 0),i)){var d=c&&("load"===c.type?"missing":c.type),p=c&&c.target&&c.target.src;o.message="Loading chunk "+u+" failed.\n("+d+": "+p+")",o.name="ChunkLoadError",o.type=d,o.request=p,i[1](o)}},"chunk-"+u,u)}else e[u]=0},n.O.j=function(u){return 0===e[u]};var a=function(u,f){var o,l,i=f[0],r=f[1],s=f[2],c=0;for(o in r)n.o(r,o)&&(n.m[o]=r[o]);if(s)var d=s(n);for(u&&u(f);c<i.length;c++)l=i[c],n.o(e,l)&&e[l]&&e[l][0](),e[i[c]]=0;return n.O(d)},t=self.webpackChunkbip39_ng_app=self.webpackChunkbip39_ng_app||[];t.forEach(a.bind(null,0)),t.push=a.bind(null,t.push.bind(t))}()}();
import blueThemegirl from '../assets/svg/about/blueTheme-girl.svg' import blueThemeboy from '../assets/svg/about/blueTheme-boy.svg' import bwThemeboy from '../assets/svg/about/bwTheme-boy.svg' import bwThemegirl from '../assets/svg/about/bwTheme-girl.svg' import greenThemeboy from '../assets/svg/about/greenTheme-boy.svg' import greenThemegirl from '../assets/svg/about/greenTheme-girl.svg' import orangeThemeboy from '../assets/svg/about/orangeTheme-boy.svg' import orangeThemegirl from '../assets/svg/about/orangeTheme-girl.svg' import pinkThemeboy from '../assets/svg/about/pinkTheme-boy.svg' import pinkThemegirl from '../assets/svg/about/pinkTheme-girl.svg' import purpleThemeboy from '../assets/svg/about/purpleTheme-boy.svg' import purpleThemegirl from '../assets/svg/about/purpleTheme-girl.svg' import redThemeboy from '../assets/svg/about/redTheme-boy.svg' import redThemegirl from '../assets/svg/about/redTheme-girl.svg' import yellowThemeboy from '../assets/svg/about/yellowTheme-boy.svg' import yellowThemegirl from '../assets/svg/about/yellowTheme-girl.svg' import eduBlue from '../assets/svg/education/eduBlue.svg' import eduGreen from '../assets/svg/education/eduGreen.svg' import eduBlack from '../assets/svg/education/eduBlack.svg' import eduOrange from '../assets/svg/education/eduOrange.svg' import eduPink from '../assets/svg/education/eduPink.svg' import eduPurple from '../assets/svg/education/eduPurple.svg' import eduRed from '../assets/svg/education/eduRed.svg' import eduYellow from '../assets/svg/education/eduYellow.svg' import expBlue from '../assets/svg/experience/expBlue.svg' import expGreen from '../assets/svg/experience/expGreen.svg' import expBlack from '../assets/svg/experience/expBlack.svg' import expOrange from '../assets/svg/experience/expOrange.svg' import expPink from '../assets/svg/experience/expPink.svg' import expPurple from '../assets/svg/experience/expPurple.svg' import expRed from '../assets/svg/experience/expRed.svg' import expYellow from '../assets/svg/experience/expYellow.svg' import contactsBlue from '../assets/svg/contacts/contactsBlue.svg' import contactsGreen from '../assets/svg/contacts/contactsGreen.svg' import contactsBlack from '../assets/svg/contacts/contactsBlack.svg' import contactsOrange from '../assets/svg/contacts/contactsOrange.svg' import contactsPink from '../assets/svg/contacts/contactsPink.svg' import contactsPurple from '../assets/svg/contacts/contactsPurple.svg' import contactsRed from '../assets/svg/contacts/contactsRed.svg' import contactsYellow from '../assets/svg/contacts/contactsYellow.svg' import developer from '../assets/svg/about/developer.svg' import dev from '../assets/svg/about/dev.svg' import learning from '../assets/svg/about/learning.svg' import contact from '../assets/svg/about/contact.svg' export { blueThemegirl, blueThemeboy, bwThemeboy, bwThemegirl, greenThemeboy, greenThemegirl, orangeThemeboy, orangeThemegirl, pinkThemeboy, pinkThemegirl, purpleThemeboy, purpleThemegirl, redThemeboy, redThemegirl, yellowThemeboy,yellowThemegirl,eduBlue,eduBlack,eduGreen,eduOrange,eduPink,eduPurple,eduRed,eduYellow, expBlue,expBlack,expGreen,expOrange,expPink,expPurple,expRed,expYellow,contactsBlue,contactsBlack, contactsGreen,contactsOrange,contactsPink,contactsPurple,contactsRed,contactsYellow,developer,dev,learning,contact }
const boom = require('@hapi/boom') function validatorHandler(schema, property) { return (req, res, next) => { const data = req[property]; const { error } = schema.validate(data, { abortEarly: false }); if (error) { next(boom.badRequest(error)); } next(); } } module.exports = validatorHandler;
import { Router } from 'express'; import * as NoteController from '../controllers/note.controller'; const router = new Router(); // Add a new Note router.route('/notes').post(NoteController.addNote); // Delete a Note router.route('/notes/:noteId').delete(NoteController.deleteNote); // Edit note router.route('/notes/:noteId').put(NoteController.editNote); export default router;
export default function merge(data) { const obj = {} data.forEach((el, index) => { for (const key in el) { if (!obj[key]) { obj[key] = [] } obj[key].push(data[index][key]) } }) return obj }
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-a6de055c"],{"333d":function(e,t,a){"use strict";var i=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{staticClass:"pagination-container",class:{hidden:e.hidden}},[a("el-pagination",e._b({attrs:{background:e.background,"current-page":e.currentPage,"page-size":e.pageSize,layout:e.layout,"page-sizes":e.pageSizes,total:e.total},on:{"update:currentPage":function(t){e.currentPage=t},"update:current-page":function(t){e.currentPage=t},"update:pageSize":function(t){e.pageSize=t},"update:page-size":function(t){e.pageSize=t},"size-change":e.handleSizeChange,"current-change":e.handleCurrentChange}},"el-pagination",e.$attrs,!1))],1)},n=[];a("c5f6");Math.easeInOutQuad=function(e,t,a,i){return e/=i/2,e<1?a/2*e*e+t:(e--,-a/2*(e*(e-2)-1)+t)};var l=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)}}();function o(e){document.documentElement.scrollTop=e,document.body.parentNode.scrollTop=e,document.body.scrollTop=e}function r(){return document.documentElement.scrollTop||document.body.parentNode.scrollTop||document.body.scrollTop}function s(e,t,a){var i=r(),n=e-i,s=20,c=0;t="undefined"===typeof t?500:t;var u=function e(){c+=s;var r=Math.easeInOutQuad(c,i,n,t);o(r),c<t?l(e):a&&"function"===typeof a&&a()};u()}var c={name:"Pagination",props:{total:{required:!0,type:Number},page:{type:Number,default:1},limit:{type:Number,default:20},pageSizes:{type:Array,default:function(){return[10,20,30,50]}},layout:{type:String,default:"total, sizes, prev, pager, next, jumper"},background:{type:Boolean,default:!0},autoScroll:{type:Boolean,default:!0},hidden:{type:Boolean,default:!1}},computed:{currentPage:{get:function(){return this.page},set:function(e){this.$emit("update:page",e)}},pageSize:{get:function(){return this.limit},set:function(e){this.$emit("update:limit",e)}}},methods:{handleSizeChange:function(e){this.$emit("pagination",{page:this.currentPage,limit:e}),this.autoScroll&&s(0,800)},handleCurrentChange:function(e){this.$emit("pagination",{page:e,limit:this.pageSize}),this.autoScroll&&s(0,800)}}},u=c,d=(a("e498"),a("2877")),p=Object(d["a"])(u,i,n,!1,null,"6af373ef",null);t["a"]=p.exports},"3a8d":function(e,t,a){"use strict";a.r(t);var i=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{staticClass:"app-container"},[a("div",{staticClass:"filter-container"},[a("el-input",{staticClass:"filter-item",staticStyle:{width:"200px"},attrs:{clearable:"",placeholder:"业务类型"},model:{value:e.listQuery.category,callback:function(t){e.$set(e.listQuery,"category",t)},expression:"listQuery.category"}}),e._v(" "),a("el-input",{staticClass:"filter-item",staticStyle:{width:"200px"},attrs:{clearable:"",placeholder:"业务标识"},model:{value:e.listQuery.bizNo,callback:function(t){e.$set(e.listQuery,"bizNo",t)},expression:"listQuery.bizNo"}}),e._v(" "),a("el-input",{staticClass:"filter-item",staticStyle:{width:"200px"},attrs:{clearable:"",placeholder:"操作人"},model:{value:e.listQuery.operator,callback:function(t){e.$set(e.listQuery,"operator",t)},expression:"listQuery.operator"}}),e._v(" "),a("el-button",{directives:[{name:"waves",rawName:"v-waves"}],staticClass:"filter-item",attrs:{type:"primary",icon:"el-icon-search"},on:{click:e.fetchData}},[e._v("\n 搜索\n ")])],1),e._v(" "),a("el-table",{directives:[{name:"loading",rawName:"v-loading",value:e.listLoading,expression:"listLoading"}],attrs:{data:e.list,"element-loading-text":"Loading",stripe:"",fit:"","highlight-current-row":""}},[a("el-table-column",{attrs:{label:"序号",fixed:"",width:"95"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v(e._s(t.$index+1))]}}])}),e._v(" "),a("el-table-column",{attrs:{label:"业务类型",width:"200"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v(e._s(t.row.category))]}}])}),e._v(" "),a("el-table-column",{attrs:{label:"业务标识",width:"340"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v(e._s(t.row.bizNo))]}}])}),e._v(" "),a("el-table-column",{attrs:{label:"日志内容",width:"500"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v(e._s(e._f("ellipsis")(t.row.action)))]}}])}),e._v(" "),a("el-table-column",{attrs:{label:"操作人",width:"140"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v(e._s(t.row.operator)+"\n ")]}}])}),e._v(" "),a("el-table-column",{attrs:{label:"创建时间",width:"160"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v(e._s(t.row.createTime))]}}])}),e._v(" "),a("el-table-column",{attrs:{label:"操作",fixed:"right",width:"120","class-name":"small-padding fixed-width"},scopedSlots:e._u([{key:"default",fn:function(t){var i=t.row;return[a("el-button",{attrs:{type:"text",size:"small"},on:{click:function(t){return e.handleUpdate(i)}}},[e._v("\n 查看\n ")])]}}])})],1),e._v(" "),a("pagination",{directives:[{name:"show",rawName:"v-show",value:e.total>0,expression:"total>0"}],attrs:{total:e.total,page:e.listQuery.current,limit:e.listQuery.size},on:{"update:page":function(t){return e.$set(e.listQuery,"current",t)},"update:limit":function(t){return e.$set(e.listQuery,"size",t)},pagination:e.fetchData}}),e._v(" "),a("el-dialog",{attrs:{title:e.textMap[e.dialogStatus],visible:e.dialogFormVisible,width:"800px"},on:{"update:visible":function(t){e.dialogFormVisible=t}}},[a("el-form",{ref:"dataForm",attrs:{model:e.temp,"label-position":"left","label-width":"100px"}},[a("el-form-item",{attrs:{label:"业务类型",prop:"category"}},[a("el-input",{staticStyle:{width:"40%"},attrs:{disabled:!0,placeholder:"业务类型"},model:{value:e.temp.category,callback:function(t){e.$set(e.temp,"category",t)},expression:"temp.category"}})],1),e._v(" "),a("el-form-item",{attrs:{label:"业务标识",prop:"bizNo"}},[a("el-input",{staticStyle:{width:"40%"},attrs:{disabled:!0,placeholder:"业务标识"},model:{value:e.temp.bizNo,callback:function(t){e.$set(e.temp,"bizNo",t)},expression:"temp.bizNo"}})],1),e._v(" "),a("el-form-item",{attrs:{label:"操作人",prop:"operator"}},[a("el-input",{staticStyle:{width:"40%"},attrs:{disabled:!0,placeholder:"操作人"},model:{value:e.temp.operator,callback:function(t){e.$set(e.temp,"operator",t)},expression:"temp.operator"}})],1),e._v(" "),a("el-form-item",{attrs:{label:"创建时间",prop:"createTime"}},[a("el-input",{staticStyle:{width:"40%"},attrs:{disabled:!0,placeholder:"创建时间"},model:{value:e.temp.createTime,callback:function(t){e.$set(e.temp,"createTime",t)},expression:"temp.createTime"}})],1),e._v(" "),a("el-form-item",{attrs:{label:"日志内容",prop:"action"}},[a("el-input",{staticStyle:{width:"60%"},attrs:{disabled:!0,autosize:{minRows:4,maxRows:10},type:"textarea",placeholder:"日志内容"},model:{value:e.temp.action,callback:function(t){e.$set(e.temp,"action",t)},expression:"temp.action"}})],1)],1)],1),e._v(" "),a("el-dialog",{attrs:{visible:e.dialogPluginVisible,title:"Reading statistics"},on:{"update:visible":function(t){e.dialogPluginVisible=t}}},[a("el-table",{staticStyle:{width:"100%"},attrs:{data:e.pluginData,border:"",fit:"","highlight-current-row":""}},[a("el-table-column",{attrs:{prop:"key",label:"Channel"}}),e._v(" "),a("el-table-column",{attrs:{prop:"pv",label:"Pv"}})],1),e._v(" "),a("span",{staticClass:"dialog-footer",attrs:{slot:"footer"},slot:"footer"},[a("el-button",{attrs:{type:"primary"},on:{click:function(t){e.dialogPvVisible=!1}}},[e._v("Confirm")])],1)],1)],1)},n=[],l=a("b775");function o(e){return Object(l["a"])({url:"/hippo4j/v1/cs/log/query/page",method:"post",data:e})}var r=a("6724"),s=a("333d"),c={name:"JobProject",components:{Pagination:s["a"]},directives:{waves:r["a"]},filters:{statusFilter:function(e){var t={published:"success",draft:"gray",deleted:"danger"};return t[e]},ellipsis:function(e){return e?e.length>100?e.slice(0,100)+"...":e:""}},data:function(){return{list:null,listLoading:!0,total:0,listQuery:{current:1,size:10,tenantId:""},pluginTypeOptions:["reader","writer"],dialogPluginVisible:!1,pluginData:[],dialogFormVisible:!1,dialogStatus:"",textMap:{update:"Info",create:"Create"},temp:{id:void 0,tenantId:"",tenantName:"",owner:"",tenantDesc:""},visible:!0}},created:function(){this.fetchData()},methods:{fetchData:function(){var e=this;this.listLoading=!0,o(this.listQuery).then((function(t){var a=t.records,i=t.total;e.total=i,e.list=a,e.listLoading=!1}))},resetTemp:function(){this.temp={id:void 0,tenantName:"",tenantDesc:""}},handleCreate:function(){var e=this;this.resetTemp(),this.dialogStatus="create",this.dialogFormVisible=!0,this.$nextTick((function(){e.$refs["dataForm"].clearValidate()}))},createData:function(){var e=this;this.$refs["dataForm"].validate((function(t){t&&jobProjectApi.created(e.temp).then((function(){e.fetchData(),e.dialogFormVisible=!1,e.$notify({title:"Success",message:"Created Successfully",type:"success",duration:2e3})}))}))},handleUpdate:function(e){var t=this;this.temp=Object.assign({},e),this.dialogStatus="update",this.dialogFormVisible=!0,this.$nextTick((function(){t.$refs["dataForm"].clearValidate()}))},updateData:function(){var e=this;this.$refs["dataForm"].validate((function(t){if(t){var a=Object.assign({},e.temp);jobProjectApi.updated(a).then((function(){e.fetchData(),e.dialogFormVisible=!1,e.$notify({title:"Success",message:"Update Successfully",type:"success",duration:2e3})}))}}))},handleDelete:function(e){var t=this;console.log("删除"),jobProjectApi.deleted(e.tenantId).then((function(e){t.fetchData(),t.$notify({title:"Success",message:"Delete Successfully",type:"success",duration:2e3})}))}}},u=c,d=a("2877"),p=Object(d["a"])(u,i,n,!1,null,null,null);t["default"]=p.exports},6724:function(e,t,a){"use strict";a("8d41");var i="@@wavesContext";function n(e,t){function a(a){var i=Object.assign({},t.value),n=Object.assign({ele:e,type:"hit",color:"rgba(0, 0, 0, 0.15)"},i),l=n.ele;if(l){l.style.position="relative",l.style.overflow="hidden";var o=l.getBoundingClientRect(),r=l.querySelector(".waves-ripple");switch(r?r.className="waves-ripple":(r=document.createElement("span"),r.className="waves-ripple",r.style.height=r.style.width=Math.max(o.width,o.height)+"px",l.appendChild(r)),n.type){case"center":r.style.top=o.height/2-r.offsetHeight/2+"px",r.style.left=o.width/2-r.offsetWidth/2+"px";break;default:r.style.top=(a.pageY-o.top-r.offsetHeight/2-document.documentElement.scrollTop||document.body.scrollTop)+"px",r.style.left=(a.pageX-o.left-r.offsetWidth/2-document.documentElement.scrollLeft||document.body.scrollLeft)+"px"}return r.style.backgroundColor=n.color,r.className="waves-ripple z-active",!1}}return e[i]?e[i].removeHandle=a:e[i]={removeHandle:a},a}var l={bind:function(e,t){e.addEventListener("click",n(e,t),!1)},update:function(e,t){e.removeEventListener("click",e[i].removeHandle,!1),e.addEventListener("click",n(e,t),!1)},unbind:function(e){e.removeEventListener("click",e[i].removeHandle,!1),e[i]=null,delete e[i]}},o=function(e){e.directive("waves",l)};window.Vue&&(window.waves=l,Vue.use(o)),l.install=o;t["a"]=l},7456:function(e,t,a){},"8d41":function(e,t,a){},e498:function(e,t,a){"use strict";a("7456")}}]);
const USERS = require('../proxies/users'); const i18n = require('../i18n'); const chunk = (input, size) => { return input.reduce((arr, item, idx) => { return idx % size === 0 ? [...arr, [item]] : [...arr.slice(0, -1), [...arr.slice(-1)[0], item]]; }, []); }; exports.replyKeyboard = async (ctx, next) => { const kbs = Object.keys(i18n).map((i) => { return { text: i, callback_data: `CHANGE_LANG_${i}_${ctx.state.chat.id}` }; }); await ctx.telegram.sendMessage( ctx.chat.id, i18n[ctx.state.lang]['CHOOSE_LANG'], { parse_mode: 'HTML', disable_web_page_preview: true, reply_markup: { inline_keyboard: chunk(kbs, 5) } } ); await next(); }; exports.changeLangCallback = async (ctx, next) => { const cb = ctx.callbackQuery; const data = cb.data.split('_'); const lang = data[data.length - 2]; const id = data[data.length - 1]; await USERS.setLangById(id, lang); ctx.telegram.answerCbQuery(cb.id, i18n[lang]['SET_LANG_TO'] + ' ' + lang); await ctx.telegram.deleteMessage(cb.message.chat.id, cb.message.message_id); await next(); };
// Set new default font family and font color to mimic Bootstrap's default styling Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif'; Chart.defaults.global.defaultFontColor = '#292b2c'; // Bar Chart Example $(function () { var questions = ['Question 1', 'Question 2', 'Question 3', 'Question 4', 'Question 5']; var i = 0; var ctx = document.getElementById("systemBarChart"); var myLineChart = new Chart(ctx, { type: 'bar', data: { labels: questions, datasets: [{ label: "Score", backgroundColor: "rgba(2,117,216,1)", borderColor: "rgba(2,117,216,1)", data: feedbackObject, }], }, options: { scales: { xAxes: [{ time: { unit: 'month' }, gridLines: { display: false }, ticks: { maxTicksLimit: 12 } }], yAxes: [{ ticks: { min: 0, max: 5, maxTicksLimit: 5 }, gridLines: { display: true } }], }, legend: { display: false } } }); var ctx = document.getElementById("serviceBarChart"); var myLineChart = new Chart(ctx, { type: 'bar', data: { labels: questions, datasets: [{ label: "Score", backgroundColor: "rgba(2,117,216,1)", borderColor: "rgba(2,117,216,1)", data: feedbackObject2, }], }, options: { scales: { xAxes: [{ time: { unit: 'month' }, gridLines: { display: false }, ticks: { maxTicksLimit: 12 } }], yAxes: [{ ticks: { min: 0, max: 5, maxTicksLimit: 5 }, gridLines: { display: true } }], }, legend: { display: false } } }); });
/* Template Name: Landrick - Saas & Software Landing Page Template Author: Shreethemes E-mail: shreethemes@gmail.com Version: 1.0.0 Created: August 2019 File Description: Main JS file of the template */ /****************************/ /* INDEX */ /*=========================== * 01. Loader * * 02. Menu * * 03. Sticky Menu * * 03. Back to top * ===========================*/ ! function($) { "use strict"; // Loader $(window).on('load', function() { $('#status').fadeOut(); $('#preloader').delay(350).fadeOut('slow'); $('body').delay(350).css({ 'overflow': 'visible' }); }); // Menu $('.navbar-toggle').on('click', function (event) { $(this).toggleClass('open'); $('#navigation').slideToggle(400); }); $('.navigation-menu>li').slice(-1).addClass('last-elements'); $('.menu-arrow,.submenu-arrow').on('click', function (e) { if ($(window).width() < 992) { e.preventDefault(); $(this).parent('li').toggleClass('open').find('.submenu:first').toggleClass('open'); } }); $(".navigation-menu a").each(function () { if (this.href == window.location.href) { $(this).parent().addClass("active"); $(this).parent().parent().parent().addClass("active"); $(this).parent().parent().parent().parent().parent().addClass("active"); } }); // Clickable Menu $(".has-submenu a").click(function() { if(window.innerWidth < 992){ if($(this).parent().hasClass('open')){ $(this).siblings('.submenu').removeClass('open'); $(this).parent().removeClass('open'); } else { $(this).siblings('.submenu').addClass('open'); $(this).parent().addClass('open'); } } }); $('.mouse-down').on('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top - 0 }, 1500, 'easeInOutExpo'); event.preventDefault(); }); //Sticky $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 50) { $(".sticky").addClass("nav-sticky"); } else { $(".sticky").removeClass("nav-sticky"); } }); // Back to top $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('.back-to-top').fadeIn(); } else { $('.back-to-top').fadeOut(); } }); $('.back-to-top').click(function(){ $("html, body").animate({ scrollTop: 0 }, 3000); return false; }); //Tooltip $(function () { $('[data-toggle="tooltip"]').tooltip() }); //Popover $(function () { $('[data-toggle="popover"]').popover() }); // AOS.init({ // easing: 'ease-in-out-sine', // duration: 1000 // }); }(jQuery)
/** * @license AngularJS v1.3.6 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * # ngCookies * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * * <div doc-module-components="ngCookies"></div> * * See {@link ngCookies.$cookies `$cookies`} and * {@link ngCookies.$cookieStore `$cookieStore`} for usage. */ angular.module('ngCookies', ['ng']). /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from this object, new * cookies are created/deleted at the end of current $eval. * The object's properties can only be strings. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * angular.module('cookiesExample', ['ngCookies']) * .controller('ExampleController', ['$cookies', function($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.myFavorite; * // Setting a cookie * $cookies.myFavorite = 'oatmeal'; * }]); * ``` */ factory('$cookies', ['$rootScope', '$browser', function($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were * stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for (name in cookies) { value = cookies[name]; if (!angular.isString(value)) { value = '' + value; cookies[name] = value; } if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated) { updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc service * @name $cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * angular.module('cookieStoreExample', ['ngCookies']) * .controller('ExampleController', ['$cookieStore', function($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie * var favoriteCookie = $cookieStore.get('myFavorite'); * // Removing a cookie * $cookieStore.remove('myFavorite'); * }]); * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name $cookieStore#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { var value = $cookies[key]; return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookieStore#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name $cookieStore#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
import React from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import styled, { createGlobalStyle } from "styled-components" import Header from "./layouts/Header" import Footer from "./layouts/Footer" const GlobalStyle = createGlobalStyle` html { font-family: sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; margin: 0; padding: 0; background-color: black; } body { margin: 0; padding: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background-image: url('https://c1.wallpaperflare.com/preview/231/148/943/soccer-playing-field-stadium.jpg'); background-position: right center; background-repeat: no-repeat; background-size: cover; background-attachment: fixed; } ` const StyledLayout = styled.main` height: 100%; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: space-between; `; // const StyledCore = styled.div` // width: 90%; // padding: 1rem; // `; const Layout = ({ children }) => { const data = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title } } } `) return ( <StyledLayout> <GlobalStyle /> <Header siteTitle={data.site.siteMetadata.title} /> {children} <Footer /> </StyledLayout> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
import { Behavior } from '../../../core/eventBus/Behavior'; export class DoubleClickTextstyleBehavior extends Behavior { constructor ( edit, commandStack) { super(); this.edit = edit; } during (event, attribute) { this.edit.setDblClickedActivationBool(attribute); } }
import React, { useState, useEffect, useCallback } from 'react' import { useTheme } from 'next-themes' import siteMetadata from '@/data/siteMetadata' const Giscus = ({ mapping }) => { const [enableLoadComments, setEnabledLoadComments] = useState(true) const { theme, resolvedTheme } = useTheme() const commentsTheme = siteMetadata.comment.giscusConfig.themeURL === '' ? theme === 'dark' || resolvedTheme === 'dark' ? siteMetadata.comment.giscusConfig.darkTheme : siteMetadata.comment.giscusConfig.theme : siteMetadata.comment.giscusConfig.themeURL const COMMENTS_ID = 'comments-container' const LoadComments = useCallback(() => { setEnabledLoadComments(false) const script = document.createElement('script') script.src = 'https://giscus.app/client.js' script.setAttribute('data-repo', siteMetadata.comment.giscusConfig.repo) script.setAttribute('data-repo-id', siteMetadata.comment.giscusConfig.repositoryId) script.setAttribute('data-category', siteMetadata.comment.giscusConfig.category) script.setAttribute('data-category-id', siteMetadata.comment.giscusConfig.categoryId) script.setAttribute('data-mapping', mapping) script.setAttribute('data-reactions-enabled', siteMetadata.comment.giscusConfig.reactions) script.setAttribute('data-emit-metadata', siteMetadata.comment.giscusConfig.metadata) script.setAttribute('data-input-position', siteMetadata.comment.giscusConfig.inputPosition) script.setAttribute('data-lang', siteMetadata.comment.giscusConfig.lang) script.setAttribute('data-theme', commentsTheme) script.setAttribute('crossorigin', 'anonymous') script.async = true const comments = document.getElementById(COMMENTS_ID) if (comments) comments.appendChild(script) return () => { const comments = document.getElementById(COMMENTS_ID) if (comments) comments.innerHTML = '' } }, [commentsTheme, mapping]) // Reload on theme change useEffect(() => { const iframe = document.querySelector('iframe.giscus-frame') if (!iframe) return LoadComments() }, [LoadComments]) return ( <div className="pt-6 pb-6 text-center text-gray-700 dark:text-gray-300"> {enableLoadComments && <button onClick={LoadComments}>Afficher les commentaires</button>} <div className="giscus" id={COMMENTS_ID} /> </div> ) } export default Giscus
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.lang.cy={dir:'ltr',editorTitle:'Rich text editor, %1, press ALT 0 for help.',toolbar:'Toolbar',editor:'Rich Text Editor',source:'Tarddle',newPage:'Tudalen newydd',save:'Cadw',preview:'Rhagolwg',cut:'Torri',copy:'Copïo',paste:'Gludo',print:'Argraffu',underline:'Tanlinellu',bold:'Bras',italic:'Italig',selectAll:'Dewis Popeth',removeFormat:'Tynnu Fformat',strike:'Llinell Trwyddo',subscript:'Is-sgript',superscript:'Uwchsgript',horizontalrule:'Mewnosod Llinell Lorweddol',pagebreak:'Mewnosod Toriad Tudalen i Argraffu',unlink:'Datgysylltu',undo:'Dadwneud',redo:'Ailadrodd',common:{browseServer:"Pori'r Gweinydd",url:'URL',protocol:'Protocol',upload:'Lanlwytho',uploadSubmit:"Anfon i'r Gweinydd",image:'Delwedd',flash:'Flash',form:'Ffurflen',checkbox:'Blwch ticio',radio:'Botwm Radio',textField:'Maes Testun',textarea:'Ardal Testun',hiddenField:'Maes Cudd',button:'Botwm',select:'Maes Dewis',imageButton:'Botwm Delwedd',notSet:'<heb osod>',id:'Id',name:'Name',langDir:'Cyfeiriad Iaith',langDirLtr:"Chwith i'r Dde (LTR)",langDirRtl:"Dde i'r Chwith (RTL)",langCode:'Cod Iaith',longDescr:'URL Disgrifiad Hir',cssClass:'Dosbarth Dalen Arddull',advisoryTitle:'Teitl Cynghorol',cssStyle:'Arddull',ok:'Iawn',cancel:'Diddymu',close:'Close',preview:'Preview',generalTab:'Cyffredinol',advancedTab:'Uwch',validateNumberFailed:"Nid yw'r gwerth hwn yn rhif.",confirmNewPage:"Byddwch yn colli unrhyw newidiadau i'r cynnwys sydd heb eu cadw. A ydych am barhau i lwytho tudalen newydd?",confirmCancel:"Mae rhai o'r opsiynau wedi'u newid. A ydych wir am gau'r deialog?",options:'Options',target:'Target',targetNew:'New Window (_blank)',targetTop:'Topmost Window (_top)',targetSelf:'Same Window (_self)',targetParent:'Parent Window (_parent)',langDirLTR:'Left to Right (LTR)',langDirRTL:'Right to Left (RTL)',styles:'Style',cssClasses:'Stylesheet Classes',unavailable:'%1<span class="cke_accessibility">, ddim ar gael</span>'},contextmenu:{options:'Context Menu Options'},specialChar:{toolbar:'Mewnosod Nodau Arbennig',title:'Dewis Nod Arbennig',options:'Special Character Options'},link:{toolbar:'Dolen',other:'<eraill>',menu:'Golygu Dolen',title:'Dolen',info:'Gwyb ar y Ddolen',target:'Targed',upload:'Lanlwytho',advanced:'Uwch',type:'Math y Ddolen',toUrl:'URL',toAnchor:'Dolen at angor yn y testun',toEmail:'E-bost',targetFrame:'<ffrâm>',targetPopup:'<ffenestr bop>',targetFrameName:'Enw Ffrâm y Targed',targetPopupName:'Enw Ffenestr Bop',popupFeatures:'Nodweddion Ffenestr Bop',popupResizable:'Ailfeintiol',popupStatusBar:'Bar Statws',popupLocationBar:'Bar Safle',popupToolbar:'Bar Offer',popupMenuBar:'Dewislen',popupFullScreen:'Sgrin Llawn (IE)',popupScrollBars:'Barrau Sgrolio',popupDependent:'Dibynnol (Netscape)',popupWidth:'Lled',popupLeft:'Safle Chwith',popupHeight:'Uchder',popupTop:'Safle Top',id:'Id',langDir:'Cyfeiriad Iaith',langDirLTR:"Chwith i'r Dde (LTR)",langDirRTL:"Dde i'r Chwith (RTL)",acccessKey:'Allwedd Mynediad',name:'Enw',langCode:'Cod Iaith',tabIndex:'Indecs Tab',advisoryTitle:'Teitl Cynghorol',advisoryContentType:'Math y Cynnwys Cynghorol',cssClasses:'Dosbarthiadau Dalen Arddull',charset:"Set nodau'r Adnodd Cysylltiedig",styles:'Arddull',selectAnchor:'Dewiswch Angor',anchorName:"Gan Enw'r Angor",anchorId:'Gan Id yr Elfen',emailAddress:'Cyfeiriad E-Bost',emailSubject:'Testun y Message Subject',emailBody:'Pwnc y Neges',noAnchors:'(Dim angorau ar gael yn y ddogfen)',noUrl:'Teipiwch URL y ddolen',noEmail:'Teipiwch gyfeiriad yr e-bost'},anchor:{toolbar:'Angor',menu:'Golygwch yr Angor',title:"Priodweddau'r Angor",name:"Enw'r Angor",errorName:"Teipiwch enw'r angor"},list:{numberedTitle:'Numbered List Properties',bulletedTitle:'Bulleted List Properties',type:'Type',start:'Start',validateStartNumber:'List start number must be a whole number.',circle:'Circle',disc:'Disc',square:'Square',none:'None',notset:'<not set>',armenian:'Armenian numbering',georgian:'Georgian numbering (an, ban, gan, etc.)',lowerRoman:'Lower Roman (i, ii, iii, iv, v, etc.)',upperRoman:'Upper Roman (I, II, III, IV, V, etc.)',lowerAlpha:'Lower Alpha (a, b, c, d, e, etc.)',upperAlpha:'Upper Alpha (A, B, C, D, E, etc.)',lowerGreek:'Lower Greek (alpha, beta, gamma, etc.)',decimal:'Decimal (1, 2, 3, etc.)',decimalLeadingZero:'Decimal leading zero (01, 02, 03, etc.)'},findAndReplace:{title:'Chwilio ac Amnewid',find:'Chwilio',replace:'Amnewid',findWhat:"Chwilio'r term:",replaceWith:'Amnewid gyda:',notFoundMsg:"Nid oedd y testun wedi'i ddarganfod.",matchCase:"Cyfateb i'r cas",matchWord:'Cyfateb gair cyfan',matchCyclic:'Cyfateb cylchol',replaceAll:'Amnewid pob un',replaceSuccessMsg:'Amnewidiwyd %1 achlysur.'},table:{toolbar:'Tabl',title:'Nodweddion Tabl',menu:'Nodweddion Tabl',deleteTable:'Dileu Tabl',rows:'Rhesi',columns:'Colofnau',border:'Maint yr Ymyl',align:'Aliniad',alignLeft:'Chwith',alignCenter:'Canol',alignRight:'Dde',width:'Lled',widthPx:'picsel',widthPc:'y cant',widthUnit:'width unit',height:'Uchder',cellSpace:"Bylchu'r gell",cellPad:"Padio'r gell",caption:'Pennawd',summary:'Crynodeb',headers:'Penynnau',headersNone:'Dim',headersColumn:'Colofn gyntaf',headersRow:'Rhes gyntaf',headersBoth:'Y Ddau',invalidRows:"Mae'n rhaid cael o leiaf un rhes.",invalidCols:"Mae'n rhaid cael o leiaf un golofn.",invalidBorder:"Mae'n rhaid i faint yr ymyl fod yn rhif.",invalidWidth:"Mae'n rhaid i led y tabl fod yn rhif.",invalidHeight:"Mae'n rhaid i uchder y tabl fod yn rhif.",invalidCellSpacing:"Mae'n rhaid i fylchiad y gell fod yn rhif.",invalidCellPadding:"Mae'n rhaid i badiad y gell fod yn rhif.",cell:{menu:'Cell',insertBefore:'Mewnosod Cell Cyn',insertAfter:'Mewnosod Cell Ar Ôl',deleteCell:'Dileu Celloedd',merge:'Cyfuno Celloedd',mergeRight:"Cyfuno i'r Dde",mergeDown:'Cyfuno i Lawr',splitHorizontal:"Hollti'r Gell yn Lorweddol",splitVertical:"Hollti'r Gell yn Fertigol",title:"Priodweddau'r Gell",cellType:'Math y Gell',rowSpan:'Rhychwant Rhesi',colSpan:'Rhychwant Colofnau',wordWrap:'Lapio Geiriau',hAlign:'Aliniad Llorweddol',vAlign:'Aliniad Fertigol',alignTop:'Top',alignMiddle:'Canol',alignBottom:'Gwaelod',alignBaseline:'Baslinell',bgColor:'Lliw Cefndir',borderColor:'Lliw Ymyl',data:'Data',header:'Pennyn',yes:'Ie',no:'Na',invalidWidth:"Mae'n rhaid i led y gell fod yn rhif.",invalidHeight:"Mae'n rhaid i uchder y gell fod yn rhif.",invalidRowSpan:"Mae'n rhaid i rychwant y rhesi fod yn gyfanrif.",invalidColSpan:"Mae'n rhaid i rychwant y colofnau fod yn gyfanrif.",chooseColor:'Choose'},row:{menu:'Rhes',insertBefore:'Mewnosod Rhes Cyn',insertAfter:'Mewnosod Rhes Ar Ôl',deleteRow:'Dileu Rhesi'},column:{menu:'Colofn',insertBefore:'Mewnosod Colofn Cyn',insertAfter:'Mewnosod Colofn Ar Ôl',deleteColumn:'Dileu Colofnau'}},button:{title:'Priodweddau Botymau',text:'Testun (Gwerth)',type:'Math',typeBtn:'Botwm',typeSbm:'Gyrru',typeRst:'Ailosod'},checkboxAndRadio:{checkboxTitle:'Priodweddau Blwch Ticio',radioTitle:'Priodweddau Botwm Radio',value:'Gwerth',selected:'Dewiswyd'},form:{title:'Priodweddau Ffurflen',menu:'Priodweddau Ffurflen',action:'Gweithred',method:'Dull',encoding:'Amgodio'},select:{title:'Priodweddau Maes Dewis',selectInfo:'Gwyb Dewis',opAvail:'Opsiynau ar Gael',value:'Gwerth',size:'Maint',lines:'llinellau',chkMulti:'Caniatàu aml-ddewisiadau',opText:'Testun',opValue:'Gwerth',btnAdd:'Ychwanegu',btnModify:'Newid',btnUp:'Lan',btnDown:'Lawr',btnSetValue:'Gosod fel gwerth a ddewiswyd',btnDelete:'Dileu'},textarea:{title:'Priodweddau Ardal Testun',cols:'Colofnau',rows:'Rhesi'},textfield:{title:'Priodweddau Maes Testun',name:'Enw',value:'Gwerth',charWidth:'Lled Nod',maxChars:'Uchafswm y Nodau',type:'Math',typeText:'Testun',typePass:'Cyfrinair'},hidden:{title:'Priodweddau Maes Cudd',name:'Enw',value:'Gwerth'},image:{title:'Priodweddau Delwedd',titleButton:'Priodweddau Botwm Delwedd',menu:'Priodweddau Delwedd',infoTab:'Gwyb Delwedd',btnUpload:"Anfon i'r Gweinydd",upload:'lanlwytho',alt:'Testun Amgen',width:'Lled',height:'Uchder',lockRatio:'Cloi Cymhareb',unlockRatio:'Unlock Ratio',resetSize:'Ailosod Maint',border:'Ymyl',hSpace:'BwlchLl',vSpace:'BwlchF',align:'Alinio',alignLeft:'Chwith',alignRight:'Dde',alertUrl:'Rhowch URL y ddelwedd',linkTab:'Dolen',button2Img:"Ydych am drawsffurfio'r botwm ddelwedd hwn ar ddelwedd syml?",img2Button:"Ydych am drawsffurfio'r ddelwedd hon ar fotwm delwedd?",urlMissing:"URL tarddle'r ddelwedd ar goll.",validateWidth:'Width must be a whole number.',validateHeight:'Height must be a whole number.',validateBorder:'Border must be a whole number.',validateHSpace:'HSpace must be a whole number.',validateVSpace:'VSpace must be a whole number.'},flash:{properties:'Priodweddau Flash',propertiesTab:'Priodweddau',title:'Priodweddau Flash',chkPlay:'AwtoChwarae',chkLoop:'Lwpio',chkMenu:'Galluogi Dewislen Flash',chkFull:'Caniatàu Sgrin Llawn',scale:'Graddfa',scaleAll:'Dangos pob',scaleNoBorder:'Dim Ymyl',scaleFit:'Ffit Union',access:'Mynediad Sgript',accessAlways:'Pob amser',accessSameDomain:"R'un parth",accessNever:'Byth',align:'Alinio',alignLeft:'Chwith',alignAbsBottom:'Gwaelod Abs',alignAbsMiddle:'Canol Abs',alignBaseline:'Baslinell',alignBottom:'Gwaelod',alignMiddle:'Canol',alignRight:'Dde',alignTextTop:'Testun Top',alignTop:'Top',quality:'Ansawdd',qualityBest:'Gorau',qualityHigh:'Uchel',qualityAutoHigh:'Uchel Awto',qualityMedium:'Canolig',qualityAutoLow:'Isel Awto',qualityLow:'Isel',windowModeWindow:'Ffenestr',windowModeOpaque:'Afloyw',windowModeTransparent:'Tryloyw',windowMode:'Modd ffenestr',flashvars:'Newidynnau ar gyfer Flash',bgcolor:'Lliw cefndir',width:'Lled',height:'Uchder',hSpace:'BwlchLl',vSpace:'BwlchF',validateSrc:'Ni all yr URL fod yn wag.',validateWidth:"Rhaid i'r Lled fod yn rhif.",validateHeight:"Rhaid i'r Uchder fod yn rhif.",validateHSpace:"Rhaid i'r BwlchLl fod yn rhif.",validateVSpace:"Rhaid i'r BwlchF fod yn rhif."},spellCheck:{toolbar:'Gwirio Sillafu',title:'Gwirio Sillafu',notAvailable:"Nid yw'r gwasanaeth hwn ar gael yn bresennol.",errorLoading:'Error loading application service host: %s.',notInDic:"Nid i'w gael yn y geiriadur",changeTo:'Newid i',btnIgnore:'Anwybyddu Un',btnIgnoreAll:'Anwybyddu Pob',btnReplace:'Amnewid Un',btnReplaceAll:'Amnewid Pob',btnUndo:'Dadwneud',noSuggestions:'- Dim awgrymiadau -',progress:'Gwirio sillafu yn ar y gweill...',noMispell:'Gwirio sillafu wedi gorffen: Dim camsillaf.',noChanges:'Gwirio sillafu wedi gorffen: Dim newidiadau',oneChange:'Gwirio sillafu wedi gorffen: Newidiwyd 1 gair',manyChanges:'Gwirio sillafu wedi gorffen: Newidiwyd %1 gair',ieSpellDownload:'Gwirydd sillafu heb ei arsefydlu. A ydych am ei lawrlwytho nawr?'},smiley:{toolbar:'Gwenoglun',title:'Mewnosod Gwenoglun',options:'Smiley Options'},elementsPath:{eleLabel:'Elements path',eleTitle:'Elfen %1'},numberedlist:'Mewnosod/Tynnu Rhestr Rhifol',bulletedlist:'Mewnosod/Tynnu Rhestr Bwled',indent:"Cynyddu'r Mewnoliad",outdent:"Lleihau'r Mewnoliad",justify:{left:"Alinio i'r Chwith",center:"Alinio i'r Canol",right:"Alinio i'r Dde",block:'Aliniad Bloc'},blockquote:'Dyfyniad bloc',clipboard:{title:'Gludo',cutError:"Nid yw gosodiadau diogelwch eich porwr yn caniatàu'r golygydd i gynnal 'gweithredoedd torri' yn awtomatig. Defnyddiwch y bysellfwrdd (Ctrl/Cmd+X).",copyError:"Nid yw gosodiadau diogelwch eich porwr yn caniatàu'r golygydd i gynnal 'gweithredoedd copïo' yn awtomatig. Defnyddiwch y bysellfwrdd (Ctrl/Cmd+C).",pasteMsg:"Gludwch i mewn i'r blwch canlynol gan ddefnyddio'r bysellfwrdd (<strong>Ctrl/Cmd+V</strong>) a phwyso <strong>Iawn</strong>.",securityMsg:"Oherwydd gosodiadau diogelwch eich porwr, nid yw'r porwr yn gallu ennill mynediad i'r data ar y clipfwrdd yn uniongyrchol. Mae angen i chi ei ludo eto i'r ffenestr hon.",pasteArea:'Paste Area'},pastefromword:{confirmCleanup:'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?',toolbar:'Gludo o Word',title:'Gludo o Word',error:'It was not possible to clean up the pasted data due to an internal error'},pasteText:{button:'Gludo fel testun plaen',title:'Gludo fel Testun Plaen'},templates:{button:'Templedi',title:'Templedi Cynnwys',options:'Template Options',insertOption:'Amnewid y cynnwys go iawn',selectPromptMsg:"Dewiswch dempled i'w agor yn y golygydd",emptyListMsg:"(Dim templedi wedi'u diffinio)"},showBlocks:'Dangos Blociau',stylesCombo:{label:'Arddulliau',panelTitle:'Formatting Styles',panelTitle1:'Arddulliau Bloc',panelTitle2:'Arddulliau Mewnol',panelTitle3:'Arddulliau Gwrthrych'},format:{label:'Fformat',panelTitle:'Fformat Paragraff',tag_p:'Normal',tag_pre:"Wedi'i Fformatio",tag_address:'Cyfeiriad',tag_h1:'Pennawd 1',tag_h2:'Pennawd 2',tag_h3:'Pennawd 3',tag_h4:'Pennawd 4',tag_h5:'Pennawd 5',tag_h6:'Pennawd 6',tag_div:'Normal (DIV)'},div:{title:'Create Div Container',toolbar:'Create Div Container',cssClassInputLabel:'Stylesheet Classes',styleSelectLabel:'Style',IdInputLabel:'Id',languageCodeInputLabel:' Language Code',inlineStyleInputLabel:'Inline Style',advisoryTitleInputLabel:'Advisory Title',langDirLabel:'Language Direction',langDirLTRLabel:'Left to Right (LTR)',langDirRTLLabel:'Right to Left (RTL)',edit:'Edit Div',remove:'Remove Div'},font:{label:'Ffont',voiceLabel:'Ffont',panelTitle:"Enw'r Ffont"},fontSize:{label:'Maint',voiceLabel:'Maint y Ffont',panelTitle:'Maint y Ffont'},colorButton:{textColorTitle:'Lliw Testun',bgColorTitle:'Lliw Cefndir',panelTitle:'Colors',auto:'Awtomatig',more:'Mwy o Liwiau...'},colors:{'000':'Du',800000:'Marwn','8B4513':'Brown Cyfrwy','2F4F4F':'Llechen Tywyll','008080':'Corhwyad','000080':'Nefi','4B0082':'Indigo',696969:'Llwyd Pwl',B22222:'Bric Tân',A52A2A:'Brown',DAA520:'Rhoden Aur','006400':'Gwyrdd Tywyll','40E0D0':'Gwyrddlas','0000CD':'Glas Canolig',800080:'Porffor',808080:'Llwyd',F00:'Coch',FF8C00:'Oren Tywyll',FFD700:'Aur','008000':'Gwyrdd','0FF':'Cyan','00F':'Glas',EE82EE:'Fioled',A9A9A9:'Llwyd Tywyll',FFA07A:'Samwn Golau',FFA500:'Oren',FFFF00:'Melyn','00FF00':'Leim',AFEEEE:'Gwyrddlas Golau',ADD8E6:'Glas Golau',DDA0DD:'Eirinen',D3D3D3:'Llwyd Golau',FFF0F5:'Gwrid Lafant',FAEBD7:'Gwyn Hynafol',FFFFE0:'Melyn Golau',F0FFF0:'Melwn Gwyrdd Golau',F0FFFF:'Aswr',F0F8FF:'Glas Alys',E6E6FA:'Lafant',FFF:'Gwyn'},scayt:{title:"Gwirio'r Sillafu Wrth Deipio",opera_title:'Not supported by Opera',enable:'Galluogi SCAYT',disable:'Analluogi SCAYT',about:'Ynghylch SCAYT',toggle:'Togl SCAYT',options:'Opsiynau',langs:'Ieithoedd',moreSuggestions:'Awgrymiadau pellach',ignore:'Anwybyddu',ignoreAll:'Anwybyddu pob',addWord:'Ychwanegu Gair',emptyDic:"Ni ddylai enw'r geiriadur fod yn wag.",optionsTab:'Opsiynau',allCaps:'Ignore All-Caps Words',ignoreDomainNames:'Ignore Domain Names',mixedCase:'Ignore Words with Mixed Case',mixedWithDigits:'Ignore Words with Numbers',languagesTab:'Ieithoedd',dictionariesTab:'Geiriaduron',dic_field_name:'Dictionary name',dic_create:'Create',dic_restore:'Restore',dic_delete:'Delete',dic_rename:'Rename',dic_info:'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.',aboutTab:'Ynghylch'},about:{title:'Ynghylch CKEditor',dlgTitle:'Ynghylch CKEditor',moreInfo:"Am wybodaeth ynghylch trwyddedau, ewch i'n gwefan:",copy:'Hawlfraint &copy; $1. Cedwir pob hawl.'},maximize:'Mwyhau',minimize:'Lleihau',fakeobjects:{anchor:'Angor',flash:'Animeiddiant Flash',div:'Toriad Tudalen',unknown:'Gwrthrych Anhysbys'},resize:'Llusgo i ailfeintio',colordialog:{title:'Dewis lliw',options:'Color Options',highlight:'Uwcholeuo',selected:'Dewiswyd',clear:'Clirio'},toolbarCollapse:"Cyfangu'r Bar Offer",toolbarExpand:"Ehangu'r Bar Offer",bidi:{ltr:'Text direction from left to right',rtl:'Text direction from right to left'}};
import { take, takeLatest, put, fork } from 'redux-saga/effects'; import { push } from 'connected-react-router'; import XcelTrip from '../../utils/apiHelper'; import * as actions from './actions'; import * as types from './constants'; const apiUri = `login`; function* redirectOnSuccess() { const action = yield take(types.SUBMIT_INFO_SUCCESS); yield put(push('/admin')); } function* fetchData(action) { const { data } = action; const successWatcher = yield fork(redirectOnSuccess); yield fork( XcelTrip.post( apiUri, actions.submitLoginInfoSuccess, actions.submitLoginInfoError, data, '', ), ); } export default function* loginFormSaga() { yield takeLatest(types.SUBMIT_INFO_REQUEST, fetchData); }
/** * DocuSign REST API * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient', 'model/ErrorDetails'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./ErrorDetails')); } else { // Browser globals (root is window) if (!root.Docusign) { root.Docusign = {}; } root.Docusign.DocumentVisibility = factory(root.Docusign.ApiClient, root.Docusign.ErrorDetails); } }(this, function(ApiClient, ErrorDetails) { 'use strict'; /** * The DocumentVisibility model module. * @module model/DocumentVisibility */ /** * Constructs a new <code>DocumentVisibility</code>. * @alias module:model/DocumentVisibility * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>DocumentVisibility</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/DocumentVisibility} obj Optional instance to populate. * @return {module:model/DocumentVisibility} The populated <code>DocumentVisibility</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('documentId')) { obj['documentId'] = ApiClient.convertToType(data['documentId'], 'String'); } if (data.hasOwnProperty('errorDetails')) { obj['errorDetails'] = ErrorDetails.constructFromObject(data['errorDetails']); } if (data.hasOwnProperty('recipientId')) { obj['recipientId'] = ApiClient.convertToType(data['recipientId'], 'String'); } if (data.hasOwnProperty('rights')) { obj['rights'] = ApiClient.convertToType(data['rights'], 'String'); } if (data.hasOwnProperty('visible')) { obj['visible'] = ApiClient.convertToType(data['visible'], 'String'); } } return obj; } /** * Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute. * @member {String} documentId */ exports.prototype['documentId'] = undefined; /** * @member {module:model/ErrorDetails} errorDetails */ exports.prototype['errorDetails'] = undefined; /** * Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document. * @member {String} recipientId */ exports.prototype['recipientId'] = undefined; /** * * @member {String} rights */ exports.prototype['rights'] = undefined; /** * * @member {String} visible */ exports.prototype['visible'] = undefined; return exports; }));
import { __extends } from "tslib"; import { Container } from "./container"; import { Control } from "./control"; import { _TypeStore } from '@babylonjs/core/Misc/typeStore'; /** Class used to create 2D ellipse containers */ var Ellipse = /** @class */ (function (_super) { __extends(Ellipse, _super); /** * Creates a new Ellipse * @param name defines the control name */ function Ellipse(name) { var _this = _super.call(this, name) || this; _this.name = name; _this._thickness = 1; return _this; } Object.defineProperty(Ellipse.prototype, "thickness", { /** Gets or sets border thickness */ get: function () { return this._thickness; }, set: function (value) { if (this._thickness === value) { return; } this._thickness = value; this._markAsDirty(); }, enumerable: false, configurable: true }); Ellipse.prototype._getTypeName = function () { return "Ellipse"; }; Ellipse.prototype._localDraw = function (context) { context.save(); if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) { context.shadowColor = this.shadowColor; context.shadowBlur = this.shadowBlur; context.shadowOffsetX = this.shadowOffsetX; context.shadowOffsetY = this.shadowOffsetY; } Control.drawEllipse(this._currentMeasure.left + this._currentMeasure.width / 2, this._currentMeasure.top + this._currentMeasure.height / 2, this._currentMeasure.width / 2 - this._thickness / 2, this._currentMeasure.height / 2 - this._thickness / 2, context); if (this._background) { context.fillStyle = this._background; context.fill(); } if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) { context.shadowBlur = 0; context.shadowOffsetX = 0; context.shadowOffsetY = 0; } if (this._thickness) { if (this.color) { context.strokeStyle = this.color; } context.lineWidth = this._thickness; context.stroke(); } context.restore(); }; Ellipse.prototype._additionalProcessing = function (parentMeasure, context) { _super.prototype._additionalProcessing.call(this, parentMeasure, context); this._measureForChildren.width -= 2 * this._thickness; this._measureForChildren.height -= 2 * this._thickness; this._measureForChildren.left += this._thickness; this._measureForChildren.top += this._thickness; }; Ellipse.prototype._clipForChildren = function (context) { Control.drawEllipse(this._currentMeasure.left + this._currentMeasure.width / 2, this._currentMeasure.top + this._currentMeasure.height / 2, this._currentMeasure.width / 2, this._currentMeasure.height / 2, context); context.clip(); }; return Ellipse; }(Container)); export { Ellipse }; _TypeStore.RegisteredTypes["BABYLON.GUI.Ellipse"] = Ellipse; //# sourceMappingURL=ellipse.js.map
define(["exports", "../utils.js"], function (_exports, _utils) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.default = void 0; /* istanbul ignore next: coverage is calculated in Chrome, this code is for IE */ function getAnchorOrigin(anchor) { // IE11: on HTTP and HTTPS the default port is not included into // window.location.origin, so won't include it here either. var port = anchor.port; var protocol = anchor.protocol; var defaultHttp = protocol === 'http:' && port === '80'; var defaultHttps = protocol === 'https:' && port === '443'; var host = defaultHttp || defaultHttps ? anchor.hostname // does not include the port number (e.g. www.example.org) : anchor.host; // does include the port number (e.g. www.example.org:80) return "".concat(protocol, "//").concat(host); } // The list of checks is not complete: // - SVG support is missing // - the 'rel' attribute is not considered function vaadinRouterGlobalClickHandler(event) { // ignore the click if the default action is prevented if (event.defaultPrevented) { return; } // ignore the click if not with the primary mouse button if (event.button !== 0) { return; } // ignore the click if a modifier key is pressed if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) { return; } // find the <a> element that the click is at (or within) var anchor = event.target; var path = event.composedPath ? event.composedPath() : event.path || []; // FIXME(web-padawan): `Symbol.iterator` used by webcomponentsjs is broken for arrays // example to check: `for...of` loop here throws the "Not yet implemented" error for (var i = 0; i < path.length; i++) { var target = path[i]; if (target.nodeName && target.nodeName.toLowerCase() === 'a') { anchor = target; break; } } while (anchor && anchor.nodeName.toLowerCase() !== 'a') { anchor = anchor.parentNode; } // ignore the click if not at an <a> element if (!anchor || anchor.nodeName.toLowerCase() !== 'a') { return; } // ignore the click if the <a> element has a non-default target if (anchor.target && anchor.target.toLowerCase() !== '_self') { return; } // ignore the click if the <a> element has the 'download' attribute if (anchor.hasAttribute('download')) { return; } // ignore the click if the <a> element has the 'router-ignore' attribute if (anchor.hasAttribute('router-ignore')) { return; } // ignore the click if the target URL is a fragment on the current page if (anchor.pathname === window.location.pathname && anchor.hash !== '') { return; } // ignore the click if the target is external to the app // In IE11 HTMLAnchorElement does not have the `origin` property var origin = anchor.origin || getAnchorOrigin(anchor); if (origin !== window.location.origin) { return; } // if none of the above, convert the click into a navigation event var _anchor = anchor, pathname = _anchor.pathname, search = _anchor.search, hash = _anchor.hash; if ((0, _utils.fireRouterEvent)('go', { pathname: pathname, search: search, hash: hash })) { event.preventDefault(); } } /** * A navigation trigger for Vaadin Router that translated clicks on `<a>` links * into Vaadin Router navigation events. * * Only regular clicks on in-app links are translated (primary mouse button, no * modifier keys, the target href is within the app's URL space). * * @memberOf Router.NavigationTrigger * @type {NavigationTrigger} */ var CLICK = { activate: function activate() { window.document.addEventListener('click', vaadinRouterGlobalClickHandler); }, inactivate: function inactivate() { window.document.removeEventListener('click', vaadinRouterGlobalClickHandler); } }; var _default = CLICK; _exports.default = _default; });
<% _.each(collection.toArray().slice(0, 10), function(m) { %> <li<% if (m.id == model.id) { %> class="active"<% } %>><a href="<%= m.url() %>"> <%= m.id %> <span><%= Genghis.Util.humanizeCount(m.get('count') || 0) %></span> </a></li> <% }); %> <% if (collection.size() > 10) { %> <li class="divider"></li> <li><a href="<%= collection.url %>">More &raquo;</a></li> <% } %>
module.exports = { preset: 'react-native', collectCoverage: true, moduleDirectories: ['node_modules', 'src'], moduleNameMapper: { 'react-native-slide-to-unlock': '<rootDir>/__mock__/react-native-slide-to-unlock.tsx', '@react-native-community/blur': '<rootDir>/__mock__/blurview.tsx', DeviceType: '<rootDir>/__mock__/DeviceTypeModule.ts', }, setupFiles: ['<rootDir>/__mock__/setup.js'], testPathIgnorePatterns: ['/node_modules/'], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], coveragePathIgnorePatterns: ['<rootDir>/__mock__/', '<rootDir>/src/asset'], };
import React from 'react'; import SearchUI from './SearchUI'; const SearchLoader = () => { const openSearchUI = () => { document.querySelector(".sk-layout").classList.add("is-active"); setTimeout(function() { document.querySelector(".sk-search-box__text").focus(); }, 500); }; return ( <span className="page-link"> <span className="sk-search-loader fa fa-search" onClick={openSearchUI} /> </span> ) }; const Search = () => { const [showSearchUI, setShowSearchUI] = React.useState(false); const closeSearchUI = () => document.querySelector(".sk-layout").classList.remove("is-active"); const escSearchUI = (event) => { if (event.keyCode == 27) { closeSearchUI(); } }; return ( <div className="sk-layout" onKeyUp={escSearchUI}> <div className="sk-layout__wrapper"> <span className="sk-layout__close fa fa-times" onClick={closeSearchUI} /> <SearchUI /> </div> </div> ) }; export {SearchLoader, Search};
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { InvalidNonce, InsufficientFunds, AuthenticationError, InvalidOrder, ExchangeError, OrderNotFound, AccountSuspended, BadSymbol, OrderImmediatelyFillable, RateLimitExceeded, OnMaintenance, PermissionDenied } = require ('./base/errors'); // --------------------------------------------------------------------------- module.exports = class zonda extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'zonda', 'name': 'Zonda', 'countries': [ 'EE' ], // Estonia 'rateLimit': 1000, 'has': { 'cancelOrder': true, 'CORS': true, 'createOrder': true, 'fetchBalance': true, 'fetchLedger': true, 'fetchMarkets': true, 'fetchMyTrades': true, 'fetchOHLCV': true, 'fetchOpenOrders': true, 'fetchOrderBook': true, 'fetchTicker': true, 'fetchTrades': true, 'withdraw': true, }, 'timeframes': { '1m': '60', '3m': '180', '5m': '300', '15m': '900', '30m': '1800', '1h': '3600', '2h': '7200', '4h': '14400', '6h': '21600', '12h': '43200', '1d': '86400', '3d': '259200', '1w': '604800', }, 'hostname': 'zondaglobal.com', 'urls': { 'referral': 'https://auth.zondaglobal.com/ref/jHlbB4mIkdS1', 'logo': 'https://user-images.githubusercontent.com/1294454/27766132-978a7bd8-5ece-11e7-9540-bc96d1e9bbb8.jpg', 'www': 'https://zondaglobal.com', 'api': { 'public': 'https://{hostname}/API/Public', 'private': 'https://{hostname}/API/Trading/tradingApi.php', 'v1_01Public': 'https://api.{hostname}/rest', 'v1_01Private': 'https://api.{hostname}/rest', }, 'doc': [ 'https://docs.zonda.exchange/', 'https://github.com/BitBayNet/API', ], 'support': 'https://zondaglobal.com/en/helpdesk/zonda-exchange', 'fees': 'https://zondaglobal.com/legal/zonda-exchange/fees', }, 'api': { 'public': { 'get': [ '{id}/all', '{id}/market', '{id}/orderbook', '{id}/ticker', '{id}/trades', ], }, 'private': { 'post': [ 'info', 'trade', 'cancel', 'orderbook', 'orders', 'transfer', 'withdraw', 'history', 'transactions', ], }, 'v1_01Public': { 'get': [ 'trading/ticker', 'trading/ticker/{symbol}', 'trading/stats', 'trading/orderbook/{symbol}', 'trading/transactions/{symbol}', 'trading/candle/history/{symbol}/{resolution}', ], }, 'v1_01Private': { 'get': [ 'payments/withdrawal/{detailId}', 'payments/deposit/{detailId}', 'trading/offer', 'trading/config/{symbol}', 'trading/history/transactions', 'balances/BITBAY/history', 'balances/BITBAY/balance', 'fiat_cantor/rate/{baseId}/{quoteId}', 'fiat_cantor/history', ], 'post': [ 'trading/offer/{symbol}', 'trading/config/{symbol}', 'balances/BITBAY/balance', 'balances/BITBAY/balance/transfer/{source}/{destination}', 'fiat_cantor/exchange', ], 'delete': [ 'trading/offer/{symbol}/{id}/{side}/{price}', ], 'put': [ 'balances/BITBAY/balance/{id}', ], }, }, 'fees': { 'trading': { 'maker': this.parseNumber ('0.0'), 'taker': this.parseNumber ('0.001'), 'percentage': true, 'tierBased': false, }, 'fiat': { 'maker': 0.30 / 100, 'taker': 0.43 / 100, 'percentage': true, 'tierBased': true, 'tiers': { 'taker': [ [ 0.0043, 0 ], [ 0.0042, 1250 ], [ 0.0041, 3750 ], [ 0.0040, 7500 ], [ 0.0039, 10000 ], [ 0.0038, 15000 ], [ 0.0037, 20000 ], [ 0.0036, 25000 ], [ 0.0035, 37500 ], [ 0.0034, 50000 ], [ 0.0033, 75000 ], [ 0.0032, 100000 ], [ 0.0031, 150000 ], [ 0.0030, 200000 ], [ 0.0029, 250000 ], [ 0.0028, 375000 ], [ 0.0027, 500000 ], [ 0.0026, 625000 ], [ 0.0025, 875000 ], ], 'maker': [ [ 0.0030, 0 ], [ 0.0029, 1250 ], [ 0.0028, 3750 ], [ 0.0028, 7500 ], [ 0.0027, 10000 ], [ 0.0026, 15000 ], [ 0.0025, 20000 ], [ 0.0025, 25000 ], [ 0.0024, 37500 ], [ 0.0023, 50000 ], [ 0.0023, 75000 ], [ 0.0022, 100000 ], [ 0.0021, 150000 ], [ 0.0021, 200000 ], [ 0.0020, 250000 ], [ 0.0019, 375000 ], [ 0.0018, 500000 ], [ 0.0018, 625000 ], [ 0.0017, 875000 ], ], }, }, 'funding': { 'withdraw': {}, }, }, 'options': { 'fiatCurrencies': [ 'EUR', 'USD', 'GBP', 'PLN' ], }, 'exceptions': { '400': ExchangeError, // At least one parameter wasn't set '401': InvalidOrder, // Invalid order type '402': InvalidOrder, // No orders with specified currencies '403': InvalidOrder, // Invalid payment currency name '404': InvalidOrder, // Error. Wrong transaction type '405': InvalidOrder, // Order with this id doesn't exist '406': InsufficientFunds, // No enough money or crypto // code 407 not specified are not specified in their docs '408': InvalidOrder, // Invalid currency name '501': AuthenticationError, // Invalid public key '502': AuthenticationError, // Invalid sign '503': InvalidNonce, // Invalid moment parameter. Request time doesn't match current server time '504': ExchangeError, // Invalid method '505': AuthenticationError, // Key has no permission for this action '506': AccountSuspended, // Account locked. Please contact with customer service // codes 507 and 508 are not specified in their docs '509': ExchangeError, // The BIC/SWIFT is required for this currency '510': BadSymbol, // Invalid market name 'FUNDS_NOT_SUFFICIENT': InsufficientFunds, 'OFFER_FUNDS_NOT_EXCEEDING_MINIMUMS': InvalidOrder, 'OFFER_NOT_FOUND': OrderNotFound, 'OFFER_WOULD_HAVE_BEEN_PARTIALLY_FILLED': OrderImmediatelyFillable, 'ACTION_LIMIT_EXCEEDED': RateLimitExceeded, 'UNDER_MAINTENANCE': OnMaintenance, 'REQUEST_TIMESTAMP_TOO_OLD': InvalidNonce, 'PERMISSIONS_NOT_SUFFICIENT': PermissionDenied, }, 'commonCurrencies': { 'GGC': 'Global Game Coin', }, }); } async fetchMarkets (params = {}) { const response = await this.v1_01PublicGetTradingTicker (params); const fiatCurrencies = this.safeValue (this.options, 'fiatCurrencies', []); // // { // status: 'Ok', // items: { // 'BSV-USD': { // market: { // code: 'BSV-USD', // first: { currency: 'BSV', minOffer: '0.00035', scale: 8 }, // second: { currency: 'USD', minOffer: '5', scale: 2 } // }, // time: '1557569762154', // highestBid: '52.31', // lowestAsk: '62.99', // rate: '63', // previousRate: '51.21', // }, // }, // } // const result = []; const items = this.safeValue (response, 'items'); const keys = Object.keys (items); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const item = items[key]; const market = this.safeValue (item, 'market', {}); const first = this.safeValue (market, 'first', {}); const second = this.safeValue (market, 'second', {}); const baseId = this.safeString (first, 'currency'); const quoteId = this.safeString (second, 'currency'); const id = baseId + quoteId; const base = this.safeCurrencyCode (baseId); const quote = this.safeCurrencyCode (quoteId); const symbol = base + '/' + quote; const precision = { 'amount': this.safeInteger (first, 'scale'), 'price': this.safeInteger (second, 'scale'), }; let fees = this.safeValue (this.fees, 'trading', {}); if (this.inArray (base, fiatCurrencies) || this.inArray (quote, fiatCurrencies)) { fees = this.safeValue (this.fees, 'fiat', {}); } const maker = this.safeNumber (fees, 'maker'); const taker = this.safeNumber (fees, 'taker'); // todo: check that the limits have ben interpreted correctly // todo: parse the fees page result.push ({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'baseId': baseId, 'quoteId': quoteId, 'precision': precision, 'type': 'spot', 'spot': true, 'active': undefined, 'maker': maker, 'taker': taker, 'limits': { 'amount': { 'min': this.safeNumber (first, 'minOffer'), 'max': undefined, }, 'price': { 'min': undefined, 'max': undefined, }, 'cost': { 'min': this.safeNumber (second, 'minOffer'), 'max': undefined, }, }, 'info': item, }); } return result; } async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const request = {}; const response = await this.v1_01PrivateGetTradingOffer (this.extend (request, params)); const items = this.safeValue (response, 'items', []); return this.parseOrders (items, undefined, since, limit, { 'status': 'open' }); } parseOrder (order, market = undefined) { // // { // market: 'ETH-EUR', // offerType: 'Sell', // id: '93d3657b-d616-11e9-9248-0242ac110005', // currentAmount: '0.04', // lockedAmount: '0.04', // rate: '280', // startAmount: '0.04', // time: '1568372806924', // postOnly: false, // hidden: false, // mode: 'limit', // receivedAmount: '0.0', // firstBalanceId: '5b816c3e-437c-4e43-9bef-47814ae7ebfc', // secondBalanceId: 'ab43023b-4079-414c-b340-056e3430a3af' // } // const marketId = this.safeString (order, 'market'); const symbol = this.safeSymbol (marketId, market, '-'); const timestamp = this.safeInteger (order, 'time'); const amount = this.safeString (order, 'startAmount'); const remaining = this.safeString (order, 'currentAmount'); const postOnly = this.safeValue (order, 'postOnly'); return this.safeOrder2 ({ 'id': this.safeString (order, 'id'), 'clientOrderId': undefined, 'info': order, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'lastTradeTimestamp': undefined, 'status': undefined, 'symbol': symbol, 'type': this.safeString (order, 'mode'), 'timeInForce': undefined, 'postOnly': postOnly, 'side': this.safeStringLower (order, 'offerType'), 'price': this.safeString (order, 'rate'), 'stopPrice': undefined, 'amount': amount, 'cost': undefined, 'filled': undefined, 'remaining': remaining, 'average': undefined, 'fee': undefined, 'trades': undefined, }, market); } async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const request = {}; if (symbol) { const markets = [ this.marketId (symbol) ]; request['markets'] = markets; } const query = { 'query': this.json (this.extend (request, params)) }; const response = await this.v1_01PrivateGetTradingHistoryTransactions (query); // // { // status: 'Ok', // totalRows: '67', // items: [ // { // id: 'b54659a0-51b5-42a0-80eb-2ac5357ccee2', // market: 'BTC-EUR', // time: '1541697096247', // amount: '0.00003', // rate: '4341.44', // initializedBy: 'Sell', // wasTaker: false, // userAction: 'Buy', // offerId: 'bd19804a-6f89-4a69-adb8-eb078900d006', // commissionValue: null // }, // ] // } // const items = this.safeValue (response, 'items'); const result = this.parseTrades (items, undefined, since, limit); if (symbol === undefined) { return result; } return this.filterBySymbol (result, symbol); } async fetchBalance (params = {}) { await this.loadMarkets (); const response = await this.v1_01PrivateGetBalancesBITBAYBalance (params); const balances = this.safeValue (response, 'balances'); if (balances === undefined) { throw new ExchangeError (this.id + ' empty balance response ' + this.json (response)); } const result = { 'info': response }; for (let i = 0; i < balances.length; i++) { const balance = balances[i]; const currencyId = this.safeString (balance, 'currency'); const code = this.safeCurrencyCode (currencyId); const account = this.account (); account['used'] = this.safeString (balance, 'lockedFunds'); account['free'] = this.safeString (balance, 'availableFunds'); result[code] = account; } return this.safeBalance (result); } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); const request = { 'id': this.marketId (symbol), }; const orderbook = await this.publicGetIdOrderbook (this.extend (request, params)); return this.parseOrderBook (orderbook, symbol); } parseTicker (ticker, market = undefined) { const symbol = this.safeSymbol (undefined, market); const timestamp = this.milliseconds (); const baseVolume = this.safeNumber (ticker, 'volume'); const vwap = this.safeNumber (ticker, 'vwap'); let quoteVolume = undefined; if (baseVolume !== undefined && vwap !== undefined) { quoteVolume = baseVolume * vwap; } const last = this.safeNumber (ticker, 'last'); return this.safeTicker ({ 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'high': this.safeNumber (ticker, 'max'), 'low': this.safeNumber (ticker, 'min'), 'bid': this.safeNumber (ticker, 'bid'), 'bidVolume': undefined, 'ask': this.safeNumber (ticker, 'ask'), 'askVolume': undefined, 'vwap': vwap, 'open': undefined, 'close': last, 'last': last, 'previousClose': undefined, 'change': undefined, 'percentage': undefined, 'average': this.safeNumber (ticker, 'average'), 'baseVolume': baseVolume, 'quoteVolume': quoteVolume, 'info': ticker, }, market); } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'id': market['id'], }; const response = await this.publicGetIdTicker (this.extend (request, params)); return this.parseTicker (response, market); } async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) { const balanceCurrencies = []; if (code !== undefined) { const currency = this.currency (code); balanceCurrencies.push (currency['id']); } let request = { 'balanceCurrencies': balanceCurrencies, }; if (since !== undefined) { request['fromTime'] = since; } if (limit !== undefined) { request['limit'] = limit; } request = this.extend (request, params); const response = await this.v1_01PrivateGetBalancesBITBAYHistory ({ 'query': this.json (request) }); const items = response['items']; return this.parseLedger (items, undefined, since, limit); } parseLedgerEntry (item, currency = undefined) { // // FUNDS_MIGRATION // { // "historyId": "84ea7a29-7da5-4de5-b0c0-871e83cad765", // "balance": { // "id": "821ec166-cb88-4521-916c-f4eb44db98df", // "currency": "LTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "LTC" // }, // "detailId": null, // "time": 1506128252968, // "type": "FUNDS_MIGRATION", // "value": 0.0009957, // "fundsBefore": { "total": 0, "available": 0, "locked": 0 }, // "fundsAfter": { "total": 0.0009957, "available": 0.0009957, "locked": 0 }, // "change": { "total": 0.0009957, "available": 0.0009957, "locked": 0 } // } // // CREATE_BALANCE // { // "historyId": "d0fabd8d-9107-4b5e-b9a6-3cab8af70d49", // "balance": { // "id": "653ffcf2-3037-4ebe-8e13-d5ea1a01d60d", // "currency": "BTG", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTG" // }, // "detailId": null, // "time": 1508895244751, // "type": "CREATE_BALANCE", // "value": 0, // "fundsBefore": { "total": null, "available": null, "locked": null }, // "fundsAfter": { "total": 0, "available": 0, "locked": 0 }, // "change": { "total": 0, "available": 0, "locked": 0 } // } // // BITCOIN_GOLD_FORK // { // "historyId": "2b4d52d3-611c-473d-b92c-8a8d87a24e41", // "balance": { // "id": "653ffcf2-3037-4ebe-8e13-d5ea1a01d60d", // "currency": "BTG", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTG" // }, // "detailId": null, // "time": 1508895244778, // "type": "BITCOIN_GOLD_FORK", // "value": 0.00453512, // "fundsBefore": { "total": 0, "available": 0, "locked": 0 }, // "fundsAfter": { "total": 0.00453512, "available": 0.00453512, "locked": 0 }, // "change": { "total": 0.00453512, "available": 0.00453512, "locked": 0 } // } // // ADD_FUNDS // { // "historyId": "3158236d-dae5-4a5d-81af-c1fa4af340fb", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": "8e83a960-e737-4380-b8bb-259d6e236faa", // "time": 1520631178816, // "type": "ADD_FUNDS", // "value": 0.628405, // "fundsBefore": { "total": 0.00453512, "available": 0.00453512, "locked": 0 }, // "fundsAfter": { "total": 0.63294012, "available": 0.63294012, "locked": 0 }, // "change": { "total": 0.628405, "available": 0.628405, "locked": 0 } // } // // TRANSACTION_PRE_LOCKING // { // "historyId": "e7d19e0f-03b3-46a8-bc72-dde72cc24ead", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": null, // "time": 1520706403868, // "type": "TRANSACTION_PRE_LOCKING", // "value": -0.1, // "fundsBefore": { "total": 0.63294012, "available": 0.63294012, "locked": 0 }, // "fundsAfter": { "total": 0.63294012, "available": 0.53294012, "locked": 0.1 }, // "change": { "total": 0, "available": -0.1, "locked": 0.1 } // } // // TRANSACTION_POST_OUTCOME // { // "historyId": "c4010825-231d-4a9c-8e46-37cde1f7b63c", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": "bf2876bc-b545-4503-96c8-ef4de8233876", // "time": 1520706404032, // "type": "TRANSACTION_POST_OUTCOME", // "value": -0.01771415, // "fundsBefore": { "total": 0.63294012, "available": 0.53294012, "locked": 0.1 }, // "fundsAfter": { "total": 0.61522597, "available": 0.53294012, "locked": 0.08228585 }, // "change": { "total": -0.01771415, "available": 0, "locked": -0.01771415 } // } // // TRANSACTION_POST_INCOME // { // "historyId": "7f18b7af-b676-4125-84fd-042e683046f6", // "balance": { // "id": "ab43023b-4079-414c-b340-056e3430a3af", // "currency": "EUR", // "type": "FIAT", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "EUR" // }, // "detailId": "f5fcb274-0cc7-4385-b2d3-bae2756e701f", // "time": 1520706404035, // "type": "TRANSACTION_POST_INCOME", // "value": 628.78, // "fundsBefore": { "total": 0, "available": 0, "locked": 0 }, // "fundsAfter": { "total": 628.78, "available": 628.78, "locked": 0 }, // "change": { "total": 628.78, "available": 628.78, "locked": 0 } // } // // TRANSACTION_COMMISSION_OUTCOME // { // "historyId": "843177fa-61bc-4cbf-8be5-b029d856c93b", // "balance": { // "id": "ab43023b-4079-414c-b340-056e3430a3af", // "currency": "EUR", // "type": "FIAT", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "EUR" // }, // "detailId": "f5fcb274-0cc7-4385-b2d3-bae2756e701f", // "time": 1520706404050, // "type": "TRANSACTION_COMMISSION_OUTCOME", // "value": -2.71, // "fundsBefore": { "total": 766.06, "available": 766.06, "locked": 0 }, // "fundsAfter": { "total": 763.35,"available": 763.35, "locked": 0 }, // "change": { "total": -2.71, "available": -2.71, "locked": 0 } // } // // TRANSACTION_OFFER_COMPLETED_RETURN // { // "historyId": "cac69b04-c518-4dc5-9d86-e76e91f2e1d2", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": null, // "time": 1520714886425, // "type": "TRANSACTION_OFFER_COMPLETED_RETURN", // "value": 0.00000196, // "fundsBefore": { "total": 0.00941208, "available": 0.00941012, "locked": 0.00000196 }, // "fundsAfter": { "total": 0.00941208, "available": 0.00941208, "locked": 0 }, // "change": { "total": 0, "available": 0.00000196, "locked": -0.00000196 } // } // // WITHDRAWAL_LOCK_FUNDS // { // "historyId": "03de2271-66ab-4960-a786-87ab9551fc14", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": "6ad3dc72-1d6d-4ec2-8436-ca43f85a38a6", // "time": 1522245654481, // "type": "WITHDRAWAL_LOCK_FUNDS", // "value": -0.8, // "fundsBefore": { "total": 0.8, "available": 0.8, "locked": 0 }, // "fundsAfter": { "total": 0.8, "available": 0, "locked": 0.8 }, // "change": { "total": 0, "available": -0.8, "locked": 0.8 } // } // // WITHDRAWAL_SUBTRACT_FUNDS // { // "historyId": "b0308c89-5288-438d-a306-c6448b1a266d", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": "6ad3dc72-1d6d-4ec2-8436-ca43f85a38a6", // "time": 1522246526186, // "type": "WITHDRAWAL_SUBTRACT_FUNDS", // "value": -0.8, // "fundsBefore": { "total": 0.8, "available": 0, "locked": 0.8 }, // "fundsAfter": { "total": 0, "available": 0, "locked": 0 }, // "change": { "total": -0.8, "available": 0, "locked": -0.8 } // } // // TRANSACTION_OFFER_ABORTED_RETURN // { // "historyId": "b1a3c075-d403-4e05-8f32-40512cdd88c0", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": null, // "time": 1522512298662, // "type": "TRANSACTION_OFFER_ABORTED_RETURN", // "value": 0.0564931, // "fundsBefore": { "total": 0.44951311, "available": 0.39302001, "locked": 0.0564931 }, // "fundsAfter": { "total": 0.44951311, "available": 0.44951311, "locked": 0 }, // "change": { "total": 0, "available": 0.0564931, "locked": -0.0564931 } // } // // WITHDRAWAL_UNLOCK_FUNDS // { // "historyId": "0ed569a2-c330-482e-bb89-4cb553fb5b11", // "balance": { // "id": "3a7e7a1e-0324-49d5-8f59-298505ebd6c7", // "currency": "BTC", // "type": "CRYPTO", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "BTC" // }, // "detailId": "0c7be256-c336-4111-bee7-4eb22e339700", // "time": 1527866360785, // "type": "WITHDRAWAL_UNLOCK_FUNDS", // "value": 0.05045, // "fundsBefore": { "total": 0.86001578, "available": 0.80956578, "locked": 0.05045 }, // "fundsAfter": { "total": 0.86001578, "available": 0.86001578, "locked": 0 }, // "change": { "total": 0, "available": 0.05045, "locked": -0.05045 } // } // // TRANSACTION_COMMISSION_RETURN // { // "historyId": "07c89c27-46f1-4d7a-8518-b73798bf168a", // "balance": { // "id": "ab43023b-4079-414c-b340-056e3430a3af", // "currency": "EUR", // "type": "FIAT", // "userId": "a34d361d-7bad-49c1-888e-62473b75d877", // "name": "EUR" // }, // "detailId": null, // "time": 1528304043063, // "type": "TRANSACTION_COMMISSION_RETURN", // "value": 0.6, // "fundsBefore": { "total": 0, "available": 0, "locked": 0 }, // "fundsAfter": { "total": 0.6, "available": 0.6, "locked": 0 }, // "change": { "total": 0.6, "available": 0.6, "locked": 0 } // } // const timestamp = this.safeInteger (item, 'time'); const balance = this.safeValue (item, 'balance', {}); const currencyId = this.safeString (balance, 'currency'); const code = this.safeCurrencyCode (currencyId); const change = this.safeValue (item, 'change', {}); let amount = this.safeNumber (change, 'total'); let direction = 'in'; if (amount < 0) { direction = 'out'; amount = -amount; } const id = this.safeString (item, 'historyId'); // there are 2 undocumented api calls: (v1_01PrivateGetPaymentsDepositDetailId and v1_01PrivateGetPaymentsWithdrawalDetailId) // that can be used to enrich the transfers with txid, address etc (you need to use info.detailId as a parameter) const referenceId = this.safeString (item, 'detailId'); const type = this.parseLedgerEntryType (this.safeString (item, 'type')); const fundsBefore = this.safeValue (item, 'fundsBefore', {}); const before = this.safeNumber (fundsBefore, 'total'); const fundsAfter = this.safeValue (item, 'fundsAfter', {}); const after = this.safeNumber (fundsAfter, 'total'); return { 'info': item, 'id': id, 'direction': direction, 'account': undefined, 'referenceId': referenceId, 'referenceAccount': undefined, 'type': type, 'currency': code, 'amount': amount, 'before': before, 'after': after, 'status': 'ok', 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'fee': undefined, }; } parseLedgerEntryType (type) { const types = { 'ADD_FUNDS': 'transaction', 'BITCOIN_GOLD_FORK': 'transaction', 'CREATE_BALANCE': 'transaction', 'FUNDS_MIGRATION': 'transaction', 'WITHDRAWAL_LOCK_FUNDS': 'transaction', 'WITHDRAWAL_SUBTRACT_FUNDS': 'transaction', 'WITHDRAWAL_UNLOCK_FUNDS': 'transaction', 'TRANSACTION_COMMISSION_OUTCOME': 'fee', 'TRANSACTION_COMMISSION_RETURN': 'fee', 'TRANSACTION_OFFER_ABORTED_RETURN': 'trade', 'TRANSACTION_OFFER_COMPLETED_RETURN': 'trade', 'TRANSACTION_POST_INCOME': 'trade', 'TRANSACTION_POST_OUTCOME': 'trade', 'TRANSACTION_PRE_LOCKING': 'trade', }; return this.safeString (types, type, type); } parseOHLCV (ohlcv, market = undefined) { // // [ // '1582399800000', // { // o: '0.0001428', // c: '0.0001428', // h: '0.0001428', // l: '0.0001428', // v: '4', // co: '1' // } // ] // const first = this.safeValue (ohlcv, 1, {}); return [ this.safeInteger (ohlcv, 0), this.safeNumber (first, 'o'), this.safeNumber (first, 'h'), this.safeNumber (first, 'l'), this.safeNumber (first, 'c'), this.safeNumber (first, 'v'), ]; } async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const tradingSymbol = market['baseId'] + '-' + market['quoteId']; const request = { 'symbol': tradingSymbol, 'resolution': this.timeframes[timeframe], // 'from': 1574709092000, // unix timestamp in milliseconds, required // 'to': 1574709092000, // unix timestamp in milliseconds, required }; if (limit === undefined) { limit = 100; } const duration = this.parseTimeframe (timeframe); const timerange = limit * duration * 1000; if (since === undefined) { request['to'] = this.milliseconds (); request['from'] = request['to'] - timerange; } else { request['from'] = parseInt (since); request['to'] = this.sum (request['from'], timerange); } const response = await this.v1_01PublicGetTradingCandleHistorySymbolResolution (this.extend (request, params)); // // { // "status":"Ok", // "items":[ // ["1591503060000",{"o":"0.02509572","c":"0.02509438","h":"0.02509664","l":"0.02509438","v":"0.02082165","co":"17"}], // ["1591503120000",{"o":"0.02509606","c":"0.02509515","h":"0.02509606","l":"0.02509487","v":"0.04971703","co":"13"}], // ["1591503180000",{"o":"0.02509532","c":"0.02509589","h":"0.02509589","l":"0.02509454","v":"0.01332236","co":"7"}], // ] // } // const items = this.safeValue (response, 'items', []); return this.parseOHLCVs (items, market, timeframe, since, limit); } parseTrade (trade, market = undefined) { // // createOrder trades // // { // "rate": "0.02195928", // "amount": "0.00167952" // } // // fetchMyTrades (private) // // { // amount: "0.29285199", // commissionValue: "0.00125927", // id: "11c8203a-a267-11e9-b698-0242ac110007", // initializedBy: "Buy", // market: "ETH-EUR", // offerId: "11c82038-a267-11e9-b698-0242ac110007", // rate: "277", // time: "1562689917517", // userAction: "Buy", // wasTaker: true, // } // // fetchTrades (public) // // { // id: 'df00b0da-e5e0-11e9-8c19-0242ac11000a', // t: '1570108958831', // a: '0.04776653', // r: '0.02145854', // ty: 'Sell' // } // const timestamp = this.safeInteger2 (trade, 'time', 't'); const side = this.safeStringLower2 (trade, 'userAction', 'ty'); const wasTaker = this.safeValue (trade, 'wasTaker'); let takerOrMaker = undefined; if (wasTaker !== undefined) { takerOrMaker = wasTaker ? 'taker' : 'maker'; } const priceString = this.safeString2 (trade, 'rate', 'r'); const amountString = this.safeString2 (trade, 'amount', 'a'); const feeCostString = this.safeString (trade, 'commissionValue'); const marketId = this.safeString (trade, 'market'); market = this.safeMarket (marketId, market, '-'); const symbol = market['symbol']; let fee = undefined; if (feeCostString !== undefined) { const feeCurrency = (side === 'buy') ? market['base'] : market['quote']; fee = { 'currency': feeCurrency, 'cost': feeCostString, }; } const order = this.safeString (trade, 'offerId'); // todo: check this logic let type = undefined; if (order !== undefined) { type = order ? 'limit' : 'market'; } return this.safeTrade ({ 'id': this.safeString (trade, 'id'), 'order': order, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'type': type, 'side': side, 'price': priceString, 'amount': amountString, 'cost': undefined, 'takerOrMaker': takerOrMaker, 'fee': fee, 'info': trade, }, market); } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const tradingSymbol = market['baseId'] + '-' + market['quoteId']; const request = { 'symbol': tradingSymbol, }; if (since !== undefined) { request['fromTime'] = since - 1; // result does not include exactly `since` time therefore decrease by 1 } if (limit !== undefined) { request['limit'] = limit; // default - 10, max - 300 } const response = await this.v1_01PublicGetTradingTransactionsSymbol (this.extend (request, params)); const items = this.safeValue (response, 'items'); return this.parseTrades (items, market, since, limit); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const tradingSymbol = market['baseId'] + '-' + market['quoteId']; const request = { 'symbol': tradingSymbol, 'offerType': side, 'amount': amount, 'mode': type, }; if (type === 'limit') { request['rate'] = price; price = parseFloat (price); } amount = parseFloat (amount); const response = await this.v1_01PrivatePostTradingOfferSymbol (this.extend (request, params)); // // unfilled (open order) // // { // status: 'Ok', // completed: false, // can deduce status from here // offerId: 'ce9cc72e-d61c-11e9-9248-0242ac110005', // transactions: [], // can deduce order info from here // } // // filled (closed order) // // { // "status": "Ok", // "offerId": "942a4a3e-e922-11e9-8c19-0242ac11000a", // "completed": true, // "transactions": [ // { // "rate": "0.02195928", // "amount": "0.00167952" // }, // { // "rate": "0.02195928", // "amount": "0.00167952" // }, // { // "rate": "0.02196207", // "amount": "0.27704177" // } // ] // } // // partially-filled (open order) // // { // "status": "Ok", // "offerId": "d0ebefab-f4d7-11e9-8c19-0242ac11000a", // "completed": false, // "transactions": [ // { // "rate": "0.02106404", // "amount": "0.0019625" // }, // { // "rate": "0.02106404", // "amount": "0.0019625" // }, // { // "rate": "0.02105901", // "amount": "0.00975256" // } // ] // } // const timestamp = this.milliseconds (); // the real timestamp is missing in the response const id = this.safeString (response, 'offerId'); const completed = this.safeValue (response, 'completed', false); const status = completed ? 'closed' : 'open'; let filled = 0; let cost = undefined; const transactions = this.safeValue (response, 'transactions'); let trades = undefined; if (transactions !== undefined) { trades = this.parseTrades (transactions, market, undefined, undefined, { 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'side': side, 'type': type, 'orderId': id, }); cost = 0; for (let i = 0; i < trades.length; i++) { filled = this.sum (filled, trades[i]['amount']); cost = this.sum (cost, trades[i]['cost']); } } const remaining = amount - filled; return { 'id': id, 'info': response, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'lastTradeTimestamp': undefined, 'status': status, 'symbol': symbol, 'type': type, 'side': side, 'price': price, 'amount': amount, 'cost': cost, 'filled': filled, 'remaining': remaining, 'average': undefined, 'fee': undefined, 'trades': trades, 'clientOrderId': undefined, }; } async cancelOrder (id, symbol = undefined, params = {}) { const side = this.safeString (params, 'side'); if (side === undefined) { throw new ExchangeError (this.id + ' cancelOrder() requires a `side` parameter ("buy" or "sell")'); } const price = this.safeValue (params, 'price'); if (price === undefined) { throw new ExchangeError (this.id + ' cancelOrder() requires a `price` parameter (float or string)'); } await this.loadMarkets (); const market = this.market (symbol); const tradingSymbol = market['baseId'] + '-' + market['quoteId']; const request = { 'symbol': tradingSymbol, 'id': id, 'side': side, 'price': price, }; // { status: 'Fail', errors: [ 'NOT_RECOGNIZED_OFFER_TYPE' ] } -- if required params are missing // { status: 'Ok', errors: [] } return this.v1_01PrivateDeleteTradingOfferSymbolIdSidePrice (this.extend (request, params)); } isFiat (currency) { const fiatCurrencies = { 'USD': true, 'EUR': true, 'PLN': true, }; return this.safeValue (fiatCurrencies, currency, false); } async withdraw (code, amount, address, tag = undefined, params = {}) { [ tag, params ] = this.handleWithdrawTagAndParams (tag, params); this.checkAddress (address); await this.loadMarkets (); let method = undefined; const currency = this.currency (code); const request = { 'currency': currency['id'], 'quantity': amount, }; if (this.isFiat (code)) { method = 'privatePostWithdraw'; // request['account'] = params['account']; // they demand an account number // request['express'] = params['express']; // whatever it means, they don't explain // request['bic'] = ''; } else { method = 'privatePostTransfer'; if (tag !== undefined) { address += '?dt=' + tag.toString (); } request['address'] = address; } const response = await this[method] (this.extend (request, params)); return { 'info': response, 'id': undefined, }; } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { let url = this.implodeHostname (this.urls['api'][api]); if (api === 'public') { const query = this.omit (params, this.extractParams (path)); url += '/' + this.implodeParams (path, params) + '.json'; if (Object.keys (query).length) { url += '?' + this.urlencode (query); } } else if (api === 'v1_01Public') { const query = this.omit (params, this.extractParams (path)); url += '/' + this.implodeParams (path, params); if (Object.keys (query).length) { url += '?' + this.urlencode (query); } } else if (api === 'v1_01Private') { this.checkRequiredCredentials (); const query = this.omit (params, this.extractParams (path)); url += '/' + this.implodeParams (path, params); const nonce = this.milliseconds ().toString (); let payload = undefined; if (method !== 'POST') { if (Object.keys (query).length) { url += '?' + this.urlencode (query); } payload = this.apiKey + nonce; } else if (body === undefined) { body = this.json (query); payload = this.apiKey + nonce + body; } headers = { 'Request-Timestamp': nonce, 'Operation-Id': this.uuid (), 'API-Key': this.apiKey, 'API-Hash': this.hmac (this.encode (payload), this.encode (this.secret), 'sha512'), 'Content-Type': 'application/json', }; } else { this.checkRequiredCredentials (); body = this.urlencode (this.extend ({ 'method': path, 'moment': this.nonce (), }, params)); headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'API-Key': this.apiKey, 'API-Hash': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'), }; } return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) { if (response === undefined) { return; // fallback to default error handler } if ('code' in response) { // // bitbay returns the integer 'success': 1 key from their private API // or an integer 'code' value from 0 to 510 and an error message // // { 'success': 1, ... } // { 'code': 502, 'message': 'Invalid sign' } // { 'code': 0, 'message': 'offer funds not exceeding minimums' } // // 400 At least one parameter wasn't set // 401 Invalid order type // 402 No orders with specified currencies // 403 Invalid payment currency name // 404 Error. Wrong transaction type // 405 Order with this id doesn't exist // 406 No enough money or crypto // 408 Invalid currency name // 501 Invalid public key // 502 Invalid sign // 503 Invalid moment parameter. Request time doesn't match current server time // 504 Invalid method // 505 Key has no permission for this action // 506 Account locked. Please contact with customer service // 509 The BIC/SWIFT is required for this currency // 510 Invalid market name // const code = this.safeString (response, 'code'); // always an integer const feedback = this.id + ' ' + body; this.throwExactlyMatchedException (this.exceptions, code, feedback); throw new ExchangeError (feedback); } else if ('status' in response) { // // {"status":"Fail","errors":["OFFER_FUNDS_NOT_EXCEEDING_MINIMUMS"]} // const status = this.safeString (response, 'status'); if (status === 'Fail') { const errors = this.safeValue (response, 'errors'); const feedback = this.id + ' ' + body; for (let i = 0; i < errors.length; i++) { const error = errors[i]; this.throwExactlyMatchedException (this.exceptions, error, feedback); } throw new ExchangeError (feedback); } } } };
"use strict"; import config from "./config.json"; import { findCorrespondingRightBracket } from "./texParser.js"; // import { // mathQuillEditHandlerActive // } from "./editHandler.js"; import { setEditHandlerActive } from "./switchEditHandler.js"; export function getSelection(mf, options) { // if options.erase is undefined, erase defaults to false var erase = options.erase || false; console.log('getSelection: erase=' + erase); // typeof mf = mathField var ori = mf.latex(); console.log('ori= ' + ori); var erased = ori; if (erase) { erased = eraseInputfieldClass(ori); } var replacementCharacter = createreplacementCharacter(ori); if (ori.indexOf(replacementCharacter) === -1) { // replacement has to be done before erase of class{... // Do replacement! // eslint-disable-next-line no-import-assign setEditHandlerActive(false); mf.typedText(replacementCharacter); // eslint-disable-next-line no-import-assign setEditHandlerActive(true); // erase class{inputfield} var replacedAndErased = mf.latex(); if (erase) { replacedAndErased = eraseInputfieldClass(replacedAndErased); } console.log('replacedAndErased= ' + replacedAndErased); var preSelected = '?'; var selected = '?'; var postSelected = '?'; var pos = replacedAndErased.indexOf(replacementCharacter); preSelected = replacedAndErased.substring(0, pos); // selected = replacement postSelected = replacedAndErased.substring(pos + replacementCharacter.length); // Delete preSelected from beginning of erased // and delete postSelected from end of erased var check = erased.substr(0, preSelected.length); if (check !== preSelected) { console.error('Something went wrong with replacement of input field', check, preSelected); } erased = erased.substring(preSelected.length); check = erased.substring(erased.length - postSelected.length); if (check !== postSelected) { console.error('Something went wrong with replacement of input field', check, postSelected); } selected = erased.substring(0, erased.length - postSelected.length); // var result = [preSelected, selected, postSelected, ori]; old syntax, DELETE var result = { preSelected: preSelected, selected: selected, postSelected: postSelected, ori: ori }; return result; } } export function setInput(editorMf) { var sel = getSelection(editorMf, { erase: true }); var preSelected = sel.preSelected; var selected = sel.selected; var postSelected = sel.postSelected; var result = {}; result['old'] = sel.ori; var newLatex = sel.ori; if (selected.length > 0) { newLatex = preSelected + '\\class{inputfield}{' + selected + '}' + postSelected; } else { newLatex = sanitizeInputfieldTag(newLatex); } result['new'] = newLatex; return result; } function getPositionOfUnitTags(latex, unitTag) { // get position of exising unit tags var pos = 0; var startOfUnitTags = []; var endOfUnitTags = []; do { pos = latex.indexOf(unitTag, pos); if (pos >= 0) { var rest = latex.substr(pos + unitTag.length - 1); var bracket = findCorrespondingRightBracket(rest, '{'); var posRightBracket = pos + unitTag.length + bracket.rightPos; startOfUnitTags.push(pos); endOfUnitTags.push(posRightBracket); //posRightBracket points to char right of the right bracket pos++; } } while (pos >= 0) return { sofUnitTags: startOfUnitTags, eofUnitTags: endOfUnitTags }; } export function setUnit(mf) { var i, k; var unitTag = config.unit_replacement; var sel = getSelection(mf, { erase: false }); var preSelected = sel.preSelected; var selected = sel.selected; var postSelected = sel.postSelected; var ori = sel.ori; var start = preSelected.length; var end = start + selected.length; var selectpattern = '.'.repeat(ori.length).split(''); // split: transform from string to array for (k = start; k < end; k++) { selectpattern[k] = 's'; } var posn = getPositionOfUnitTags(ori, unitTag); var startOfUnitTags = posn.sofUnitTags; var endOfUnitTags = posn.eofUnitTags; var pattern = '.'.repeat(ori.length).split(''); // split: transform from string to array for (i = 0; i < startOfUnitTags.length; i++) { for (k = startOfUnitTags[i]; k < endOfUnitTags[i]; k++) { pattern[k] = '#'; } } // inspect selection start for (i = 0; i < startOfUnitTags.length; i++) { if (startOfUnitTags[i] < start && start <= endOfUnitTags[i]) { // move start leftwards start = startOfUnitTags[i]; // short circuit: i = startOfUnitTags.length; } } // inspect selection end for (i = 0; i < startOfUnitTags.length; i++) { if (startOfUnitTags[i] <= end && end <= endOfUnitTags[i]) { // move end rightwards end = endOfUnitTags[i]; // short circuit: i = startOfUnitTags.length; } } // debug selectpattern = '.'.repeat(ori.length).split(''); // split: transform from string to array for (k = start; k < end; k++) { selectpattern[k] = 's'; } // delete unittags inside selection var ori_array = ori.split(''); for (i = 0; i < startOfUnitTags.length; i++) { if (start <= startOfUnitTags[i] && endOfUnitTags[i] <= end) { for (k = startOfUnitTags[i]; k < startOfUnitTags[i] + unitTag.length; k++) { ori_array[k] = '§'; } ori_array[endOfUnitTags[i] - 1] = '§'; } } ori = ori_array.join(''); if (selected.length > 0) { // new calculation necessary preSelected = ori.substring(0, start); selected = ori.substring(start, end); postSelected = ori.substring(end); var newLatex = preSelected + unitTag + selected + '}' + postSelected; // newLatex = newLatex.replace(/\xA7/g, ''); newLatex = newLatex.replace(/§/g, ''); } else { newLatex = ori.replace(/§/g, ''); } mf.latex(sanitizeInputfieldTag(newLatex)); } function sanitizeInputfieldTag(latex) { var result; if (typeof latex === 'undefined') { result = ''; } else { // first make shorter result = latex.replace('\\class{inputfield}{', '\\class{'); // then make longer again result = result.replace('\\class{', '\\class{inputfield}{'); return result; } } export function eraseUnit(mf) { // var unitTag = '\\textcolor{blue}{'; var unitTag = config.unit_replacement; var sel = getSelection(mf, { erase: false }); var ori = sel.ori; // get position of unittags var posn = getPositionOfUnitTags(ori, unitTag); var startOfUnitTags = posn.sofUnitTags; var endOfUnitTags = posn.eofUnitTags; // delete unittag outside cursor (or left boundary of selection) var cursorpos = sel.preSelected.length; var ori_array = ori.split(''); for (var i = 0; i < startOfUnitTags.length; i++) { if (startOfUnitTags[i] <= cursorpos && cursorpos <= endOfUnitTags[i]) { for (var k = startOfUnitTags[i]; k < startOfUnitTags[i] + unitTag.length; k++) { ori_array[k] = '§'; } ori_array[endOfUnitTags[i] - 1] = '§'; } } ori = ori_array.join(''); ori = ori.replace(/§/g, ''); // restore selection-checked mf mf.latex(sanitizeInputfieldTag(ori)); } /** * * @param {string} latex string containing latex code * @returns {object} object consisting of three strings: before, tag, after * @example result = separateInputfield("bli\\class{inputfield}{bla}blu"), then * @example result.before = "bli", result.tag = "bla", result.after = "blu" * @example result = separateInputfield("string_without_inputfield"), then * @example result.before = "", result.tag = "", result.after = "string_without_inputfield" */ // separateInputfield is also used by refreshResultField. export function separateInputfield(latex) { var beforeTag, tag, afterTag; var classTag = '\\class{inputfield}{'; var pos = latex.indexOf(classTag); if (pos > -1) { beforeTag = latex.substring(0, pos); var rest = latex.substring(pos + classTag.length - 1); // rest starts with { var bracket = findCorrespondingRightBracket(rest, '{'); if (bracket.leftPos !== 0 || bracket.bracketLength !== 1 || bracket.rightBracketLength !== 1) { console.error('Something went wront at separateInputfield()', bracket); } tag = rest.substring(1, bracket.rightPos); afterTag = rest.substring(bracket.rightPos + 1); } else { beforeTag = ''; tag = ''; afterTag = latex; } var result = { before: beforeTag, tag: tag, after: afterTag }; // console.info(latex); // console.info(beforeTag + '|' + tag + '|' + afterTag); return result; } function eraseInputfieldClass(latex) { // latex = 'abc\\class{inputfield}{def}ghi'; // temp = {before: 'abc', tag: 'def', after: 'ghi'}; // return 'abcdefghi'; var temp = separateInputfield(latex); return temp.before + temp.tag + temp.after; } export function createreplacementCharacter(latexstring) { const separators = '∀µ∉ö∋∐∔∝∤∮∱∸∺∽≀'; var i = 0; sep = ''; do { var sep = separators[i]; var found = (latexstring.indexOf(sep) > -1); var cont = found; i++; if (i > separators.length) { cont = false; sep = 'no replacementCharacter char found'; } } while (cont) return sep; }
const tabs_1 = document.querySelectorAll('[data-level="1"]>.tab-button'); tabs_1.forEach((item) => { const contents = document.querySelectorAll('[data-level="1"]>.content'); item.addEventListener('click', event => { changeClass(event.target, tabs_1); changeContent(event.target.dataset.button, contents) }); }); const tabs_2 = document.querySelectorAll('[data-level="2"]>.tab-button'); tabs_2.forEach((item) => { const contents = document.querySelectorAll('[data-level="2"]>.content'); item.addEventListener('click', event => { changeClass(event.target, tabs_2); changeContent(event.target.dataset.button, contents) }); }); function changeClass(element, component) { console.log(element); for(let item of component){ item.classList.remove("active"); } element.classList.add("active"); } function changeContent(currTab, component) { for(let item of component){ if(item.dataset.content === currTab) { item.classList.add("active"); } else { item.classList.remove("active"); } } }
// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // An input string is valid if: // Open brackets must be closed by the same type of brackets. // Open brackets must be closed in the correct order. //create a peek method so it can be implemented function peek(stack) { return stack[stack.length -1] } function validateParentheses(str) { // set a var equal to an empty array to create a stack //iterate through every lettter of the string, if the letter is an opening parn, push it on the stack for (let i= 0; i < str.length; i++) { let char = str.charAt(i) if (char === '(') { stack.push(char) } else if (char === ')') { if (stack.length === 0) { return false; } else if (peek(stack) === '(') { stack.pop() } else { return false; } } } //if the letter is a closing paren, make sure it has a matching opening paren return stack.length === 0 } //without peek method? //taken from leetcode solutions var isValid = function(s) { if (s === null || s.length <= 0) return true; var cArr = s.split(''); var stack = []; for (var c of cArr) { if (c === '[') stack.push(']'); else if (c === '{') stack.push('}'); else if (c === '(') stack.push(')'); else if (stack.length === 0 || c !== stack.pop()) return false; } if (stack.length === 0) return true; return false; };
require("campaign/planet"); print("Load Complete!"); /* credit(){ younggam: "answering tons of question", deltaNedas: "refer to routorio, rtfm", sk7725: "answering tons of question, refer to testers" } */
define('node_modules/lodash/fp/add', function(require, exports, module) { var convert = require('node_modules/lodash/fp/convert'), func = convert('add', require('node_modules/lodash/add')); func.placeholder = require('node_modules/lodash/fp/placeholder'); module.exports = func; });
const sm = require('sitemap') const posts = require('./posts') const sitemap = sm.createSitemap({ hostname: 'https://sitemap-robots.now.sh', cacheTime: 600000 // 600 sec - cache purge period }) const setup = ({ server }) => { const Posts = posts() for (let i = 0; i < Posts.length; i += 1) { const post = Posts[i] sitemap.add({ url: `/posts/${post.slug}`, changefreq: 'daily', priority: 0.9 }) } sitemap.add({ url: '/a', changefreq: 'daily', priority: 1 }) sitemap.add({ url: '/b', changefreq: 'daily', priority: 1 }) server.get('/sitemap.xml', (req, res) => { sitemap.toXML((err, xml) => { if (err) { res.status(500).end() return } res.header('Content-Type', 'application/xml') res.send(xml) }) }) } module.exports = setup
var os = require('os'); module.exports = function() { var platform = os.platform(); if (process.env.NOBLE_WEBSOCKET || process.title === 'browser') { return require('./websocket/bindings'); } else if (process.env.NOBLE_DISTRIBUTED) { return require('./distributed/bindings'); } else if (platform === 'darwin') { return require('./mac/bindings'); } else if (platform === 'linux' || platform === 'freebsd' || platform === 'win32') { return require('./hci-socket/bindings'); } else { throw new Error('Unsupported platform'); } };
import { container } from "../../../../assets/jss/material-kit-react"; const cityHomeStyle = theme => ({ container: { ...container, position: "relative", width: "100%", height: "100%", display: "flex", justifyContent: "flex-end", alignItems: "flex-end" }, content: { margin: "20px 0px" }, addPlaceButton: { backgroundColor: "#fff", margin: "20px", zIndex: 1100, color: "#000" }, parrallexClass:{ height:"50vh", }, myAddFavAction: { position: "fixed", bottom: theme.spacing.unit * 4, right: theme.spacing.unit * 4 } }); export default cityHomeStyle;
import React from 'react'; import PropTypes from 'prop-types'; import dayjs from 'dayjs'; import { Link } from 'react-router-dom'; // const goToProjectDetails = () => { // localStorage.setItem('projectId') // } const Cell = ({ data }) => ( <div className="cell-container"> <article className="mini-post"> <header> <h3><Link to={`/projects/${data.projectId}`}>{data.title}</Link></h3> <time className="published">{dayjs(data.date).format('MMMM, YYYY')}</time> </header> <Link to={`/projects/${data.projectId}`} className="image"> <img src={`${process.env.PUBLIC_URL}${data.image}`} alt={data.title} /> </Link> <div className="description"> <p>{data.desc}</p> </div> </article> </div> ); Cell.propTypes = { data: PropTypes.shape({ projectId: PropTypes.string, title: PropTypes.string.isRequired, link: PropTypes.string, image: PropTypes.string.isRequired, date: PropTypes.string.isRequired, desc: PropTypes.string.isRequired, }).isRequired, }; export default Cell;
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var proximityDevice = null; var page = WinJS.UI.Pages.define("/html/Scenario4_ProximityDeviceEvents.html", { ready: function (element, options) { proximityDevice = ProximityHelpers.initializeProximityDevice(); if (proximityDevice) { // Register for device arrived and departed events to know when a proximate device is in range. proximityDevice.addEventListener("devicearrived", deviceArrived); proximityDevice.addEventListener("devicedeparted", deviceDeparted); } }, unload: function () { ProximityHelpers.clearLog(ProximityHelpers.id("proximityDeviceEvents_Output")); if (proximityDevice) { proximityDevice.removeEventListener("devicearrived", deviceArrived); proximityDevice.removeEventListener("devicedeparted", deviceDeparted); } } }); function deviceArrived(arrivingDevice) { ProximityHelpers.logInfo(ProximityHelpers.id("proximityDeviceEvents_Output"), "Proximate device arrived"); } function deviceDeparted(departingDevice) { ProximityHelpers.logInfo(ProximityHelpers.id("proximityDeviceEvents_Output"), "Proximate device departed"); } })();
webpackJsonp([43],{"17fl":function(e,t,n){(e.exports=n("FZ+f")(!1)).push([e.i,"\n.example-btn[data-v-02f9ea3e] {\n display: inline-block;\n margin-bottom: 0;\n font-weight: 500;\n text-align: center;\n -ms-touch-action: manipulation;\n touch-action: manipulation;\n cursor: pointer;\n background-image: none;\n border: 1px solid transparent;\n white-space: nowrap;\n line-height: 1.5;\n padding: 4px 15px;\n font-size: 12px;\n border-radius: 4px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n -webkit-transition: all .3s cubic-bezier(.645, .045, .355, 1);\n transition: all .3s cubic-bezier(.645, .045, .355, 1);\n position: relative;\n color: rgba(0, 0, 0, .65);\n background-color: #fff;\n border-color: #d9d9d9;\n}\n.example-btn[data-v-02f9ea3e]:hover {\n color: #4AB7BD;\n background-color: #fff;\n border-color: #4AB7BD;\n}\n.example[data-v-02f9ea3e] {\n font-size: 50px;\n color: #F6416C;\n display: block;\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n font-weight: 500;\n}\n.label[data-v-02f9ea3e] {\n color: #2f4f4f;\n font-size: 16px;\n display: inline-block;\n margin: 15px 30px 15px 0;\n}\ninput[data-v-02f9ea3e] {\n position: relative;\n display: inline-block;\n padding: 4px 7px;\n width: 70px;\n height: 28px;\n cursor: text;\n font-size: 12px;\n line-height: 1.5;\n color: rgba(0, 0, 0, .65);\n background-color: #fff;\n background-image: none;\n border: 1px solid #d9d9d9;\n border-radius: 4px;\n -webkit-transition: all .3s;\n transition: all .3s;\n}\n.startBtn[data-v-02f9ea3e] {\n margin-left: 20px;\n font-size: 20px;\n color: #30B08F;\n background-color: #fff;\n}\n.startBtn[data-v-02f9ea3e]:hover {\n background-color: #30B08F;\n color: #fff;\n border-color: #30B08F;\n}\n.pause-resume-btn[data-v-02f9ea3e] {\n font-size: 20px;\n color: #E65D6E;\n background-color: #fff;\n}\n.pause-resume-btn[data-v-02f9ea3e]:hover {\n background-color: #E65D6E;\n color: #fff;\n border-color: #E65D6E;\n}\n",""])},"G/2s":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n("WBHA"),r={name:"countTo-demo",components:{countTo:n.n(a).a},data:function(){return{setStartVal:0,setEndVal:2017,setDuration:4e3,setDecimals:0,setSeparator:",",setSuffix:" rmb",setPrefix:"¥ "}},computed:{_startVal:function(){return this.setStartVal?this.setStartVal:0},_endVal:function(){return this.setEndVal?this.setEndVal:0},_duration:function(){return this.setDuration?this.setDuration:100},_decimals:function(){return this.setDecimals?this.setDecimals<0||this.setDecimals>20?(alert("digits argument must be between 0 and 20"),0):this.setDecimals:0},_separator:function(){return this.setSeparator},_suffix:function(){return this.setSuffix},_prefix:function(){return this.setPrefix}},methods:{start:function(){this.$refs.example.start()},pauseResume:function(){this.$refs.example.pauseResume()}}},s={render:function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"components-container"},[e._m(0),e._v(" "),n("count-to",{ref:"example",staticClass:"example",attrs:{"start-val":e._startVal,"end-val":e._endVal,duration:e._duration,decimals:e._decimals,separator:e._separator,prefix:e._prefix,suffix:e._suffix,autoplay:!1}}),e._v(" "),n("div",{staticStyle:{"margin-left":"25%","margin-top":"40px"}},[n("label",{staticClass:"label",attrs:{for:"startValInput"}},[e._v("startVal:\n "),n("input",{directives:[{name:"model",rawName:"v-model.number",value:e.setStartVal,expression:"setStartVal",modifiers:{number:!0}}],attrs:{type:"number",name:"startValInput"},domProps:{value:e.setStartVal},on:{input:function(t){t.target.composing||(e.setStartVal=e._n(t.target.value))},blur:function(t){e.$forceUpdate()}}})]),e._v(" "),n("label",{staticClass:"label",attrs:{for:"endValInput"}},[e._v("endVal:\n "),n("input",{directives:[{name:"model",rawName:"v-model.number",value:e.setEndVal,expression:"setEndVal",modifiers:{number:!0}}],attrs:{type:"number",name:"endVaInput"},domProps:{value:e.setEndVal},on:{input:function(t){t.target.composing||(e.setEndVal=e._n(t.target.value))},blur:function(t){e.$forceUpdate()}}})]),e._v(" "),n("label",{staticClass:"label",attrs:{for:"durationInput"}},[e._v("duration:\n "),n("input",{directives:[{name:"model",rawName:"v-model.number",value:e.setDuration,expression:"setDuration",modifiers:{number:!0}}],attrs:{type:"number",name:"durationInput"},domProps:{value:e.setDuration},on:{input:function(t){t.target.composing||(e.setDuration=e._n(t.target.value))},blur:function(t){e.$forceUpdate()}}})]),e._v(" "),n("div",{staticClass:"startBtn example-btn",on:{click:e.start}},[e._v("开始")]),e._v(" "),n("div",{staticClass:"pause-resume-btn example-btn",on:{click:e.pauseResume}},[e._v("暂停/恢复")]),e._v(" "),n("br"),e._v(" "),n("label",{staticClass:"label",attrs:{for:"decimalsInput"}},[e._v("decimals:\n "),n("input",{directives:[{name:"model",rawName:"v-model.number",value:e.setDecimals,expression:"setDecimals",modifiers:{number:!0}}],attrs:{type:"number",name:"decimalsInput"},domProps:{value:e.setDecimals},on:{input:function(t){t.target.composing||(e.setDecimals=e._n(t.target.value))},blur:function(t){e.$forceUpdate()}}})]),e._v(" "),n("label",{staticClass:"label",attrs:{for:"separatorInput"}},[e._v("separator:\n "),n("input",{directives:[{name:"model",rawName:"v-model",value:e.setSeparator,expression:"setSeparator"}],attrs:{name:"separatorInput"},domProps:{value:e.setSeparator},on:{input:function(t){t.target.composing||(e.setSeparator=t.target.value)}}})]),e._v(" "),n("label",{staticClass:"label",attrs:{for:"prefixInput"}},[e._v("prefix:\n "),n("input",{directives:[{name:"model",rawName:"v-model",value:e.setPrefix,expression:"setPrefix"}],attrs:{name:"prefixInput"},domProps:{value:e.setPrefix},on:{input:function(t){t.target.composing||(e.setPrefix=t.target.value)}}})]),e._v(" "),n("label",{staticClass:"label",attrs:{for:"suffixInput"}},[e._v("suffix:\n "),n("input",{directives:[{name:"model",rawName:"v-model",value:e.setSuffix,expression:"setSuffix"}],attrs:{name:"suffixInput"},domProps:{value:e.setSuffix},on:{input:function(t){t.target.composing||(e.setSuffix=t.target.value)}}})])]),e._v(" "),n("code",[e._v("<count-to :start-val='"+e._s(e._startVal)+"' :end-val='"+e._s(e._endVal)+"' :duration='"+e._s(e._duration)+"'\n :decimals='"+e._s(e._decimals)+"' :separator='"+e._s(e._separator)+"' :prefix='"+e._s(e._prefix)+"' :suffix='"+e._s(e._suffix)+"'\n :autoplay=false>")])],1)},staticRenderFns:[function(){var e=this.$createElement,t=this._self._c||e;return t("p",{staticClass:"warn-content"},[t("a",{attrs:{href:"https://github.com/PanJiaChen/vue-countTo",target:"_blank"}},[this._v("countTo-component")])])}]};var o=n("VU/8")(r,s,!1,function(e){n("aEYS")},"data-v-02f9ea3e",null);t.default=o.exports},aEYS:function(e,t,n){var a=n("17fl");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);n("rjj0")("262245ed",a,!0)}});
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import SearchBar from './components/searchbar'; import YTSearch from 'youtube-api-search' import VideoList from './components/list'; import VideoDetail from './components/videodetail'; import _ from 'lodash' const API_KEY='' //PUT API KEY HERE Google Youtube API V3 class App extends Component{ constructor(props){ super(props) this.state={ searchTerm:'', selectedVideo:null, videos:[] } this.videoSearch() } videoSearch(term){ YTSearch({key:API_KEY,term:term},(videos)=>{ this.setState({ videos:videos, selectedVideo:videos[0] }) }); console.log(term) } render(){ const videoSearch=_.debounce((term)=>this.videoSearch(term),400) return ( <div> <SearchBar onSearch={videoSearch}/> <VideoDetail video={this.state.selectedVideo}/> <VideoList videos={this.state.videos} onVideoClicked={selectedVideo=>this.setState({selectedVideo})} /> </div> ); } } ReactDOM.render(<App/>,document.querySelector('.container'));
import '../../style/base.less'; import '../../badge/index.less'; import '../../icon/index.less'; import '../../checkbox/index.less'; import '../../checkbox-group/index.less'; import '../index.less';
import test from "ava"; import fs from "fs"; import path from "path"; import rimraf from "rimraf"; import webpack from "webpack"; import createTestDirectory from "./helpers/createTestDirectory"; const defaultCacheDir = path.join( __dirname, "../node_modules/.cache/babel-loader", ); const cacheDir = path.join(__dirname, "output/cache/cachefiles"); const outputDir = path.join(__dirname, "output/cache"); const babelLoader = path.join(__dirname, "../lib"); const globalConfig = { entry: path.join(__dirname, "fixtures/basic.js"), module: { loaders: [ { test: /\.js$/, loader: babelLoader, exclude: /node_modules/, }, ], }, }; // Create a separate directory for each test so that the tests // can run in parallel test.cb.beforeEach(t => { createTestDirectory(outputDir, t.title, (err, directory) => { if (err) return t.end(err); t.context.directory = directory; t.end(); }); }); test.cb.beforeEach(t => { createTestDirectory(cacheDir, t.title, (err, directory) => { if (err) return t.end(err); t.context.cacheDirectory = directory; t.end(); }); }); test.cb.beforeEach(t => rimraf(defaultCacheDir, t.end)); test.cb.afterEach(t => rimraf(t.context.directory, t.end)); test.cb.afterEach(t => rimraf(t.context.cacheDirectory, t.end)); test.cb("should output files to cache directory", t => { const config = Object.assign({}, globalConfig, { output: { path: t.context.directory, }, module: { loaders: [ { test: /\.js$/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: t.context.cacheDirectory, presets: ["@babel/preset-env"], }, }, ], }, }); webpack(config, err => { t.is(err, null); fs.readdir(t.context.cacheDirectory, (err, files) => { t.is(err, null); t.true(files.length > 0); t.end(); }); }); }); test.cb.serial( "should output json.gz files to standard cache dir by default", t => { const config = Object.assign({}, globalConfig, { output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: true, presets: ["@babel/preset-env"], }, }, ], }, }); webpack(config, err => { t.is(err, null); fs.readdir(defaultCacheDir, (err, files) => { files = files.filter(file => /\b[0-9a-f]{5,40}\.json\.gz\b/.test(file)); t.is(err, null); t.true(files.length > 0); t.end(); }); }); }, ); test.cb.serial( "should output files to standard cache dir if set to true in query", t => { const config = Object.assign({}, globalConfig, { output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: `${babelLoader}?cacheDirectory=true&presets[]=@babel/preset-env`, exclude: /node_modules/, }, ], }, }); webpack(config, err => { t.is(err, null); fs.readdir(defaultCacheDir, (err, files) => { files = files.filter(file => /\b[0-9a-f]{5,40}\.json\.gz\b/.test(file)); t.is(err, null); t.true(files.length > 0); t.end(); }); }); }, ); test.cb.skip("should read from cache directory if cached file exists", t => { const config = Object.assign({}, globalConfig, { output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: t.context.cacheDirectory, presets: ["@babel/preset-env"], }, }, ], }, }); // @TODO Find a way to know if the file as correctly read without relying on // Istanbul for coverage. webpack(config, err => { t.is(err, null); webpack(config, err => { t.is(err, null); fs.readdir(t.context.cacheDirectory, (err, files) => { t.is(err, null); t.true(files.length > 0); t.end(); }); }); }); }); test.cb("should have one file per module", t => { const config = Object.assign({}, globalConfig, { output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: t.context.cacheDirectory, presets: ["@babel/preset-env"], }, }, ], }, }); webpack(config, err => { t.is(err, null); fs.readdir(t.context.cacheDirectory, (err, files) => { t.is(err, null); t.true(files.length === 3); t.end(); }); }); }); test.cb("should generate a new file if the identifier changes", t => { const configs = [ Object.assign({}, globalConfig, { output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: t.context.cacheDirectory, cacheIdentifier: "a", presets: ["@babel/preset-env"], }, }, ], }, }), Object.assign({}, globalConfig, { output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: t.context.cacheDirectory, cacheIdentifier: "b", presets: ["@babel/preset-env"], }, }, ], }, }), ]; let counter = configs.length; configs.forEach(config => { webpack(config, err => { t.is(err, null); counter -= 1; if (!counter) { fs.readdir(t.context.cacheDirectory, (err, files) => { t.is(err, null); t.true(files.length === 6); t.end(); }); } }); }); }); test.cb("should allow to specify the .babelrc file", t => { const config = [ Object.assign({}, globalConfig, { entry: path.join(__dirname, "fixtures/constant.js"), output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: t.context.cacheDirectory, babelrc: path.join(__dirname, "fixtures/babelrc"), presets: ["@babel/preset-env"], }, }, ], }, }), Object.assign({}, globalConfig, { entry: path.join(__dirname, "fixtures/constant.js"), output: { path: t.context.directory, }, module: { loaders: [ { test: /\.jsx?/, loader: babelLoader, exclude: /node_modules/, query: { cacheDirectory: t.context.cacheDirectory, presets: ["@babel/preset-env"], }, }, ], }, }), ]; webpack(config, err => { t.is(err, null); fs.readdir(t.context.cacheDirectory, (err, files) => { t.is(err, null); t.true(files.length === 2); t.end(); }); }); });
"use strict";$(".menu .item[data-title]").popup({position:"bottom center"});var ides=["IntelliJ IDEA","PhpStorm","WebStorm","PyCharm","RubyMine","AppCode","CLion","Gogland","DataGrip","Rider","Android Studio"],fade=function e(){var t=$(".ide"),i=(ides.indexOf(t.text())+1)%ides.length;t.delay(1e3).fadeOut("slow",function(){return t.text(ides[i])}).fadeIn("slow",e)};fade();
/*global define*/ define([ '../Core/DeveloperError', '../Core/defaultValue', '../Core/defined', '../Core/Color', '../Core/destroyObject', '../Core/Math', '../Core/Extent', '../Core/Ellipsoid', '../Core/GeometryInstance', '../Core/ExtentGeometry', './EllipsoidSurfaceAppearance', './Primitive', './Material' ], function( DeveloperError, defaultValue, defined, Color, destroyObject, CesiumMath, Extent, Ellipsoid, GeometryInstance, ExtentGeometry, EllipsoidSurfaceAppearance, Primitive, Material) { "use strict"; /** * A renderable rectangular extent. * * @alias ExtentPrimitive * @constructor * * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid that the extent is drawn on. * @param {Extent} [options.extent=undefined] The extent, which defines the rectangular region to draw. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude in the underlying geometry. * @param {Number} [options.height=0.0] The height, in meters, that the extent is raised above the {@link ExtentPrimitive#ellipsoid}. * @param {Number} [options.rotation=0.0] The angle, in radians, relative to north that the extent is rotated. Positive angles rotate counter-clockwise. * @param {Number} [options.textureRotationAngle=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise. * @param {Boolean} [options.show=true] Determines if this primitive will be shown. * @param {Material} [options.material=undefined] The surface appearance of the primitive. * @param {Object} [options.id=undefined] A user-defined object to return when the instance is picked with {@link Scene#pick} * @param {Boolean} [options.asynchronous=true] Determines if the extent will be created asynchronously or block until ready. * * @example * var extentPrimitive = new ExtentPrimitive({ * extent : Extent.fromDegrees(0.0, 20.0, 10.0, 30.0) * }); * primitives.add(extentPrimitive); */ var ExtentPrimitive = function(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); /** * The ellipsoid that the extent is drawn on. * * @type Ellipsoid * * @default Ellipsoid.WGS84 */ this.ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84); this._ellipsoid = undefined; /** * The extent, which defines the rectangular region to draw. * * @type Extent * * @default undefined */ this.extent = Extent.clone(options.extent); this._extent = undefined; /** * The distance, in radians, between each latitude and longitude in the underlying geometry. * A lower granularity fits the curvature of the {@link ExtentPrimitive#ellipsoid} better, * but uses more triangles. * * @type Number * * @default CesiumMath.RADIANS_PER_DEGREE */ this.granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE); this._granularity = undefined; /** * The height, in meters, that the extent is raised above the {@link ExtentPrimitive#ellipsoid}. * * @type Number * * @default 0.0 */ this.height = defaultValue(options.height, 0.0); this._height = undefined; /** * The angle, in radians, relative to north that the extent is rotated. * Positive angles rotate counter-clockwise. * * @type Number * * @default 0.0 */ this.rotation = defaultValue(options.rotation, 0.0); this._rotation = undefined; /** * The angle, in radians, relative to north that the primitive's texture is rotated. * Positive angles rotate counter-clockwise. * * @type Number * * @default 0.0 */ this.textureRotationAngle = defaultValue(options.textureRotationAngle, 0.0); this._textureRotationAngle = undefined; /** * Determines if this primitive will be shown. * * @type Boolean * * @default true */ this.show = defaultValue(options.show, true); var material = Material.fromType(Material.ColorType); material.uniforms.color = new Color(1.0, 1.0, 0.0, 0.5); /** * The surface appearance of the primitive. This can be one of several built-in {@link Material} objects or a custom material, scripted with * <a href='https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric'>Fabric</a>. * <p> * The default material is <code>Material.ColorType</code>. * </p> * * @type Material * * @example * // 1. Change the color of the default material to yellow * extent.material.uniforms.color = new Color(1.0, 1.0, 0.0, 1.0); * * // 2. Change material to horizontal stripes * extent.material = Material.fromType(Material.StripeType); * * @see <a href='https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric'>Fabric</a> */ this.material = defaultValue(options.material, material); /** * User-defined object returned when the extent is picked. * * @type Object * * @default undefined * * @see Scene#pick */ this.id = options.id; this._id = undefined; /** * Determines if the geometry instances will be created and batched on * a web worker. * * @type Boolean * * @default true */ this.asynchronous = defaultValue(options.asynchronous, true); this._primitive = undefined; }; /** * @private */ ExtentPrimitive.prototype.update = function(context, frameState, commandList) { if (!defined(this.ellipsoid)) { throw new DeveloperError('this.ellipsoid must be defined.'); } if (!defined(this.material)) { throw new DeveloperError('this.material must be defined.'); } if (this.granularity < 0.0) { throw new DeveloperError('this.granularity and scene2D/scene3D overrides must be greater than zero.'); } if (!this.show || (!defined(this.extent))) { return; } if (!Extent.equals(this._extent, this.extent) || (this._ellipsoid !== this.ellipsoid) || (this._granularity !== this.granularity) || (this._height !== this.height) || (this._rotation !== this.rotation) || (this._textureRotationAngle !== this.textureRotationAngle) || (this._id !== this.id)) { this._extent = Extent.clone(this.extent, this._extent); this._ellipsoid = this.ellipsoid; this._granularity = this.granularity; this._height = this.height; this._rotation = this.rotation; this._textureRotationAngle = this.textureRotationAngle; this._id = this.id; var instance = new GeometryInstance({ geometry : new ExtentGeometry({ extent : this.extent, vertexFormat : EllipsoidSurfaceAppearance.VERTEX_FORMAT, ellipsoid : this.ellipsoid, granularity : this.granularity, height : this.height, rotation : this.rotation, stRotation : this.textureRotationAngle }), id : this.id, pickPrimitive : this }); if (defined(this._primitive)) { this._primitive.destroy(); } this._primitive = new Primitive({ geometryInstances : instance, appearance : new EllipsoidSurfaceAppearance({ aboveGround : (this.height > 0.0) }), asynchronous : this.asynchronous }); } this._primitive.appearance.material = this.material; this._primitive.update(context, frameState, commandList); }; /** * Returns true if this object was destroyed; otherwise, false. * <br /><br /> * If this object was destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. * * @memberof Extent * * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>. * * @see Extent#destroy */ ExtentPrimitive.prototype.isDestroyed = function() { return false; }; /** * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic * release of WebGL resources, instead of relying on the garbage collector to destroy this object. * <br /><br /> * Once an object is destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore, * assign the return value (<code>undefined</code>) to the object as done in the example. * * @memberof Extent * * @returns {undefined} * * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called. * * @see Extent#isDestroyed * * @example * extent = extent && extent.destroy(); */ ExtentPrimitive.prototype.destroy = function() { this._primitive = this._primitive && this._primitive.destroy(); return destroyObject(this); }; return ExtentPrimitive; });
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for goog.Uri. * */ goog.provide('goog.UriTest'); goog.require('goog.Uri'); goog.require('goog.testing.jsunit'); goog.setTestOnly('goog.UriTest'); function testUriParse() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); assertEquals('http', uri.getScheme()); assertEquals('', uri.getUserInfo()); assertEquals('www.google.com', uri.getDomain()); assertEquals(80, uri.getPort()); assertEquals('/path', uri.getPath()); assertEquals('q=query', uri.getQuery()); assertEquals('fragmento', uri.getFragment()); assertEquals('terer258+foo@gmail.com', goog.Uri.parse('mailto:terer258+foo@gmail.com').getPath()); } function testUriParseAcceptsThingsWithToString() { // Ensure that the goog.Uri constructor coerces random types to strings. var uriStr = 'http://www.google.com:80/path?q=query#fragmento'; var uri = new goog.Uri({toString: function() { return uriStr; }}); assertEquals('http://www.google.com:80/path?q=query#fragmento', uri.toString()); } function testUriCreate() { assertEquals( 'http://www.google.com:81/search%20path?q=what%20to%20eat%2Bdrink%3F', goog.Uri.create('http', null, 'www.google.com', 81, '/search path', (new goog.Uri.QueryData).set('q', 'what to eat+drink?'), null) .toString()); assertEquals( 'http://www.google.com:80/search%20path?q=what%20to%20eat%2Bdrink%3F', goog.Uri.create('http', null, 'www.google.com', 80, '/search path', (new goog.Uri.QueryData).set('q', 'what to eat+drink?'), null) .toString()); assertEquals( 'http://www.google.com/search%20path?q=what%20to%20eat%2Bdrink%3F', goog.Uri.create('http', null, 'www.google.com', null, '/search path', (new goog.Uri.QueryData).set('q', 'what to eat+drink?'), null) .toString()); var createdUri = goog.Uri.create( 'http', null, 'www.google.com', null, '/search path', new goog.Uri.QueryData(null, null, true).set('Q', 'what to eat+drink?'), null); assertEquals('http://www.google.com/search%20path?q=what%20to%20eat%2Bdrink%3F', createdUri.toString()); } function testClone() { var uri1 = new goog.Uri( 'http://user:pass@www.google.com:8080/foo?a=1&b=2#c=3'); // getCount forces instantiation of internal data structures to more // thoroughly test clone. uri1.getQueryData().getCount(); var uri2 = uri1.clone(); assertNotEquals(uri1, uri2); assertEquals(uri1.toString(), uri2.toString()); assertEquals(2, uri2.getQueryData().getCount()); uri2.setParameterValues('q', 'bar'); assertFalse(uri1.getParameterValue('q') == 'bar'); } function testRelativeUris() { assertFalse(new goog.Uri('?hello').hasPath()); } function testAbsolutePathResolution() { var uri1 = new goog.Uri('http://www.google.com:8080/path?q=query#fragmento'); assertEquals('http://www.google.com:8080/foo', uri1.resolve(new goog.Uri('/foo')).toString()); assertEquals('http://www.google.com:8080/foo/bar', goog.Uri.resolve('http://www.google.com:8080/search/', '/foo/bar').toString()); } function testRelativePathResolution() { var uri1 = new goog.Uri('http://www.google.com:8080/path?q=query#fragmento'); assertEquals('http://www.google.com:8080/foo', uri1.resolve(goog.Uri.parse('foo')).toString()); var uri2 = new goog.Uri('http://www.google.com:8080/search'); assertEquals('http://www.google.com:8080/foo/bar', uri2.resolve(new goog.Uri('foo/bar')).toString()); var uri3 = new goog.Uri('http://www.google.com:8080/search/'); assertEquals('http://www.google.com:8080/search/foo/bar', uri3.resolve(new goog.Uri('foo/bar')).toString()); var uri4 = new goog.Uri('foo'); assertEquals('bar', uri4.resolve(new goog.Uri('bar')).toString()); var uri5 = new goog.Uri('http://www.google.com:8080/search/'); assertEquals('http://www.google.com:8080/search/..%2ffoo/bar', uri3.resolve(new goog.Uri('..%2ffoo/bar')).toString()); } function testDomainResolution() { assertEquals('https://www.google.com/foo/bar', new goog.Uri('https://www.fark.com:443/search/').resolve( new goog.Uri('//www.google.com/foo/bar') ).toString()); assertEquals('http://www.google.com/', goog.Uri.resolve('http://www.fark.com/search/', '//www.google.com/').toString()); } function testQueryResolution() { assertEquals('http://www.google.com/search?q=new%20search', goog.Uri.parse('http://www.google.com/search?q=old+search'). resolve(goog.Uri.parse('?q=new%20search')).toString()); assertEquals('http://www.google.com/search?q=new%20search', goog.Uri.parse('http://www.google.com/search?q=old+search#hi'). resolve(goog.Uri.parse('?q=new%20search')).toString()); } function testFragmentResolution() { assertEquals('http://www.google.com/foo/bar?q=hi#there', goog.Uri.resolve('http://www.google.com/foo/bar?q=hi', '#there').toString()); assertEquals('http://www.google.com/foo/bar?q=hi#there', goog.Uri.resolve('http://www.google.com/foo/bar?q=hi#you', '#there').toString()); } function testBogusResolution() { var uri = goog.Uri.parse('some:base/url').resolve( goog.Uri.parse('a://completely.different/url')); assertEquals('a://completely.different/url', uri.toString()); } function testDotSegmentsRemovalRemoveLeadingDots() { // Test removing leading "../" and "./" assertEquals('bar', goog.Uri.removeDotSegments('../bar')); assertEquals('bar', goog.Uri.removeDotSegments('./bar')); assertEquals('bar', goog.Uri.removeDotSegments('.././bar')); assertEquals('bar', goog.Uri.removeDotSegments('.././bar')); } function testDotSegmentRemovalRemoveSingleDot() { // Tests replacing "/./" with "/" assertEquals('/foo/bar', goog.Uri.removeDotSegments('/foo/./bar')); assertEquals('/bar/', goog.Uri.removeDotSegments('/bar/./')); // Test replacing trailing "/." with "/" assertEquals('/', goog.Uri.removeDotSegments('/.')); assertEquals('/bar/', goog.Uri.removeDotSegments('/bar/.')); } function testDotSegmentRemovalRemoveDoubleDot() { // Test resolving "/../" assertEquals('/bar', goog.Uri.removeDotSegments('/foo/../bar')); assertEquals('/', goog.Uri.removeDotSegments('/bar/../')); // Test resolving trailing "/.." assertEquals('/', goog.Uri.removeDotSegments('/..')); assertEquals('/', goog.Uri.removeDotSegments('/bar/..')); assertEquals('/foo/', goog.Uri.removeDotSegments('/foo/bar/..')); } function testDotSegmentRemovalRemovePlainDots() { // RFC 3986, section 5.2.4, point 2.D. // Test resolving plain ".." or "." assertEquals('', goog.Uri.removeDotSegments('.')); assertEquals('', goog.Uri.removeDotSegments('..')); } function testPathConcatenation() { // Check accordenance with RFC 3986, section 5.2.4 assertResolvedEquals('bar', '', 'bar'); assertResolvedEquals('/bar', '/', 'bar'); assertResolvedEquals('/bar', '/foo', '/bar'); assertResolvedEquals('/foo/foo', '/foo/bar', 'foo'); } function testPathConcatenationDontRemoveForEmptyUri() { // Resolving URIs with empty path should not result in dot segments removal. // See: algorithm in section 5.2.2: code inside 'if (R.path == "")' clause. assertResolvedEquals('/search/../foo', '/search/../foo', ''); assertResolvedEquals('/search/./foo', '/search/./foo', ''); } function testParameterGetters() { function assertArraysEqual(l1, l2) { if (!l1 || !l2) { assertEquals(l1, l2); return; } var l1s = l1.toString(), l2s = l2.toString(); assertEquals(l1s, l2s); assertEquals(l1s, l1.length, l2.length); for (var i = 0; i < l1.length; ++i) { assertEquals('part ' + i + ' of ' + l1.length + ' in ' + l1s, l1[i], l2[i]); } } assertArraysEqual(['v1', 'v2'], goog.Uri.parse('/path?a=b&key=v1&c=d&key=v2&keywithsuffix=v3'). getParameterValues('key')); assertArraysEqual(['v1', 'v2'], goog.Uri.parse('/path?a=b&keY=v1&c=d&KEy=v2&keywithsuffix=v3', true). getParameterValues('kEy')); assertEquals('v1', goog.Uri.parse('/path?key=v1&c=d&keywithsuffix=v3&key=v2'). getParameterValue('key')); assertEquals('v1', goog.Uri.parse('/path?kEY=v1&c=d&keywithsuffix=v3&key=v2', true). getParameterValue('Key')); assertEquals('v1=v2', goog.Uri.parse('/path?key=v1=v2', true).getParameterValue('key')); assertEquals('v1=v2=v3', goog.Uri.parse('/path?key=v1=v2=v3', true).getParameterValue('key')); assertArraysEqual(undefined, goog.Uri.parse('/path?key=v1&c=d&keywithsuffix=v3&key=v2'). getParameterValue('nosuchkey')); // test boundary conditions assertArraysEqual(['v1', 'v2'], goog.Uri.parse('/path?key=v1&c=d&key=v2&keywithsuffix=v3'). getParameterValues('key')); assertArraysEqual(['v1', 'v2'], goog.Uri.parse('/path?key=v1&c=d&keywithsuffix=v3&key=v2'). getParameterValues('key')); // test no = assertArraysEqual([''], goog.Uri.parse('/path?key').getParameterValues('key')); assertArraysEqual([''], goog.Uri.parse('/path?key', true).getParameterValues('key')); assertArraysEqual([''], goog.Uri.parse('/path?foo=bar&key'). getParameterValues('key')); assertArraysEqual([''], goog.Uri.parse('/path?foo=bar&key', true). getParameterValues('key')); assertEquals('', goog.Uri.parse('/path?key').getParameterValue('key')); assertEquals('', goog.Uri.parse('/path?key', true).getParameterValue('key')); assertEquals('', goog.Uri.parse('/path?foo=bar&key').getParameterValue('key')); assertEquals('', goog.Uri.parse('/path?foo=bar&key', true). getParameterValue('key')); var u = new goog.Uri('/path?a=b&key=v1&c=d&key=v2&keywithsuffix=v3'); assertArraysEqual(u.getParameterValues('a'), ['b']); assertArraysEqual(u.getParameterValues('key'), ['v1', 'v2']); assertArraysEqual(u.getParameterValues('c'), ['d']); assertArraysEqual(u.getParameterValues('keywithsuffix'), ['v3']); assertArraysEqual(u.getParameterValues('KeyWITHSuffix'), []); // Make sure constructing from another URI preserves case-sensitivity var u2 = new goog.Uri(u); assertArraysEqual(u2.getParameterValues('a'), ['b']); assertArraysEqual(u2.getParameterValues('key'), ['v1', 'v2']); assertArraysEqual(u2.getParameterValues('c'), ['d']); assertArraysEqual(u2.getParameterValues('keywithsuffix'), ['v3']); assertArraysEqual(u2.getParameterValues('KeyWITHSuffix'), []); u = new goog.Uri('/path?a=b&key=v1&c=d&kEy=v2&keywithsuffix=v3', true); assertArraysEqual(u.getParameterValues('A'), ['b']); assertArraysEqual(u.getParameterValues('keY'), ['v1', 'v2']); assertArraysEqual(u.getParameterValues('c'), ['d']); assertArraysEqual(u.getParameterValues('keyWITHsuffix'), ['v3']); // Make sure constructing from another URI preserves case-insensitivity u2 = new goog.Uri(u); assertArraysEqual(u2.getParameterValues('A'), ['b']); assertArraysEqual(u2.getParameterValues('keY'), ['v1', 'v2']); assertArraysEqual(u2.getParameterValues('c'), ['d']); assertArraysEqual(u2.getParameterValues('keyWITHsuffix'), ['v3']); } function testRemoveParameter() { assertEquals('/path?a=b&c=d&keywithsuffix=v3', goog.Uri.parse('/path?a=b&key=v1&c=d&key=v2&keywithsuffix=v3') .removeParameter('key').toString()); } function testParameterSetters() { assertEquals('/path?a=b&key=newval&c=d&keywithsuffix=v3', goog.Uri.parse('/path?a=b&key=v1&c=d&key=v2&keywithsuffix=v3') .setParameterValue('key', 'newval').toString()); assertEquals('/path?a=b&key=1&key=2&key=3&c=d&keywithsuffix=v3', goog.Uri.parse('/path?a=b&key=v1&c=d&key=v2&keywithsuffix=v3') .setParameterValues('key', ['1', '2', '3']).toString()); assertEquals('/path', goog.Uri.parse('/path?key=v1&key=v2') .setParameterValues('key', []).toString()); // Test case-insensitive setters assertEquals('/path?a=b&key=newval&c=d&keywithsuffix=v3', goog.Uri.parse('/path?a=b&key=v1&c=d&key=v2&keywithsuffix=v3', true) .setParameterValue('KEY', 'newval').toString()); assertEquals( '/path?a=b&key=1&key=2&key=3&c=d&keywithsuffix=v3', goog.Uri.parse('/path?a=b&key=v1&c=d&key=v2&keywithsuffix=v3', true) .setParameterValues('kEY', ['1', '2', '3']).toString()); } function testEncoding() { assertEquals('/foo bar baz', goog.Uri.parse('/foo%20bar%20baz').getPath()); assertEquals('/foo+bar+baz', goog.Uri.parse('/foo+bar+baz').getPath()); } function testSetScheme() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); uri.setScheme('https'); assertTrue(uri.hasScheme()); assertEquals('https', uri.getScheme()); assertEquals('https://www.google.com:80/path?q=query#fragmento', uri.toString()); uri.setScheme(encodeURIComponent('ab cd'), true); assertTrue(uri.hasScheme()); assertEquals('ab cd', uri.getScheme()); assertEquals('ab%20cd://www.google.com:80/path?q=query#fragmento', uri.toString()); uri.setScheme('http:'); assertTrue(uri.hasScheme()); assertEquals('http', uri.getScheme()); assertEquals('http://www.google.com:80/path?q=query#fragmento', uri.toString()); uri.setScheme(''); assertFalse(uri.hasScheme()); assertEquals('', uri.getScheme()); assertEquals('//www.google.com:80/path?q=query#fragmento', uri.toString()); } function testSetDomain() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); uri.setDomain('\u1e21oogle.com'); assertTrue(uri.hasDomain()); assertEquals('\u1e21oogle.com', uri.getDomain()); assertEquals('http://%E1%B8%A1oogle.com:80/path?q=query#fragmento', uri.toString()); uri.setDomain(encodeURIComponent('\u1e21oogle.com'), true); assertTrue(uri.hasDomain()); assertEquals('\u1e21oogle.com', uri.getDomain()); assertEquals('http://%E1%B8%A1oogle.com:80/path?q=query#fragmento', uri.toString()); uri.setDomain(''); assertFalse(uri.hasDomain()); assertEquals('', uri.getDomain()); assertEquals('http:/path?q=query#fragmento', uri.toString()); } function testSetPort() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); assertThrows(function() { uri.setPort(-1); }); assertEquals(80, uri.getPort()); assertThrows(function() { uri.setPort('a'); }); assertEquals(80, uri.getPort()); uri.setPort(443); assertTrue(uri.hasPort()); assertEquals(443, uri.getPort()); assertEquals('http://www.google.com:443/path?q=query#fragmento', uri.toString()); // TODO(chrishenry): This is undocumented, but exist in previous unit // test. We should clarify whether this is intended (alternatively, // setPort(0) also works). uri.setPort(null); assertFalse(uri.hasPort()); assertEquals(null, uri.getPort()); assertEquals('http://www.google.com/path?q=query#fragmento', uri.toString()); } function testSetPath() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); uri.setPath('/search path/'); assertTrue(uri.hasPath()); assertEquals('/search path/', uri.getPath()); assertEquals( 'http://www.google.com:80/search%20path/?q=query#fragmento', uri.toString()); uri.setPath(encodeURIComponent('search path 2/'), true); assertTrue(uri.hasPath()); assertEquals('search path 2%2F', uri.getPath()); assertEquals( 'http://www.google.com:80/search%20path%202%2F?q=query#fragmento', uri.toString()); uri.setPath(''); assertFalse(uri.hasPath()); assertEquals('', uri.getPath()); assertEquals( 'http://www.google.com:80?q=query#fragmento', uri.toString()); } function testSetFragment() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); uri.setFragment('foo?bar=a b&baz=2'); assertTrue(uri.hasFragment()); assertEquals('foo?bar=a b&baz=2', uri.getFragment()); assertEquals( 'http://www.google.com:80/path?q=query#foo?bar=a%20b&baz=2', uri.toString()); uri.setFragment(encodeURIComponent('foo?bar=a b&baz=3'), true); assertTrue(uri.hasFragment()); assertEquals('foo?bar=a b&baz=3', uri.getFragment()); assertEquals( 'http://www.google.com:80/path?q=query#foo?bar=a%20b&baz=3', uri.toString()); uri.setFragment(''); assertFalse(uri.hasFragment()); assertEquals('', uri.getFragment()); assertEquals( 'http://www.google.com:80/path?q=query', uri.toString()); } function testSetUserInfo() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); uri.setUserInfo('user:pw d'); assertTrue(uri.hasUserInfo()); assertEquals('user:pw d', uri.getUserInfo()); assertEquals('http://user:pw%20d@www.google.com:80/path?q=query#fragmento', uri.toString()); uri.setUserInfo(encodeURIComponent('user:pw d2'), true); assertTrue(uri.hasUserInfo()); assertEquals('user:pw d2', uri.getUserInfo()); assertEquals('http://user:pw%20d2@www.google.com:80/path?q=query#fragmento', uri.toString()); uri.setUserInfo('user'); assertTrue(uri.hasUserInfo()); assertEquals('user', uri.getUserInfo()); assertEquals('http://user@www.google.com:80/path?q=query#fragmento', uri.toString()); uri.setUserInfo(''); assertFalse(uri.hasUserInfo()); assertEquals('', uri.getUserInfo()); assertEquals('http://www.google.com:80/path?q=query#fragmento', uri.toString()); } function testSetParameterValues() { var uri = new goog.Uri('http://www.google.com:80/path?q=query#fragmento'); uri.setParameterValues('q', ['foo', 'other query']); assertEquals('http://www.google.com:80/path?q=foo&q=other%20query#fragmento', uri.toString()); uri.setParameterValues('lang', 'en'); assertEquals( 'http://www.google.com:80/path?q=foo&q=other%20query&lang=en#fragmento', uri.toString()); } function testTreatmentOfAt1() { var uri = new goog.Uri('http://www.google.com?q=johndoe@gmail.com'); assertEquals('http', uri.getScheme()); assertEquals('www.google.com', uri.getDomain()); assertEquals('johndoe@gmail.com', uri.getParameterValue('q')); uri = goog.Uri.create('http', null, 'www.google.com', null, null, 'q=johndoe@gmail.com', null); assertEquals('http://www.google.com?q=johndoe%40gmail.com', uri.toString()); } function testTreatmentOfAt2() { var uri = new goog.Uri('http://www/~johndoe@gmail.com/foo'); assertEquals('http', uri.getScheme()); assertEquals('www', uri.getDomain()); assertEquals('/~johndoe@gmail.com/foo', uri.getPath()); assertEquals('http://www/~johndoe@gmail.com/foo', goog.Uri.create('http', null, 'www', null, '/~johndoe@gmail.com/foo', null, null). toString()); } function testTreatmentOfAt3() { var uri = new goog.Uri('ftp://skroob:1234@teleport/~skroob@vacuum'); assertEquals('ftp', uri.getScheme()); assertEquals('skroob:1234', uri.getUserInfo()); assertEquals('teleport', uri.getDomain()); assertEquals('/~skroob@vacuum', uri.getPath()); assertEquals('ftp://skroob:1234@teleport/~skroob@vacuum', goog.Uri.create('ftp', 'skroob:1234', 'teleport', null, '/~skroob@vacuum', null, null).toString()); } function testTreatmentOfAt4() { assertEquals('ftp://darkhelmet:45%4078@teleport/~dhelmet@vacuum', goog.Uri.create('ftp', 'darkhelmet:45@78', 'teleport', null, '/~dhelmet@vacuum', null, null).toString()); } function testSameDomain1() { var uri1 = 'http://www.google.com/a'; var uri2 = 'http://www.google.com/b'; assertTrue(goog.Uri.haveSameDomain(uri1, uri2)); assertTrue(goog.Uri.haveSameDomain(uri2, uri1)); } function testSameDomain2() { var uri1 = 'http://www.google.com:1234/a'; var uri2 = 'http://www.google.com/b'; assertFalse(goog.Uri.haveSameDomain(uri1, uri2)); assertFalse(goog.Uri.haveSameDomain(uri2, uri1)); } function testSameDomain3() { var uri1 = 'www.google.com/a'; var uri2 = 'http://www.google.com/b'; assertFalse(goog.Uri.haveSameDomain(uri1, uri2)); assertFalse(goog.Uri.haveSameDomain(uri2, uri1)); } function testSameDomain4() { var uri1 = '/a'; var uri2 = 'http://www.google.com/b'; assertFalse(goog.Uri.haveSameDomain(uri1, uri2)); assertFalse(goog.Uri.haveSameDomain(uri2, uri1)); } function testSameDomain5() { var uri1 = 'http://www.google.com/a'; var uri2 = 'http://mail.google.com/b'; assertFalse(goog.Uri.haveSameDomain(uri1, uri2)); assertFalse(goog.Uri.haveSameDomain(uri2, uri1)); } function testSameDomain6() { var uri1 = '/a'; var uri2 = '/b'; assertTrue(goog.Uri.haveSameDomain(uri1, uri2)); assertTrue(goog.Uri.haveSameDomain(uri2, uri1)); } function testMakeUnique() { var uri1 = new goog.Uri('http://www.google.com/setgmail'); uri1.makeUnique(); var uri2 = new goog.Uri('http://www.google.com/setgmail'); uri2.makeUnique(); assertTrue(uri1.getQueryData().containsKey(goog.Uri.RANDOM_PARAM)); assertTrue(uri1.toString() != uri2.toString()); } function testSetReadOnly() { var uri = new goog.Uri('http://www.google.com/setgmail'); uri.setReadOnly(true); assertThrows(function() { uri.setParameterValue('cant', 'dothis'); }); } function testSetReadOnlyChained() { var uri = new goog.Uri('http://www.google.com/setgmail').setReadOnly(true); assertThrows(function() { uri.setParameterValue('cant', 'dothis'); }); } function testQueryDataCount() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); assertEquals(5, qd.getCount()); } function testQueryDataRemove() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.remove('c'); assertEquals(4, qd.getCount()); assertEquals('a=A&a=A2&b=B&b=B2', String(qd)); qd.remove('a'); assertEquals(2, qd.getCount()); assertEquals('b=B&b=B2', String(qd)); } function testQueryDataClear() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.clear(); assertEquals(0, qd.getCount()); assertEquals('', String(qd)); } function testQueryDataIsEmpty() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.remove('a'); assertFalse(qd.isEmpty()); qd.remove('b'); assertFalse(qd.isEmpty()); qd.remove('c'); assertTrue(qd.isEmpty()); qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.clear(); assertTrue(qd.isEmpty()); qd = new goog.Uri.QueryData(''); assertTrue(qd.isEmpty()); } function testQueryDataContainsKey() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); assertTrue(qd.containsKey('a')); assertTrue(qd.containsKey('b')); assertTrue(qd.containsKey('c')); qd.remove('a'); assertFalse(qd.containsKey('a')); assertTrue(qd.containsKey('b')); assertTrue(qd.containsKey('c')); qd.remove('b'); assertFalse(qd.containsKey('a')); assertFalse(qd.containsKey('b')); assertTrue(qd.containsKey('c')); qd.remove('c'); assertFalse(qd.containsKey('a')); assertFalse(qd.containsKey('b')); assertFalse(qd.containsKey('c')); qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.clear(); assertFalse(qd.containsKey('a')); assertFalse(qd.containsKey('b')); assertFalse(qd.containsKey('c')); // Test case-insensitive qd = new goog.Uri.QueryData('aaa=A&bbb=B&aaa=A2&bbbb=B2&ccc=C', null, true); assertTrue(qd.containsKey('aaa')); assertTrue(qd.containsKey('bBb')); assertTrue(qd.containsKey('CCC')); qd = new goog.Uri.QueryData('a=b=c'); assertTrue(qd.containsKey('a')); assertFalse(qd.containsKey('b')); } function testQueryDataContainsValue() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); assertTrue(qd.containsValue('A')); assertTrue(qd.containsValue('B')); assertTrue(qd.containsValue('A2')); assertTrue(qd.containsValue('B2')); assertTrue(qd.containsValue('C')); qd.remove('a'); assertFalse(qd.containsValue('A')); assertTrue(qd.containsValue('B')); assertFalse(qd.containsValue('A2')); assertTrue(qd.containsValue('B2')); assertTrue(qd.containsValue('C')); qd.remove('b'); assertFalse(qd.containsValue('A')); assertFalse(qd.containsValue('B')); assertFalse(qd.containsValue('A2')); assertFalse(qd.containsValue('B2')); assertTrue(qd.containsValue('C')); qd.remove('c'); assertFalse(qd.containsValue('A')); assertFalse(qd.containsValue('B')); assertFalse(qd.containsValue('A2')); assertFalse(qd.containsValue('B2')); assertFalse(qd.containsValue('C')); qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.clear(); assertFalse(qd.containsValue('A')); assertFalse(qd.containsValue('B')); assertFalse(qd.containsValue('A2')); assertFalse(qd.containsValue('B2')); assertFalse(qd.containsValue('C')); qd = new goog.Uri.QueryData('a=b=c'); assertTrue(qd.containsValue('b=c')); assertFalse(qd.containsValue('b')); assertFalse(qd.containsValue('c')); } function testQueryDataGetKeys() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C=extra'); assertEquals('aabbc', qd.getKeys().join('')); qd.remove('a'); assertEquals('bbc', qd.getKeys().join('')); qd.add('d', 'D'); qd.add('d', 'D'); assertEquals('bbcdd', qd.getKeys().join('')); // Test case-insensitive qd = new goog.Uri.QueryData('A=A&B=B&a=A2&b=B2&C=C=extra', null, true); assertEquals('aabbc', qd.getKeys().join('')); qd.remove('a'); assertEquals('bbc', qd.getKeys().join('')); qd.add('d', 'D'); qd.add('D', 'D'); assertEquals('bbcdd', qd.getKeys().join('')); } function testQueryDataGetValues() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C=extra'); assertArrayEquals(['A', 'A2', 'B', 'B2', 'C=extra'], qd.getValues()); qd.remove('a'); assertArrayEquals(['B', 'B2', 'C=extra'], qd.getValues()); qd.add('d', 'D'); qd.add('d', 'D'); assertArrayEquals(['B', 'B2', 'C=extra', 'D', 'D'], qd.getValues()); qd.add('e', new String('Eee')); assertArrayEquals(['B', 'B2', 'C=extra', 'D', 'D', 'Eee'], qd.getValues()); assertArrayEquals(['Eee'], qd.getValues('e')); } function testQueryDataSet() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.set('d', 'D'); assertEquals('a=A&a=A2&b=B&b=B2&c=C&d=D', String(qd)); qd.set('d', 'D2'); assertEquals('a=A&a=A2&b=B&b=B2&c=C&d=D2', String(qd)); qd.set('a', 'A3'); assertEquals('a=A3&b=B&b=B2&c=C&d=D2', String(qd)); qd.remove('a'); qd.set('a', 'A4'); // this is different in IE and Mozilla so we cannot use the toString to test assertEquals('A4', qd.get('a')); } function testQueryDataGet() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C=extra'); assertEquals('A', qd.get('a')); assertEquals('B', qd.get('b')); assertEquals('C=extra', qd.get('c')); assertEquals('Default', qd.get('d', 'Default')); qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C=extra', null, true); assertEquals('A', qd.get('A')); assertEquals('B', qd.get('b')); assertEquals('C=extra', qd.get('C')); assertEquals('Default', qd.get('D', 'Default')); // Some unit tests pass undefined to get method (even though the type // for key is {string}). This is not caught by JsCompiler as // tests aren't typically compiled. assertUndefined(qd.get(undefined)); } function testQueryDataSetValues() { var qd = new goog.Uri.QueryData('a=A&b=B&a=A2&b=B2&c=C'); qd.setValues('a', ['A3', 'A4', 'A5']); assertEquals('a=A3&a=A4&a=A5&b=B&b=B2&c=C', String(qd)); qd.setValues('d', ['D']); assertEquals('a=A3&a=A4&a=A5&b=B&b=B2&c=C&d=D', String(qd)); qd.setValues('e', []); assertEquals('a=A3&a=A4&a=A5&b=B&b=B2&c=C&d=D', String(qd)); } function testQueryDataSetIgnoreCase() { var qd = new goog.Uri.QueryData('aaA=one&BBb=two&cCc=three'); assertEquals('one', qd.get('aaA')); assertEquals(undefined, qd.get('aaa')); qd.setIgnoreCase(true); assertEquals('one', qd.get('aaA')); assertEquals('one', qd.get('aaa')); qd.setIgnoreCase(false); assertEquals(undefined, qd.get('aaA')); assertEquals('one', qd.get('aaa')); qd.add('DdD', 'four'); assertEquals('four', qd.get('DdD')); assertEquals(undefined, qd.get('ddd')); } function testQueryDataSetIgnoreCaseWithMultipleValues() { var qd = new goog.Uri.QueryData('aaA=one&aaA=two'); qd.setIgnoreCase(true); assertArrayEquals(['one', 'two'], qd.getValues('aaA')); assertArrayEquals(['one', 'two'], qd.getValues('aaa')); } function testQueryDataExtend() { var qd1 = new goog.Uri.QueryData('a=A&b=B&c=C'); var qd2 = new goog.Uri.QueryData('d=D&e=E'); qd1.extend(qd2); assertEquals('a=A&b=B&c=C&d=D&e=E', String(qd1)); qd1 = new goog.Uri.QueryData('a=A&b=B&c=C'); qd2 = new goog.Uri.QueryData('d=D&e=E'); var qd3 = new goog.Uri.QueryData('f=F&g=G'); qd1.extend(qd2, qd3); assertEquals('a=A&b=B&c=C&d=D&e=E&f=F&g=G', String(qd1)); qd1 = new goog.Uri.QueryData('a=A&b=B&c=C'); qd2 = new goog.Uri.QueryData('a=A&c=C'); qd1.extend(qd2); assertEquals('a=A&a=A&b=B&c=C&c=C', String(qd1)); } function testQueryDataCreateFromMap() { assertEquals('', String(goog.Uri.QueryData.createFromMap({}))); assertEquals('a=A&b=B&c=C', String(goog.Uri.QueryData.createFromMap({a: 'A', b: 'B', c: 'C'}))); assertEquals('a=foo%26bar', String(goog.Uri.QueryData.createFromMap({a: 'foo&bar'}))); } function testQueryDataCreateFromMapWithArrayValues() { var obj = {'key': ['1', '2', '3']}; var qd = goog.Uri.QueryData.createFromMap(obj); assertEquals('key=1&key=2&key=3', qd.toString()); qd.add('breakCache', 1); obj.key.push('4'); assertEquals('key=1&key=2&key=3&breakCache=1', qd.toString()); } function testQueryDataCreateFromKeysValues() { assertEquals('', String(goog.Uri.QueryData.createFromKeysValues([], []))); assertEquals('a=A&b=B&c=C', String(goog.Uri.QueryData.createFromKeysValues( ['a', 'b', 'c'], ['A', 'B', 'C']))); assertEquals('a=A&a=B&a=C', String(goog.Uri.QueryData.createFromKeysValues( ['a', 'a', 'a'], ['A', 'B', 'C']))); } function testQueryDataAddMultipleValuesWithSameKey() { var qd = new goog.Uri.QueryData(); qd.add('abc', 'v'); qd.add('abc', 'v2'); qd.add('abc', 'v3'); assertEquals('abc=v&abc=v2&abc=v3', qd.toString()); } function testQueryDataAddWithArray() { var qd = new goog.Uri.QueryData(); qd.add('abc', ['v', 'v2']); assertEquals('abc=v%2Cv2', qd.toString()); } function testFragmentEncoding() { var allowedInFragment = /[A-Za-z0-9\-\._~!$&'()*+,;=:@/?]/g; var sb = []; for (var i = 33; i < 500; i++) { // arbitrarily use first 500 chars. sb.push(String.fromCharCode(i)); } var testString = sb.join(''); var fragment = new goog.Uri().setFragment(testString).toString(); // Remove first '#' character. fragment = fragment.substr(1); // Strip all percent encoded characters, as they're ok. fragment = fragment.replace(/%[0-9A-F][0-9A-F]/g, ''); // Remove allowed characters. fragment = fragment.replace(allowedInFragment, ''); // Only illegal characters should remain, which is a fail. assertEquals('String should be empty', 0, fragment.length); } function testStrictDoubleEncodingRemoval() { var url = goog.Uri.parse('dummy/a%25invalid'); assertEquals('dummy/a%25invalid', url.toString()); url = goog.Uri.parse('dummy/a%252fdouble-encoded-slash'); assertEquals('dummy/a%2fdouble-encoded-slash', url.toString()); } // Tests, that creating URI from components and then // getting the components back yields equal results. // The special attention is payed to test proper encoding // and decoding of URI components. function testComponentsAfterUriCreate() { var createdUri = new goog.Uri.create('%40', // scheme '%41', // user info '%42', // domain 43, // port '%44', // path '%45', // query '%46'); // fragment assertEquals('%40', createdUri.getScheme()); assertEquals('%41', createdUri.getUserInfo()); assertEquals('%42', createdUri.getDomain()); assertEquals(43, createdUri.getPort()); assertEquals('%44', createdUri.getPath()); assertEquals('%2545', createdUri.getQuery()); // returns encoded value assertEquals('%45', createdUri.getDecodedQuery()); assertEquals('%2545', createdUri.getEncodedQuery()); assertEquals('%46', createdUri.getFragment()); } // Tests setting the query string and then reading back // query parameter values. function testSetQueryAndGetParameterValue() { var uri = new goog.Uri(); // Sets query as decoded string. uri.setQuery('i=j&k'); assertEquals('?i=j&k', uri.toString()); assertEquals('i=j&k', uri.getDecodedQuery()); assertEquals('i=j&k', uri.getEncodedQuery()); assertEquals('i=j&k', uri.getQuery()); // returns encoded value assertEquals('j', uri.getParameterValue('i')); assertEquals('', uri.getParameterValue('k')); // Sets query as encoded string. uri.setQuery('i=j&k', true); assertEquals('?i=j&k', uri.toString()); assertEquals('i=j&k', uri.getDecodedQuery()); assertEquals('i=j&k', uri.getEncodedQuery()); assertEquals('i=j&k', uri.getQuery()); // returns encoded value assertEquals('j', uri.getParameterValue('i')); assertEquals('', uri.getParameterValue('k')); // Sets query as decoded string. uri.setQuery('i=j%26k'); assertEquals('?i=j%2526k', uri.toString()); assertEquals('i=j%26k', uri.getDecodedQuery()); assertEquals('i=j%2526k', uri.getEncodedQuery()); assertEquals('i=j%2526k', uri.getQuery()); // returns encoded value assertEquals('j%26k', uri.getParameterValue('i')); assertUndefined(uri.getParameterValue('k')); // Sets query as encoded string. uri.setQuery('i=j%26k', true); assertEquals('?i=j%26k', uri.toString()); assertEquals('i=j&k', uri.getDecodedQuery()); assertEquals('i=j%26k', uri.getEncodedQuery()); assertEquals('i=j%26k', uri.getQuery()); // returns encoded value assertEquals('j&k', uri.getParameterValue('i')); assertUndefined(uri.getParameterValue('k')); } // Tests setting query parameter values and the reading back the query string. function testSetParameterValueAndGetQuery() { var uri = new goog.Uri(); uri.setParameterValue('a', 'b&c'); assertEquals('?a=b%26c', uri.toString()); assertEquals('a=b&c', uri.getDecodedQuery()); assertEquals('a=b%26c', uri.getEncodedQuery()); assertEquals('a=b%26c', uri.getQuery()); // returns encoded value uri.setParameterValue('a', 'b%26c'); assertEquals('?a=b%2526c', uri.toString()); assertEquals('a=b%26c', uri.getDecodedQuery()); assertEquals('a=b%2526c', uri.getEncodedQuery()); assertEquals('a=b%2526c', uri.getQuery()); // returns encoded value } // Tests that building a URI with a query string and then reading it back // gives the same result. function testQueryNotModified() { assertEquals('?foo', new goog.Uri('?foo').toString()); assertEquals('?foo=', new goog.Uri('?foo=').toString()); assertEquals('?foo=bar', new goog.Uri('?foo=bar').toString()); assertEquals('?&=&=&', new goog.Uri('?&=&=&').toString()); } function testRelativePathEscapesColon() { assertEquals('javascript%3aalert(1)', new goog.Uri().setPath('javascript:alert(1)').toString()); } function testAbsolutePathDoesNotEscapeColon() { assertEquals('/javascript:alert(1)', new goog.Uri('/javascript:alert(1)').toString()); } function testColonInPathNotUnescaped() { assertEquals('/javascript%3aalert(1)', new goog.Uri('/javascript%3aalert(1)').toString()); assertEquals('javascript%3aalert(1)', new goog.Uri('javascript%3aalert(1)').toString()); assertEquals('javascript:alert(1)', new goog.Uri('javascript:alert(1)').toString()); assertEquals('http://www.foo.bar/path:with:colon/x', new goog.Uri('http://www.foo.bar/path:with:colon/x').toString()); assertEquals('//www.foo.bar/path:with:colon/x', new goog.Uri('//www.foo.bar/path:with:colon/x').toString()); } // verifies bug http://b/9821952 function testGetQueryForEmptyString() { var queryData = new goog.Uri.QueryData('a=b&c=d'); assertArrayEquals(['b', 'd'], queryData.getValues()); assertArrayEquals([], queryData.getValues('')); queryData = new goog.Uri.QueryData('a=b&c=d&=e'); assertArrayEquals(['e'], queryData.getValues('')); } function testRestrictedCharactersArePreserved() { var uri = new goog.Uri( 'ht%74p://hos%74.example.%2f.com/pa%74h%2f-with-embedded-slash/'); assertEquals('http', uri.getScheme()); assertEquals('host.example.%2f.com', uri.getDomain()); assertEquals('/path%2f-with-embedded-slash/', uri.getPath()); assertEquals('http://host.example.%2f.com/path%2f-with-embedded-slash/', uri.toString()); } function assertDotRemovedEquals(expected, path) { assertEquals(expected, goog.Uri.removeDotSegments(path)); } function assertResolvedEquals(expected, base, other) { assertEquals(expected, goog.Uri.resolve(base, other).toString()); }
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("babylonjs")); else if(typeof define === 'function' && define.amd) define("babylonjs-procedural-textures", ["babylonjs"], factory); else if(typeof exports === 'object') exports["babylonjs-procedural-textures"] = factory(require("babylonjs")); else root["PROCEDURALTEXTURES"] = factory(root["BABYLON"]); })((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function(__WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_decorators__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./legacy/legacy-brick.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "../../node_modules/tslib/tslib.es6.js": /*!***********************************************************!*\ !*** E:/Repos/Babylon.js/node_modules/tslib/tslib.es6.js ***! \***********************************************************/ /*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __values, __read, __spread, __spreadArrays, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } /***/ }), /***/ "../../node_modules/webpack/buildin/global.js": /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ "./brick/brickProceduralTexture.fragment.ts": /*!**************************************************!*\ !*** ./brick/brickProceduralTexture.fragment.ts ***! \**************************************************/ /*! exports provided: brickProceduralTexturePixelShader */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "brickProceduralTexturePixelShader", function() { return brickProceduralTexturePixelShader; }); /* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Materials/effect */ "babylonjs/Misc/decorators"); /* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__); var name = 'brickProceduralTexturePixelShader'; var shader = "precision highp float;\nvarying vec2 vPosition;\nvarying vec2 vUV;\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n,vec2(12.9898,4.1414)))*43758.5453);\n}\nfloat noise(vec2 n) {\nconst vec2 d=vec2(0.0,1.0);\nvec2 b=floor(n),f=smoothstep(vec2(0.0),vec2(1.0),fract(n));\nreturn mix(mix(rand(b),rand(b+d.yx),f.x),mix(rand(b+d.xy),rand(b+d.yy),f.x),f.y);\n}\nfloat fbm(vec2 n) {\nfloat total=0.0,amplitude=1.0;\nfor (int i=0; i<4; i++) {\ntotal+=noise(n)*amplitude;\nn+=n;\namplitude*=0.5;\n}\nreturn total;\n}\nfloat roundF(float number){\nreturn sign(number)*floor(abs(number)+0.5);\n}\nvoid main(void)\n{\nfloat brickW=1.0/numberOfBricksWidth;\nfloat brickH=1.0/numberOfBricksHeight;\nfloat jointWPercentage=0.01;\nfloat jointHPercentage=0.05;\nvec3 color=brickColor;\nfloat yi=vUV.y/brickH;\nfloat nyi=roundF(yi);\nfloat xi=vUV.x/brickW;\nif (mod(floor(yi),2.0) == 0.0){\nxi=xi-0.5;\n}\nfloat nxi=roundF(xi);\nvec2 brickvUV=vec2((xi-floor(xi))/brickH,(yi-floor(yi))/brickW);\nif (yi<nyi+jointHPercentage && yi>nyi-jointHPercentage){\ncolor=mix(jointColor,vec3(0.37,0.25,0.25),(yi-nyi)/jointHPercentage+0.2);\n}\nelse if (xi<nxi+jointWPercentage && xi>nxi-jointWPercentage){\ncolor=mix(jointColor,vec3(0.44,0.44,0.44),(xi-nxi)/jointWPercentage+0.2);\n}\nelse {\nfloat brickColorSwitch=mod(floor(yi)+floor(xi),3.0);\nif (brickColorSwitch == 0.0)\ncolor=mix(color,vec3(0.33,0.33,0.33),0.3);\nelse if (brickColorSwitch == 2.0)\ncolor=mix(color,vec3(0.11,0.11,0.11),0.3);\n}\ngl_FragColor=vec4(color,1.0);\n}"; babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__["Effect"].ShadersStore[name] = shader; /** @hidden */ var brickProceduralTexturePixelShader = { name: name, shader: shader }; /***/ }), /***/ "./brick/brickProceduralTexture.ts": /*!*****************************************!*\ !*** ./brick/brickProceduralTexture.ts ***! \*****************************************/ /*! exports provided: BrickProceduralTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrickProceduralTexture", function() { return BrickProceduralTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../../node_modules/tslib/tslib.es6.js"); /* harmony import */ var babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! babylonjs/Misc/decorators */ "babylonjs/Misc/decorators"); /* harmony import */ var babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _brickProceduralTexture_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./brickProceduralTexture.fragment */ "./brick/brickProceduralTexture.fragment.ts"); var BrickProceduralTexture = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BrickProceduralTexture, _super); function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) { var _this = _super.call(this, name, size, "brickProceduralTexture", scene, fallbackTexture, generateMipMaps) || this; _this._numberOfBricksHeight = 15; _this._numberOfBricksWidth = 5; _this._jointColor = new babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Color3"](0.72, 0.72, 0.72); _this._brickColor = new babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["Color3"](0.77, 0.47, 0.40); _this.updateShaderUniforms(); return _this; } BrickProceduralTexture.prototype.updateShaderUniforms = function () { this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight); this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth); this.setColor3("brickColor", this._brickColor); this.setColor3("jointColor", this._jointColor); }; Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", { get: function () { return this._numberOfBricksHeight; }, set: function (value) { this._numberOfBricksHeight = value; this.updateShaderUniforms(); }, enumerable: true, configurable: true }); Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", { get: function () { return this._numberOfBricksWidth; }, set: function (value) { this._numberOfBricksWidth = value; this.updateShaderUniforms(); }, enumerable: true, configurable: true }); Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", { get: function () { return this._jointColor; }, set: function (value) { this._jointColor = value; this.updateShaderUniforms(); }, enumerable: true, configurable: true }); Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", { get: function () { return this._brickColor; }, set: function (value) { this._brickColor = value; this.updateShaderUniforms(); }, enumerable: true, configurable: true }); /** * Serializes this brick procedural texture * @returns a serialized brick procedural texture object */ BrickProceduralTexture.prototype.serialize = function () { var serializationObject = babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this, _super.prototype.serialize.call(this)); serializationObject.customType = "BABYLON.BrickProceduralTexture"; return serializationObject; }; /** * Creates a Brick Procedural Texture from parsed brick procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing brick procedural texture information * @returns a parsed Brick Procedural Texture */ BrickProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) { var texture = babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new BrickProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl); return texture; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BrickProceduralTexture.prototype, "numberOfBricksHeight", null); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BrickProceduralTexture.prototype, "numberOfBricksWidth", null); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], BrickProceduralTexture.prototype, "jointColor", null); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], BrickProceduralTexture.prototype, "brickColor", null); return BrickProceduralTexture; }(babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["ProceduralTexture"])); babylonjs_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["_TypeStore"].RegisteredTypes["BABYLON.BrickProceduralTexture"] = BrickProceduralTexture; /***/ }), /***/ "./brick/index.ts": /*!************************!*\ !*** ./brick/index.ts ***! \************************/ /*! exports provided: BrickProceduralTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _brickProceduralTexture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./brickProceduralTexture */ "./brick/brickProceduralTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BrickProceduralTexture", function() { return _brickProceduralTexture__WEBPACK_IMPORTED_MODULE_0__["BrickProceduralTexture"]; }); /***/ }), /***/ "./legacy/legacy-brick.ts": /*!********************************!*\ !*** ./legacy/legacy-brick.ts ***! \********************************/ /*! exports provided: BrickProceduralTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _brick_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../brick/index */ "./brick/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BrickProceduralTexture", function() { return _brick_index__WEBPACK_IMPORTED_MODULE_0__["BrickProceduralTexture"]; }); /** * This is the entry point for the UMD module. * The entry point for a future ESM package should be index.ts */ var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined); if (typeof globalObject !== "undefined") { for (var key in _brick_index__WEBPACK_IMPORTED_MODULE_0__) { globalObject.BABYLON[key] = _brick_index__WEBPACK_IMPORTED_MODULE_0__[key]; } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "babylonjs/Misc/decorators": /*!****************************************************************************************************!*\ !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***! \****************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_decorators__; /***/ }) /******/ }); }); //# sourceMappingURL=babylon.brickProceduralTexture.js.map
/*********************************************************************** Write a function named `spreadItOut(array1, array2)` that accepts two arrays and uses *spread operator* syntax to return a single array. Examples: spreadItOut([3,5,6], [1,2,3]); // => [3,5,6,1,2,3]; spreadItOut([], [1,2,3]); // => 14; spreadItOut(["apple", "banana"], [1,2,3]); // => ["apple", "banana", 1, 2, 3]; ***********************************************************************/ function spreadItOut(array1, array2) { let joinedArray = [...array1, ...array2]; return joinedArray; } module.exports = spreadItOut;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @emails oncall+relay * @format */ 'use strict'; const CompilerContext = require('../../core/CompilerContext'); const ConnectionTransform = require('../ConnectionTransform'); const DeferStreamTransform = require('../DeferStreamTransform'); const IRPrinter = require('../../core/IRPrinter'); const Schema = require('../../core/Schema'); const {transformASTSchema} = require('../../core/ASTConvert'); const { TestSchema, generateTestsFromFixtures, parseGraphQLText, } = require('relay-test-utils-internal'); describe('DeferStreamTransform', () => { const extendedSchema = transformASTSchema(TestSchema, [ ConnectionTransform.SCHEMA_EXTENSION, ]); describe('when streaming is enabled', () => { generateTestsFromFixtures( `${__dirname}/fixtures/relay-defer-stream-transform`, text => { const {definitions} = parseGraphQLText(extendedSchema, text); const compilerSchema = Schema.DEPRECATED__create( TestSchema, extendedSchema, ); return new CompilerContext(compilerSchema) .addAll(definitions) .applyTransforms([ ConnectionTransform.transform, DeferStreamTransform.transform, ]) .documents() .map(doc => IRPrinter.print(compilerSchema, doc)) .join('\n'); }, ); }); });
import React from "react"; function SearchForm(props) { return ( <form> <div className="form-group"> <label htmlFor="search">Search:</label> <input onChange={props.handleInputChange} value={props.value} name="search" type="text" className="form-control" placeholder="Search For a Food" id="search" /> <br /> <button onClick={props.handleFormSubmit} className="btn btn-primary"> Search </button> </div> </form> ); } export default SearchForm;
import React, { Suspense, lazy, useState, useEffect } from 'react' import { Row, Col, Typography, Avatar } from 'antd' import ProgressiveImage from 'react-progressive-graceful-image' import * as images from '../../assets/images' import './style.css' const About = () => { const Skills = lazy(() => import('./Skills')) const Experience = lazy(() => import('./Experience')) const Education = lazy(() => import('./Education')) const { Title, Paragraph } = Typography const roles = ['developer', 'learner', 'dreamer', 'gamer', 'cat lover'] const skills = [ { title: 'Javascript', tech: [ { name: 'Javascript', image: images.javascript }, { name: 'React', image: images.react }, { name: 'Node.js', image: images.nodejs }, { name: 'Expressjs', image: images.expressjs } ] }, { title: 'HTML', tech: [ { name: 'HTML', image: images.html5 }, { name: 'JSX', image: images.jsx } ] }, { title: 'CSS', tech: [ { name: 'CSS3', image: images.css3 }, { name: 'Bootstrap', image: images.bootstrap }, { name: 'Ant Design', image: images.antdesign } ] }, { title: 'Database', tech: [ { name: 'MongoDB', image: images.mongodb }, { name: 'Firebase', image: images.firebase } ] }, { title: 'Container', tech: [ { name: 'Docker', image: images.docker } ] }, { title: 'Cloud Platform', tech: [ { name: 'Google Cloud Platform', image: images.googlecloudplatform }, { name: 'Alibaba Cloud', image: images.alibabacloud } ] }, { title: 'Version Control', tech: [ { name: 'Github', image: images.github }, { name: 'Source Tree', image: images.sourcetree } ] }, { title: 'Wireframe', tech: [ { name: 'MockFlow', image: images.mockflow } ] } ] const experience = [ { title: 'Tuaton Co.,Ltd.', image: images.tuaton, position: 'Software Engineer', responsibilities: [ 'Designed APIs with Node.js and Expressjs.', 'Implemented web applications with HTML, CSS, and React.', 'Deployed and maintained APIs and web applications on Ubuntu server.', 'Guide best practices around accessible, semantic UI/UX.', 'Set up and maintained an identity server, Gluu.' ], period: 'Jun 2019 - Present | Bangkok, Thailand' }, { title: 'Tangerine Co.,Ltd.', image: images.tangerine, position: 'Software Developer, Intern', responsibilities: [ 'Designed a RESTful API with Python and Flask.', 'Implemented a Google authenticaition service with OAuth2.' ], period: 'Jun 2018 - Jul 2018 | Bangkok, Thailand' } ] const education = [ { title: "King Mongut's Institute of Technology Ladkrabang", image: images.kmitl, major: 'Bachelor of Engineer in Computer Engineering, 2019' } ] const [height, setHeight] = useState('calc(100vh - 400px)') useEffect(() => { const handleResize = () => { if (window.innerHeight > window.innerWidth) setHeight('calc(100vh - 400px)') else setHeight('calc(100vh - 150px)') } window.addEventListener('resize', handleResize) return () => window.removeEventListener('resize', handleResize) }, []) return ( <Col className='content'> {/* first section - welcome */} <Row className='section' align='middle' justify='center'> <ProgressiveImage src={images.cover} placeholder={images.cover}> {(src, loading) => ( <img className='cover-img' src={src} alt={src} style={{ height: height, filter: loading ? 'blur(10px)' : 'blur(0)', transition: '1s filter linear' }} /> )} </ProgressiveImage> <Col span={24}> <Row align='middle' justify='center'> <Title className='headline' style={{ marginBottom: 0, filter: 'drop-shadow(0 0 0.2rem black)' }} > I'm Kittinan. </Title> </Row> <Row align='middle' justify='center'> <Paragraph className='subheading' style={{ marginBottom: 0, filter: 'drop-shadow(0 0 0.1rem black)' }} > And I'm a </Paragraph> <div className='role subheading'> <div className='role_container'> <ul className='role_container_list'> {roles.map(role => ( <li key={role} className='role_container_list_item' style={{ filter: 'drop-shadow(0 0 0.1rem black)' }} > {role} </li> ))} </ul> </div> </div> </Row> </Col> </Row> {/* second section - introduction */} <Row className='section' align='middle' justify='center'> <Col style={{ maxWidth: '390px' }}> <Row align='middle' justify='center'> <ProgressiveImage src={images.profile} placeholder={images.profile}> {(src, loading) => ( <Avatar src={src} size={140} style={{ filter: loading ? 'blur(10px)' : 'blur(0)', transition: '1s filter linear' }} /> )} </ProgressiveImage> </Row> <Row style={{ marginTop: '50px' }}> <Col> <Row align='middle' justify='center'> <Paragraph className='text' style={{ color: '#45b29a' }}> Hi. </Paragraph> </Row> <Row align='middle' justify='center'> <Paragraph className='text' style={{ color: '#45b29a' }}> I'm a software developer based in Bangkok, Thailand. I have a passion for software development and <b> I love to code because it is usable art</b>. </Paragraph> </Row> </Col> </Row> </Col> </Row> {/* third section - skills */} <Suspense fallback={<div />}> <Skills skills={skills} /> </Suspense> {/* fourth section - experience */} <Suspense fallback={<div />}> <Experience experience={experience} /> </Suspense> {/* fifth section - education */} <Suspense fallback={<div />}> <Education education={education} /> </Suspense> </Col> ) } export default About
const jwt = require('jsonwebtoken'); const User = require('../models/user') const auth = async (req, res, next) => { try { const token = req.header('Authorization').replace('Bearer ', ''); const decoded = jwt.verify( token, 'thisismynewcourse') const user = await User.findOne({ _id : decoded._id , 'tokens.token': token}) if (!user){ throw new Error() } req.token = token req.user = user next() } catch (e) { res.status(401).send( {error: 'Please authenticate.'}) } } module.exports = auth
"use strict"; var db = require("../database"); var async = require('async'); var noop = function () { }; module.exports = { init: function () { }, fetchById: function(pid, callback) { callback = callback || noop; pid = parseInt(pid); db.query( "SELECT * FROM `alts` WHERE `id` = ? LIMIT 1", [pid], function(err, rows) { if (err) return callback(err); if (rows.length == 0) return callback(null, null); callback(null, rows[0]); } ); }, fetchByName: function(name, callback) { callback = callback || noop; db.query( "SELECT * FROM `alts` WHERE `name` = ? LIMIT 1", [name], function(err, rows) { if (err) return callback(err); if (rows.length == 0) return callback(null, null); callback(null, rows[0]); } ); }, fetch: function(limit, offset, callback) { callback = callback || noop; limit = limit || 20; offset = offset || 0; limit = parseInt(limit); offset = parseInt(offset); if (isNaN(limit)) { limit = 20; } if (isNaN(offset)) { offset = 0; } var sql = "SELECT * FROM `alts` " + "ORDER BY `id` DESC " + "LIMIT " + offset + ", " + limit; db.query(sql, [], callback); }, fetchByChannel: function(channel, callback) { callback = callback || noop; var sql = "SELECT * FROM `alts` WHERE `channels` LIKE ?"; db.query(sql, ['%' + channel + '%'], callback); }, update: function(id, name, password, channels, responses, playlist, queue_interval, is_enabled, callback) { callback = callback || noop; db.query( "UPDATE `alts` SET `name` = ?, `password` = ?, `channels` = ?, `responses` = ?, `playlist` = ?, `queue_interval` = ?, `is_enabled` = ? WHERE `id` = ? LIMIT 1", [name, password, channels, responses, playlist, queue_interval, is_enabled, id], callback ); }, insert: function(name, password, channels, responses, playlist, queue_interval, is_enabled, callback) { callback = callback || noop; db.query( "INSERT INTO `alts` (`name`, `password`, `channels`, `responses`, `playlist`, `queue_interval`, `is_enabled`) VALUES(?, ?, ?, ?, ?, ?, ?)", [name, password, channels, responses, playlist, queue_interval, is_enabled], callback ); } };
import utils from './utils'; class Setting { constructor(player) { this.player = player; this.dWidth = 200; this.hover = [false, false]; this.player.template.danmakuOpacityThumb.setAttribute('aria-label', (this.player.user.get('opacity') * 100).toFixed(0) + '%'); this.player.template.mask.addEventListener('click', () => { this.hide(); }); // hover icon 2 show panel this.player.template.settingButton.addEventListener('mouseover', () => { this.show(); this.hover[0] = true; }); this.player.template.settingButtonMobile.addEventListener('mouseover', () => { this.show(); this.hover[0] = true; }); this.player.template.speed.addEventListener('mouseover', () => { this.showSpeed(); this.hover[1] = true; }); // auto disappear this.player.template.settingButton.addEventListener('mouseleave', () => { this.hover[0] = setTimeout(() => { this.hover[0] && this.hide(); }, 300); }); this.player.template.settingButtonMobile.addEventListener('mouseleave', () => { this.hover[0] = setTimeout(() => { this.hover[0] && this.hide(); }, 300); }); this.player.template.speed.addEventListener('mouseleave', () => { this.hover[1] = setTimeout(() => { this.hover[1] && this.hideSpeed(); }, 300); }); // enter & clear timer this.player.template.settingBox.addEventListener('mouseenter', () => { clearTimeout(this.hover[0]); }); this.player.template.settingBoxMobile.addEventListener('mouseenter', () => { clearTimeout(this.hover[0]); }); this.player.template.speedBox.addEventListener('mouseenter', () => { clearTimeout(this.hover[1]); }); // disapper when leave this.player.template.settingBox.addEventListener('mouseleave', () => { this.hide(); }); this.player.template.settingBoxMobile.addEventListener('mouseleave', () => { this.hide(); }); this.player.template.speedBox.addEventListener('mouseleave', () => { this.hideSpeed(); }); // loop this.loop = this.player.options.loop; this.player.template.loopToggle.checked = this.loop; this.player.template.loop.addEventListener('click', () => { this.player.template.loopToggle.checked = !this.player.template.loopToggle.checked; if (this.player.template.loopToggle.checked) { this.loop = true; } else { this.loop = false; } // this.hide(); }); this.player.template.loopToggleMobile.checked = this.loop; this.player.template.loopMobile.addEventListener('click', () => { this.player.template.loopToggleMobile.checked = !this.player.template.loopToggleMobile.checked; if (this.player.template.loopToggleMobile.checked) { this.loop = true; } else { this.loop = false; } // this.hide(); }); // show danmaku this.showDanmaku = this.player.user.get('danmaku'); if (!this.showDanmaku) { this.player.danmaku && this.player.danmaku.hide(); } this.player.template.showDanmakuToggle.checked = this.showDanmaku; this.player.template.showDanmaku.addEventListener('click', () => { this.player.template.showDanmakuToggle.checked = !this.player.template.showDanmakuToggle.checked; if (this.player.template.showDanmakuToggle.checked) { this.showDanmaku = true; this.player.danmaku.show(); } else { this.showDanmaku = false; this.player.danmaku.hide(); } this.player.user.set('danmaku', this.showDanmaku ? 1 : 0); // this.hide(); }); // unlimit danmaku this.unlimitDanmaku = this.player.user.get('unlimited'); this.player.template.unlimitDanmakuToggle.checked = this.unlimitDanmaku; this.player.template.unlimitDanmaku.addEventListener('click', () => { this.player.template.unlimitDanmakuToggle.checked = !this.player.template.unlimitDanmakuToggle.checked; if (this.player.template.unlimitDanmakuToggle.checked) { this.unlimitDanmaku = true; this.player.danmaku.unlimit(true); } else { this.unlimitDanmaku = false; this.player.danmaku.unlimit(false); } this.player.user.set('unlimited', this.unlimitDanmaku ? 1 : 0); // this.hide(); }); // danmaku range if (this.player.danmaku) { this.player.on('danmaku_range', (range) => { this.player.user.set('range', range); }); this.player.danmaku.range(this.player.user.get('range')); const selector = document.querySelector(`.dplayer-setting .dplayer-selector-option[data-range="${this.player.danmaku.getRange()}"]`); selector && selector.classList.add('range-selected'); const selectorMobile = document.querySelector(`.dplayer-settingmobile .dplayer-selector-option[data-range="${this.player.danmaku.getRange()}"]`); selectorMobile && selectorMobile.classList.add('range-selected'); for (let i = 0; i < this.player.template.commentRangeSelector.length; i++) { this.player.template.commentRangeSelector[i].addEventListener('click', () => { const rangeSelectedBefore = document.querySelectorAll('.dplayer-selector-option.range-selected'); rangeSelectedBefore && rangeSelectedBefore.forEach((selected) => selected.classList.remove('range-selected')); const range = this.player.template.commentRangeSelector[i].dataset.range; const rangeSelected = document.querySelectorAll(`.dplayer-selector-option[data-range="${range}"]`); rangeSelected && rangeSelected.forEach((selected) => selected.classList.add('range-selected')); this.player.danmaku.range(range); }); } } // speed this.player.template.speed.addEventListener('click', () => { if (this.player.template.speed.classList.contains('active')) {this.hideSpeed();} else {this.showSpeed();} }); for (let i = 0; i < this.player.template.speedItem.length; i++) { this.player.template.speedItem[i].addEventListener('click', () => { const speedSelected = document.querySelector('.dplayer-setting-speed-item.speed-selected'); speedSelected && speedSelected.classList.remove('speed-selected'); this.player.speed(this.player.template.speedItem[i].dataset.speed); const num = this.player.template.speedItem[i].dataset.speed; this.player.template.speed.innerText = (num.length === 1 ? num + '.0' : num) + 'x'; this.player.template.speedItem[i].classList.add('speed-selected'); utils.isMobile || this.hide(); }); } // danmaku opacity if (this.player.danmaku) { this.player.on('danmaku_opacity', (percentage) => { this.player.bar.set('danmaku', percentage, 'width'); this.player.bar.set('danmakuMobile', percentage, 'width'); this.player.user.set('opacity', 0.9 * percentage + 0.1); this.player.template.danmakuOpacityThumb.setAttribute('aria-label', (percentage * 90 + 10).toFixed(0) + '%'); }); this.player.danmaku.opacity(this.player.user.get('opacity')); const danmakuMove = (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuOpacityBarWrap)) / this.player.template.danmakuOpacityBarWrap.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.opacity(percentage); }; const danmakuMoveMobile = (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuOpacityBarWrapMobile)) / this.player.template.danmakuOpacityBarWrapMobile.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.opacity(percentage); }; const danmakuUp = () => { document.removeEventListener(utils.nameMap.dragEnd, danmakuUp); document.removeEventListener(utils.nameMap.dragMove, danmakuMove); document.removeEventListener(utils.nameMap.dragMove, danmakuMoveMobile); this.player.template.danmakuOpacityBox.classList.remove('dplayer-setting-danmaku-active'); this.player.template.danmakuOpacityBoxMobile.classList.remove('dplayer-setting-danmaku-active'); }; this.player.template.danmakuOpacityBarWrapWrap.addEventListener('click', (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuOpacityBarWrap)) / this.player.template.danmakuOpacityBarWrap.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.opacity(percentage); this.player.template.danmakuOpacityThumb.setAttribute('aria-label', (percentage * 90 + 10).toFixed(0) + '%'); }); this.player.template.danmakuOpacityBarWrapWrapMobile.addEventListener('click', (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuOpacityBarWrapMobile)) / this.player.template.danmakuOpacityBarWrapMobile.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.opacity(percentage); this.player.template.danmakuOpacityThumbMobile.setAttribute('aria-label', (percentage * 90 + 10).toFixed(0) + '%'); }); this.player.template.danmakuOpacityBarWrapWrap.addEventListener(utils.nameMap.dragStart, () => { document.addEventListener(utils.nameMap.dragMove, danmakuMove); document.addEventListener(utils.nameMap.dragEnd, danmakuUp); this.player.template.danmakuOpacityBox.classList.add('dplayer-setting-danmaku-active'); }); this.player.template.danmakuOpacityBarWrapWrapMobile.addEventListener(utils.nameMap.dragStart, () => { document.addEventListener(utils.nameMap.dragMove, danmakuMove); document.addEventListener(utils.nameMap.dragEnd, danmakuUp); this.player.template.danmakuOpacityBoxMobile.classList.add('dplayer-setting-danmaku-active'); }); } // danmaku speed if (this.player.danmaku) { this.player.on('danmaku_speed', (speed) => { this.player.bar.set('speed', (speed - 5000) / 15000, 'width'); this.player.bar.set('speedMobile', (speed - 5000) / 15000, 'width'); this.player.user.set('speed', speed); }); this.player.danmaku.speed(this.player.user.get('speed')); const danmakuSpeedMove = (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuSpeedBarWrap)) / this.player.template.danmakuSpeedBarWrap.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.speed(percentage.toFixed(2) * 15000 + 5000); }; const danmakuSpeedMoveMobile = (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuSpeedBarWrapMobile)) / this.player.template.danmakuSpeedBarWrapMobile.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.speed(percentage.toFixed(2) * 15000 + 5000); }; const danmakuSpeedUp = () => { document.removeEventListener(utils.nameMap.dragEnd, danmakuSpeedUp); document.removeEventListener(utils.nameMap.dragMove, danmakuSpeedMove); document.removeEventListener(utils.nameMap.dragMove, danmakuSpeedMoveMobile); this.player.template.danmakuSpeedBox.classList.remove('dplayer-setting-danmaku-active'); this.player.template.danmakuSpeedBoxMobile.classList.remove('dplayer-setting-danmaku-active'); }; this.player.template.danmakuSpeedBarWrapWrap.addEventListener('click', (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuSpeedBarWrap)) / this.player.template.danmakuSpeedBarWrap.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.speed(percentage.toFixed(2) * 15000 + 5000); }); this.player.template.danmakuSpeedBarWrapWrapMobile.addEventListener('click', (event) => { const e = event || window.event; let percentage = ((e.clientX || e.changedTouches[0].clientX) - utils.getBoundingClientRectViewLeft(this.player.template.danmakuSpeedBarWrapMobile)) / this.player.template.danmakuSpeedBarWrapMobile.offsetWidth; percentage = Math.max(percentage, 0); percentage = Math.min(percentage, 1); this.player.danmaku.speed(percentage.toFixed(2) * 15000 + 5000); }); this.player.template.danmakuSpeedBarWrapWrap.addEventListener(utils.nameMap.dragStart, () => { document.addEventListener(utils.nameMap.dragMove, danmakuSpeedMove); document.addEventListener(utils.nameMap.dragEnd, danmakuSpeedUp); this.player.template.danmakuSpeedBox.classList.add('dplayer-setting-danmaku-active'); }); this.player.template.danmakuSpeedBarWrapWrapMobile.addEventListener(utils.nameMap.dragStart, () => { document.addEventListener(utils.nameMap.dragMove, danmakuSpeedMoveMobile); document.addEventListener(utils.nameMap.dragEnd, danmakuSpeedUp); this.player.template.danmakuSpeedBoxMobile.classList.add('dplayer-setting-danmaku-active'); }); } this.resize(); } hide() { this.player.template.settingBox.classList.remove('dplayer-setting-box-open'); this.player.template.settingBoxMobile.classList.remove('dplayer-setting-box-open'); // this.player.template.mask.classList.remove('dplayer-mask-show'); this.player.controller.disableAutoHide = false; } show() { // this.dWidth = this.player.template.danmakuOpacityBarWrap.offsetWidth this.player.template.settingBox.classList.add('dplayer-setting-box-open'); this.player.template.settingBoxMobile.classList.add('dplayer-setting-box-open'); // this.player.template.mask.classList.add('dplayer-mask-show'); this.player.controller.disableAutoHide = true; this.hideSpeed(); } hideSpeed() { this.player.template.speed.classList.remove('active'); } showSpeed() { this.player.template.speed.classList.add('active'); this.player.controller.disableAutoHide = true; this.hide(); } resize() { if (utils.orientationAngle() === 0 || utils.orientationAngle() === 180) { this.player.template.settingBoxMobile.classList.add('vertical'); } else { this.player.template.settingBoxMobile.classList.remove('vertical'); } } } export default Setting;
define(function(require) { 'use strict'; var $ = require('jquery'); var _ = require('underscore'); var scrollspy = require('oroui/js/scrollspy'); var mediator = require('oroui/js/mediator'); var tools = require('oroui/js/tools'); var scrollHelper = require('oroui/js/tools/scroll-helper'); var Popover = require('bootstrap-popover'); require('jquery-ui'); var document = window.document; var console = window.console; var pageRenderedCbPool = []; var layout = { /** * Default padding to keep when calculate available height for fullscreen layout */ PAGE_BOTTOM_PADDING: 10, /** * Height of header on mobile devices */ MOBILE_HEADER_HEIGHT: scrollHelper.MOBILE_HEADER_HEIGHT, /** * Height of header on mobile devices */ MOBILE_POPUP_HEADER_HEIGHT: scrollHelper.MOBILE_POPUP_HEADER_HEIGHT, /** * Minimal height for fullscreen layout */ minimalHeightForFullScreenLayout: 300, /** * List of elements with disabled scroll. Used to reset theirs state * @private */ _scrollDisabledElements: null, /** * Initializes form widgets, scrollspy, and triggers `initLayout` event * * @param {string|HTMLElement|jQuery.Element} container */ init: function(container) { var $container; $container = $(container); this.styleForm($container); scrollspy.init($container); $container.trigger('initLayout'); $container.on({ 'content:changed': this.onContentChanged, 'content:remove': this.onContentRemove }); }, initPopover: function(container, options) { var $items = container.find('[data-toggle="popover"]').filter(function() { // skip already initialized popovers return !$(this).data(Popover.DATA_KEY); }); this.initPopoverForElements($items, options); }, initPopoverForElements: function($items, options, overrideOptionsByData) { options = _.defaults(options || {}, { animation: false, delay: {show: 0, hide: 0}, html: true, container: false, trigger: 'manual' }); if (overrideOptionsByData) { options = $.extend(options, $items.data()); } $items.not('[data-close="false"]').each(function(i, el) { // append close link var content = el.getAttribute('data-content'); content += '<i class="fa-close popover-close"></i>'; el.setAttribute('data-content', content); }); $items.popover(options).on('click' + Popover.EVENT_KEY, function(e) { if ($(this).is('.disabled, :disabled')) { return; } $(this).popover('toggle'); e.preventDefault(); }); $('body') .on('click.popover-hide', function(e) { var $target = $(e.target); // '[aria-describedby]' -- meens the popover is opened $items.filter('[aria-describedby]').each(function() { // the 'is' for buttons that trigger popups // the 'has' for icons within a button that triggers a popup if ( !$(this).is($target) && $(this).has($target).length === 0 && ($('.popover').has($target).length === 0 || $target.hasClass('popover-close')) ) { $(this).popover('hide'); } }); }).on('click.popover-prevent', '.popover', function(e) { if (e.target.tagName.toLowerCase() !== 'a') { e.preventDefault(); } }).on('focus.popover-hide', 'select, input, textarea', function() { // '[aria-describedby]' -- meens the popover is opened $items.filter('[aria-describedby]').popover('hide'); }); mediator.once('page:request', function() { $('body').off('.popover-hide .popover-prevent'); }); }, /** * Disposes form widgets and triggers `disposeLayout` event * * @param {string|HTMLElement|jQuery.Element} container */ dispose: function(container) { var $container; $container = $(container); $container.off({ 'content:changed': this.onContentChanged, 'content:remove': this.onContentRemove }); this.unstyleForm($container); $container.trigger('disposeLayout'); }, hideProgressBar: function() { var $bar = $('#progressbar'); if ($bar.is(':visible')) { $bar.hide(); $('#page').show(); } }, /** * Bind forms widget and plugins to elements * * @param {jQuery=} $container */ styleForm: function($container) { $container.inputWidget('seekAndCreate'); }, /** * Removes forms widget and plugins from elements * * @param {jQuery=} $container */ unstyleForm: function($container) { $container.inputWidget('seekAndDestroy'); }, onPageRendered: function(cb) { if (document.pageReady) { _.defer(cb); } else { pageRenderedCbPool.push(cb); } }, pageRendering: function() { document.pageReady = false; pageRenderedCbPool = []; }, pageRendered: function() { document.pageReady = true; _.each(pageRenderedCbPool, function(cb) { try { cb(); } catch (ex) { if (console && (typeof console.log === 'function')) { console.log(ex); } } }); pageRenderedCbPool = []; }, /** * Returns available height for element if page will be transformed to fullscreen mode * * @param $mainEl * @param boundingClientRect - pass boundingClientRect of $mainEl to avoid it expensive calculation * @returns {number} */ getAvailableHeight: function($mainEl, boundingClientRect) { var $parents = $mainEl.parents(); var documentHeight = scrollHelper.documentHeight(); var heightDiff = documentHeight - (boundingClientRect ? boundingClientRect : $mainEl[0].getBoundingClientRect()).top; $parents.each(function() { heightDiff += this.scrollTop; }); heightDiff -= documentHeight - $('#container')[0].getBoundingClientRect().bottom; heightDiff -= this.PAGE_BOTTOM_PADDING; return heightDiff; }, /** * Returns name of preferred layout for $mainEl * * @param $mainEl * @param boundingClientRect - pass boundingClientRect of $mainEl to avoid it expensive calculation * @returns {string} */ getPreferredLayout: function($mainEl, boundingClientRect) { if (!this.hasHorizontalScroll() && !tools.isMobile() && this.getAvailableHeight($mainEl, boundingClientRect) > this.minimalHeightForFullScreenLayout) { return 'fullscreen'; } else { return 'scroll'; } }, /** * Disables ability to scroll of $mainEl's scrollable parents * * @param $mainEl * @returns {string} */ disablePageScroll: function($mainEl) { if (this._scrollDisabledElements && this._scrollDisabledElements.length) { this.enablePageScroll(); } var $scrollableParents = $mainEl.parents(); $scrollableParents.scrollTop(0); $scrollableParents.addClass('disable-scroll'); this._scrollDisabledElements = $scrollableParents; }, /** * Enables ability to scroll where it was previously disabled * * @returns {string} */ enablePageScroll: function() { if (this._scrollDisabledElements && this._scrollDisabledElements.length) { this._scrollDisabledElements.parents().removeClass('disable-scroll'); delete this._scrollDisabledElements; } }, /** * Returns true if page has horizontal scroll * @returns {boolean} */ hasHorizontalScroll: function() { return Math.round($('body').outerWidth()) > $(window).width(); }, /** * Try to calculate the scrollbar width for your browser/os * @return {Number} */ scrollbarWidth: function() { return scrollHelper.scrollbarWidth(); }, onContentChanged: function(e) { layout.styleForm($(e.target)); }, onContentRemove: function(e) { layout.unstyleForm($(e.target)); }, /** * Adjust width for form labels into dialog form * @private */ adjustLabelsWidth: function($context) { var controlGroups = $context.find('.control-group').filter(function(i, group) { return !$(group).find('> .control-label').length && !$(group).closest('.tab-content, .controls').length; }); var labels = $context.find('.control-label').filter(function(i, label) { return !$(label).closest('.widget-title-container').length; }); labels.css('width', ''); var width = labels.map(function(i, label) { return label.getBoundingClientRect().width; }).get(); var newWidth = Math.ceil(Math.max.apply(null, width)); labels.css('width', newWidth); controlGroups.each(function(i, group) { var prop = 'margin-' + (_.isRTL() ? 'right' : 'left'); var controls = $(group).find('> .controls'); controls .css(prop, '') .css(prop, parseInt(controls.css(prop)) + newWidth); }); } }; return layout; });
const path = require('path'); module.exports = { plugins: [ `gatsby-plugin-emotion`, `gatsby-plugin-react-helmet`, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, `gatsby-plugin-offline`, `gatsby-plugin-typescript`, { resolve: 'gatsby-plugin-root-import', options: { components: path.join(__dirname, 'src/components'), context: path.join(__dirname, 'src/context'), mock: path.join(__dirname, 'src/mock'), styles: path.join(__dirname, 'src/styles'), types: path.join(__dirname, '@types'), src: path.join(__dirname, 'src'), pages: path.join(__dirname, 'src/pages'), }, }, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images/`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `pages`, path: `${__dirname}/src/pages/`, }, }, { resolve: `gatsby-plugin-manifest`, options: { name: `Gatsby Simplefolio`, short_name: `Simplefolio`, start_url: `/`, background_color: `#fff`, theme_color: `#02aab0`, display: `standalone`, icon: 'src/images/favicon.png', }, }, ], };
function draw() { // 颜色格子 +function () { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' + Math.floor(255 - 42.5 * j) + ',0)'; ctx.fillRect(j * 25, i * 25, 25, 25); } } } }(); // 基本图形 ~function () { var canvas = document.getElementById("canvas2"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)"; ctx.fillRect(10, 10, 55, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect(30, 30, 55, 50); } }(); // 绘制矩形 !function () { var canvas = document.getElementById("canvas3"); // canvas.style.backgroundColor = 'red'; if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); } }(); // 绘制路径 - 绘制一个三角形 (function () { var canvas = document.getElementById("canvas4"); // canvas.style.backgroundColor = 'red'; if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(75, 50); ctx.lineTo(100, 75); ctx.lineTo(100, 25); ctx.closePath(); ctx.fill(); } }()); // 绘制路径 - 移动笔触 (function () { var canvas = document.getElementById("canvas5"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(75, 75, 50, 0, Math.PI * 2, true); // 绘制 ctx.moveTo(110, 75); ctx.arc(75, 75, 35, 0, Math.PI, false); // 口(顺时针) ctx.moveTo(65, 65); ctx.arc(60, 65, 5, 0, Math.PI * 2, true); // 左眼 ctx.moveTo(95, 65); ctx.arc(90, 65, 5, 0, Math.PI * 2, true); // 右眼 ctx.stroke(); } }()); // 绘制路径 - 线 (function () { var canvas = document.getElementById("canvas6"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // 填充三角形 ctx.beginPath(); ctx.moveTo(25, 25); ctx.lineTo(105, 25); ctx.lineTo(25, 105); ctx.fill(); // 描边三角形 ctx.beginPath(); ctx.moveTo(125, 125); ctx.lineTo(125, 45); ctx.lineTo(45, 125); ctx.closePath(); ctx.stroke(); } }()); // 绘制路径 - 圆弧 (function () { var canvas = document.getElementById("canvas7"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 4; i++) { for (var j = 0; j < 3; j++) { ctx.beginPath(); var x = 25 + j * 50; // x 坐标值 var y = 25 + i * 50; // y 坐标值 var radius = 20; // 圆弧半径 var startAngle = 0; // 开始点 var endAngle = Math.PI + (Math.PI * j) / 2; // 结束点 var anticlockwise = i % 2 == 0 ? false : true; // 顺时针或逆时针 ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise); if (i > 1) { ctx.fill(); } else { ctx.stroke(); } } } } }()); // 绘制路径 - 二次贝赛尔曲线 (function () { var canvas = document.getElementById("canvas8"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // 二次贝塞尔曲线 ctx.beginPath(); ctx.moveTo(75, 25); ctx.quadraticCurveTo(25, 25, 25, 62.5); ctx.quadraticCurveTo(25, 100, 50, 100); ctx.quadraticCurveTo(50, 120, 30, 125); ctx.quadraticCurveTo(60, 120, 65, 100); ctx.quadraticCurveTo(125, 100, 125, 62.5); ctx.quadraticCurveTo(125, 25, 75, 25); ctx.stroke(); } }()); // 绘制路径 - 三次贝赛尔曲线 (function () { var canvas = document.getElementById("canvas9"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); //三次贝塞尔曲线 ctx.beginPath(); ctx.moveTo(75, 40); ctx.bezierCurveTo(75, 37, 70, 25, 50, 25); ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5); ctx.bezierCurveTo(20, 80, 40, 102, 75, 120); ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5); ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25); ctx.bezierCurveTo(85, 25, 75, 37, 75, 40); ctx.fill(); } }()); // 绘制路径 - 组合使用 (function () { var canvas = document.getElementById("canvas10"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); roundedRect(ctx, 12, 12, 150, 150, 15); roundedRect(ctx, 19, 19, 150, 150, 9); roundedRect(ctx, 53, 53, 49, 33, 10); roundedRect(ctx, 53, 119, 49, 16, 6); roundedRect(ctx, 135, 53, 49, 33, 10); roundedRect(ctx, 135, 119, 25, 49, 10); ctx.beginPath(); ctx.arc(37, 37, 13, Math.PI / 7, -Math.PI / 7, false); ctx.lineTo(31, 37); ctx.fill(); for (var i = 0; i < 8; i++) { ctx.fillRect(51 + i * 16, 35, 4, 4); } for (i = 0; i < 6; i++) { ctx.fillRect(115, 51 + i * 16, 4, 4); } for (i = 0; i < 8; i++) { ctx.fillRect(51 + i * 16, 99, 4, 4); } ctx.beginPath(); ctx.moveTo(83, 116); ctx.lineTo(83, 102); ctx.bezierCurveTo(83, 94, 89, 88, 97, 88); ctx.bezierCurveTo(105, 88, 111, 94, 111, 102); ctx.lineTo(111, 116); ctx.lineTo(106.333, 111.333); ctx.lineTo(101.666, 116); ctx.lineTo(97, 111.333); ctx.lineTo(92.333, 116); ctx.lineTo(87.666, 111.333); ctx.lineTo(83, 116); ctx.fill(); ctx.fillStyle = "white"; ctx.beginPath(); ctx.moveTo(91, 96); ctx.bezierCurveTo(88, 96, 87, 99, 87, 101); ctx.bezierCurveTo(87, 103, 88, 106, 91, 106); ctx.bezierCurveTo(94, 106, 95, 103, 95, 101); ctx.bezierCurveTo(95, 99, 94, 96, 91, 96); ctx.moveTo(103, 96); ctx.bezierCurveTo(100, 96, 99, 99, 99, 101); ctx.bezierCurveTo(99, 103, 100, 106, 103, 106); ctx.bezierCurveTo(106, 106, 107, 103, 107, 101); ctx.bezierCurveTo(107, 99, 106, 96, 103, 96); ctx.fill(); ctx.fillStyle = "black"; ctx.beginPath(); ctx.arc(101, 102, 2, 0, Math.PI * 2, true); ctx.fill(); ctx.beginPath(); ctx.arc(89, 102, 2, 0, Math.PI * 2, true); ctx.fill(); } // 封装的一个用于绘制圆角矩形的函数. function roundedRect(ctx, x, y, width, height, radius) { ctx.beginPath(); ctx.moveTo(x, y + radius); ctx.lineTo(x, y + height - radius); ctx.quadraticCurveTo(x, y + height, x + radius, y + height); ctx.lineTo(x + width - radius, y + height); ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius); ctx.lineTo(x + width, y + radius); ctx.quadraticCurveTo(x + width, y, x + width - radius, y); ctx.lineTo(x + radius, y); ctx.quadraticCurveTo(x, y, x, y + radius); ctx.stroke(); } }()); // 绘制路径 - Path2D对象 (function () { var canvas = document.getElementById("canvas11"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); var rectangle = new Path2D(); rectangle.rect(10, 10, 50, 50); var circle = new Path2D(); circle.moveTo(125, 35); circle.arc(100, 35, 25, 0, 2 * Math.PI); ctx.stroke(rectangle); ctx.fill(circle); } })(); // 颜色与样式 - fillStyle (function () { var canvas = document.getElementById("canvas12"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' + Math.floor(255 - 42.5 * j) + ',0)'; ctx.fillRect(j * 25, i * 25, 25, 25); } } } })(); // 颜色与样式 - fillStyle (function () { var canvas = document.getElementById("canvas12"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' + Math.floor(255 - 42.5 * j) + ',0)'; ctx.fillRect(j * 25, i * 25, 25, 25); } } } })(); // 颜色与样式 - strokeStyle (function () { var canvas = document.getElementById("canvas13"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.strokeStyle = 'rgb(0,' + Math.floor(255 - 42.5 * i) + ',' + Math.floor(255 - 42.5 * j) + ')'; ctx.beginPath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true); ctx.stroke(); } } } })(); // 颜色与样式 - globalAlpha (function () { var canvas = document.getElementById("canvas14"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // 画背景 ctx.fillStyle = '#FD0'; ctx.fillRect(0, 0, 75, 75); ctx.fillStyle = '#6C0'; ctx.fillRect(75, 0, 75, 75); ctx.fillStyle = '#09F'; ctx.fillRect(0, 75, 75, 75); ctx.fillStyle = '#F30'; ctx.fillRect(75, 75, 75, 75); ctx.fillStyle = '#FFF'; // 设置透明度值 ctx.globalAlpha = 0.2; // 画半透明圆 for (var i = 0; i < 7; i++) { ctx.beginPath(); ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true); ctx.fill(); } } })(); // 颜色与样式 - RGBA (function () { var canvas = document.getElementById("canvas15"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // 画背景 ctx.fillStyle = 'rgb(255,221,0)'; ctx.fillRect(0, 0, 150, 37.5); ctx.fillStyle = 'rgb(102,204,0)'; ctx.fillRect(0, 37.5, 150, 37.5); ctx.fillStyle = 'rgb(0,153,255)'; ctx.fillRect(0, 75, 150, 37.5); ctx.fillStyle = 'rgb(255,51,0)'; ctx.fillRect(0, 112.5, 150, 37.5); // 画半透明矩形 for (var i = 0; i < 10; i++) { ctx.fillStyle = 'rgba(255,255,255,' + (i + 1) / 10 + ')'; for (var j = 0; j < 4; j++) { ctx.fillRect(5 + i * 14, 5 + j * 37.5, 14, 27.5) } } } })(); // 线型 Line styles - lineWidth (function () { var canvas = document.getElementById("canvas16"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 10; i++) { ctx.lineWidth = 1 + i; ctx.beginPath(); ctx.moveTo(5 + i * 14, 5); ctx.lineTo(5 + i * 14, 140); ctx.stroke(); } } })(); // 线型 Line styles - lineCap (function () { var canvas = document.getElementById("canvas17"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); var lineCap = ['butt', 'round', 'square']; // 创建路径 ctx.strokeStyle = '#09f'; ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(140, 10); ctx.moveTo(10, 140); ctx.lineTo(140, 140); ctx.stroke(); // 画线条 ctx.strokeStyle = 'black'; for (var i = 0; i < lineCap.length; i++) { ctx.lineWidth = 15; ctx.lineCap = lineCap[i]; ctx.beginPath(); ctx.moveTo(25 + i * 50, 10); ctx.lineTo(25 + i * 50, 140); ctx.stroke(); } } })(); // 线型 Line styles - lineJoin (function () { var canvas = document.getElementById("canvas18"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); var lineJoin = ['round', 'bevel', 'miter']; ctx.lineWidth = 10; for (var i = 0; i < lineJoin.length; i++) { ctx.lineJoin = lineJoin[i]; ctx.beginPath(); ctx.moveTo(-5, 5 + i * 40); ctx.lineTo(35, 45 + i * 40); ctx.lineTo(75, 5 + i * 40); ctx.lineTo(115, 45 + i * 40); ctx.lineTo(155, 5 + i * 40); ctx.stroke(); } } })(); // 线型 Line styles - 使用虚线 (function () { var canvas = document.getElementById("canvas19"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); var offset = 0; function drawDash() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.setLineDash([4, 2]); ctx.lineDashOffset = -offset; ctx.strokeRect(10, 10, 100, 100); } function march() { offset++; if (offset > 16) { offset = 0; } drawDash(); setTimeout(march, 20); } march(); } })(); // 线型 Line styles - 线性渐变 (function () { var canvas = document.getElementById("canvas20"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // Create gradients var lingrad = ctx.createLinearGradient(0, 0, 0, 150); lingrad.addColorStop(0, '#00ABEB'); lingrad.addColorStop(0.5, '#fff'); lingrad.addColorStop(0.5, '#26C000'); lingrad.addColorStop(1, '#fff'); var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95); lingrad2.addColorStop(0.5, '#000'); lingrad2.addColorStop(1, 'rgba(0,0,0,0)'); // assign gradients to fill and stroke styles ctx.fillStyle = lingrad; ctx.strokeStyle = lingrad2; // draw shapes ctx.fillRect(10, 10, 130, 130); ctx.strokeRect(50, 50, 50, 50); } })(); // 线型 Line styles - 径向渐变 (function () { var canvas = document.getElementById("canvas21"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // 创建渐变 var radgrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30); radgrad.addColorStop(0, '#A7D30C'); radgrad.addColorStop(0.9, '#019F62'); radgrad.addColorStop(1, 'rgba(1,159,98,0)'); var radgrad2 = ctx.createRadialGradient(105, 105, 20, 112, 120, 50); radgrad2.addColorStop(0, '#FF5F98'); radgrad2.addColorStop(0.75, '#FF0188'); radgrad2.addColorStop(1, 'rgba(255,1,136,0)'); var radgrad3 = ctx.createRadialGradient(95, 15, 15, 102, 20, 40); radgrad3.addColorStop(0, '#00C9FF'); radgrad3.addColorStop(0.8, '#00B5E2'); radgrad3.addColorStop(1, 'rgba(0,201,255,0)'); var radgrad4 = ctx.createRadialGradient(0, 150, 50, 0, 140, 90); radgrad4.addColorStop(0, '#F4F201'); radgrad4.addColorStop(0.8, '#E4C700'); radgrad4.addColorStop(1, 'rgba(228,199,0,0)'); // 画图形 ctx.fillStyle = radgrad4; ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad3; ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad2; ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad; ctx.fillRect(0, 0, 150, 150); } })(); // 图案样式 Patterns (function () { var canvas = document.getElementById("canvas22"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // 创建新 image 对象,用作图案 var img = new Image(); img.src = '/static/images/zan.png'; img.onload = function () { // 创建图案 var ptrn = ctx.createPattern(img, 'repeat'); ctx.fillStyle = ptrn; ctx.fillRect(0, 0, 150, 150); } } })(); // 文字阴影 (function () { var canvas = document.getElementById("canvas23"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; ctx.shadowBlur = 2; ctx.shadowColor = "rgba(0, 0, 0, 0.5)"; ctx.font = "20px 楷体"; ctx.fillStyle = "Black"; ctx.fillText("我爱你,中国", 5, 30); } })(); // Canvas 填充规则 (function () { var canvas = document.getElementById("canvas24"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(50, 50, 30, 0, Math.PI * 2, true); ctx.arc(50, 50, 15, 0, Math.PI * 2, true); ctx.fill("evenodd"); } })(); // 缩放 Scaling (function () { var canvas = document.getElementById("canvas25"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function () { for (var i = 0; i < 4; i++) { for (var j = 0; j < 3; j++) { ctx.drawImage(img, j * 50, i * 38, 50, 38); } } }; img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg'; } })(); // 缩放 Scaling (function () { var canvas = document.getElementById("canvas26"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillRect(0, 0, 150, 150); // 使用默认设置绘制一个矩形 ctx.save(); // 保存默认状态 ctx.fillStyle = '#09F' // 在原有配置基础上对颜色做改变 ctx.fillRect(15, 15, 120, 120); // 使用新的设置绘制一个矩形 ctx.save(); // 保存当前状态 ctx.fillStyle = '#FFF' // 再次改变颜色配置 ctx.globalAlpha = 0.5; ctx.fillRect(30, 30, 90, 90); // 使用新的配置绘制一个矩形 ctx.restore(); // 重新加载之前的颜色状态 ctx.fillRect(45, 45, 60, 60); // 使用上一次的配置绘制一个矩形 ctx.restore(); // 加载默认颜色配置 ctx.fillRect(60, 60, 30, 30); // 使用加载的配置绘制一个矩形 } })(); // translate (function () { var canvas = document.getElementById("canvas27"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { ctx.save(); ctx.fillStyle = 'rgb(' + (51 * i) + ', ' + (255 - 51 * i) + ', 255)'; ctx.translate(10 + j * 50, 10 + i * 50); ctx.fillRect(0, 0, 25, 25); ctx.restore(); } } } })(); // rotate (function () { var canvas = document.getElementById("canvas28"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.translate(75, 75); for (var i = 1; i < 6; i++) { // Loop through rings (from inside to out) ctx.save(); ctx.fillStyle = 'rgb(' + (51 * i) + ',' + (255 - 51 * i) + ',255)'; for (var j = 0; j < i * 6; j++) { // draw individual dots ctx.rotate(Math.PI * 2 / (i * 6)); ctx.beginPath(); ctx.arc(0, i * 12.5, 5, 0, Math.PI * 2, true); ctx.fill(); } ctx.restore(); } } })(); // scale (function () { var canvas = document.getElementById("canvas29"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // draw a simple rectangle, but scale it. ctx.save(); ctx.scale(10, 3); ctx.fillRect(1, 10, 10, 10); ctx.restore(); // mirror horizontally ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.fillText('MDN', -135, 120); } })(); // clip (function () { var canvas = document.getElementById("canvas30"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillRect(0, 0, 150, 150); ctx.translate(75, 75); // Create a circular clipping path ctx.beginPath(); ctx.arc(0, 0, 60, 0, Math.PI * 2, true); ctx.clip(); // draw background var lingrad = ctx.createLinearGradient(0, -75, 0, 75); lingrad.addColorStop(0, '#232256'); lingrad.addColorStop(1, '#143778'); ctx.fillStyle = lingrad; ctx.fillRect(-75, -75, 150, 150); // draw stars for (var j = 1; j < 50; j++) { ctx.save(); ctx.fillStyle = '#fff'; ctx.translate(75 - Math.floor(Math.random() * 150), 75 - Math.floor(Math.random() * 150)); drawStar(ctx, Math.floor(Math.random() * 4) + 2); ctx.restore(); } function drawStar(ctx, r) { ctx.save(); ctx.beginPath() ctx.moveTo(r, 0); for (var i = 0; i < 9; i++) { ctx.rotate(Math.PI / 5); if (i % 2 == 0) { ctx.lineTo((r / 0.525731) * 0.200811, 0); } else { ctx.lineTo(r, 0); } } ctx.closePath(); ctx.fill(); ctx.restore(); } } })(); // 太阳系动画 (function () { var sun = new Image(); var moon = new Image(); var earth = new Image(); function init() { sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png'; moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png'; earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png'; window.requestAnimationFrame(draw); } function draw() { var ctx = document.getElementById('canvas31').getContext('2d'); ctx.globalCompositeOperation = 'destination-over'; ctx.clearRect(0, 0, 300, 300); // clear canvas ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.strokeStyle = 'rgba(0,153,255,0.4)'; ctx.save(); ctx.translate(150, 150); // Earth var time = new Date(); ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds()); ctx.translate(105, 0); ctx.fillRect(0, -12, 50, 24); // Shadow ctx.drawImage(earth, -12, -12); // Moon ctx.save(); ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * time.getMilliseconds()); ctx.translate(0, 28.5); ctx.drawImage(moon, -3.5, -3.5); ctx.restore(); ctx.restore(); ctx.beginPath(); ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit ctx.stroke(); ctx.drawImage(sun, 0, 0, 300, 300); window.requestAnimationFrame(draw); } init(); })(); // 动画时钟 (function () { function init() { window.requestAnimationFrame(clock); } function clock() { var now = new Date(); var ctx = document.getElementById('canvas32').getContext('2d'); ctx.save(); ctx.clearRect(0, 0, 150, 150); ctx.translate(75, 75); ctx.scale(0.4, 0.4); ctx.rotate(-Math.PI / 2); ctx.strokeStyle = "black"; ctx.fillStyle = "white"; ctx.lineWidth = 8; ctx.lineCap = "round"; // Hour marks ctx.save(); for (var i = 0; i < 12; i++) { ctx.beginPath(); ctx.rotate(Math.PI / 6); ctx.moveTo(100, 0); ctx.lineTo(120, 0); ctx.stroke(); } ctx.restore(); // Minute marks ctx.save(); ctx.lineWidth = 5; for (i = 0; i < 60; i++) { if (i % 5 != 0) { ctx.beginPath(); ctx.moveTo(117, 0); ctx.lineTo(120, 0); ctx.stroke(); } ctx.rotate(Math.PI / 30); } ctx.restore(); var sec = now.getSeconds(); var min = now.getMinutes(); var hr = now.getHours(); hr = hr >= 12 ? hr - 12 : hr; ctx.fillStyle = "black"; // write Hours ctx.save(); ctx.rotate(hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) * sec) ctx.lineWidth = 14; ctx.beginPath(); ctx.moveTo(-20, 0); ctx.lineTo(80, 0); ctx.stroke(); ctx.restore(); // write Minutes ctx.save(); ctx.rotate((Math.PI / 30) * min + (Math.PI / 1800) * sec) ctx.lineWidth = 10; ctx.beginPath(); ctx.moveTo(-28, 0); ctx.lineTo(112, 0); ctx.stroke(); ctx.restore(); // Write seconds ctx.save(); ctx.rotate(sec * Math.PI / 30); ctx.strokeStyle = "#D40000"; ctx.fillStyle = "#D40000"; ctx.lineWidth = 6; ctx.beginPath(); ctx.moveTo(-30, 0); ctx.lineTo(83, 0); ctx.stroke(); ctx.beginPath(); ctx.arc(0, 0, 10, 0, Math.PI * 2, true); ctx.fill(); ctx.beginPath(); ctx.arc(95, 0, 10, 0, Math.PI * 2, true); ctx.stroke(); ctx.fillStyle = "rgba(0,0,0,0)"; ctx.arc(0, 0, 3, 0, Math.PI * 2, true); ctx.fill(); ctx.restore(); ctx.beginPath(); ctx.lineWidth = 14; ctx.strokeStyle = '#325FA2'; ctx.arc(0, 0, 142, 0, Math.PI * 2, true); ctx.stroke(); ctx.restore(); window.requestAnimationFrame(clock); } init(); })(); // 循环全景照片 (function () { var img = new Image(); // User Variables - customize these to change the image being scrolled, its // direction, and the speed. img.src = 'https://mdn.mozillademos.org/files/4553/Capitan_Meadows,_Yosemite_National_Park.jpg'; var CanvasXSize = 800; var CanvasYSize = 200; var speed = 30; //lower is faster var scale = 1.05; var y = -4.5; //vertical offset // Main program var dx = 0.75; var imgW; var imgH; var x = 0; var clearX; var clearY; var ctx; img.onload = function () { imgW = img.width * scale; imgH = img.height * scale; if (imgW > CanvasXSize) { x = CanvasXSize - imgW; } // image larger than canvas if (imgW > CanvasXSize) { clearX = imgW; } // image larger than canvas else { clearX = CanvasXSize; } if (imgH > CanvasYSize) { clearY = imgH; } // image larger than canvas else { clearY = CanvasYSize; } //Get Canvas Element ctx = document.getElementById('canvas33').getContext('2d'); //Set Refresh Rate return setInterval(draw, speed); } function draw() { //Clear Canvas ctx.clearRect(0, 0, clearX, clearY); //If image is <= Canvas Size if (imgW <= CanvasXSize) { //reset, start from beginning if (x > (CanvasXSize)) { x = 0; } //draw aditional image if (x > (CanvasXSize - imgW)) { ctx.drawImage(img, x - CanvasXSize + 1, y, imgW, imgH); } } //If image is > Canvas Size else { //reset, start from beginning if (x > (CanvasXSize)) { x = CanvasXSize - imgW; } //draw aditional image if (x > (CanvasXSize - imgW)) { ctx.drawImage(img, x - imgW + 1, y, imgW, imgH); } } //draw image ctx.drawImage(img, x, y, imgW, imgH); //amount to move x += dx; } })(); // 颜色选择器 (function () { var img = new Image(); img.src = '/static/images/fk_1.png'; var canvas = document.getElementById('canvas34'); var ctx = canvas.getContext('2d'); img.onload = function () { ctx.drawImage(img, 0, 0); img.style.display = 'none'; }; var color = document.getElementById('color'); function pick(event) { var x = event.layerX; var y = event.layerY; var pixel = ctx.getImageData(x, y, 1, 1); var data = pixel.data; var rgba = 'rgba(' + data[0] + ',' + data[1] + ',' + data[2] + ',' + (data[3] / 255) + ')'; color.style.background = rgba; color.textContent = rgba; } canvas.addEventListener('mousemove', pick); })(); // 图片灰度和反相颜色 (function () { var img = new Image(); img.src = '/static/images/fk_1.png'; img.onload = function () { draw(this); }; function draw(img) { var canvas = document.getElementById('canvas35'); var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); img.style.display = 'none'; var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); var data = imageData.data; var invert = function () { for (var i = 0; i < data.length; i += 4) { data[i] = 255 - data[i]; // red data[i + 1] = 255 - data[i + 1]; // green data[i + 2] = 255 - data[i + 2]; // blue } ctx.putImageData(imageData, 0, 0); }; var grayscale = function () { for (var i = 0; i < data.length; i += 4) { var avg = (data[i] + data[i + 1] + data[i + 2]) / 3; data[i] = avg; // red data[i + 1] = avg; // green data[i + 2] = avg; // blue } ctx.putImageData(imageData, 0, 0); }; var invertbtn = document.getElementById('invertbtn'); invertbtn.addEventListener('click', invert); var grayscalebtn = document.getElementById('grayscalebtn'); grayscalebtn.addEventListener('click', grayscale); } })(); // 缩放和反锯齿 (function () { var img = new Image(); img.src = '/static/images/fk_1.png'; img.onload = function () { draw(this); }; function draw(img) { var canvas = document.getElementById('canvas36'); var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); img.style.display = 'none'; var zoomctx = document.getElementById('zoom').getContext('2d'); var smoothbtn = document.getElementById('smoothbtn'); var toggleSmoothing = function (event) { zoomctx.imageSmoothingEnabled = this.checked; zoomctx.mozImageSmoothingEnabled = this.checked; zoomctx.webkitImageSmoothingEnabled = this.checked; zoomctx.msImageSmoothingEnabled = this.checked; }; smoothbtn.addEventListener('change', toggleSmoothing); var zoom = function (event) { var x = event.layerX; var y = event.layerY; zoomctx.drawImage(canvas, Math.abs(x - 5), Math.abs(y - 5), 10, 10, 0, 0, 200, 200); }; canvas.addEventListener('mousemove', zoom); } })(); }
//// [templateStringInInstanceOfES6.ts] var x = `abc${ 0 }def` instanceof String; //// [templateStringInInstanceOfES6.js] var x = `abc${0}def` instanceof String;
'use strict'; const should = require('should'); const testHelper = require('./test-helper'); const { priceFinder, verifyPrice, verifyItemDetails } = testHelper; describe('price-finder for GameStop Store URIs', () => { // Video Games describe('testing a Video Game item', () => { // Mario Kart 8 const uri = 'https://www.gamestop.com/wii-u/games/mario-kart-8/113373'; it('should respond with a price for findItemPrice()', (done) => { priceFinder.findItemPrice(uri, (err, price) => { should(err).be.null(); verifyPrice(price); done(); }); }); it('should respond with a price, and the right category and name for findItemDetails()', (done) => { priceFinder.findItemDetails(uri, (err, itemDetails) => { should(err).be.null(); verifyItemDetails(itemDetails, 'Mario Kart 8', 'Video Games'); done(); }); }); }); });
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var abrev_model_1 = require("./abrev.model"); function createAbrev(req, res) { return __awaiter(this, void 0, void 0, function () { var abrev, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, abrev_model_1.default.create(req.body)]; case 1: abrev = _a.sent(); return [2 /*return*/, res.status(201).json(abrev)]; case 2: e_1 = _a.sent(); return [2 /*return*/, res.status(400).json(e_1)]; case 3: return [2 /*return*/]; } }); }); } exports.createAbrev = createAbrev; function getAbrevByIndex(req, res) { return __awaiter(this, void 0, void 0, function () { var abrev, e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, abrev_model_1.default.findOne({ abrev: req.params.index })]; case 1: abrev = _a.sent(); return [2 /*return*/, res.status(200).json(abrev.toIdJSON())]; case 2: e_2 = _a.sent(); return [2 /*return*/, res.status(400).json(e_2)]; case 3: return [2 /*return*/]; } }); }); } exports.getAbrevByIndex = getAbrevByIndex; function getAbrevList(req, res) { return __awaiter(this, void 0, void 0, function () { var abrev, e_3; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, abrev_model_1.default.find()]; case 1: abrev = _a.sent(); return [2 /*return*/, res.status(200).json(abrev.map(function (abr) { return abr.toIdJSON(); }))]; case 2: e_3 = _a.sent(); return [2 /*return*/, res.status(400).json(e_3)]; case 3: return [2 /*return*/]; } }); }); } exports.getAbrevList = getAbrevList; function updateAbrev(req, res) { return __awaiter(this, void 0, void 0, function () { var abrev_1, _a, _b, e_4; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 3, , 4]); return [4 /*yield*/, abrev_model_1.default.findOne({ abrev: req.params.index })]; case 1: abrev_1 = _c.sent(); if (!abrev_1) { return [2 /*return*/, res.sendStatus(404)]; } Object.keys(req.body).forEach(function (key) { abrev_1[key] = req.body[key]; }); _b = (_a = res.status(200)).json; return [4 /*yield*/, abrev_1.save()]; case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])]; case 3: e_4 = _c.sent(); return [2 /*return*/, res.status(400).json(e_4)]; case 4: return [2 /*return*/]; } }); }); } exports.updateAbrev = updateAbrev; function deleteAbrev(req, res) { return __awaiter(this, void 0, void 0, function () { var abrev, e_5; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, , 4]); return [4 /*yield*/, abrev_model_1.default.findOne({ abrev: req.params.index })]; case 1: abrev = _a.sent(); if (!abrev) { res.sendStatus(404); } return [4 /*yield*/, abrev.remove()]; case 2: _a.sent(); return [2 /*return*/, res.sendStatus(200)]; case 3: e_5 = _a.sent(); return [2 /*return*/, res.status(400).json(e_5)]; case 4: return [2 /*return*/]; } }); }); } exports.deleteAbrev = deleteAbrev;
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, find, click, fillIn, blur } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; const TEMPLATE = hbs` <EditableLabel @value={{this.value}} @onChange={{this.onChange}} />`; module('Integration | Component | Editable Label', function(hooks) { setupRenderingTest(hooks); test('edit label triggers action', async function(assert) { assert.expect(3); this.set('value', 'Default Value'); this.set('onChange', value => { assert.equal(value, 'Edited Value', '`onChange` action sent an updated value'); }); await render(TEMPLATE); await click('.editable-label__icon'); assert.dom('.editable-label__input').hasValue('Default Value', 'Label contains the default value'); await fillIn('.editable-label__input', 'Edited Value'); await blur('.editable-label__input'); assert.equal(this.value, 'Default Value', 'Editing the label does not mutate the provided `value` attribute'); }); test('no change in value', async function(assert) { assert.expect(1); this.set('value', 'Default Value'); this.set('onChange', () => { assert.notOk(true, '`onChange` is not invoked if `value` is not updated'); }); await render(TEMPLATE); await click('.editable-label__icon'); await blur('.editable-label__input'); assert.equal( this.get('value'), 'Default Value', 'Editing the label does not mutate the provided `value` attribute' ); }); test('_inputSize', async function(assert) { assert.expect(3); this.set('value', ''); this.set('onChange', () => {}); await render(TEMPLATE); await click('.editable-label__icon'); assert.dom('.editable-label__input').hasAttribute('size', '1', 'Size of the input is greater or equal to 1'); await fillIn('.editable-label__input', 'Default Value'); assert .dom('.editable-label__input') .hasAttribute( 'size', String(find('.editable-label__input').value.length + 1), 'Size of the input is the string length plus 1' ); let longValue = Array(100) .fill(1) .join(''); await fillIn('.editable-label__input', longValue); assert.dom('.editable-label__input').hasAttribute('size', '50', 'Size of the input is less than or equal to 50'); }); test('value is reset when editing', async function(assert) { assert.expect(3); this.set('value', 'Initial value'); this.set('onChange', () => {}); await render(TEMPLATE); await click('.editable-label__icon'); assert .dom('.editable-label__input') .hasValue('Initial value', 'Input starts with text equal to given value property'); await fillIn('.editable-label__input', 'Something else'); assert.dom('.editable-label__input').hasValue('Something else', 'Input text changes with user input'); await blur('.editable-label__input'); await click('.editable-label__icon'); assert .dom('.editable-label__input') .hasValue('Initial value', 'When focusing in and out, input text is reset to given value property'); }); });
import mongoose from 'mongoose'; const mongoConnect = async () => { try { await mongoose.connect( 'mongodb+srv://guest:guest1234@repositoriescluster.m2ul7.mongodb.net/repositoriesdb?retryWrites=true&w=majority' ); console.log("Conexão com o MongoDB estabelecida"); } catch (err) { console.log("Erro ao conectar no MongoDB", err); } }; export default mongoConnect;
/***************************************************************************** * Open MCT, Copyright (c) 2014-2017, United States Government * as represented by the Administrator of the National Aeronautics and Space * Administration. All rights reserved. * * Open MCT is licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * Open MCT includes source code licensed under additional open source * licenses. See the Open Source Licenses file (LICENSES.md) included with * this source code distribution or the Licensing information page available * at runtime from the About dialog for additional information. *****************************************************************************/ define( ['../../src/directives/MCTScroll'], function (MCTScroll) { var EVENT_PROPERTY = "testProperty", ATTRIBUTE = "testAttribute", EXPRESSION = "some.expression"; // MCTScroll is the commonality between mct-scroll-x and // mct-scroll-y; it gets the event property to watch and // the attribute which contains the associated assignable // expression. describe("An mct-scroll-* directive", function () { var mockParse, mockParsed, mockScope, mockElement, testAttrs, mctScroll; beforeEach(function () { mockParse = jasmine.createSpy('$parse'); mockParsed = jasmine.createSpy('parsed'); mockParsed.assign = jasmine.createSpy('assign'); mockScope = jasmine.createSpyObj('$scope', ['$watch', '$apply']); mockElement = [{ testProperty: 42 }]; mockElement.on = jasmine.createSpy('on'); mockParse.andReturn(mockParsed); testAttrs = {}; testAttrs[ATTRIBUTE] = EXPRESSION; mctScroll = new MCTScroll( mockParse, EVENT_PROPERTY, ATTRIBUTE ); mctScroll.link(mockScope, mockElement, testAttrs); }); it("is available for attributes", function () { expect(mctScroll.restrict).toEqual('A'); }); it("does not create an isolate scope", function () { expect(mctScroll.scope).toBeUndefined(); }); it("watches for changes in observed expression", function () { expect(mockScope.$watch).toHaveBeenCalledWith( EXPRESSION, jasmine.any(Function) ); // Should have been only watch (other tests need this to be true) expect(mockScope.$watch.calls.length).toEqual(1); }); it("listens for scroll events", function () { expect(mockElement.on).toHaveBeenCalledWith( 'scroll', jasmine.any(Function) ); // Should have been only listener (other tests need this to be true) expect(mockElement.on.calls.length).toEqual(1); }); it("publishes initial scroll state", function () { expect(mockParse).toHaveBeenCalledWith(EXPRESSION); expect(mockParsed.assign).toHaveBeenCalledWith(mockScope, 42); }); it("updates scroll state when scope changes", function () { mockScope.$watch.mostRecentCall.args[1](64); expect(mockElement[0].testProperty).toEqual(64); }); it("updates scope when scroll state changes", function () { mockElement[0].testProperty = 12321; mockElement.on.mostRecentCall.args[1]({ target: mockElement[0] }); expect(mockParsed.assign).toHaveBeenCalledWith(mockScope, 12321); expect(mockScope.$apply).toHaveBeenCalledWith(EXPRESSION); }); // This would trigger an infinite digest exception it("does not call $apply during construction", function () { expect(mockScope.$apply).not.toHaveBeenCalled(); }); }); } );
import React from 'react' import PropTypes from 'prop-types' import RssIcon from './icons/rss-icon' const SocialRss = ({ url }) => ( <a className="rss-button" href={ `https://feedly.com/i/subscription/feed/${url}/rss` } target="_blank" rel="noopener noreferrer" title="Rss"><RssIcon /></a> ) SocialRss.propTypes = { url: PropTypes.string.isRequired, } export default SocialRss
exports.newEnvironment = function () { let thisObject = { WEB_SERVER_URL: 'localhost', WEB_SOCKETS_INTERFACE_PORT: 18041, HTTP_INTERFACE_PORT: 34248, PATH_TO_TASK_SERVER: './TaskServer', PATH_TO_DATA_STORAGE: './Data-Storage', PATH_TO_PROJECTS: './Projects', PATH_TO_LOG_FILES: './Log-Files', PATH_TO_PROJECTS_REQUIRED: '../Projects', PATH_TO_UI: './UI', PATH_TO_DATA_FILES: './UI/Data-Files/src', PATH_TO_CLIENT: './Client/', PATH_TO_DEFAULT_WORKSPACE: './Projects/Superalgos/Plugins/Workspaces', PATH_TO_MY_WORKSPACES: './My-Workspaces', PATH_TO_FONTS: './Client/WebServer/Fonts' } return thisObject }
const url = require('url'); exports.address = function address(app, pathname, spec = {}) { const { pkg, env, version = '' } = spec; const { address, port } = app.servers.http.address(); if (pkg && env) { pathname = `${pathname}/${pkg}/${env}/${version}`; } const uri = url.format({ protocol: 'http', hostname: address, port, pathname }); return { uri, json: true }; };
const { MessageEmbed } = require("discord.js"); const { stripIndents } = require("common-tags"); module.exports = { name: "report", category: "moderation", description: "Reports a member", usage: "<mention | id> <reason>", run: async (client, message, args, ops) => { if ( message.deletable ) message.delete(); let rMember = message.mentions.members.first() || message.guild.members.get(args[0]); let rAuthor = message.guild.members.cache.get(message.author.id); //find member if ( !rMember ) return message.reply("Couldn't find that member!"); //check if author has permission and if the member is a bot if ( !rAuthor.hasPermission("BAN_MEMBERS") || rMember.user.bot ) return message.reply("Can't report that member!"); //check reason if ( !args[1] ) return message.channel.send("Please provide a reason for the report!"); const channel = message.guild.channels.cache.find(channel => channel.name === "reports"); //check if text channel #reports exist if ( !channel ) return message.channel.send("Couldn't find a \`#reports\` channel!"); const embed = new MessageEmbed() .setColor("$ff0000") .setTimestamp() .setFooter(message.guild.name, message.guild.iconURL) .setAuthor("Reported member: ", rMember.user.displayAvatarURL) .setDescription(stripIndents` **Member:** ${rMember} (${rMember.id}) **Reported by:** ${message.member} (${message.member.id}) **Reported in:** ${message.channel} **Reason:** ${args.slice(1).join(" ")}`); return channel.send(embed); } }
import { example, suite } from 'washington' import Color from '../src/Color' export default suite( 'fromOf', example( 'test red', () => Color.of(250, 167, 23, 0.8).red, 250, ), example( 'test green', () => Color.of(250, 167, 23, 0.8).green, 167, ), example( 'test blue', () => Color.of(250, 167, 23, 0.8).blue, 23, ), example( 'test alpha', () => Color.of(250, 167, 23, 0.8).alpha, 0.8, ), )
window.rootPath = (function(src) { src = document.scripts[document.scripts.length - 1].src; return src.substring(0, src.lastIndexOf("/") + 1); })(); layui.config({ base: rootPath + "module/", version: true }).extend({ admin: "admin", menu: "menu", frame: "frame", tab: "tab", echarts: "echarts", echartsTheme: "echartsTheme", hash: "hash", document: "document", select: "select", drawer: "drawer", notice: "notice", step:"step", tag:"tag", popup:"popup", iconPicker:"iconPicker", treetable:"treetable", dtree:"dtree", tinymce:"tinymce/tinymce", area:"area", count:"count", topBar: "topBar", button: "button", design: "design", common: "common", eleTree: "eleTree", dictionary: 'dictionary', json: 'json' });
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var net = require('net'); var setTimeout = require('timers').setTimeout; var allocCluster = require('./lib/alloc-cluster'); var RelayHandler = require('../relay_handler'); allocCluster.test('relaying to init timeout server', { numPeers: 2 }, function t(cluster, assert) { var deadServer = net.createServer(); deadServer.listen(0, '127.0.0.1', onListen); function onListen() { var deadPort = deadServer.address().port; var deadHostPort = '127.0.0.1:' + deadPort; var client = cluster.channels[0]; var relay = cluster.channels[1]; relay.initTimeout = 250; var relayChan = relay.makeSubChannel({ serviceName: 'dead-service', peers: [deadHostPort], initTimeout: 250 }); relayChan.handler = new RelayHandler(relayChan); var clientChan = client.makeSubChannel({ serviceName: 'dead-service', peers: [relay.hostPort], requestDefaults: { serviceName: 'dead-service', headers: { as: 'raw', cn: 'client' } } }); clientChan.request({ hasNoParent: true, timeout: 50 }).send('echo', '', '', onResponse); function onResponse(err) { // should expect in timeout assert.ok(err); // console.log('err', err); assert.ok(err.type === 'tchannel.request.timeout' || err.type === 'tchannel.timeout' ); assert.equal(cluster.logger.items().length, 0); cluster.logger.whitelist('warn', 'destroying due to init timeout'); cluster.logger.whitelist('warn', 'resetting connection'); cluster.logger.whitelist('warn', 'Got a connection error'); setTimeout(function onTimeout() { var logs = cluster.logger.items(); assert.equal(logs.length, 3, 'expected 3 logs'); var record1 = logs[0]; var record2 = logs[1]; var record3 = logs[2]; assert.equal(record1.msg, 'destroying due to init timeout'); assert.equal(record2.msg, 'resetting connection'); assert.equal(record3.msg, 'Got a connection error'); deadServer.close(); assert.end(); }, 350); } } });
const bytes = require('utf8-length'); const fs = require('fs'); const { sha3_256 } = require('js-sha3'); const Command = require('../command'); const Encryption = require('../../Encryption'); const Utilities = require('../../Utilities'); const Models = require('../../../models/index'); const ImportUtilities = require('../../ImportUtilities'); /** * Imports data for replication */ class DhReplicationImportCommand extends Command { constructor(ctx) { super(ctx); this.config = ctx.config; this.importService = ctx.importService; this.web3 = ctx.web3; this.graphStorage = ctx.graphStorage; this.logger = ctx.logger; this.transport = ctx.transport; this.remoteControl = ctx.remoteControl; this.blockchain = ctx.blockchain; this.challengeService = ctx.challengeService; } /** * Executes command and produces one or more events * @param command */ async execute(command) { const { offerId, dataSetId, documentPath, dcWallet, dcNodeId, litigationPublicKey, litigationRootHash, distributionPublicKey, distributionPrivateKey, distributionEpk, transactionHash, encColor, } = command.data; const otJson = JSON.parse(fs.readFileSync(documentPath, { encoding: 'utf-8' })); const { decryptedDataset, encryptedMap } = await ImportUtilities.decryptDataset(otJson, litigationPublicKey, offerId, encColor); const calculatedDataSetId = await ImportUtilities.calculateGraphHash(decryptedDataset['@graph']); if (dataSetId !== calculatedDataSetId) { throw new Error(`Calculated data set ID ${calculatedDataSetId} differs from DC data set ID ${dataSetId}`); } const decryptedGraphRootHash = ImportUtilities.calculateDatasetRootHash(decryptedDataset['@graph'], decryptedDataset['@id'], decryptedDataset.datasetHeader.dataCreator); const blockchainRootHash = await this.blockchain.getRootHash(dataSetId); if (decryptedGraphRootHash !== blockchainRootHash) { throw Error(`Calculated root hash ${decryptedGraphRootHash} differs from Blockchain root hash ${blockchainRootHash}`); } // Verify litigation root hash const encryptedGraphRootHash = this.challengeService.getLitigationRootHash(otJson['@graph']); if (encryptedGraphRootHash !== litigationRootHash) { throw Error(`Calculated distribution hash ${encryptedGraphRootHash} differs from DC distribution hash ${litigationRootHash}`); } const originalRootHash = otJson.datasetHeader.dataIntegrity.proofs[0].proofValue; if (decryptedGraphRootHash !== originalRootHash) { throw Error(`Calculated root hash ${decryptedGraphRootHash} differs from document root hash ${originalRootHash}`); } // TODO: Verify EPK checksum // TODO: Verify distribution keys and hashes // TODO: Verify data creator id const holdingData = await Models.holding_data.findOne({ where: { offer_id: offerId, data_set_id: dataSetId, color: encColor, source_wallet: dcWallet, }, }); if (holdingData == null) { // Store holding information and generate keys for eventual data replication. const newHoldingEntry = { data_set_id: dataSetId, source_wallet: dcWallet, litigation_public_key: litigationPublicKey, litigation_root_hash: litigationRootHash, distribution_public_key: distributionPublicKey, distribution_private_key: distributionPrivateKey, distribution_epk: distributionEpk, transaction_hash: transactionHash, color: encColor, offer_id: offerId, }; await Models.holding_data.create(newHoldingEntry); } const dataInfo = await Models.data_info.findOne({ where: { data_set_id: dataSetId, }, }); const importResult = await this.importService.importFile({ document: decryptedDataset, encryptedMap, }); fs.unlinkSync(documentPath); if (importResult.error) { throw Error(importResult.error); } if (dataInfo == null) { const dataSize = bytes(JSON.stringify(decryptedDataset)); const dataHash = Utilities.normalizeHex(sha3_256(`${otJson}`)); await Models.data_info.create({ data_set_id: dataSetId, total_documents: decryptedDataset['@graph'].length, root_hash: decryptedGraphRootHash, // TODO: add field data_provider_id: 'Perutnina Ptuj ERC...' // otjson.datasetHeader.dataProvider || 'Unknown' // TODO: add field data_provider_id_type: 'ERC725' || 'Unknown' // TODO: add field data_creator_id: otjson.datasetHeader.dataCreator // TODO: add field data_creator_id_type: 'ERC725' || 'Unknown' data_provider_wallet: dcWallet, // TODO: rename to data_creator_wallet import_timestamp: new Date(), otjson_size_in_bytes: dataSize, data_hash: dataHash, origin: 'HOLDING', }); } this.logger.important(`[DH] Replication finished for offer ID ${offerId}`); const toSign = [ Utilities.denormalizeHex(offerId), Utilities.denormalizeHex(this.config.erc725Identity)]; const messageSignature = Encryption .signMessage(this.web3, toSign, Utilities.normalizeHex(this.config.node_private_key)); const replicationFinishedMessage = { offerId, dhIdentity: this.config.erc725Identity, messageSignature: messageSignature.signature, }; await this.transport.replicationFinished(replicationFinishedMessage, dcNodeId); this.logger.info(`Replication request for ${offerId} sent to ${dcNodeId}`); return { commands: [ { name: 'dhOfferFinalizedCommand', deadline_at: Date.now() + (60 * 60 * 1000), // One hour. period: 10 * 1000, data: { offerId, }, }, ], }; } /** * Try to recover command * @param command * @param err * @return {Promise<{commands: *[]}>} */ async recover(command, err) { const { offerId, } = command.data; const bid = await Models.bids.findOne({ where: { offer_id: offerId } }); bid.status = 'FAILED'; await bid.save({ fields: ['status'] }); return Command.empty(); } /** * Builds default * @param map * @returns {{add, data: *, delay: *, deadline: *}} */ default(map) { const command = { name: 'dhReplicationImportCommand', delay: 0, transactional: false, }; Object.assign(command, map); return command; } } module.exports = DhReplicationImportCommand;
const chai = require('chai'); const sonicxwebBuilder = require('../helpers/sonicxwebBuilder'); const assert = chai.assert; describe('SonicxWeb.utils.code', function () { describe('#bin2String()', function () { it("should convert a byte to a hex string", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.equal(tronWeb.utils.code.bin2String([78, 112, 87, 69, 99, 65]), 'NpWEcA'); }); }); describe('#arrayEquals()', function () { it("should compare two arrays to see if they are equal", async function () { const tronWeb = sonicxwebBuilder.createInstance(); const a = [78, 112, 87, 69, 99, 65]; const b = [78, 112, 69, 99, 65]; const c = [78, 112, 69, 99, 65]; const d = [78, 'casa', {a: 1}, 99, [65, 2]]; const e = [78, 'casa', {a: 1}, 99, [65, 2]]; assert.isTrue(tronWeb.utils.code.arrayEquals(a, a)); assert.isTrue(tronWeb.utils.code.arrayEquals(b, c)); assert.isTrue(tronWeb.utils.code.arrayEquals(d, e)); assert.isFalse(tronWeb.utils.code.arrayEquals(a, b)); assert.isFalse(tronWeb.utils.code.arrayEquals(d, e, true)); }); }); describe('#stringToBytes()', function () { it("should convert a string to an array of bytes", async function () { const tronWeb = sonicxwebBuilder.createInstance(); const a = 'Қࡀпω'; assert.isTrue(tronWeb.utils.code.arrayEquals(tronWeb.utils.code.stringToBytes('Қࡀпω'), [210, 154, 224, 161, 128, 208, 191, 207, 137], true)); // TODO We have something wrong, in fact this should be the reverse of the command above: assert.equal(tronWeb.utils.bytes.bytesToString([1178, 2112, 1087, 969]), 'Қࡀпω'); }); it("should throw if something else than a string is passed as input", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.throws(() => { tronWeb.utils.code.stringToBytes([210, 154, 224, 161, 128, 208, 191, 207, 137]) }, 'The passed string is not a string'); assert.throws(() => { tronWeb.utils.code.stringToBytes(356253) }, 'The passed string is not a string'); }); }); describe('#hexChar2byte()', function () { it("should convert an hex char to a byte", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.equal(tronWeb.utils.code.hexChar2byte('0'), 0); assert.equal(tronWeb.utils.code.hexChar2byte('D'), 13); assert.equal(tronWeb.utils.code.hexChar2byte('d'), 13); assert.equal(tronWeb.utils.code.hexChar2byte('7'), 7); }); it("should throw if something else than a string is passed as input", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.throws(() => { tronWeb.utils.code.hexChar2byte(12) }, 'The passed hex char is not a valid hex char'); assert.throws(() => { tronWeb.utils.code.hexChar2byte('Z') }, 'The passed hex char is not a valid hex char'); }); }); describe('#isHexChar()', function () { it("should verify that an hex char is a valid hex char", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.equal(tronWeb.utils.code.isHexChar('0'), 1); assert.equal(tronWeb.utils.code.isHexChar('e'), 1); assert.equal(tronWeb.utils.code.isHexChar('D'), 1); assert.equal(tronWeb.utils.code.isHexChar('Z'), 0); assert.equal(tronWeb.utils.code.isHexChar(66), 0); }); }); describe('#hexStr2byteArray()', function () { it("should verify that an hex char is a valid hex char", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.isTrue(tronWeb.utils.code.arrayEquals(tronWeb.utils.code.hexStr2byteArray('49206C6F7665206461726B20636F6D6564696573'), [73, 32, 108, 111, 118, 101, 32, 100, 97, 114, 107, 32, 99, 111, 109, 101, 100, 105, 101, 115])); }); it("should throw if we pass an invalid hex string", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.throws(() => { tronWeb.utils.code.hexStr2byteArray('ZASSyue') }, 'The passed hex char is not a valid hex string'); assert.throws(() => { tronWeb.utils.code.hexStr2byteArray(123) }, 'The passed string is not a string'); }); }); describe('#strToDate()', function () { it("should verify that an hex char is a valid hex char", async function () { const tronWeb = sonicxwebBuilder.createInstance(); let input = '2018-09-23 13-45-03'; let regex = RegExp('Sep 23 2018 13:45:03') assert.isTrue(regex.test(tronWeb.utils.code.strToDate(input).toString())); input = '2018-09-23'; regex = RegExp('Sep 23 2018 00:00:00') assert.isTrue(regex.test(tronWeb.utils.code.strToDate(input).toString())); }); it("should throw if we pass an invalid hex string", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.throws(() => { tronWeb.utils.code.strToDate('2018-02-') }, 'The passed date string is not valid'); assert.throws(() => { tronWeb.utils.code.strToDate(123) }, 'The passed date string is not valid'); assert.throws(() => { tronWeb.utils.code.strToDate('2018-0212') }, 'The passed date string is not valid'); assert.throws(() => { tronWeb.utils.code.strToDate('90-22-21') }, 'The passed date string is not valid'); }); }); describe('#isNumber()', function () { it("should verify that an numeric char is a number", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.equal(tronWeb.utils.code.isNumber('0'), 1); assert.equal(tronWeb.utils.code.isHexChar('Z'), 0); }); }); describe('#getStringType()', function () { it("should return the type of a string", async function () { const tronWeb = sonicxwebBuilder.createInstance(); assert.equal(tronWeb.utils.code.getStringType('bf7e69851988c80e5484e52f4f6aca99479458b6'), 1); // TODO Should the next test return 1? assert.equal(tronWeb.utils.code.getStringType('4136b9c3690c3be15a4ad697965b1e5e088ae131f2'), 3); assert.equal(tronWeb.utils.code.getStringType('3534'), 2); assert.equal(tronWeb.utils.code.getStringType('ERC20Token'), 3); assert.equal(tronWeb.utils.code.getStringType(3.45), -1); }); }); });
const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const { TOKEN_SECRET, COOKIE_NAME } = require('../config/index'); const userService = require('../services/user'); module.exports = () => (req, res, next) => { if (parseToken(req, res)) { req.auth = { async register(username, password) { const token = await register(username, password); res.cookie(COOKIE_NAME, token); }, async login(username, password) { const token = await login(username, password); res.cookie(COOKIE_NAME, token); }, logout() { res.clearCookie(COOKIE_NAME); } }; next(); } } async function register(username, password) { const existing = await userService.getUserByUsername(username); if (existing) { throw new Error('Username is taken'); } const hashedPassword = await bcrypt.hash(password, 10); const user = await userService.createUser(username, hashedPassword); return generateToken(user); } async function login(username, password) { const user = await userService.getUserByUsername(username); if (!user) { const err = new Error('No such user'); err.type = 'credential'; throw err; } const hashMatched = await bcrypt.compare(password, user.hashedPassword); if (!hashMatched) { const err = new Error('Incorrect password'); err.type = 'credential'; throw err; } return generateToken(user); } function generateToken(userData) { return jwt.sign({ _id: userData._id, username: userData.username }, TOKEN_SECRET); } function parseToken(req, res) { const token = req.cookies[COOKIE_NAME]; if(token){ try { const userData = jwt.verify(token, TOKEN_SECRET); req.user = userData; res.locals.user = userData; } catch (err) { res.clearCookie(COOKIE_NAME); res.redirect('/auth/login'); return false; } } return true; }
const fetch = require('node-fetch') const base64 = require('base-64') const Action = require('./Action') class HomeAssistantAction extends Action { process() { this.request(this.payload()) } payload() { const envVars = this.envVars() const payload = {} Object.keys(envVars).forEach(key => { if (key.includes('HOMEASSISTANT')) { return } payload[key.toLowerCase()] = envVars[key] }) return payload } async request(payload) { const protocol = this.config.ssl ? 'https://' : 'http://' const baseURL = `${protocol}${this.config.host}:${ this.config.port }/api/events/magic_card_scanned` let headers = {'Content-Type': 'application/json'} if (this.config.token) { headers['Authorization'] = `Bearer ${this.config.token}` } else if (this.config.password) { headers['x-ha-access'] = this.config.password } return fetch(baseURL, { method: 'POST', headers: headers, body: JSON.stringify(payload), }) .then(res => res.text()) .then(body => console.log(body)) .catch(error => console.log(error)) } } module.exports = HomeAssistantAction
import moment from 'moment'; import selectExpenses from '../../selectors/expenses'; import expenses from '../fixtures/expenses'; test('should filter by text value', () => { const filters = { text: 'e', sortBy: 'date', startDate: undefined, endDate: undefined }; const result = selectExpenses(expenses, filters); expect(result).toEqual([ expenses[2], expenses[1] ]); }); test('should filter by startDate', () => { const filters = { text: '', sortBy: 'date', startDate: moment(0), endDate: undefined }; const result = selectExpenses(expenses, filters); expect(result).toEqual([ expenses[2], expenses[0] ]); }); test('should filter by endDate', () => { const filters = { text: '', sortBy: 'date', startDate: undefined, endDate: moment(0).add(1, 'days') }; const result = selectExpenses(expenses, filters); expect(result).toEqual([ expenses[0], expenses[1] ]); }); test('should sort by date', () => { const filters = { text: '', sortBy: 'date', startDate: undefined, endDate: undefined }; const result = selectExpenses(expenses, filters); expect(result).toEqual([ expenses[2], expenses[0], expenses[1] ]); }); test('should sort by amount', () => { const filters = { text: '', sortBy: 'amount', startDate: undefined, endDate: undefined }; const result = selectExpenses(expenses, filters); expect(result).toEqual([ expenses[1], expenses[2], expenses[0] ]); });
var searchData= [ ['vmaallocatememory_0',['vmaAllocateMemory',['../vk__mem__alloc_8h.html#abf28077dbf82d0908b8acbe8ee8dd9b8',1,'vk_mem_alloc.h']]], ['vmaallocatememoryforbuffer_1',['vmaAllocateMemoryForBuffer',['../vk__mem__alloc_8h.html#a7fdf64415b6c3d83c454f28d2c53df7b',1,'vk_mem_alloc.h']]], ['vmaallocatememoryforimage_2',['vmaAllocateMemoryForImage',['../vk__mem__alloc_8h.html#a0faa3f9e5fb233d29d1e00390650febb',1,'vk_mem_alloc.h']]], ['vmaallocatememorypages_3',['vmaAllocateMemoryPages',['../vk__mem__alloc_8h.html#ad37e82e492b3de38fc3f4cffd9ad0ae1',1,'vk_mem_alloc.h']]], ['vmabegindefragmentationpass_4',['vmaBeginDefragmentationPass',['../vk__mem__alloc_8h.html#ac0f01545b6262f7d4d128fc8f8e5c77b',1,'vk_mem_alloc.h']]], ['vmabindbuffermemory_5',['vmaBindBufferMemory',['../vk__mem__alloc_8h.html#a6b0929b914b60cf2d45cac4bf3547470',1,'vk_mem_alloc.h']]], ['vmabindbuffermemory2_6',['vmaBindBufferMemory2',['../vk__mem__alloc_8h.html#a927c944f45e0f2941182abb6f608e64a',1,'vk_mem_alloc.h']]], ['vmabindimagememory_7',['vmaBindImageMemory',['../vk__mem__alloc_8h.html#a3d3ca45799923aa5d138e9e5f9eb2da5',1,'vk_mem_alloc.h']]], ['vmabindimagememory2_8',['vmaBindImageMemory2',['../vk__mem__alloc_8h.html#aa8251ee81b0045a443e35b8e8aa021bc',1,'vk_mem_alloc.h']]], ['vmabuildstatsstring_9',['vmaBuildStatsString',['../vk__mem__alloc_8h.html#aa4fee7eb5253377599ef4fd38c93c2a0',1,'vk_mem_alloc.h']]], ['vmabuildvirtualblockstatsstring_10',['vmaBuildVirtualBlockStatsString',['../vk__mem__alloc_8h.html#a52d810e1222c592e5d80556ad005f1e6',1,'vk_mem_alloc.h']]], ['vmacalculatestats_11',['vmaCalculateStats',['../vk__mem__alloc_8h.html#a333b61c1788cb23559177531e6a93ca3',1,'vk_mem_alloc.h']]], ['vmacalculatevirtualblockstats_12',['vmaCalculateVirtualBlockStats',['../vk__mem__alloc_8h.html#a95169b4730e94757897470086ec2768a',1,'vk_mem_alloc.h']]], ['vmacheckcorruption_13',['vmaCheckCorruption',['../vk__mem__alloc_8h.html#a49329a7f030dafcf82f7b73334c22e98',1,'vk_mem_alloc.h']]], ['vmacheckpoolcorruption_14',['vmaCheckPoolCorruption',['../vk__mem__alloc_8h.html#ad535935619c7a549bf837e1bb0068f89',1,'vk_mem_alloc.h']]], ['vmaclearvirtualblock_15',['vmaClearVirtualBlock',['../vk__mem__alloc_8h.html#a5eda6f55919fb05bd2f56a112590c571',1,'vk_mem_alloc.h']]], ['vmacreateallocator_16',['vmaCreateAllocator',['../vk__mem__alloc_8h.html#a200692051ddb34240248234f5f4c17bb',1,'vk_mem_alloc.h']]], ['vmacreatebuffer_17',['vmaCreateBuffer',['../vk__mem__alloc_8h.html#ac72ee55598617e8eecca384e746bab51',1,'vk_mem_alloc.h']]], ['vmacreatebufferwithalignment_18',['vmaCreateBufferWithAlignment',['../vk__mem__alloc_8h.html#aa06a690013a0d01e60894ac378083834',1,'vk_mem_alloc.h']]], ['vmacreateimage_19',['vmaCreateImage',['../vk__mem__alloc_8h.html#a02a94f25679275851a53e82eacbcfc73',1,'vk_mem_alloc.h']]], ['vmacreatelostallocation_20',['vmaCreateLostAllocation',['../vk__mem__alloc_8h.html#ae5c9657d9e94756269145b01c05d16f1',1,'vk_mem_alloc.h']]], ['vmacreatepool_21',['vmaCreatePool',['../vk__mem__alloc_8h.html#a5c8770ded7c59c8caac6de0c2cb00b50',1,'vk_mem_alloc.h']]], ['vmacreatevirtualblock_22',['vmaCreateVirtualBlock',['../vk__mem__alloc_8h.html#ab585754076877265fdae33e5c40ef13b',1,'vk_mem_alloc.h']]], ['vmadefragment_23',['vmaDefragment',['../vk__mem__alloc_8h.html#a9f0f8f56db5f7f57fe4454f465142dac',1,'vk_mem_alloc.h']]], ['vmadefragmentationbegin_24',['vmaDefragmentationBegin',['../vk__mem__alloc_8h.html#a36ba776fd7fd5cb1e9359fdc0d8e6e8a',1,'vk_mem_alloc.h']]], ['vmadefragmentationend_25',['vmaDefragmentationEnd',['../vk__mem__alloc_8h.html#a8774e20e91e245aae959ba63efa15dd2',1,'vk_mem_alloc.h']]], ['vmadestroyallocator_26',['vmaDestroyAllocator',['../vk__mem__alloc_8h.html#aa8d164061c88f22fb1fd3c8f3534bc1d',1,'vk_mem_alloc.h']]], ['vmadestroybuffer_27',['vmaDestroyBuffer',['../vk__mem__alloc_8h.html#a0d9f4e4ba5bf9aab1f1c746387753d77',1,'vk_mem_alloc.h']]], ['vmadestroyimage_28',['vmaDestroyImage',['../vk__mem__alloc_8h.html#ae50d2cb3b4a3bfd4dd40987234e50e7e',1,'vk_mem_alloc.h']]], ['vmadestroypool_29',['vmaDestroyPool',['../vk__mem__alloc_8h.html#a5485779c8f1948238fc4e92232fa65e1',1,'vk_mem_alloc.h']]], ['vmadestroyvirtualblock_30',['vmaDestroyVirtualBlock',['../vk__mem__alloc_8h.html#a3795f7783ae2c182cede067d656f66a5',1,'vk_mem_alloc.h']]], ['vmaenddefragmentationpass_31',['vmaEndDefragmentationPass',['../vk__mem__alloc_8h.html#a1b9ffa538bed905af55c747cc48963bd',1,'vk_mem_alloc.h']]], ['vmafindmemorytypeindex_32',['vmaFindMemoryTypeIndex',['../vk__mem__alloc_8h.html#aef15a94b58fbcb0fe706d5720e84a74a',1,'vk_mem_alloc.h']]], ['vmafindmemorytypeindexforbufferinfo_33',['vmaFindMemoryTypeIndexForBufferInfo',['../vk__mem__alloc_8h.html#ae790ab9ffaf7667fb8f62523e6897888',1,'vk_mem_alloc.h']]], ['vmafindmemorytypeindexforimageinfo_34',['vmaFindMemoryTypeIndexForImageInfo',['../vk__mem__alloc_8h.html#a088da83d8eaf3ce9056d9ea0b981d472',1,'vk_mem_alloc.h']]], ['vmaflushallocation_35',['vmaFlushAllocation',['../vk__mem__alloc_8h.html#a30c37c1eec6025f397be41644f48490f',1,'vk_mem_alloc.h']]], ['vmaflushallocations_36',['vmaFlushAllocations',['../vk__mem__alloc_8h.html#ac3dd00da721875ed99fa8a881922bdfc',1,'vk_mem_alloc.h']]], ['vmafreememory_37',['vmaFreeMemory',['../vk__mem__alloc_8h.html#a5fea5518972ae9094b1526cbcb19b05f',1,'vk_mem_alloc.h']]], ['vmafreememorypages_38',['vmaFreeMemoryPages',['../vk__mem__alloc_8h.html#a834b1e4aef395c0a1d56a28e69a4a17e',1,'vk_mem_alloc.h']]], ['vmafreestatsstring_39',['vmaFreeStatsString',['../vk__mem__alloc_8h.html#a3104eb30d8122c84dd8541063f145288',1,'vk_mem_alloc.h']]], ['vmafreevirtualblockstatsstring_40',['vmaFreeVirtualBlockStatsString',['../vk__mem__alloc_8h.html#a47fb8d8aa69df4a7c23a9719b4080623',1,'vk_mem_alloc.h']]], ['vmagetallocationinfo_41',['vmaGetAllocationInfo',['../vk__mem__alloc_8h.html#a86dd08aba8633bfa4ad0df2e76481d8b',1,'vk_mem_alloc.h']]], ['vmagetallocationmemoryproperties_42',['vmaGetAllocationMemoryProperties',['../vk__mem__alloc_8h.html#a571e87dd38e552249b56b1b0b982fad1',1,'vk_mem_alloc.h']]], ['vmagetallocatorinfo_43',['vmaGetAllocatorInfo',['../vk__mem__alloc_8h.html#afa02231a791b37255720d566a52683e7',1,'vk_mem_alloc.h']]], ['vmagetheapbudgets_44',['vmaGetHeapBudgets',['../vk__mem__alloc_8h.html#a9f88db9d46a432c0ad7278cecbc5eaa7',1,'vk_mem_alloc.h']]], ['vmagetmemoryproperties_45',['vmaGetMemoryProperties',['../vk__mem__alloc_8h.html#ab88db292a17974f911182543fda52d19',1,'vk_mem_alloc.h']]], ['vmagetmemorytypeproperties_46',['vmaGetMemoryTypeProperties',['../vk__mem__alloc_8h.html#a8701444752eb5de4464adb5a2b514bca',1,'vk_mem_alloc.h']]], ['vmagetphysicaldeviceproperties_47',['vmaGetPhysicalDeviceProperties',['../vk__mem__alloc_8h.html#aecabf7b6e91ea87d0316fa0a9e014fe0',1,'vk_mem_alloc.h']]], ['vmagetpoolname_48',['vmaGetPoolName',['../vk__mem__alloc_8h.html#af09b4e4eafdbee812e8d73ddf960f030',1,'vk_mem_alloc.h']]], ['vmagetpoolstats_49',['vmaGetPoolStats',['../vk__mem__alloc_8h.html#ae8bf76997b234ef68aad922616df4153',1,'vk_mem_alloc.h']]], ['vmagetvirtualallocationinfo_50',['vmaGetVirtualAllocationInfo',['../vk__mem__alloc_8h.html#ab5fcb961ffea69023e7e0ea100bdad8e',1,'vk_mem_alloc.h']]], ['vmainvalidateallocation_51',['vmaInvalidateAllocation',['../vk__mem__alloc_8h.html#aaa8412919139ef413a4215ac6a290fae',1,'vk_mem_alloc.h']]], ['vmainvalidateallocations_52',['vmaInvalidateAllocations',['../vk__mem__alloc_8h.html#ab25b558d75f7378ec944a1522fdcc3c5',1,'vk_mem_alloc.h']]], ['vmaisvirtualblockempty_53',['vmaIsVirtualBlockEmpty',['../vk__mem__alloc_8h.html#acd53b5b1d23f8fcbad692ccfdc1811f1',1,'vk_mem_alloc.h']]], ['vmamakepoolallocationslost_54',['vmaMakePoolAllocationsLost',['../vk__mem__alloc_8h.html#a736bd6cbda886f36c891727e73bd4024',1,'vk_mem_alloc.h']]], ['vmamapmemory_55',['vmaMapMemory',['../vk__mem__alloc_8h.html#ad5bd1243512d099706de88168992f069',1,'vk_mem_alloc.h']]], ['vmasetallocationuserdata_56',['vmaSetAllocationUserData',['../vk__mem__alloc_8h.html#af9147d31ffc11d62fc187bde283ed14f',1,'vk_mem_alloc.h']]], ['vmasetcurrentframeindex_57',['vmaSetCurrentFrameIndex',['../vk__mem__alloc_8h.html#ade56bf8dc9f5a5eaddf5f119ed525236',1,'vk_mem_alloc.h']]], ['vmasetpoolname_58',['vmaSetPoolName',['../vk__mem__alloc_8h.html#adbae3a0b4ab078024462fc85c37f3b58',1,'vk_mem_alloc.h']]], ['vmasetvirtualallocationuserdata_59',['vmaSetVirtualAllocationUserData',['../vk__mem__alloc_8h.html#a4b96f835d38686df937e097a0c7db5e9',1,'vk_mem_alloc.h']]], ['vmatouchallocation_60',['vmaTouchAllocation',['../vk__mem__alloc_8h.html#a43d8ba9673c846f049089a5029d5c73a',1,'vk_mem_alloc.h']]], ['vmaunmapmemory_61',['vmaUnmapMemory',['../vk__mem__alloc_8h.html#a9bc268595cb33f6ec4d519cfce81ff45',1,'vk_mem_alloc.h']]], ['vmavirtualallocate_62',['vmaVirtualAllocate',['../vk__mem__alloc_8h.html#a1c15925e6745dacee0cfc877fffecec2',1,'vk_mem_alloc.h']]], ['vmavirtualfree_63',['vmaVirtualFree',['../vk__mem__alloc_8h.html#a13f01c44b3c1a06e695f1f5d24b80639',1,'vk_mem_alloc.h']]] ];
import React, { Component } from 'react'; import 'whatwg-fetch'; import ReactTable from 'react-table'; import 'react-table/react-table.css'; import { Link } from 'react-router-dom'; const extract = (str, pattern) => (str.match(pattern) || []).pop() || ''; const extractAlphanum = (str) => extract(str, "[0-9a-zA-Z]+"); const limitLength = (str, length) => str.substring(0, length); class SubmitRoom extends Component { constructor(props) { super(props); this.state = { rooms: [], roomlocations: [] }; //this.handleChange = this.handleChange.bind(this); this.componentDidMount = this.componentDidMount.bind(this); this.newRoom = this.newRoom.bind(this); this.deleteRoom = this.deleteRoom.bind(this); this._modifyRoom = this._modifyRoom.bind(this); this.newRoomLocation = this.newRoomLocation.bind(this); this.deleteRoomLocation = this.deleteRoomLocation.bind(this); this._modifyRoomLocation = this._modifyRoomLocation.bind(this); } /* handleChange(event) { this.setState({roomName: limitLength(extractAlphanum(event.target.roomName), 25)}); this.setState({roomAddress: limitLength(extractAlphanum(event.target.roomAddress), 25)}); } */ componentDidMount() { fetch('/api/rooms', { method: 'GET' }) .then(res => res.json()) .then(json => { this.setState({ rooms: json }); }); fetch('/api/roomlocations', { method: 'GET' }) .then(res => res.json()) .then(json => { this.setState({ roomlocations: json }); }); } newRoom() { fetch('/api/rooms', { method: 'POST' }) .then(res => res.json()) .then(json => { let data = this.state.rooms; data.push(json); this.setState({ rooms: data }); }); } deleteRoom(index) { const id = this.state.rooms[index]._id; fetch(`/api/rooms/${id}`, { method: 'DELETE' }) .then(_ => { this._modifyRoom(index, null); }); } _modifyRoom(index, data) { let prevData = this.state.rooms; if (data) { prevData[index] = data; } else { prevData.splice(index, 1); } this.setState({ rooms: prevData }); } newRoomLocation() { fetch('/api/roomlocations', { method: 'POST' }) .then(res => res.json()) .then(json => { let data = this.state.roomlocations; data.push(json); this.setState({ roomlocations: data }); }); } deleteRoomLocation(index) { const id = this.state.roomlocations[index]._id; fetch(`/api/roomlocations/${id}`, { method: 'DELETE' }) .then(_ => { this._modifyRoomLocation(index, null); }); } _modifyRoomLocation(index, data) { let prevData = this.state.roomlocations; if (data) { prevData[index] = data; } else { prevData.splice(index, 1); } this.setState({ roomlocations: prevData }); } render() { return ( <div> <h1>Submit Room:</h1> <form target="_blank" method="post" action="/api/rooms"> <p>Room Name: <input type="text" name="name" /></p> <p>Location Name: <select name="location_id"> { this.state.roomlocations.map((roomlocation, i) => ( <option key={i} value={roomlocation._id}>{roomlocation.name}</option> )) } </select></p> <p>Time Available: <input type="number" name="time_available_minutes" /></p> <p>Max Players: <input type="number" name="max_players" /></p> <p>Min Players: <input type="number" name="min_players" /></p> <p>Completion Percentage: <input type="number" name="reported_completion_percentage" /></p> <p>Difficulty: <input type="number" name="reported_difficulty" /></p> <p>Price: <input type="number" name="price" /></p> <p>Room URL: <input type="text" name="room_URL" /></p> <p>Image URL: <input type="text" name="image_URL" /></p> <p>Notes: <input type="text" name="notes" /></p> <input type="submit" /> </form> <h1>Submit Room Location:</h1> <form target="_blank" method="post" action="/api/roomlocations"> <p>Location Name: <input type="text" name="name" /></p> <p>Website: <input type="text" name="website" /></p> <p>Telephone: <input type="number" name="tel" /></p> <p>Email: <input type="text" name="email" /></p> <p>Address: <input type="text" name="address" /></p> <p>Booking URL: <input type="text" name="booking_URL" /></p> <input type="submit" /> </form> </div> ); } } export default SubmitRoom;
import findUp from 'find-up' import { CONFIG_FILE } from 'next-server/constants' const targets = ['server', 'serverless'] const defaultConfig = { env: [], webpack: null, webpackDevMiddleware: null, poweredByHeader: true, distDir: '.next', assetPrefix: '', configOrigin: 'default', useFileSystemPublicRoutes: true, generateBuildId: () => null, generateEtags: true, pageExtensions: ['jsx', 'js'], target: 'server', onDemandEntries: { maxInactiveAge: 60 * 1000, pagesBufferLength: 2 }, experimental: { amp: false } } function normalizeConfig (phase, config) { if (typeof config === 'function') { return config(phase, { defaultConfig }) } return config } export default function loadConfig (phase, dir, customConfig) { if (customConfig) { return { ...defaultConfig, configOrigin: 'server', ...customConfig } } const path = findUp.sync(CONFIG_FILE, { cwd: dir }) // If config file was found if (path && path.length) { const userConfigModule = require(path) const userConfig = normalizeConfig(phase, userConfigModule.default || userConfigModule) if (userConfig.target && !targets.includes(userConfig.target)) { throw new Error(`Specified target is invalid. Provided: "${userConfig.target}" should be one of ${targets.join(', ')}`) } if (userConfig.experimental) { userConfig.experimental = { ...defaultConfig.experimental, ...userConfig.experimental } } if (userConfig.onDemandEntries) { userConfig.onDemandEntries = { ...defaultConfig.onDemandEntries, ...userConfig.onDemandEntries } } return { ...defaultConfig, configOrigin: CONFIG_FILE, ...userConfig } } return defaultConfig }