Best JavaScript code snippet using storybook-root
contentscript.js
Source:contentscript.js
1const fs = require('fs')2const path = require('path')3const pump = require('pump')4const LocalMessageDuplexStream = require('post-message-stream')5const PongStream = require('ping-pong-stream/pong')6const ObjectMultiplex = require('obj-multiplex')7const extension = require('extensionizer')8const PortStream = require('./lib/port-stream.js')9const inpageContent = fs.readFileSync(path.join(__dirname, '..', '..', 'dist', 'chrome', 'inpage.js')).toString()10const inpageSuffix = '//# sourceURL=' + extension.extension.getURL('inpage.js') + '\n'11const inpageBundle = inpageContent + inpageSuffix12// Eventually this streaming injection could be replaced with:13// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.exportFunction14//15// But for now that is only Firefox16// If we create a FireFox-only code path using that API,17// MetaMask will be much faster loading and performant on Firefox.18if (shouldInjectWeb3()) {19 setupInjection()20 setupStreams()21}22/**23 * Creates a script tag that injects inpage.js24 */25function setupInjection () {26 try {27 // inject in-page script28 var scriptTag = document.createElement('script')29 scriptTag.textContent = inpageBundle30 scriptTag.onload = function () { this.parentNode.removeChild(this) }31 var container = document.head || document.documentElement32 // append as first child33 container.insertBefore(scriptTag, container.children[0])34 } catch (e) {35 console.error('Metamask injection failed.', e)36 }37}38/**39 * Sets up two-way communication streams between the40 * browser extension and local per-page browser context41 */42function setupStreams () {43 // setup communication to page and plugin44 const pageStream = new LocalMessageDuplexStream({45 name: 'contentscript',46 target: 'inpage',47 })48 const pluginPort = extension.runtime.connect({ name: 'contentscript' })49 const pluginStream = new PortStream(pluginPort)50 // forward communication plugin->inpage51 pump(52 pageStream,53 pluginStream,54 pageStream,55 (err) => logStreamDisconnectWarning('MetaMask Contentscript Forwarding', err)56 )57 // setup local multistream channels58 const mux = new ObjectMultiplex()59 mux.setMaxListeners(25)60 pump(61 mux,62 pageStream,63 mux,64 (err) => logStreamDisconnectWarning('MetaMask Inpage', err)65 )66 pump(67 mux,68 pluginStream,69 mux,70 (err) => logStreamDisconnectWarning('MetaMask Background', err)71 )72 // connect ping stream73 const pongStream = new PongStream({ objectMode: true })74 pump(75 mux,76 pongStream,77 mux,78 (err) => logStreamDisconnectWarning('MetaMask PingPongStream', err)79 )80 // connect phishing warning stream81 const phishingStream = mux.createStream('phishing')82 phishingStream.once('data', redirectToPhishingWarning)83 // ignore unused channels (handled by background, inpage)84 mux.ignoreStream('provider')85 mux.ignoreStream('publicConfig')86}87/**88 * Error handler for page to plugin stream disconnections89 *90 * @param {string} remoteLabel Remote stream name91 * @param {Error} err Stream connection error92 */93function logStreamDisconnectWarning (remoteLabel, err) {94 let warningMsg = `MOACmaskContentscript - lost connection to ${remoteLabel}`95 if (err) warningMsg += '\n' + err.stack96 console.warn(warningMsg)97}98/**99 * Determines if Web3 should be injected100 *101 * @returns {boolean} {@code true} if Web3 should be injected102 */103function shouldInjectWeb3 () {104 return doctypeCheck() && suffixCheck()105 && documentElementCheck() && !blacklistedDomainCheck()106}107/**108 * Checks the doctype of the current document if it exists109 *110 * @returns {boolean} {@code true} if the doctype is html or if none exists111 */112function doctypeCheck () {113 const doctype = window.document.doctype114 if (doctype) {115 return doctype.name === 'html'116 } else {117 return true118 }119}120/**121 * Checks the current document extension122 *123 * @returns {boolean} {@code true} if the current extension is not prohibited124 */125function suffixCheck () {126 var prohibitedTypes = ['xml', 'pdf']127 var currentUrl = window.location.href128 var currentRegex129 for (let i = 0; i < prohibitedTypes.length; i++) {130 currentRegex = new RegExp(`\\.${prohibitedTypes[i]}$`)131 if (currentRegex.test(currentUrl)) {132 return false133 }134 }135 return true136}137/**138 * Checks the documentElement of the current document139 *140 * @returns {boolean} {@code true} if the documentElement is an html node or if none exists141 */142function documentElementCheck () {143 var documentElement = document.documentElement.nodeName144 if (documentElement) {145 return documentElement.toLowerCase() === 'html'146 }147 return true148}149/**150 * Checks if the current domain is blacklisted151 *152 * @returns {boolean} {@code true} if the current domain is blacklisted153 */154function blacklistedDomainCheck () {155 var blacklistedDomains = [156 'uscourts.gov',157 'dropbox.com',158 'webbyawards.com',159 'cdn.shopify.com/s/javascripts/tricorder/xtld-read-only-frame.html',160 'adyen.com',161 'gravityforms.com',162 ]163 var currentUrl = window.location.href164 var currentRegex165 for (let i = 0; i < blacklistedDomains.length; i++) {166 const blacklistedDomain = blacklistedDomains[i].replace('.', '\\.')167 currentRegex = new RegExp(`(?:https?:\\/\\/)(?:(?!${blacklistedDomain}).)*$`)168 if (!currentRegex.test(currentUrl)) {169 return true170 }171 }172 return false173}174/**175 * Redirects the current page to a phishing information page176 */177function redirectToPhishingWarning () {178 console.log('MetaMask - redirecting to phishing warning')179 window.location.href = 'https://metamask.io/phishing.html'...
appcache_tests-client.js
Source:appcache_tests-client.js
1const manifestUrl = '/app.manifest';2function appcacheTest(name, cb) {3 Tinytest.addAsync(`appcache - ${name}`, test => {4 return fetch(manifestUrl).then(5 res => cb(test, res),6 err => test.fail(err)7 );8 });9}10// Verify that the code status of the HTTP response is "OK"11appcacheTest('presence', (test, manifest) =>12 test.equal(manifest.status, 200, 'manifest not served'));13// Verify the content-type HTTP header14appcacheTest('content type', (test, manifest) =>15 test.equal(manifest.headers.get('content-type'), 'text/cache-manifest'));16// Verify that each section header is only set once.17appcacheTest('sections uniqueness', async (test, manifest) => {18 const content = await manifest.text();19 const mandatorySectionHeaders = ['CACHE:', 'NETWORK:', 'FALLBACK:'];20 const optionalSectionHeaders = ['SETTINGS'];21 const allSectionHeaders = [22 ...mandatorySectionHeaders,23 ...optionalSectionHeaders.filter(24 header => !mandatorySectionHeaders.includes(header)25 ),26 ];27 allSectionHeaders.forEach(sectionHeader => {28 const globalSearch = new RegExp(sectionHeader, "g");29 const matches = content.match(globalSearch) || [];30 test.isTrue(matches.length <= 1, `${sectionHeader} is set twice`);31 if (mandatorySectionHeaders.includes(sectionHeader)) {32 test.isTrue(matches.length == 1, `${sectionHeader} is not set`);33 }34 });35});36// Verify the content of the header and of each section of the manifest using37// regular expressions. Regular expressions matches malformed URIs but that's38// not what we're trying to catch here (the user is free to add its own content39// in the manifest -- even malformed).40appcacheTest('sections validity', async (test, manifest) => {41 const lines = (await manifest.text()).split('\n');42 let i = 0;43 let currentRegex = null;44 let line = null;45 const nextLine = () => lines[i++];46 const eof = () => i >= lines.length;47 const nextLineMatches = (expected, n) => {48 n = n || 1;49 for(let j = 0; j < n; j++) {50 const testFunc = toString.call(expected) === '[object RegExp]' ?51 'matches' :52 'equal';53 test[testFunc](nextLine(), expected);54 }55 };56 // Verify header validity57 nextLineMatches('CACHE MANIFEST');58 nextLineMatches('');59 nextLineMatches(/^# [a-z0-9]+$/i);60 nextLineMatches('');61 // Verify body validity62 while (! eof()) {63 line = nextLine();64 // There are three distinct sections: 'CACHE', 'FALLBACK', and 'NETWORK'.65 // A section start with its name suffixed by a colon. When we read a new66 // section header, we update the currentRegex expression for the next lines67 // of the section.68 // XXX There is also a 'SETTINGS' section, not used by this package. If this69 // section is used, the test will fail.70 if (line === 'CACHE:' || line === 'NETWORK:')71 currentRegex = /^\S+$/;72 else if (line === 'FALLBACK:')73 currentRegex = /^\S+ \S+$/;74 // Blank lines and lines starting with a `#` (comments) are valid75 else if (line == '' || line.match(/^#.+/))76 continue;77 // Outside sections, only blanks lines and comments are valid78 else if (currentRegex === null)79 test.fail(`Invalid line ${i}: ${line}`);80 // Inside a section, a star is a valid expression81 else if (line === '*')82 continue;83 // If it is not a blank line, not a comment, and not a header it must84 // match the current section format85 else86 test.matches(line, currentRegex, `line ${i}`);87 }88});89// Verify that resources declared on the server with the `onlineOnly` parameter90// are present in the network section of the manifest. The `appcache` package91// also automatically add the manifest (`app.manifest`) add the star symbol to92// this list and therefore we also check the presence of these two elements.93appcacheTest('network section content', async (test, manifest) => {94 const shouldBePresentInNetworkSection = [95 "/app.manifest",96 "/online/",97 "/bigimage.jpg",98 "/largedata.json",99 "*"100 ];101 const lines = (await manifest.text()).split('\n');102 const startNetworkSection = lines.indexOf('NETWORK:');103 // We search the end of the 'NETWORK:' section by looking at the beginning104 // of any potential other section. By default we set this value to105 // `lines.length - 1` which is the index of the last line.106 const otherSections = ['CACHE:', 'FALLBACK:', 'SETTINGS'];107 const endNetworkSection = otherSections.reduce((min, sectionName) => {108 const position = lines.indexOf(sectionName);109 return position > startNetworkSection && position < min ? position : min;110 }, lines.length - 1);111 // We remove the first line because it's the 'NETWORK:' header line.112 const networkLines = lines.slice(startNetworkSection + 1, endNetworkSection);113 shouldBePresentInNetworkSection.forEach(114 item => test.include(networkLines, item)115 );...
script.js
Source:script.js
1const signs = ['(', ')', '-', ' ', ':']2const masks = document.querySelectorAll('.mask')3masks.forEach(input => {4 const pattern = input.dataset.pattern.split('')5 console.log(pattern);6 input.addEventListener('keypress', e => {7 e.preventDefault()8 check(e.key)9 })10 //test 555aa355555511 //test 555555555512 input.addEventListener('paste', e => {13 e.preventDefault()14 const paste = e.clipboardData.getData('text').replaceAll(' ', '').split('')15 paste.forEach((char, index) => {16 let currentRegex17 if (pattern[index] != '0' && pattern[index] != '#') return18 if (pattern[index] === '0') currentRegex = /\d/19 if (pattern[index] === '#') currentRegex = /[a-zA-Z]/20 if (!currentRegex.test(char)) {21 paste.splice(index, 1)22 if (!currentRegex.test(char)) {23 paste.splice(index, 1)24 }25 }26 })27 pattern.forEach((item, index) => {28 if (signs.includes(item)) {29 paste.splice(index, 0, item)30 }31 })32 input.value = paste.join('').substring(0, pattern.length)33 })34 input.addEventListener('keyup', e => {35 if (e.key !== 'Backspace') return36 removeCharacter()37 })38 function check(char) {39 if (signs.includes(pattern[input.value.length])) {40 input.value += pattern[input.value.length]41 if (signs.includes(pattern[input.value.length])) {42 check(pattern[input.value.length])43 }44 }45 let currentRegex46 if (pattern[input.value.length] != '0' && pattern[input.value.length] != '#') return47 if (pattern[input.value.length] === '0') currentRegex = /\d/48 if (pattern[input.value.length] === '#') currentRegex = /[a-zA-Z]/49 if (currentRegex.test(char)) input.value += char50 }51 function removeCharacter() {52 if (signs.includes(pattern[input.value.length - 1])) {53 input.value = input.value.slice(0, -1)54 if (signs.includes(pattern[input.value.length - 1])) {55 removeCharacter()56 }57 }58 }...
Using AI Code Generation
1import { currentRegex } from 'storybook-root';2import { currentRegex } from 'storybook-root';3import { currentRegex } from 'storybook-root';4import { currentRegex } from 'storybook-root';5import { currentRegex } from 'storybook-root';6import { currentRegex } from 'storybook-root';7import { currentRegex } from 'storybook-root';8import { currentRegex } from 'storybook-root';9import { currentRegex } from 'storybook-root';10import { currentRegex } from 'storybook-root';11import { currentRegex } from 'storybook-root';12import { currentRegex } from 'storybook-root';13import { currentRegex } from 'storybook-root';14import { currentRegex } from 'storybook-root';15import { currentRegex } from 'storybook-root';16import { currentRegex } from 'storybook-root';17import { currentRegex } from 'storybook-root';18import { currentRegex } from 'storybook-root';19import { currentRegex } from 'storybook-root';20import { currentRegex } from 'storybook-root';
Using AI Code Generation
1const storybookRoot = require('storybook-root')2const storybookRoot = require('storybook-root')3const storybookRoot = require('storybook-root')4const storybookRoot = require('storybook-root')5const storybookRoot = require('storybook-root')6const storybookRoot = require('storybook-root')7const storybookRoot = require('storybook-root')8const storybookRoot = require('storybook-root')9const storybookRoot = require('storybook-root')10const storybookRoot = require('storybook-root')11const storybookRoot = require('storybook-root')12const storybookRoot = require('storybook-root')13const storybookRoot = require('storybook-root')
Using AI Code Generation
1import { currentRegex } from 'storybook-root';2import { storiesOf } from '@storybook/react';3storiesOf('StorybookRoot', module)4 .add('should be visible', () => <div>visible</div>)5 .add('should not be visible', () => <div>not visible</div>)6 .add('should be visible', () => <div>visible</div>)7 .add('should not be visible', () => <div>not visible</div>)8 .add('should be visible', () => <div>visible</div>)9 .add('should not be visible', () => <div>not visible</div>)10 .add('should be visible', () => <div>visible</div>)11 .add('should not be visible', () => <div>not visible</div>)12 .add('should
Using AI Code Generation
1const storybookRoot = require('storybook-root');2const currentRegex = storybookRoot.currentRegex;3const storybookRoot = require('storybook-root');4const currentRegex = storybookRoot.currentRegex;5const storybookRoot = require('storybook-root');6const currentRegex = storybookRoot.currentRegex;7const storybookRoot = require('storybook-root');8const currentRegex = storybookRoot.currentRegex;9const storybookRoot = require('storybook-root');10const currentRegex = storybookRoot.currentRegex;11const storybookRoot = require('storybook-root');12const currentRegex = storybookRoot.currentRegex;13const storybookRoot = require('storybook-root');14const currentRegex = storybookRoot.currentRegex;
Using AI Code Generation
1const currentRegex = require('storybook-root').currentRegex;2const currentStoryFile = require('storybook-root').currentStoryFile;3const currentStoryName = require('storybook-root').currentStoryName;4const currentRegex = currentRegex();5const currentStoryFile = currentStoryFile();6const currentStoryName = currentStoryName();7const testFiles = glob.sync('./src/**/*.test.js');8const filteredTestFiles = testFiles.filter(file => {9 const testFileName = path.basename(file);10 const testFileRegex = new RegExp(testFileName);11 return testFileRegex.test(currentStoryFile) && currentRegex.test(currentStoryName);12});13const { configure, addDecorator } = require('@storybook/react');14const { setOptions } = require('@storybook/addon-options');15const { withKnobs } = require('@storybook/addon-knobs');16const { setDefaults } = require('storybook-addon-jsx');17const { withTests } = require('@storybook/addon-jest');18const results = require('../jest-test-results.json');19const { setRegex } = require('storybook-root');20setDefaults({ header: false, propTables: false });21addDecorator(withKnobs);22addDecorator(withTests({ results }));23const req = require.context('../src', true, /.stories.js$/);24const stories = req.keys().forEach(filename => {25 const storyName = req(filename).default.title;26 setRegex(new RegExp(storyName));27 req(filename);28});29const { setStoryFile } = require('storybook-root');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!