Best JavaScript code snippet using playwright-internal
KeywordData.js
Source:KeywordData.js
1import { useSelector } from 'react-redux';2import {3 Accordion,4 AccordionItem,5 AccordionItemHeading,6 AccordionItemButton,7 AccordionItemPanel,8} from 'react-accessible-accordion';9import { ColumnContainerBasic } from '../../Common/ContainerElements';10import {11 ExpandableAnalysisContainer,12 AnalysisElementWrapper,13 AnalysisElement,14 ElementTitle,15 ElementText,16} from '../../Common/AnalysisElements';17import { StyledSpinner } from '../../Common/StyledSpinner';18const KeywordData = () => {19 const { keywordData, isError, isLoading } = useSelector(20 (state) => state.keywordReducer21 );22 const { keywordToCheck, isChecking } = useSelector(23 (state) => state.keywordsReducer24 );25 const dataToDisplay = isChecking ? keywordToCheck : keywordData;26 if (isError) return <span>Sorry, something went wrong</span>;27 return isLoading ? (28 <StyledSpinner viewBox='0 0 50 50'>29 <circle30 className='path'31 cx='25'32 cy='25'33 r='20'34 fill='none'35 strokeWidth='4'36 />37 </StyledSpinner>38 ) : dataToDisplay ? (39 <>40 <ColumnContainerBasic>41 <ExpandableAnalysisContainer>42 <Accordion43 allowMultipleExpanded={true}44 allowZeroExpanded={true}45 preExpanded={['1']}>46 <AccordionItem uuid='1'>47 <AccordionItemHeading>48 <AccordionItemButton className='accordion__button--analysis'>49 Basic Info50 </AccordionItemButton>51 </AccordionItemHeading>52 <AccordionItemPanel className='accordion__panel--analysis'>53 <AnalysisElementWrapper>54 <AnalysisElement>55 <ElementTitle>Keyword</ElementTitle>56 <ElementText>{dataToDisplay.keyword}</ElementText>57 </AnalysisElement>58 <AnalysisElement>59 <ElementTitle>Language </ElementTitle>60 <ElementText>{dataToDisplay.language}</ElementText>61 </AnalysisElement>62 </AnalysisElementWrapper>63 </AccordionItemPanel>64 </AccordionItem>65 </Accordion>66 </ExpandableAnalysisContainer>67 </ColumnContainerBasic>68 <ColumnContainerBasic>69 <ExpandableAnalysisContainer>70 <Accordion allowMultipleExpanded={true} allowZeroExpanded={true}>71 <AccordionItem>72 <AccordionItemHeading>73 <AccordionItemButton className='accordion__button--analysis'>74 Pytrends keywords75 </AccordionItemButton>76 </AccordionItemHeading>77 <AccordionItemPanel className='accordion__panel--analysis'>78 <AnalysisElementWrapper>79 {dataToDisplay.pytrendsKeywords.map((pytrend, i) => (80 <AnalysisElement key={i}>81 <ElementTitle>{pytrend.title}</ElementTitle>82 <ElementText>{pytrend.type}</ElementText>83 </AnalysisElement>84 ))}85 </AnalysisElementWrapper>86 </AccordionItemPanel>87 </AccordionItem>88 </Accordion>89 </ExpandableAnalysisContainer>90 </ColumnContainerBasic>91 {dataToDisplay.serpKeywords.length ? (92 <ColumnContainerBasic>93 <ExpandableAnalysisContainer>94 <Accordion allowMultipleExpanded={true} allowZeroExpanded={true}>95 <AccordionItem>96 <AccordionItemHeading>97 <AccordionItemButton className='accordion__button--analysis'>98 SERP keywords99 </AccordionItemButton>100 </AccordionItemHeading>101 <AccordionItemPanel className='accordion__panel--analysis'>102 <AnalysisElementWrapper>103 <AnalysisElement>104 {dataToDisplay.serpKeywords.map((serp, i) => (105 <ElementText key={i}>{serp}</ElementText>106 ))}107 </AnalysisElement>108 </AnalysisElementWrapper>109 </AccordionItemPanel>110 </AccordionItem>111 </Accordion>112 </ExpandableAnalysisContainer>113 </ColumnContainerBasic>114 ) : null}115 <ColumnContainerBasic>116 <ExpandableAnalysisContainer>117 <Accordion allowMultipleExpanded={true} allowZeroExpanded={true}>118 <AccordionItem>119 <AccordionItemHeading>120 <AccordionItemButton className='accordion__button--analysis'>121 Google keywords122 </AccordionItemButton>123 </AccordionItemHeading>124 <AccordionItemPanel className='accordion__panel--analysis'>125 <AnalysisElementWrapper>126 <AnalysisElement>127 {dataToDisplay.googleKeywords.map((keyword, i) => (128 <ElementText key={i}>{keyword}</ElementText>129 ))}130 </AnalysisElement>131 </AnalysisElementWrapper>132 </AccordionItemPanel>133 </AccordionItem>134 </Accordion>135 </ExpandableAnalysisContainer>136 </ColumnContainerBasic>137 <ColumnContainerBasic>138 <ExpandableAnalysisContainer>139 <Accordion allowMultipleExpanded={true} allowZeroExpanded={true}>140 <AccordionItem>141 <AccordionItemHeading>142 <AccordionItemButton className='accordion__button--analysis'>143 Google suggestions questions144 </AccordionItemButton>145 </AccordionItemHeading>146 <AccordionItemPanel className='accordion__panel--analysis'>147 <AnalysisElementWrapper>148 {dataToDisplay.googleSuggestionsQuestions.questions.map(149 ({ question, results }, i) => (150 <AnalysisElement key={i}>151 <ElementTitle>{question}</ElementTitle>152 {results.normal.map((result, i) => (153 <ElementText key={i}>{result}</ElementText>154 ))}155 {results.reversed.map((result, i) => (156 <ElementText key={i}>{result}</ElementText>157 ))}158 </AnalysisElement>159 )160 )}161 </AnalysisElementWrapper>162 </AccordionItemPanel>163 </AccordionItem>164 </Accordion>165 </ExpandableAnalysisContainer>166 </ColumnContainerBasic>167 <ColumnContainerBasic>168 <ExpandableAnalysisContainer>169 <Accordion allowMultipleExpanded={true} allowZeroExpanded={true}>170 <AccordionItem>171 <AccordionItemHeading>172 <AccordionItemButton className='accordion__button--analysis'>173 Google suggestions prepositions174 </AccordionItemButton>175 </AccordionItemHeading>176 <AccordionItemPanel className='accordion__panel--analysis'>177 <AnalysisElementWrapper>178 {dataToDisplay.googleSuggestionsPrepositions.prepositions.map(179 ({ preposition, results }, i) => (180 <AnalysisElement key={i}>181 <ElementTitle>{preposition}</ElementTitle>182 {results.normal.map((result, i) => (183 <ElementText key={i}>{result}</ElementText>184 ))}185 {results.reversed.map((result, i) => (186 <ElementText key={i}>{result}</ElementText>187 ))}188 </AnalysisElement>189 )190 )}191 </AnalysisElementWrapper>192 </AccordionItemPanel>193 </AccordionItem>194 </Accordion>195 </ExpandableAnalysisContainer>196 </ColumnContainerBasic>197 <ColumnContainerBasic>198 <ExpandableAnalysisContainer>199 <Accordion allowMultipleExpanded={true} allowZeroExpanded={true}>200 <AccordionItem>201 <AccordionItemHeading>202 <AccordionItemButton className='accordion__button--analysis'>203 Google suggestions comparisons204 </AccordionItemButton>205 </AccordionItemHeading>206 <AccordionItemPanel className='accordion__panel--analysis'>207 <AnalysisElementWrapper>208 {dataToDisplay.googleSuggestionsComparisons.comparisons.map(209 ({ comparison, results }, i) => (210 <AnalysisElement key={i}>211 <ElementTitle>{comparison}</ElementTitle>212 {results.normal.map((result, i) => (213 <ElementText key={i}>{result}</ElementText>214 ))}215 {results.reversed.map((result, i) => (216 <ElementText key={i}>{result}</ElementText>217 ))}218 </AnalysisElement>219 )220 )}221 </AnalysisElementWrapper>222 </AccordionItemPanel>223 </AccordionItem>224 </Accordion>225 </ExpandableAnalysisContainer>226 </ColumnContainerBasic>227 <ColumnContainerBasic>228 <ExpandableAnalysisContainer>229 <Accordion allowMultipleExpanded={true} allowZeroExpanded={true}>230 <AccordionItem>231 <AccordionItemHeading>232 <AccordionItemButton className='accordion__button--analysis'>233 Google suggestions alphabeticals234 </AccordionItemButton>235 </AccordionItemHeading>236 <AccordionItemPanel className='accordion__panel--analysis'>237 <AnalysisElementWrapper>238 {dataToDisplay.googleSuggestionsAlphabeticals.letters.map(239 ({ letter, results }, i) => (240 <AnalysisElement key={i}>241 <ElementTitle>{letter}</ElementTitle>242 {results.map((result, i) => (243 <ElementText key={i}>{result}</ElementText>244 ))}245 </AnalysisElement>246 )247 )}248 </AnalysisElementWrapper>249 </AccordionItemPanel>250 </AccordionItem>251 </Accordion>252 </ExpandableAnalysisContainer>253 </ColumnContainerBasic>254 </>255 ) : null;256};...
Status.js
Source:Status.js
1/* eslint-disable prettier/prettier */2import React, {useState} from 'react';3import {4 SafeAreaView,5 StyleSheet,6 ScrollView,7 View,8 Text,9 StatusBar,10 KeyboardAvoidingView,11 TouchableOpacity,12 Button,13} from 'react-native';14import { Image, TextWelcome } from '../styles/LoginStyles';15import { Container, AlignCenter, MarginTop, MarginBottom, Together, ShaddowGreen, Margin, Horizontal } from '../../components/styles/general';16import { Hoshi } from 'react-native-textinput-effects';17import colors from '../../config/colors';18import {Scroll, ImageViewOp, Nv} from '../styles/StatusStyles';19import RNPickerSelect from 'react-native-picker-select';20import fonts from '../../config/fonts';21import { BtnDefault } from "../../components/Buttons";22import metrics from '../../config/metrics';23import {Divider} from "react-native-elements";24import imagePicker from 'react-native-image-picker';25export default function Caracters(props) {26 const [preview, setPreview] = useState(null);27 const [imageThumb, setImageThumb] = useState(null);28 handleSelect = () => {29 imagePicker.showImagePicker({30 title: 'Selecionar Imagem',31 }, upload => {32 if(upload.error){33 console.log('erro imagem');34 }else if(upload.didCancel){35 console.log('usuário cancelou');36 }else{37 const prev = {38 //uri: `data:image/jpeg;base64,${upload.data}`,39 uri: upload.uri,40 };41 let prefix;42 let ext;43 if(upload.fileName){44 [prefix, ext] = upload.fileName.split('.');45 ext= ext.toLowerCase() === 'heic' ? 'jpg' : ext;46 }else{47 prefix = new Date().getTime();48 ext = 'jpg';49 }50 const imagethumb = {51 uri: upload.uri,52 type: upload.type,53 name: `${prefix}.${ext}`,54 };55 console.log(prev);56 setPreview(prev);57 setImageThumb(imagethumb);58 }59 })60 }61 dropdown = () => (62 <RNPickerSelect63 textInputProps={styles.pickerSelect}64 placeholder={{65 label: 'Tipo',66 value: 'Tipo',67 color: '#000'68 }}69 onValueChange={(value) => arrayItems[4] = value}70 items={[71 { label: 'Jogador', value: 'Jogador', key: '0' },72 { label: 'Mestre', value: 'Mestre', key: '1' },73 ]}74 />75 );76 AboveFlatList = () => (77 <>78 <MarginTop />79 <AlignCenter>80 <ImageViewOp onPress={() => { handleSelect()}} >81 {preview != null ? <Image source={preview} /> : console.log('') }82 </ImageViewOp>83 </AlignCenter>84 <MarginBottom />85 </>86 )87 88 return (89 <>90 <MarginTop />91 <KeyboardAvoidingView style={styles.background}>92 <View style={styles.containerInputs}>93 <SafeAreaView>94 <Margin>95 <Scroll>96 <AboveFlatList /> 97 <View style={styles.Element}> 98 <Horizontal>99 <Text style={styles.ElementText}>NÃvel: </Text>100 <Nv style={styles.nvStyle}>XX</Nv>101 <Text style={styles.ElementText}>HP: </Text>102 <Nv style={styles.nvStyle}>XX</Nv>103 <Text style={styles.ElementText}>EP: </Text>104 <Nv style={styles.nvStyle}>XX</Nv>105 </Horizontal>106 </View> 107 108 <Text style={styles.title}>Forças de ataque</Text>109 <View style={styles.Element}> 110 <Horizontal>111 <Text style={styles.ElementText}>FOR: </Text>112 <Nv style={styles.nvStyle}>XX</Nv>113 <Text style={styles.ElementText}>DES: </Text>114 <Nv style={styles.nvStyle}>XX</Nv>115 <Text style={styles.ElementText}>PDF: </Text>116 <Nv style={styles.nvStyle}>XX</Nv>117 118 </Horizontal>119 </View> 120 <Text style={styles.title}>Forças de defesas</Text>121 122 <View style={styles.Element}> 123 <Horizontal>124 <Text style={styles.ElementText}>DEF: </Text>125 <Nv style={styles.nvStyle}>XX</Nv>126 <Text style={styles.ElementText}>DEFM:</Text>127 <Nv style={styles.nvStyle}>XX</Nv>128 129 <Text style={styles.ElementText}></Text>130 <Nv style={styles.nvStyle}></Nv>131 </Horizontal>132 </View> 133 <Text style={styles.title}>Testes de evasão</Text>134 <View style={styles.Element}> 135 <Horizontal>136 <Text style={styles.ElementText}>Ev F: </Text>137 <Nv style={styles.nvStyle}>XX</Nv>138 <Text style={styles.ElementText}>Ev M:</Text>139 <Nv style={styles.nvStyle}>XX</Nv>140 <Text style={styles.ElementText}></Text>141 <Nv style={styles.nvStyle}></Nv>142 </Horizontal>143 </View> 144 <Text style={styles.title}>Testes de precisão</Text>145 <View style={styles.Element}> 146 <Horizontal>147 <Text style={styles.ElementText}>Pre F:</Text>148 <Nv style={styles.nvStyle}>XX</Nv>149 <Text style={styles.ElementText}>Pre D:</Text>150 <Nv style={styles.nvStyle}>XX</Nv>151 <Text style={styles.ElementText}>Pre PDF:</Text>152 <Nv style={styles.nvStyle}>XX</Nv>153 154 <Text style={styles.ElementText}>Pre Mag:</Text>155 <Nv style={styles.nvStyle}>XX</Nv>156 </Horizontal>157 </View> 158 <Text style={styles.title}>Forças de ataque</Text>159 <View style={styles.Element}> 160 <Horizontal>161 <Text style={styles.ElementText}>XP: </Text>162 <Nv style={styles.nvStyle}>XX</Nv>163 <Text style={styles.ElementText}>PC: </Text>164 <Nv style={styles.nvStyle}>XX</Nv>165 <Text style={styles.ElementText}>GIL: </Text>166 <Nv style={styles.nvStyle}>XX</Nv>167 168 </Horizontal>169 </View>170 <BtnDefault name={'Salvar'}171 styles={styles.enter}172 onPress={()=>{}}173 TextBtn={'Salvar'} 174 /> 175 176 </Scroll>177 </Margin> 178 </SafeAreaView>179 </View>180 </KeyboardAvoidingView> 181 </>182 );183}184const styles = StyleSheet.create({185 pickerSelect: {186 fontSize: fonts.textInput,187 height: 50,188 fontWeight: 'bold',189 color: colors.grayWhite,190 marginTop: 7,191 marginBottom: 7,192 padding: 15,193 borderRadius: metrics.baseRadius,194 backgroundColor: colors.white,195 justifyContent: 'center',196 }, 197 background:{198 flex:1,199 justifyContent: 'flex-start',200 },201 inputStyle: {202 flex: 1,203 },204 nvStyle: {205 flex:1,206 },207 enter: {208 flex: 1,209 width: '100%',210 marginTop: 10,211 marginBottom: 10,212 flexWrap: 'wrap',213 },214 Element:{215 marginTop: 5,216 },217 ElementText: {218 fontSize: 16,219 color: colors.blueActive,220 fontWeight: 'bold',221 },222 title:{223 fontSize: 20,224 marginTop: 20,225 color: colors.blueActive,226 fontWeight: 'bold',227 textAlign: 'center'228 }, 229 ElementTextDef: {230 fontSize: 16,231 color: colors.blueActive,232 fontWeight: 'bold',233 marginTop: 40,234 marginLeft: 20235 },236 nvStyleDef: {237 flex:1,238 marginTop: 40,239 },240});241 ...
sharedRules.js
Source:sharedRules.js
1const sharedRules = (isInterpreted) => {2 return {3 'div': node => {4 const type = node.getAttribute('type')5 const subtype = node.getAttribute('subtype')6 const n = node.getAttribute('n')7 if (type === 'textpart') {8 const title = document.createElement('span')9 title.className += ' section-heading';10 title.append(`${subtype} ${n}`)11 node.prepend(title)12 } else if (type === 'edition' && subtype === 'transliteration') {13 const title = document.createElement('span')14 title.className += ' section-heading';15 title.append(`Transliteration`)16 node.prepend(title)17 }18 },19 'ab': node => {20 const span = document.createElement('span')21 span.className += ' leiden-transcription';22 [...node.childNodes].forEach(child => span.appendChild(child));23 node.appendChild(span)24 },25 'milestone': node => {26 const sup = document.createElement('sup')27 sup.textContent = `${node.getAttribute('n')}`28 node.append('|')29 node.append(sup)30 },31 'cb': node => {32 const title = document.createElement('span')33 title.className += ' section-heading';34 title.append(`Col. ${node.getAttribute('n')}`)35 node.prepend(title)36 }, 37 'lb': node => {38 const breakAttr = node.getAttribute('break');39 const n = node.getAttribute('n')40 const style = node.getAttribute('style')41 let textIndicator = ' '42 if (style === "text-direction:r-to-l") {43 textIndicator = 'â'44 } else if (style === "text-direction:l-to-r") {45 textIndicator = 'â'46 } else if (style === "text-direction:spiral-clockwise") {47 textIndicator = 'â»'48 } else if (style === "text-direction:circular-clockwise") {49 textIndicator = 'â»'50 } else if (style === "text-direction:spiral-anticlockwise") {51 textIndicator = 'âº'52 } else if (style === "text-direction:circular-anticlockwise") {53 textIndicator = 'âº'54 } else if (style === "text-direction:upwards") {55 textIndicator = 'â'56 } else if (style === "text-direction:downwards") {57 textIndicator = 'â'58 } 59 if (breakAttr === 'no' && isInterpreted) node.append('-');60 if (n !== 1) node.append(document.createElement('br'));61 const numSpan = document.createElement('span')62 numSpan.className += ' leiden-num-span'63 numSpan.append(`${n}. ${textIndicator}`)64 node.append(numSpan)65 },66 'space': node => {67 const extent = node.getAttribute('extent'); 68 const unit = node.getAttribute('unit'); // character or line69 const isUncertain = node.getAttribute('cert') === 'low'70 const quantity = node.getAttribute('quantity'); 71 let textContent = '('72 if (unit === 'line') {73 textContent += 'vacat'74 } else {75 if (quantity || (extent === 'unknown' && isUncertain)) {76 textContent += 'vac.'77 if (quantity > 1) textContent += quantity78 if (isUncertain) textContent += '?' 79 } else if (extent === 'unknown') {80 textContent += 'vacat'81 } 82 }83 textContent += ')'84 node.textContent = textContent85 },86 'gap': node => {87 let elementText;88 const reason = node.getAttribute('reason'); // 'lost' 'illegible' 'omitted'89 const extent = node.getAttribute('extent'); // always 'unknown' if present? - never in combination with quantity or atLeast/atMost90 const quantity = node.getAttribute('quantity'); // not in combination with extent or atLeast/atMost91 const unit = node.getAttribute('unit'); // character, line, or some other unit like cm92 const atLeast = node.getAttribute('atLeast'); // not in combination with extent or quantity93 const atMost = node.getAttribute('atMost'); // not in combination with extent or quantity94 const precision = node.getAttribute('precision'); // 'low' output: ca. 95 const precisionOutput = precision && precision === 'low' ? 'ca.' : '' ;96 const isLine = (unit && unit === 'line');97 let closingDelimiter = ''98 if (reason === 'lost') {99 if (isLine) {100 if (extent==='unknown') {101 elementText = ' - - - - - ' 102 } else {103 elementText = ' [- - - - - -';104 closingDelimiter = '] '105 }106 } else {107 // Dots are used only when exact number of characters is known.108 // Dashes otherwise.109 elementText = '[';110 if (extent === 'unknown') {111 elementText += '- - ? - -';112 } else if (atLeast || atMost) {113 elementText += ` - ${atLeast}-${atMost} - `114 } else if (quantity && quantity < 5) {115 elementText += '. '.repeat(quantity).trim();116 } else if (quantity && quantity >= 5) {117 if (precision === 'low' || (unit !== 'character' && unit !== 'line')) {118 // note that we display the unit if it isn't 'character' or 'line' because it is likely 'cm'119 elementText += `- - ${precisionOutput}${quantity}${(unit !== 'character' && unit !== 'line')?unit:''} - - `120 } else {121 elementText += `. . ${quantity} . . `122 } 123 }124 closingDelimiter = ']';125 }126 } else if (reason === 'illegible') {127 const beforeText = isLine ? '(Traces of ' : '. . '128 const afterText = isLine ? ' lines)' : ' . .'129 if (extent === 'unknown') {130 elementText = isLine ?131 `${beforeText.trim()}${afterText}` :132 `${beforeText}?${afterText}`133 } else if (atLeast || atMost) {134 elementText = `${beforeText}${atLeast}-${atMost}${afterText}`135 } else if (quantity && quantity < 5) {136 elementText = '. '.repeat(quantity).trim();137 } else if (quantity && quantity >= 5) {138 elementText = `${beforeText}${precisionOutput}${quantity}${afterText}`139 }140 } else if (reason === 'omitted') {141 elementText = '<- - ? - ';142 closingDelimiter = '->'143 }144 node.prepend(elementText);145 node.append(closingDelimiter)146 },'unclear': (node) => {147 //̊ is equivalent to U+030A and \u030A148 const combiningChar = isLatinSpecifiedInAncestor(node)?'\u030A':'\u0323'149 node.textContent = node.textContent.split('').map(character => character + combiningChar).join('').trim();150 }151 }152}153const isLatinSpecifiedInAncestor = (node) => {154 if (! node) {155 return false156 } else if (node.getAttribute('xml:lang') === 'xpu-Latn') {157 return true158 } else {159 return isLatinSpecifiedInAncestor(node.parentNode);160 }161}...
assortment.js
Source:assortment.js
1$(function() {2 $('#loading').fadeOut();3 // JSON input4 var json_input_question = { "academic_id": "1", "academic_year": "2020 - 2021", "grade_id": "", "grade_name": "", "subject_id": "0", "subject_name": "Urdu", "topic_name": "", "filter_tags": [], "question_html": "اÛÙÛÙÙÙÛٹدددد Ù¾Û Ù٠اÙÙÛ", "question_details": "<p>dfsdfsdfsfdfsd</p>", "rondomize_options": true, "allow_attachment": true, "allow_partial_credit": true, "maximum_marks": "10", "maximum_time": "50", "question_images": {}, "elements": [{ "text": "Apple", "order": "00001" }, { "image_name": "cat.png", "image": "ahmed_teacher_review/img/cat.png", "text": "", "order": "00002" }, { "image_name": "ball.png", "image": "ahmed_teacher_review/img/ball.png", "text": "Ball", "order": "00005" }, { "image_name": "frog.png", "image": "ahmed_teacher_review/img/frog.png", "text": "ضÙدع", "order": "00009" }] }5 var json_input = {6 "sorted": [7 { "order": 1, "text": "Apple" },8 { "order": 2, "image": "ahmed_teacher_review/img/cat.png", "image_name": "cat.png", "text": "" },9 { "order": 3, "image": "ahmed_teacher_review/img/ball.png", "image_name": "ball.png", "text": "Ball" },10 { "order": 4, "image": "ahmed_teacher_review/img/frog.png", "image_name": "frog.png", "text": "ضÙدع" }11 ],12 "random": [13 { "order": 1, "text": "Apple" },14 { "order": 2, "image": "ahmed_teacher_review/img/frog.png", "image_name": "frog.png", "text": "ضÙدع" },15 { "order": 3, "image": "ahmed_teacher_review/img/cat.png", "image_name": "cat.png", "text": "" },16 { "order": 4, "image": "ahmed_teacher_review/img/ball.png", "image_name": "ball.png", "text": "Ball" }17 ],18 "screenshot": ""19 }20 // Sorting According Orders21 function compareElements(a, b) {22 if (a.order < b.order) {23 return -1;24 }25 if (a.order > b.order) {26 return 1;27 }28 return 0;29 }30 // set question text31 $(".questionText").html(json_input_question.question_html)32 $(".questionDetails").html(json_input_question.question_details)33 // var inputElements = json_input_question.elements34 sortedElements = json_input["sorted"].sort(compareElements)35 var kanbanFixed = new jKanban({36 element: '#sorted',37 gutter: '10px',38 dragBoards: false,39 dragItems: false,40 boards: [{41 'id': 'fixed',42 'title': 'Sorted',43 'class': 'success',44 }]45 })46 for (var i = 0; i < sortedElements.length; i++) {47 // Image & Text48 if (sortedElements[i]["image"] != undefined && sortedElements[i]["text"] != "") {49 let elementImg = "<div class='col-4 elementImg'><img src='" + sortedElements[i]["image"] + "' alt='" + sortedElements[i]["image_name"] + "'></div>"50 let elementText = "<div class='col-8 elementText'><span>" + sortedElements[i]["text"] + "</span></div>"51 kanbanFixed.addElement("fixed", { 'title': '<div class="row" data-id="' + sortedElements[i]["order"] + '">' + elementImg + elementText + '</div>' })52 } else if (sortedElements[i]["image"] != undefined) {53 let elementImg = "<div class=' col-4 elementImg'><img src='" + sortedElements[i]["image"] + "' alt='" + sortedElements[i]["image_name"] + "'></div>"54 kanbanFixed.addElement("fixed", { 'title': '<div class="row" data-id="' + sortedElements[i]["order"] + '">' + elementImg + '</div>' })55 } else if (sortedElements[i]["text"] != "") {56 let elementText = "<div class='col-12 elementText'><span>" + sortedElements[i]["text"] + "</span></div>"57 kanbanFixed.addElement("fixed", { 'title': '<div class="row" data-id="' + sortedElements[i]["order"] + '">' + elementText + '</div>' })58 }59 }60 var kanbanDynamic = new jKanban({61 element: '#random',62 gutter: '10px',63 dragBoards: false,64 dragItems: false,65 boards: [{66 'id': 'dynamic',67 'title': 'Unsorted',68 'class': 'danger',69 }]70 })71 var randomizedElements = json_input["random"].sort(compareElements)72 for (var i = 0; i < randomizedElements.length; i++) {73 // Image & Text74 if (randomizedElements[i]["image"] != undefined && randomizedElements[i]["text"] != "") {75 let elementImg = "<div class='col-4 elementImg'><img src='" + randomizedElements[i]["image"] + "' alt='" + randomizedElements[i]["image_name"] + "'></div>"76 let elementText = "<div class='col-8 elementText'><span>" + randomizedElements[i]["text"] + "</span></div>"77 kanbanDynamic.addElement("dynamic", { 'title': '<div class="row" data-id="' + randomizedElements[i]["order"] + '">' + elementImg + elementText + '</div>' })78 } else if (randomizedElements[i]["image"] != undefined) {79 let elementImg = "<div class=' col-4 elementImg'><img src='" + randomizedElements[i]["image"] + "' alt='" + randomizedElements[i]["image_name"] + "'></div>"80 kanbanDynamic.addElement("dynamic", { 'title': '<div class="row" data-id="' + randomizedElements[i]["order"] + '">' + elementImg + '</div>' })81 } else if (randomizedElements[i]["text"] != "") {82 let elementText = "<div class='col-12 elementText'><span>" + randomizedElements[i]["text"] + "</span></div>"83 kanbanDynamic.addElement("dynamic", { 'title': '<div class="row" data-id="' + randomizedElements[i]["order"] + '">' + elementText + '</div>' })84 }85 }86 totalRowsDynamic = $(".kanban-board[data-id='dynamic'] .kanban-item .row")87 totalRowsFixed = $(".kanban-board[data-id='fixed'] .kanban-item .row")88 var totalMarks = totalRowsDynamic.length;89 var studentMarks = 0;90 for (i = 1; i <= totalRowsDynamic.length; i++) {91 var dynamicItem, fixedItem = "";92 if ($(".kanban-board[data-id='dynamic'] .kanban-item .row[data-id='" + i + "']").find(".elementText").length) {93 dynamicItem = $(".kanban-board[data-id='dynamic'] .kanban-item .row[data-id='" + i + "']").find(".elementText").text()94 } else if ($(".kanban-board[data-id='dynamic'] .kanban-item .row[data-id='" + i + "']").find(".elementImg img").length) {95 dynamicItem = $(".kanban-board[data-id='dynamic'] .kanban-item .row[data-id='" + i + "']").find(".elementImg img").attr("alt")96 }97 if ($(".kanban-board[data-id='fixed'] .kanban-item .row[data-id='" + i + "']").find(".elementText").length) {98 fixedItem = $(".kanban-board[data-id='fixed'] .kanban-item .row[data-id='" + i + "']").find(".elementText").text()99 } else if ($(".kanban-board[data-id='fixed'] .kanban-item .row[data-id='" + i + "']").find(".elementImg img").length) {100 fixedItem = $(".kanban-board[data-id='fixed'] .kanban-item .row[data-id='" + i + "']").find(".elementImg img").attr("alt")101 }102 if (dynamicItem == fixedItem) {103 $(".kanban-board[data-id='dynamic'] .kanban-item .row[data-id='" + i + "']").parents(".kanban-item").css({ "background-color": "#1BC5BD", "color": "#fff" })104 studentMarks += 1;105 } else {106 $(".kanban-board[data-id='dynamic'] .kanban-item .row[data-id='" + i + "']").parents(".kanban-item").css({ "background-color": "#F64E60", "color": "#fff" })107 }108 }109 $(".studentMarks").text(`${studentMarks} of ${totalMarks}`)110 $("#submitReview").on("click", function() {111 outputJSON = JSON.stringify({112 "teacher_review": $("#teacherReview").val(),113 "teacher_marks": $(".teacherMarks").val()114 })115 console.log(outputJSON);116 })...
test_work.js
Source:test_work.js
1import Home from '../pageObjects/homePage'2import User from '../pageObjects/user'3import Auth from '../pageObjects/authPage'4import Profile from '../pageObjects/profilePage'5import basePage from '../pageObjects/basePage'6const homePage = new Home()7const user = new User()8const authPage = new Auth()9const profilePage = new Profile()10authPage.setupLocators()11homePage.setupLocators()12profilePage.setupLocators()13let userProfileDetails = {14 name: '',15 email: '',16 password: '',17 phone: '',18 address: '',19 supportPin: '',20 newsLetter: ''21}22const registeredUser = {23 email: 'ssls.automation+666@gmail.com',24 password: '123456'25}26const nonRegisteredUser = {27 email: 'random_email@gmail.com',28 password: '123456'29}30Given('I am not registered user', () => {31 user.email = nonRegisteredUser.email32 user.password = nonRegisteredUser.password33});34Given('I am registered user', () => {35 user.email = registeredUser.email36 user.password = registeredUser.password37});38Given('I am logged in user', () => {39 user.email = registeredUser.email40 user.password = registeredUser.password41 homePage.openPageURL()42 homePage.getFooterElement().should('be.visible')43 homePage.getLoginText().should('be.visible').click()44 authPage.getEmailInput().should('be.visible')45 authPage.getPasswordInput().should('be.visible')46 authPage.getEmailInput().type(user.email)47 authPage.getPasswordInput().type(user.password)48 authPage.getLoginButton().should('be.visible').click()49 homePage.getLoggedInUserIcon().should('be.visible')50 homePage.getLoginText().should('not.be.visible')51});52When('I open Home page', () => {53 homePage.openPageURL()54});55Then('I should see Home page', () => {56 homePage.getFooterElement().should('be.visible')57});58When('I click LOG IN text', () => {59 homePage.getLoginText().should('be.visible').click()60});61Then('I should see Authorization page', () => {62 authPage.getAuthPageHeader().should('be.visible')63 cy.xpath(authPage.locators.authPageHeader).should('be.visible')64});65Then('I should see credentials inputs', () => {66 authPage.getEmailInput().should('be.visible')67 authPage.getPasswordInput().should('be.visible')68});69When('I enter credentials', () => {70 authPage.getEmailInput().type(user.email)71 authPage.getPasswordInput().type(user.password)72});73When('I click on eye icon', () => {74 authPage.getEyeIcon().should('be.visible').click()75});76Then('I should see entered password', () => {77 authPage.getPasswordInput().should('have.attr', 'type', 'text')78});79When('I click on Login button', () => {80 authPage.getLoginButton().should('be.visible').click()81});82Then('I should see error message', () => {83 authPage.getErrorMessage().should('be.visible')84});85Then('I should see User icon', () => {86 homePage.getLoggedInUserIcon().should('be.visible')87 homePage.getLoginText().should('not.be.visible')88});89When('I click dropdown triangle', () => {90 homePage.getDropdownTriangle().should('be.visible').click()91});92When('I select Profile', () => {93 homePage.getProfileDropdownOption().should('be.visible').click()94});95Then('I should see Profile page', () => {96 profilePage.getProfilePageHeader().should('be.visible')97});98Then('I should see Profile details', () => {99 profilePage.getElementText(profilePage.locators.emailField)100 .then((elementText) => {101 userProfileDetails.email = elementText102 })103 profilePage.getElementText(profilePage.locators.phoneField)104 .then((elementText) => {105 userProfileDetails.phone = elementText106 })107 profilePage.getElementText(profilePage.locators.nameField)108 .then((elementText) => {109 userProfileDetails.name = elementText110 })111 profilePage.getElementText(profilePage.locators.addressField)112 .then((elementText) => {113 userProfileDetails.address = elementText114 })115 profilePage.getElementText(profilePage.locators.supportPinField)116 .then((elementText) => {117 userProfileDetails.supportPin = elementText118 })119 profilePage.getPasswordField()120 .then((elementText) => {121 if (elementText !== '') { userProfileDetails.password = 'true' }122 else { userProfileDetails.password = 'false' }123 })124 profilePage.getNewsLetterButton()125 .then((element) => {126 if (element.is("enabled")) { userProfileDetails.newsLetter = 'true' }127 else { userProfileDetails.newsLetter = 'false' }128 })129});130When('I select Log Out', () => {131 homePage.getLogOutDropdownOption().click()132});133Then('I should see the same Profile details as before', () => {134 profilePage.getElementText(profilePage.locators.emailField)135 .then((elementText) => {136 assert.equal(userProfileDetails.email, elementText)137 })138 profilePage.getElementText(profilePage.locators.phoneField)139 .then((elementText) => {140 assert.equal(userProfileDetails.phone, elementText)141 })142 profilePage.getElementText(profilePage.locators.nameField)143 .then((elementText) => {144 assert.equal(userProfileDetails.name, elementText)145 })146 profilePage.getElementText(profilePage.locators.addressField)147 .then((elementText) => {148 assert.equal(userProfileDetails.address, elementText)149 })150 profilePage.getElementText(profilePage.locators.supportPinField)151 .then((elementText) => {152 assert.equal(userProfileDetails.supportPin, elementText)153 })154 profilePage.getPasswordField()155 .then((elementText) => {156 let passwordState157 if (elementText !== '') {158 passwordState = 'true'159 }160 else {161 passwordState = 'false'162 }163 assert.equal(userProfileDetails.password, passwordState)164 })165 profilePage.getNewsLetterButton()166 .then((element) => {167 let newsLetterState168 if (element.is("enabled")) { newsLetterState = 'true' }169 else { newsLetterState = 'false' }170 assert.equal(userProfileDetails.newsLetter, newsLetterState)171 })...
jquery.truncate.js
Source:jquery.truncate.js
1(function ($) {2 'use strict';3 function findTruncPoint(dim, max, txt, start, end, $worker, token, reverse) {4 var makeContent = function (content) {5 $worker.text(content);6 $worker[reverse ? 'prepend' : 'append'](token);7 };8 var opt1, opt2, mid, opt1dim, opt2dim;9 if (reverse) {10 opt1 = start === 0 ? '' : txt.slice(-start);11 opt2 = txt.slice(-end);12 } else {13 opt1 = txt.slice(0, start);14 opt2 = txt.slice(0, end);15 }16 if (max < $worker.html(token)[dim]()) {17 return 0;18 }19 makeContent(opt2);20 opt1dim = $worker[dim]();21 makeContent(opt1);22 opt2dim = $worker[dim]();23 if (opt1dim < opt2dim) {24 return end;25 }26 mid = parseInt((start + end) / 2, 10);27 opt1 = reverse ? txt.slice(-mid) : txt.slice(0, mid);28 makeContent(opt1);29 if ($worker[dim]() === max) {30 return mid;31 }32 if ($worker[dim]() > max) {33 end = mid - 1;34 } else {35 start = mid + 1;36 }37 return findTruncPoint(dim, max, txt, start, end, $worker, token, reverse);38 }39 $.fn.truncate = function (options) {40 // backward compatibility41 if (options && !!options.center && !options.side) {42 options.side = 'center';43 delete options.center;44 }45 if (options && !(/^(left|right|center)$/).test(options.side)) {46 delete options.side;47 }48 var defaults = {49 width: 'auto',50 token: '…',51 side: 'right',52 addclass: false,53 addtitle: false,54 multiline: false,55 assumeSameStyle: false56 };57 options = $.extend(defaults, options);58 var fontCSS;59 var $element;60 var $truncateWorker;61 var elementText;62 63 if (options.assumeSameStyle) {64 $element = $(this[0]);65 fontCSS = {66 'fontFamily': $element.css('fontFamily'),67 'fontSize': $element.css('fontSize'),68 'fontStyle': $element.css('fontStyle'),69 'fontWeight': $element.css('fontWeight'),70 'font-variant': $element.css('font-variant'),71 'text-indent': $element.css('text-indent'),72 'line-height': $element.css('line-height'),73 'text-transform': $element.css('text-transform'),74 'letter-spacing': $element.css('letter-spacing'),75 'word-spacing': $element.css('word-spacing'),76 'display': 'none'77 };78 $truncateWorker = $('<span/>')79 .css(fontCSS)80 .appendTo('body');81 }82 return this.each(function () {83 $element = $(this);84 elementText = $element.text();85 if (!options.assumeSameStyle) {86 fontCSS = {87 'fontFamily': $element.css('fontFamily'),88 'fontSize': $element.css('fontSize'),89 'fontStyle': $element.css('fontStyle'),90 'fontWeight': $element.css('fontWeight'),91 'font-variant': $element.css('font-variant'),92 'text-indent': $element.css('text-indent'),93 'line-height': $element.css('line-height'),94 'text-transform': $element.css('text-transform'),95 'letter-spacing': $element.css('letter-spacing'),96 'word-spacing': $element.css('word-spacing'),97 'display': 'none'98 };99 $truncateWorker = $('<span/>')100 .css(fontCSS)101 .text(elementText)102 .appendTo('body');103 } else {104 $truncateWorker.text(elementText);105 }106 107 var originalWidth = $truncateWorker.width();108 var truncateWidth = parseInt(options.width, 10) || $element.width();109 var dimension = 'width';110 var truncatedText, originalDim, truncateDim;111 if (options.multiline) {112 $truncateWorker.width($element.width());113 dimension = 'height';114 originalDim = $truncateWorker.height();115 truncateDim = $element.height() + 1;116 }117 else {118 originalDim = originalWidth;119 truncateDim = truncateWidth;120 }121 truncatedText = {before: '', after: ''};122 if (originalDim > truncateDim) {123 var truncPoint, truncPoint2;124 $truncateWorker.text('');125 if (options.side === 'left') {126 truncPoint = findTruncPoint(127 dimension, truncateDim, elementText, 0, elementText.length,128 $truncateWorker, options.token, true129 );130 truncatedText.after = elementText.slice(-1 * truncPoint);131 } else if (options.side === 'center') {132 truncateDim = parseInt(truncateDim / 2, 10) - 1;133 truncPoint = findTruncPoint(134 dimension, truncateDim, elementText, 0, elementText.length,135 $truncateWorker, options.token, false136 );137 truncPoint2 = findTruncPoint(138 dimension, truncateDim, elementText, 0, elementText.length,139 $truncateWorker, '', true140 );141 truncatedText.before = elementText.slice(0, truncPoint);142 truncatedText.after = elementText.slice(-1 * truncPoint2);143 } else if (options.side === 'right') {144 truncPoint = findTruncPoint(145 dimension, truncateDim, elementText, 0, elementText.length,146 $truncateWorker, options.token, false147 );148 truncatedText.before = elementText.slice(0, truncPoint);149 }150 if (options.addclass) {151 $element.addClass(options.addclass);152 }153 if (options.addtitle) {154 $element.attr('title', elementText);155 }156 truncatedText.before = $truncateWorker157 .text(truncatedText158 .before).html();159 truncatedText.after = $truncateWorker160 .text(truncatedText.after)161 .html();162 $element.empty().html(163 truncatedText.before + options.token + truncatedText.after164 );165 }166 if (!options.assumeSameStyle) {167 $truncateWorker.remove();168 }169 });170 171 if (options.assumeSameStyle) {172 $truncateWorker.remove();173 }174 };...
index.js
Source:index.js
1/*jslint node : true, nomen: true, plusplus: true, vars: true, eqeq: true,*/2"use strict";3var expat = require('node-expat'),4 Transform = require('stream').Transform,5 util = require('util');6function _parser(path, readable) {7 var saxStream = new expat.Parser('UTF-8');8 var current = {},9 stack = [current],10 elementText = false;11 function parent() {12 return stack.slice(-1)[0];13 }14 function appendChild(name, obj) {15 var p = parent()[name];16 if (p) {17 if (Array.isArray(p)) {18 p.push(obj);19 } else {20 parent()[name] = [p, obj];21 }22 } else {23 parent()[name] = obj;24 }25 }26 function startElement(name, attrs) {27 current = {};28 if (attrs) {29 Object.keys(attrs).forEach(function (att) {30 current['$' + att] = attrs[att];31 });32 }33 stack.push(current);34 elementText = true;35 }36 function endElement(name) {37 current = stack.pop();38 if (elementText && 'string' === typeof elementText) {39 if (Object.keys(current) != 0) {40 current._ = elementText;41 } else {42 current = elementText;43 }44 }45 appendChild(name, current);46 elementText = false;47 if (name == path) {48 readable.push(current);49 }50 }51 function chars(text) {52 if (elementText) {53 elementText = text;54 }55 }56 saxStream57 .on('startElement', startElement)58 .on('endElement', endElement)59 .on('text', chars)60 .on('end', function () {61 if (path == '/') {62 readable.push(current);63 }64 }).on('error', function (e) {65 readable.emit('error', new Error(saxStream.getError()));66 });67 return saxStream;68}69function XMLParseStream(options) {70 if (!(this instanceof XMLParseStream)) {71 return new XMLParseStream(options);72 }73 Transform.call(this, options);74 this._writableState.objectMode = false;75 this._readableState.objectMode = true;76 this._parser = _parser(options, this);77}78util.inherits(XMLParseStream, Transform);79XMLParseStream.prototype._transform = function (chunk, encoding, cb) {80 this._parser.write(chunk);81 cb();82};83XMLParseStream.prototype._flush = function (cb) {84 this._parser.end();85 cb();86};87module.exports = {88 parse: function (opts) {89 return new XMLParseStream(opts);90 }...
text.js
Source:text.js
1var regExpNbspEntity = / /gi;2var regExpNbspHex = /\xA0/g;3var regExpSpaces = /\s+([^\s])/gm;4/**5 * Collects the text content of a given element.6 * 7 * @param node the element8 * @param trim whether to remove trailing whitespace chars9 * @param singleSpaces whether to convert multiple whitespace chars into a single space character10 */11export default function text(node, trim, singleSpaces) {12 if (trim === void 0) {13 trim = true;14 }15 if (singleSpaces === void 0) {16 singleSpaces = true;17 }18 var elementText = '';19 if (node) {20 elementText = (node.textContent || '').replace(regExpNbspEntity, ' ').replace(regExpNbspHex, ' ');21 if (trim) {22 elementText = elementText.trim();23 }24 if (singleSpaces) {25 elementText = elementText.replace(regExpSpaces, ' $1');26 }27 }28 return elementText;...
Using AI Code Generation
1const { elementText } = require('playwright-internal');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const element = await page.$('input[name="q"]');8 const text = await elementText(element);9 console.log(text);10 await browser.close();11})();
Using AI Code Generation
1const { elementText } = require('playwright/lib/server/dom.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const element = await page.$('input[name="q"]');8 const text = await elementText(page.mainFrame(), element);9 console.log(text);10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 const element = await page.$('input[name="q"]');18 const text = await element.textContent();19 console.log(text);20 await browser.close();21})();
Using AI Code Generation
1const { elementText } = require('playwright/lib/server/dom.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const element = await page.$('h1');7 const text = await elementText(element);8 console.log(text);9 await browser.close();10})();11async function elementText(element) {12 if (element.nodeType === Node.TEXT_NODE)13 return element.nodeValue;14 if (element.nodeType !== Node.ELEMENT_NODE)15 return '';16 const tagName = element.nodeName.toLowerCase();17 if (tagName === 'input' || tagName === 'textarea')18 return element.value;19 if (tagName === 'select')20 return element.value || element.options[element.selectedIndex].text;21 if (tagName === 'option')22 return element.text;23 if (tagName === 'br')24';25 if (element.isContentEditable)26 return element.textContent;27 return element.innerText;28}
Using AI Code Generation
1const { elementText } = require('@playwright/test');2const { test, expect } = require('@playwright/test');3test('elementText method test', async ({ page }) => {4 const text = await elementText(page, 'h1');5 expect(text).toBe('Playwright');6});7const { test, expect } = require('@playwright/test');8test('elementText method test', async ({ page }) => {9 const text = await page.evaluate(() => {10 return document.querySelector('h1').innerText;11 });12 expect(text).toBe('Playwright');13});14const { test, expect } = require('@playwright/test');15test('elementText method test', async ({ page }) => {16 const text = await page.textContent('h1');17 expect(text).toBe('Playwright');18});
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!