Best JavaScript code snippet using wpt
AutoSizeImage.js
Source:AutoSizeImage.js
1import React from 'react'2import PropTypes from 'prop-types'3import { View, Image, StyleSheet, PixelRatio } from 'react-native'4import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource'5import { enhanceState, enhanceProps, extraProps } from 'component'6import { emulateNative } from 'native/component'7import { shallowEqual } from 'lang'8import { Promise } from 'promise'9/*10èªå¨è®¾å® image ç尺寸111. è¥å®¹å¨æç¡®æå®äºå°ºå¯¸ï¼ä¾å¦æ¾å¼æå®äº width å heightï¼æè®¾ç½®äº flex: 1ï¼12 åå½ image 大äºå®¹å¨æ¶ï¼ä¼å°å
¶ç¼©æ¾å°å容å¨ä¸æ ·å¤§ï¼å½ image å°äºå®¹å¨æ¶ï¼ä¿ç image å大å°ï¼å¹¶å±
ä¸ã13 ï¼æè·¯æ¥èªï¼react-native-fit-imageï¼14 è¥å®¹å¨åªè®¾ç½®äºå®½åº¦æé«åº¦ï¼åå¾çå¨æ²¡è®¾ç½®å°ºå¯¸çé£ä¸è¾¹ç大å°ä¸åéå¶ã15 è¥å®½åº¦åé«åº¦é½æ²¡è®¾ç½®ï¼åå¾ç尺寸å®å
¨ä¸åéå¶ï¼æå尺寸æ¾ç¤ºã16 æ¤ component ä¼å 满容å¨ç空é´ï¼å æ¤å®¹å¨ä¸åºè®¾ç½® alignItems: 'center' å justifyContent: 'center' styleã17 让å¾çå±
ä¸çä»»å¡äº¤ç»æ¤ component æ¥å®æã182. æ ¹æ®å½å设å¤ç ratioï¼å缩å¾ç尺寸19*/20@emulateNative21@enhanceState22@enhanceProps23export class AutoSizeImage extends React.Component {24 static propTypes = {25 source: PropTypes.oneOfType([26 PropTypes.object,27 PropTypes.number, // 以 require(...) çå½¢å¼å¼å
¥æ¶ï¼source å¼æ¯æ°å28 ]).isRequired,29 style: PropTypes.any,30 // å
¶ä» props ä¼ä¼ ç» <Image />31 }32 state = {33 imgRealWidth: null,34 imgRealHeight: null,35 containerWidth: null,36 containerHeight: null,37 imgRenderWidth: 0,38 imgRenderHeight: 0,39 }40 componentWillMount() {41 this.getRealImgSize()42 }43 componentWillUnmount() {44 if(this.getSizePromise) this.getSizePromise.cancel()45 }46 componentDidReceiveProps(prevProps) {47 if(!shallowEqual(this.props.source, prevProps.source)) {48 this.getRealImgSize()49 }50 }51 containerOnLayout = event => {52 const { width, height } = event.nativeEvent.layout53 this.setState({54 containerWidth: width,55 containerHeight: height,56 })57 if(this.pendState.imgRealWidth !== null) this.computeImgSize()58 }59 getRealImgSize() {60 const { source } = this.props61 const got = (width, height) => this.batchedUpdates(() => {62 width = Math.round(width / PixelRatio.get())63 height = Math.round(height / PixelRatio.get())64 this.setState({65 imgRealWidth: width,66 imgRealHeight: height,67 })68 if(this.pendState.containerWidth !== null) {69 this.computeImgSize()70 }71 })72 if(typeof source === 'number') {73 /*74 é对éè¿ require(...) å¼å
¥è¿æ¥ç sourceï¼è¿é使ç¨äºä¸ä¸ªä» react-native æºç éæ¾åºæ¥çæ¹æ³ã75 https://github.com/facebook/react-native/blob/master/Libraries/Image/Image.android.js76 éè¿ä½¿ç¨ resolveAssetSource() å½æ°ï¼å¯ä»¥æ number ç source 解ææå®æ´ç source 对象ï¼77 顺便è¿æä¾äºå¾çç width å heightï¼å æ¤ä¹ä¸ç¨åæå¨è·åäºã78 */79 const resolvedSource = resolveAssetSource(source)80 got(resolvedSource.width, resolvedSource.height)81 } else {82 this.getSizePromise = new Promise((resolve, _, onCancel) => {83 let cancelled = false84 onCancel(() => { cancelled = true })85 Image.getSize(this.props.source.uri, (width, height) => {86 if(!cancelled) resolve([width, height])87 })88 })89 this.getSizePromise.then(([width, height]) => {90 got(width, height)91 this.getSizePromise = null92 })93 }94 }95 computeImgSize() {96 const realWidth = this.pendState.imgRealWidth,97 realHeight = this.pendState.imgRealHeight,98 maxWidth = this.pendState.containerWidth || Infinity,99 maxHeight = this.pendState.containerHeight || Infinity100 let renderWidth, renderHeight101 const scaleMultiple = Math.max(realWidth / maxWidth, realHeight / maxHeight)102 if(scaleMultiple > 1) {103 renderWidth = Math.floor(realWidth / scaleMultiple)104 renderHeight = Math.floor(realHeight/ scaleMultiple)105 } else {106 renderWidth = realWidth107 renderHeight = realHeight108 }109 this.setState({110 imgRenderWidth: renderWidth,111 imgRenderHeight: renderHeight,112 })113 }114 render() {115 const imgStyle = [116 this.props.style,117 { width: this.state.imgRenderWidth, height: this.state.imgRenderHeight },118 ]119 return <View style={styles.container} onLayout={this.containerOnLayout}>120 <Image {...extraProps(this)} source={this.props.source} style={imgStyle} />121 </View>122 }123}124const styles = StyleSheet.create({125 container: {126 flex: 1,127 alignItems: 'center',128 justifyContent: 'center',129 }...
index.js
Source:index.js
1const Assets = require("@swissquote/assets");2const { dirname } = require("path");3const functions = require("postcss-functions");4const util = require("util");5const quote = require("./quote");6const unescapeCss = require("./unescape-css");7const unquote = require("./unquote");8const generateFileUniqueId = require("./__utils__/generateFileUniqueId");9const cachedDimensions = {};10function formatUrl(url) {11 return util.format("url(%s)", quote(url));12}13function formatSize(measurements) {14 return util.format("%dpx %dpx", measurements.width, measurements.height);15}16function formatWidth(measurements) {17 return util.format("%dpx", measurements.width);18}19function formatHeight(measurements) {20 return util.format("%dpx", measurements.height);21}22function measure(params, resolver, path, density) {23 let cached = null;24 let id = "";25 let getSizePromise = null;26 return resolver.path(path).then(resolvedPath => {27 if (params.cache) {28 cached = cachedDimensions[resolvedPath];29 id = generateFileUniqueId(resolvedPath);30 }31 if (cached && id && cached[id]) {32 getSizePromise = Promise.resolve(cached[id]);33 } else {34 getSizePromise = resolver.size(path).then(size => {35 if (params.cache && id) {36 cachedDimensions[resolvedPath] = {};37 cachedDimensions[resolvedPath][id] = size;38 }39 return size;40 });41 }42 return getSizePromise.then(size => {43 if (density !== undefined) {44 return {45 width: Number((size.width / density).toFixed(4)),46 height: Number((size.height / density).toFixed(4))47 };48 }49 return size;50 });51 });52}53module.exports = (params = {}) => {54 if (params.relative === undefined) {55 params.relative = false; // eslint-disable-line no-param-reassign56 }57 const resolver = new Assets(params);58 return {59 // Initialize functions plugin as if it was this plugin60 ...functions({61 functions: {62 resolve: function resolve(path) {63 const normalizedPath = unquote(unescapeCss(path));64 return resolver.url(normalizedPath).then(formatUrl);65 },66 inline: function inline(path) {67 const normalizedPath = unquote(unescapeCss(path));68 return resolver.data(normalizedPath).then(formatUrl);69 },70 size: function size(path, density) {71 const normalizedPath = unquote(unescapeCss(path));72 return measure(params, resolver, normalizedPath, density).then(73 formatSize74 );75 },76 width: function width(path, density) {77 const normalizedPath = unquote(unescapeCss(path));78 return measure(params, resolver, normalizedPath, density).then(79 formatWidth80 );81 },82 height: function height(path, density) {83 const normalizedPath = unquote(unescapeCss(path));84 return measure(params, resolver, normalizedPath, density).then(85 formatHeight86 );87 }88 }89 }),90 // Override with our own features and name91 postcssPlugin: "postcss-assets",92 Once(root) {93 let inputDir;94 if (root.source.input.file) {95 inputDir = dirname(root.source.input.file);96 resolver.options.loadPaths = resolver.options.loadPaths || [];97 resolver.options.loadPaths.unshift(inputDir);98 if (params.relative === true) {99 resolver.options.relativeTo = inputDir;100 }101 }102 if (typeof params.relative === "string") {103 resolver.options.relativeTo = params.relative;104 }105 }106 };107};...
Using AI Code Generation
1var wpt = require('./wpt');2var wptObj = new wpt('your key here');3var options = {4 videoParams: {5 }6};7wptObj.runTest(options, function (err, data) {8 if (err) {9 return console.error(err);10 }11 wptObj.getTestStatus(data.data.testId, function (err, data) {12 if (err) {13 return console.error(err);14 }15 console.log(data);16 });17});
Using AI Code Generation
1const wpt = require('wpt-api');2wpt.getTestStatusPromise('170204_5Y_9c6c8f5f5b8c8a5a1a5f5d5e5a5f5e5f', 'www.webpagetest.org').then((data) => {3 console.log(data);4}).catch((err) => {5 console.log(err);6});7wpt.getTestStatus('170204_5Y_9c6c8f5f5b8c8a5a1a5f5d5e5a5f5e5f', 'www.webpagetest.org', (err, data) => {8 if (err) {9 console.log(err);10 } else {11 console.log(data);12 }13});14`getTestStatusPromise(testId, server)`15`getTestStatus(testId, server, callback)`16`getTestResults(testId, server, callback)`17`getTestResultsPromise(testId, server)`
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!!