Best JavaScript code snippet using webdriverio-monorepo
board-widget.js
Source:board-widget.js
1import React, { useEffect, useState } from "react"2import Board from "./board"3import SideBar from '../side-bar/side-bar'4import "./board-widget.css"5const dict = require('an-array-of-english-words')6function BoardWidget({ players, setPlayers, getCurrentPlayer, turnCount, setTurnCount, setTurnScore }) {7 const [letters, setLetters] = useState([])8 const [skipCount, setSkipCount] = useState(0)9 const [mainWord, setMainWord] = useState([])10 const [previousMainWords, setPreviousMainWords] = useState([])11 const [words, setWords] = useState([])12 const [activeSquareCoords, setActiveSquareCoords] = useState([])13 const [wordDirection, setWordDirection] = useState("")14 const [boardState, setBoardState] = useState([])15 const [previousBoardStates, setPreviousBoardStates] = useState([/* 16 [{ letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },17 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},18 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},19 {letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false},20 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},21 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},22 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},23 {letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false},24 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},25 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},26 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},27 {letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false},28 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},29 {letter: "", scoreMultiplier: "", isBlank: false, isFocused: false},30 {letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false}],31 [],32 [],33 [],34 [],35 [],36 [],37 [],38 [],39 [],40 [],41 [],42 [],43 [],44 [],45 */46 ])47 const [lastBoardState, setLastBoardState] = useState([[48 // ROW 149 [{ letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },50 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },51 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },52 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },53 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },54 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },55 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },56 { letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },57 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },58 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },59 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },60 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },61 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },62 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },63 { letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },],64 // ROW 265 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },66 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },67 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },68 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },69 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },70 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },71 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },72 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },73 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },74 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },75 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },76 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },77 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },78 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },79 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],80 // ROW 381 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },82 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },83 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },84 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },85 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },86 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },87 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },88 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },89 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },90 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },91 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },92 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },93 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },94 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },95 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],96 // ROW 497 [{ letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },98 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },99 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },100 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },101 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },102 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },103 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },104 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },105 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },106 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },107 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },108 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },109 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },110 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },111 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },],112 // ROW 5113 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },114 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },115 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },116 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },117 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },118 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },119 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },120 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },121 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },122 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },123 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },124 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },125 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },126 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },127 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],128 // ROW 6129 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },130 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },131 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },132 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },133 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },134 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },135 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },136 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },137 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },138 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },139 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },140 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },141 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },142 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },143 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],144 // ROW 7145 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },146 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },147 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },148 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },149 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },150 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },151 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },152 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },153 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },154 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },155 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },156 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },157 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },158 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },159 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],160 // ROW 8161 [{ letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },162 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },163 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },164 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },165 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },166 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },167 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },168 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },169 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },170 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },171 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },172 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },173 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },174 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },175 { letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },],176 // ROW 9177 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },178 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },179 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },180 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },181 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },182 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },183 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },184 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },185 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },186 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },187 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },188 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },189 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },190 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },191 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],192 // ROW 10193 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },194 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },195 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },196 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },197 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },198 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },199 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },200 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },201 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },202 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },203 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },204 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },205 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },206 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },207 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],208 // ROW 11209 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },210 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },211 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },212 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },213 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },214 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },215 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },216 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },217 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },218 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },219 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },220 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },221 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },222 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },223 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],224 // ROW 12225 [{ letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },226 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },227 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },228 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },229 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },230 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },231 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },232 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },233 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },234 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },235 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },236 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },237 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },238 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },239 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },],240 // ROW 13241 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },242 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },243 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },244 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },245 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },246 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },247 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },248 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },249 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },250 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },251 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },252 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },253 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },254 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },255 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],256 // ROW 14257 [{ letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },258 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },259 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },260 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },261 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },262 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },263 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },264 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },265 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },266 { letter: "", scoreMultiplier: "tl", isBlank: false, isFocused: false },267 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },268 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },269 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },270 { letter: "", scoreMultiplier: "dw", isBlank: false, isFocused: false },271 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },],272 // ROW 15273 [{ letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },274 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },275 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },276 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },277 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },278 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },279 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },280 { letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },281 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },282 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },283 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },284 { letter: "", scoreMultiplier: "dl", isBlank: false, isFocused: false },285 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },286 { letter: "", scoreMultiplier: "", isBlank: false, isFocused: false },287 { letter: "", scoreMultiplier: "tw", isBlank: false, isFocused: false },],288 ]])289 const [remainingLetters, setRemainingLetters] = useState({290 "a": 9, "b": 2, "c": 2, "d": 4, "e": 12, "f": 2,291 "g": 3, "h": 2, "i": 9, "j": 1, "k": 1, "l": 4,292 "m": 2, "n": 6, "o": 8, "p": 2, "q": 1, "r": 6,293 "s": 4, "t": 6, "u": 4, "v": 2, "w": 2, "x": 1,294 "y": 2, "z": 1, " ": 2,295 })296 // set the focus of the square in board state when the active square changes297 useEffect(() => {298 if (activeSquareCoords.length !== 0) {299 const [x, y] = activeSquareCoords300 const updatedBoardArray = boardState.map((row, rowIndex) =>301 row.map((square, squareIndex) => {302 if (rowIndex === y && squareIndex === x) {303 return { ...square, isFocused: true }304 } else {305 return { ...square, isFocused: false }306 }307 })308 )309 setBoardState([...updatedBoardArray])310 }311 }, [activeSquareCoords])312 useEffect(() => {313 if (letters.length === 0) {314 setMainWord([])315 setWords([])316 }317 }, [letters])318 const increaseNumberOfSkips = () => {319 setSkipCount(skipCount + 1)320 setTurnCount(turnCount + 1)321 setLastBoardState([...lastBoardState, lastBoardState[lastBoardState.length - 1]])322 }323 const calculateMovePoints = () => {324 let totalPoints = 0325 if (mainWord.length > 1) {326 totalPoints += calculateWordPoints(mainWord)327 }328 for (const wordObj of words) {329 totalPoints += calculateWordPoints(wordObj)330 }331 if (letters.length === 7) {332 totalPoints += 50333 }334 setTurnScore(totalPoints)335 }336 const calculateWordPoints = (wordObj) => {337 let points = 0338 let twCount = 0339 let dwCount = 0340 for (const obj of wordObj) {341 const letterValue = obj.isBlank ? 0 : getLetterValue(obj.letter)342 switch (obj.scoreMultiplier) {343 case "dl":344 points += letterValue * 2345 break346 case "tl":347 points += letterValue * 3348 break349 case "dw":350 dwCount += 1351 points += letterValue352 break353 case "tw":354 twCount += 1355 points += letterValue356 break357 default:358 points += letterValue359 }360 }361 if (twCount !== 0) {362 points *= twCount * 3363 }364 if (dwCount !== 0) {365 points *= dwCount * 2366 }367 return points;368 }369 const makeLetterMove = (letter, isBlank = false) => {370 const [x, y] = activeSquareCoords371 const letterObject = { letter: letter, scoreMultiplier: boardState[y][x].scoreMultiplier, isBlank: isBlank }372 updateBoard(letterObject)373 getWordsFormed(letterObject)374 setPreviousBoardStates([...previousBoardStates, boardState])375 setLetters([...letters, letterObject])376 shiftFocus()377 }378 const getWordsFormed = (letterObject) => {379 const horizontalSquares = appendHorizontalSquares(letterObject)380 const verticalSquares = appendVerticalSquares(letterObject)381 let newMainWord382 switch (wordDirection) {383 case "right":384 if (horizontalSquares.length !== 0) {385 newMainWord = [...mainWord, ...horizontalSquares]386 setMainWord(newMainWord)387 setPreviousMainWords([...previousMainWords, newMainWord])388 } else {389 newMainWord = [...mainWord, letterObject]390 setMainWord(newMainWord)391 setPreviousMainWords([...previousMainWords, newMainWord])392 }393 if (verticalSquares.length !== 0) {394 setWords([...words, verticalSquares])395 }396 break;397 case "down":398 if (verticalSquares.length !== 0) {399 newMainWord = [...mainWord, ...verticalSquares]400 setMainWord(newMainWord)401 setPreviousMainWords([...previousMainWords, newMainWord])402 } else {403 newMainWord = [...mainWord, letterObject]404 setMainWord(newMainWord)405 setPreviousMainWords([...previousMainWords, newMainWord])406 }407 if (horizontalSquares.length !== 0) {408 setWords([...words, horizontalSquares])409 }410 break;411 case "":412 const wordsArray = []413 if (horizontalSquares.length !== 0) {414 wordsArray.push(horizontalSquares)415 }416 if (verticalSquares.length !== 0) {417 wordsArray.push(verticalSquares)418 }419 setLetters([letterObject])420 setWords([...wordsArray])421 break;422 }423 }424 const appendHorizontalSquares = (letterObject) => {425 const lettersToRight = getSquaresToRight(...activeSquareCoords)426 const squaresToRight = lettersToRight.map((letter) => {427 return { letter: letter.letter, scoreMultiplier: "", isBlank: letter.isBlank };428 })429 const lettersToLeft = getSquaresToLeft(...activeSquareCoords).reverse()430 const squaresToLeft = lettersToLeft.map((letter) => {431 return { letter: letter.letter, scoreMultiplier: "", isBlank: letter.isBlank };432 })433 if (squaresToLeft.length !== 0 || squaresToRight.length !== 0) {434 return [...squaresToLeft, letterObject, ...squaresToRight];435 }436 return [];437 }438 const appendVerticalSquares = (letterObject) => {439 const lettersBelow = getSquaresBelow(...activeSquareCoords)440 const squaresBelow = lettersBelow.map((letter) => {441 return { letter: letter.letter, scoreMultiplier: "", isBlank: letter.isBlank };442 })443 const lettersAbove = getSquaresAbove(...activeSquareCoords).reverse()444 const squaresAbove = lettersAbove.map((letter) => {445 return { letter: letter.letter, scoreMultiplier: "", isBlank: letter.isBlank };446 })447 if (squaresAbove.length !== 0 || squaresBelow.length !== 0) {448 return [...squaresAbove, letterObject, ...squaresBelow];449 }450 return [];451 }452 const getSquaresToRight = (x, y) => {453 const nextX = x + 1454 if (x < 14) {455 const square = boardState[y][nextX]456 const { isFocused, scoreMultiplier, ...letterObj } = square457 if (letterObj.letter !== "") {458 return [letterObj, ...getSquaresToRight(nextX, y)];459 }460 }461 return [];462 }463 const getSquaresToLeft = (x, y) => {464 if (wordDirection !== "right" || mainWord.length === 0) {465 const nextX = x - 1466 if (x > 0) {467 const square = boardState[y][nextX]468 const { isFocused, scoreMultiplier, ...letterObj } = square469 if (letterObj.letter !== "") {470 return [letterObj, ...getSquaresToLeft(nextX, y)];471 }472 }473 }474 return [];475 }476 const getSquaresBelow = (x, y) => {477 const nextY = y + 1478 if (y < 14) {479 const square = boardState[nextY][x]480 const { isFocused, scoreMultiplier, ...letterObj } = square481 if (letterObj.letter !== "") {482 return [letterObj, ...getSquaresBelow(x, nextY)];483 }484 }485 return [];486 }487 const getSquaresAbove = (x, y) => {488 if (wordDirection !== "down" || mainWord.length === 0) {489 const nextY = y - 1490 if (y > 0) {491 const square = boardState[nextY][x]492 const { isFocused, scoreMultiplier, ...letterObj } = square493 if (letterObj.letter !== "") {494 return [letterObj, ...getSquaresAbove(x, nextY)];495 }496 }497 }498 return [];499 }500 const isSquareEmpty = (x, y) => {501 return (boardState[y][x].letter === "")502 }503 const handleRightArrow = (e) => {504 e.preventDefault()505 if (letters.length < 1) {506 setWordDirection("right")507 }508 }509 const handleDownArrow = (e) => {510 e.preventDefault()511 if (letters.length < 1) {512 setWordDirection("down")513 }514 }515 const shiftFocus = () => {516 if (wordDirection !== "") {517 const newCoords = getNextAvailableSquare(...activeSquareCoords)518 setActiveSquareCoords(newCoords)519 }520 }521 const getNextAvailableSquare = (x, y) => {522 switch (wordDirection) {523 case "right":524 if (x < 14) {525 const nextX = x + 1526 if (isSquareEmpty(nextX, y)) {527 return [nextX, y];528 } else {529 return getNextAvailableSquare(nextX, y);530 }531 }532 break533 case "down":534 if (y < 14) {535 const nextY = y + 1536 if (isSquareEmpty(x, nextY)) {537 return [x, nextY];538 } else {539 return getNextAvailableSquare(x, nextY);540 }541 }542 break543 default:544 break545 }546 return activeSquareCoords;547 }548 const clearFocus = () => {549 setActiveSquareCoords([])550 const updatedBoardArray = boardState.map((row) =>551 row.map((square) => {552 return { ...square, isFocused: false }553 })554 )555 setBoardState(updatedBoardArray)556 }557 const getLetterValue = (letter) => {558 switch (letter.toLowerCase()) {559 case 'a': case 'e': case 'i': case 'l': case 'n': case 'o': case 'r': case 's': case 't': case 'u':560 return 1;561 case 'd': case 'g':562 return 2;563 case 'b': case 'c': case 'm': case 'p':564 return 3;565 case 'f': case 'h': case 'v': case 'w': case 'y':566 return 4;567 case 'k':568 return 5;569 case 'j': case 'x':570 return 8;571 case 'q': case 'z':572 return 10;573 case ' ':574 return 0;575 default:576 return null;577 }578 }579 const updateRemainingLetters = (letterToRemove) => {580 const [x, y] = activeSquareCoords581 const currentLetter = boardState[y][x].letter.toLowerCase()582 const lowerCaseLetterToRemove = letterToRemove.toLowerCase()583 const updatedRemainingLetters = { ...remainingLetters }584 if (currentLetter === "") {585 updatedRemainingLetters[lowerCaseLetterToRemove] -= 1586 } else if (currentLetter !== letterToRemove) {587 updatedRemainingLetters[currentLetter] += 1588 updatedRemainingLetters[lowerCaseLetterToRemove] -= 1589 }590 setRemainingLetters(updatedRemainingLetters)591 }592 // retuns an array of the board with a letter placed at coords x, y593 const updateBoard = (letterObject) => {594 const [x, y] = activeSquareCoords595 const updatedBoardArray = boardState.map((row, rowIndex) =>596 row.map((square, squareIndex) => {597 if (rowIndex === y && squareIndex === x) {598 return letterObject599 } else {600 return square601 }602 })603 )604 setBoardState(updatedBoardArray)605 }606 const isLetterAvailable = (letter) => {607 const letterCount = remainingLetters[letter.toLowerCase()]608 if (letterCount > 0) {609 return true610 } else {611 alert(`'${(letter === " ") ? "BLANK" : letter.toUpperCase()}' tile is not available.`)612 return false613 }614 }615 const getFocusedSquareCoords = (board) => {616 let coords617 board.map((row, y) => {618 row.map((square, x) => {619 if (square.isFocused) {620 coords = [x, y]621 }622 })623 })624 return coords625 }626 const generalReset = () => {627 setMainWord([])628 setWords([])629 clearFocus()630 setWordDirection("")631 setLetters([])632 setPreviousMainWords([])633 }634 const invalidWordsAlert = (invalidWords) => {635 const message = invalidWords.slice(0, invalidWords.length - 1).map((word, index) => {636 if (index <= invalidWords.length - 1) {637 return ` '${word}'`;638 }639 })640 alert(`${message} ${(invalidWords.length > 1) ? "and" : ""} '${invalidWords[invalidWords.length - 1]}' ${(invalidWords.length === 1) ? "is" : "are"} not in the english dictionary!`)641 }642 const getInvalidWords = () => {643 let invalidWords = []644 let allWords645 if (letters.length === 1 && wordDirection !== "") {646 allWords = [...words]647 } else if (letters.length === 1 && wordDirection === "") {648 allWords = [...words]649 } else {650 allWords = [mainWord, ...words]651 }652 for (const wordObj of allWords) {653 const wordArray = wordObj.map((obj) => obj.letter)654 const word = wordArray.join("")655 const regex = new RegExp(`^${word}$`)656 const matches = dict.filter(d => regex.test(d))657 if (matches.length === 0) {658 invalidWords.push(word)659 }660 }661 return invalidWords;662 }663 const isMoveValid = () => {664 if (turnCount - skipCount === 0) {665 if (boardState[7][7].letter === "") {666 alert("Word must pass through the center square.")667 return false;668 }669 if (letters.length < 2) {670 alert("Not enough letters.")671 return false;672 }673 } else {674 // check that the word is connected to other words675 if ((mainWord.length === letters.length) && words.length === 0) {676 alert("Word must connect to existing tiles.")677 return false;678 }679 if (wordDirection === "" && words.length === 0) {680 alert("Tiles must connect to existing tiles.")681 return false;682 }683 }684 if (!areWordsValid()) {685 return false;686 }687 return true;688 }689 const areWordsValid = () => {690 const invalidWords = getInvalidWords()691 if (invalidWords.length === 0) {692 return true;693 } else {694 invalidWordsAlert(invalidWords)695 return false;696 }697 }698 const handleSpaceKey = () => {699 if (isLetterAvailable(" ")) {700 let standInLetter701 while (true) {702 const regex = /[a-z]/703 standInLetter = prompt("Input a letter for the blank tile:")704 if (standInLetter !== null) {705 if (regex.test(standInLetter) && standInLetter.length === 1) {706 makeLetterMove(standInLetter, true)707 updateRemainingLetters(" ")708 break709 } else {710 alert(`"${standInLetter}" is not a valid letter.`)711 return;712 }713 } else {714 break715 }716 }717 }718 }719 const handleBackSpaceKey = () => {720 if (letters.length > 0) {721 const previousLetter = letters[letters.length - 1]722 setLetters(letters.slice(0, letters.length - 1))723 setBoardState(previousBoardStates[previousBoardStates.length - 1])724 setPreviousBoardStates(previousBoardStates.slice(0, previousBoardStates.length - 1))725 // update the possible playable letters726 if (previousLetter.isBlank) {727 remainingLetters[" "] = remainingLetters[" "] + 1728 } else {729 remainingLetters[`${previousLetter.letter}`] = remainingLetters[`${previousLetter.letter}`] + 1730 }731 const focusedSquareCoords = getFocusedSquareCoords(previousBoardStates[previousBoardStates.length - 1])732 switch (wordDirection) {733 case "down":734 if (getSquaresToLeft(...focusedSquareCoords).length !== 0 || getSquaresToRight(...focusedSquareCoords).length !== 0) {735 setWords([...words.slice(0, words.length - 1)])736 }737 setActiveSquareCoords(focusedSquareCoords)738 break;739 case "right":740 if (getSquaresAbove(...focusedSquareCoords).length !== 0 || getSquaresBelow(...focusedSquareCoords).length !== 0) {741 setWords([...words.slice(0, words.length - 1)])742 }743 setActiveSquareCoords(focusedSquareCoords)744 break;745 case "":746 setWords([])747 break;748 default:749 break;750 }751 if (previousMainWords.length > 1) {752 setMainWord(previousMainWords[previousMainWords.length - 2])753 setPreviousMainWords([...previousMainWords.slice(0, previousMainWords.length - 1)])754 } else {755 setMainWord(mainWord.slice(0, mainWord.length - 1))756 }757 } else {758 generalReset()759 }760 }761 const handleEnterKey = () => {762 if (letters.length > 0) {763 if (isMoveValid()) {764 setTurnCount(turnCount + 1)765 const clearedBoard = boardState.map((row) => {766 return row.map((square) => {767 square.isFocused = false768 return square;769 })770 })771 setLastBoardState([...lastBoardState, clearedBoard])772 calculateMovePoints()773 generalReset()774 }775 }776 }777 const handleKeyPressed = (e) => {778 const keyCode = e.keyCode779 if (activeSquareCoords.length !== 0) {780 if (isSquareEmpty(...activeSquareCoords) && letters.length < 7) {781 // key with a letter pressed782 if (keyCode >= 65 && keyCode <= 90) {783 const letter = String.fromCharCode(keyCode + 32)784 if (isLetterAvailable(letter)) {785 makeLetterMove(letter)786 updateRemainingLetters(letter)787 }788 }789 // space bar pressed790 if (keyCode === 32) {791 handleSpaceKey()792 }793 }794 // right arrow key pressed795 if (keyCode === 39) {796 handleRightArrow(e)797 }798 // down arrow key pressed799 if (keyCode === 40) {800 handleDownArrow(e)801 }802 // enter key pressed803 if (keyCode === 13) {804 handleEnterKey()805 }806 // backspace key pressed807 if (keyCode === 8) {808 handleBackSpaceKey()809 }810 // escape key pressed811 if (keyCode === 27) {812 if (letters.length === 0) {813 generalReset()814 }815 }816 }817 }818 const setOutput = () => {819 if (players.length !== 0) {820 return (821 <div id="board-widget" onKeyUp={(e) => handleKeyPressed(e)}>822 <Board823 boardState={boardState}824 setBoardState={setBoardState}825 wordDirection={wordDirection}826 setWordDirection={setWordDirection}827 activeSquareCoords={activeSquareCoords}828 setActiveSquareCoords={setActiveSquareCoords}829 letters={letters}830 />831 <SideBar832 turnCount={turnCount}833 setTurnCount={setTurnCount}834 activeSquareCoords={activeSquareCoords}835 setActiveSquareCoords={setActiveSquareCoords}836 wordDirection={wordDirection}837 handleRightArrow={handleRightArrow}838 handleDownArrow={handleDownArrow}839 letters={letters}840 setLetters={setLetters}841 generalReset={generalReset}842 increaseNumberOfSkips={increaseNumberOfSkips}843 lastBoardState={lastBoardState}844 setLastBoardState={setLastBoardState}845 setBoardState={setBoardState}846 setMainWord={setMainWord}847 setWords={setWords}848 setTurnScore={setTurnScore}849 players={players}850 setPlayers={setPlayers}851 getCurrentPlayer={getCurrentPlayer}852 skipCount={skipCount}853 setSkipCount={setSkipCount}854 remainingLetters={remainingLetters}855 setRemainingLetters={setRemainingLetters}856 />857 </div>858 );859 } else {860 return null;861 }862 }863 return setOutput()864}...
focustracker.js
Source:focustracker.js
1/**2 * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license4 */5/* global document, Event */6import FocusTracker from '../src/focustracker';7import global from '../src/dom/global';8import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';9import { expectToThrowCKEditorError } from './_utils/utils';10describe( 'FocusTracker', () => {11 let focusTracker, container, containerFirstInput, containerSecondInput;12 testUtils.createSinonSandbox();13 beforeEach( () => {14 container = document.createElement( 'div' );15 containerFirstInput = document.createElement( 'input' );16 containerSecondInput = document.createElement( 'input' );17 container.appendChild( containerFirstInput );18 container.appendChild( containerSecondInput );19 testUtils.sinon.useFakeTimers();20 focusTracker = new FocusTracker();21 } );22 describe( 'constructor', () => {23 describe( 'isFocused', () => {24 it( 'should be false at default', () => {25 expect( focusTracker.isFocused ).to.false;26 } );27 it( 'should be observable', () => {28 const observableSpy = testUtils.sinon.spy();29 focusTracker.listenTo( focusTracker, 'change:isFocused', observableSpy );30 focusTracker.isFocused = true;31 expect( observableSpy.calledOnce ).to.true;32 } );33 } );34 describe( 'focusedElement', () => {35 it( 'should be null at default', () => {36 expect( focusTracker.focusedElement ).to.be.null;37 } );38 it( 'should be observable', () => {39 const observableSpy = testUtils.sinon.spy();40 focusTracker.listenTo( focusTracker, 'change:focusedElement', observableSpy );41 focusTracker.focusedElement = global.document.body;42 expect( observableSpy.calledOnce ).to.true;43 } );44 } );45 } );46 describe( 'add', () => {47 it( 'should throw an error when element has been already added', () => {48 focusTracker.add( containerFirstInput );49 expectToThrowCKEditorError( () => {50 focusTracker.add( containerFirstInput );51 }, 'focustracker-add-element-already-exist', focusTracker );52 } );53 describe( 'single element', () => {54 it( 'should start listening on element focus and update `isFocused` property', () => {55 focusTracker.add( containerFirstInput );56 expect( focusTracker.isFocused ).to.false;57 containerFirstInput.dispatchEvent( new Event( 'focus' ) );58 expect( focusTracker.isFocused ).to.true;59 expect( focusTracker.focusedElement ).to.equal( containerFirstInput );60 } );61 it( 'should start listening on element blur and update `isFocused` property', () => {62 focusTracker.add( containerFirstInput );63 containerFirstInput.dispatchEvent( new Event( 'focus' ) );64 expect( focusTracker.focusedElement ).to.equal( containerFirstInput );65 containerFirstInput.dispatchEvent( new Event( 'blur' ) );66 testUtils.sinon.clock.tick( 0 );67 expect( focusTracker.isFocused ).to.false;68 expect( focusTracker.focusedElement ).to.be.null;69 } );70 } );71 describe( 'container element', () => {72 it( 'should start listening on element focus using event capturing and update `isFocused` property', () => {73 focusTracker.add( container );74 expect( focusTracker.isFocused ).to.false;75 containerFirstInput.dispatchEvent( new Event( 'focus' ) );76 expect( focusTracker.isFocused ).to.true;77 expect( focusTracker.focusedElement ).to.equal( container );78 } );79 it( 'should start listening on element blur using event capturing and update `isFocused` property', () => {80 focusTracker.add( container );81 containerFirstInput.dispatchEvent( new Event( 'focus' ) );82 expect( focusTracker.focusedElement ).to.equal( container );83 containerFirstInput.dispatchEvent( new Event( 'blur' ) );84 testUtils.sinon.clock.tick( 0 );85 expect( focusTracker.isFocused ).to.false;86 expect( focusTracker.focusedElement ).to.be.null;87 } );88 it( 'should not change `isFocused` property when focus is going between child elements', () => {89 const changeSpy = testUtils.sinon.spy();90 focusTracker.add( container );91 containerFirstInput.dispatchEvent( new Event( 'focus' ) );92 expect( focusTracker.focusedElement ).to.equal( container );93 expect( focusTracker.isFocused ).to.true;94 focusTracker.listenTo( focusTracker, 'change:isFocused', changeSpy );95 containerFirstInput.dispatchEvent( new Event( 'blur' ) );96 containerSecondInput.dispatchEvent( new Event( 'focus' ) );97 testUtils.sinon.clock.tick( 0 );98 expect( focusTracker.focusedElement ).to.equal( container );99 expect( focusTracker.isFocused ).to.true;100 expect( changeSpy.notCalled ).to.true;101 } );102 // https://github.com/ckeditor/ckeditor5-utils/issues/159103 it( 'should keep `isFocused` synced when multiple blur events are followed by the focus', () => {104 focusTracker.add( container );105 container.dispatchEvent( new Event( 'focus' ) );106 expect( focusTracker.focusedElement ).to.equal( container );107 container.dispatchEvent( new Event( 'blur' ) );108 containerFirstInput.dispatchEvent( new Event( 'blur' ) );109 containerSecondInput.dispatchEvent( new Event( 'focus' ) );110 testUtils.sinon.clock.tick( 0 );111 expect( focusTracker.isFocused ).to.be.true;112 expect( focusTracker.focusedElement ).to.equal( container );113 } );114 } );115 } );116 describe( 'remove', () => {117 it( 'should do nothing when element was not added', () => {118 expect( () => {119 focusTracker.remove( container );120 } ).to.not.throw();121 } );122 it( 'should stop listening on element focus', () => {123 focusTracker.add( containerFirstInput );124 focusTracker.remove( containerFirstInput );125 containerFirstInput.dispatchEvent( new Event( 'focus' ) );126 expect( focusTracker.isFocused ).to.false;127 expect( focusTracker.focusedElement ).to.be.null;128 } );129 it( 'should stop listening on element blur', () => {130 focusTracker.add( containerFirstInput );131 focusTracker.remove( containerFirstInput );132 focusTracker.isFocused = true;133 containerFirstInput.dispatchEvent( new Event( 'blur' ) );134 testUtils.sinon.clock.tick( 0 );135 expect( focusTracker.isFocused ).to.true;136 } );137 it( 'should blur element before removing when is focused', () => {138 focusTracker.add( containerFirstInput );139 containerFirstInput.dispatchEvent( new Event( 'focus' ) );140 expect( focusTracker.focusedElement ).to.equal( containerFirstInput );141 expect( focusTracker.isFocused ).to.true;142 focusTracker.remove( containerFirstInput );143 testUtils.sinon.clock.tick( 0 );144 expect( focusTracker.isFocused ).to.false;145 expect( focusTracker.focusedElement ).to.be.null;146 } );147 } );148 describe( 'destroy()', () => {149 it( 'should stop listening', () => {150 const stopListeningSpy = sinon.spy( focusTracker, 'stopListening' );151 focusTracker.destroy();152 sinon.assert.calledOnce( stopListeningSpy );153 } );154 } );...
editableelement.js
Source:editableelement.js
1/**2 * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license4 */5import createDocumentMock from '../../tests/view/_utils/createdocumentmock';6import EditableElement from '../../src/view/editableelement';7import Range from '../../src/view/range';8import Document from '../../src/view/document';9import { StylesProcessor } from '../../src/view/stylesmap';10describe( 'EditableElement', () => {11 describe( 'is', () => {12 let el;13 before( () => {14 el = new EditableElement( new Document( new StylesProcessor() ), 'div' );15 } );16 it( 'should return true for containerElement/editable/element, also with correct name and element name', () => {17 expect( el.is( 'containerElement' ) ).to.be.true;18 expect( el.is( 'view:containerElement' ) ).to.be.true;19 expect( el.is( 'containerElement', 'div' ) ).to.be.true;20 expect( el.is( 'view:containerElement', 'div' ) ).to.be.true;21 expect( el.is( 'editableElement' ) ).to.be.true;22 expect( el.is( 'view:editableElement' ) ).to.be.true;23 expect( el.is( 'editableElement', 'div' ) ).to.be.true;24 expect( el.is( 'view:editableElement', 'div' ) ).to.be.true;25 expect( el.is( 'element' ) ).to.be.true;26 expect( el.is( 'view:element' ) ).to.be.true;27 expect( el.is( 'element', 'div' ) ).to.be.true;28 expect( el.is( 'view:element', 'div' ) ).to.be.true;29 expect( el.is( 'element', 'div' ) ).to.be.true;30 } );31 it( 'should return false for other accept values', () => {32 expect( el.is( 'rootElement', 'p' ) ).to.be.false;33 expect( el.is( 'view:rootElement', 'p' ) ).to.be.false;34 expect( el.is( 'containerElement', 'p' ) ).to.be.false;35 expect( el.is( 'view:containerElement', 'p' ) ).to.be.false;36 expect( el.is( 'element', 'p' ) ).to.be.false;37 expect( el.is( 'view:element', 'p' ) ).to.be.false;38 expect( el.is( 'element', 'p' ) ).to.be.false;39 expect( el.is( 'view:p' ) ).to.be.false;40 expect( el.is( '$text' ) ).to.be.false;41 expect( el.is( '$textProxy' ) ).to.be.false;42 expect( el.is( 'attributeElement' ) ).to.be.false;43 expect( el.is( 'uiElement' ) ).to.be.false;44 expect( el.is( 'emptyElement' ) ).to.be.false;45 expect( el.is( 'documentFragment' ) ).to.be.false;46 } );47 } );48 describe( 'isFocused', () => {49 let docMock, viewMain, viewHeader;50 beforeEach( () => {51 docMock = createDocumentMock();52 viewMain = new EditableElement( docMock, 'div' );53 viewHeader = new EditableElement( docMock, 'h1' );54 viewHeader.rootName = 'header';55 } );56 it( 'should be observable', () => {57 const root = new EditableElement( docMock, 'div' );58 expect( root.isFocused ).to.be.false;59 const isFocusedSpy = sinon.spy();60 root.on( 'change:isFocused', isFocusedSpy );61 root.isFocused = true;62 expect( root.isFocused ).to.be.true;63 expect( isFocusedSpy.calledOnce ).to.be.true;64 } );65 it( 'should change isFocused when selection changes', () => {66 const rangeMain = Range._createFromParentsAndOffsets( viewMain, 0, viewMain, 0 );67 const rangeHeader = Range._createFromParentsAndOffsets( viewHeader, 0, viewHeader, 0 );68 docMock.selection._setTo( rangeMain );69 docMock.isFocused = true;70 expect( viewMain.isFocused ).to.be.true;71 expect( viewHeader.isFocused ).to.be.false;72 docMock.selection._setTo( [ rangeHeader ] );73 expect( viewMain.isFocused ).to.be.false;74 expect( viewHeader.isFocused ).to.be.true;75 } );76 it( 'should change isFocused when document.isFocus changes', () => {77 const rangeMain = Range._createFromParentsAndOffsets( viewMain, 0, viewMain, 0 );78 const rangeHeader = Range._createFromParentsAndOffsets( viewHeader, 0, viewHeader, 0 );79 docMock.selection._setTo( rangeMain );80 docMock.isFocused = true;81 expect( viewMain.isFocused ).to.be.true;82 expect( viewHeader.isFocused ).to.be.false;83 docMock.isFocused = false;84 expect( viewMain.isFocused ).to.be.false;85 expect( viewHeader.isFocused ).to.be.false;86 docMock.selection._setTo( [ rangeHeader ] );87 expect( viewMain.isFocused ).to.be.false;88 expect( viewHeader.isFocused ).to.be.false;89 } );90 } );91 describe( 'isReadOnly', () => {92 let docMock;93 beforeEach( () => {94 docMock = createDocumentMock();95 } );96 it( 'should be observable', () => {97 const root = new EditableElement( docMock, 'div' );98 expect( root.isReadOnly ).to.be.false;99 const isReadOnlySpy = sinon.spy();100 root.on( 'change:isReadOnly', isReadOnlySpy );101 root.isReadOnly = true;102 expect( root.isReadOnly ).to.be.true;103 expect( isReadOnlySpy.calledOnce ).to.be.true;104 } );105 it( 'should be bound to the document#isReadOnly', () => {106 const root = new EditableElement( docMock, 'div' );107 root.document.isReadOnly = false;108 expect( root.isReadOnly ).to.false;109 root.document.isReadOnly = true;110 expect( root.isReadOnly ).to.true;111 } );112 } );113 describe( 'document', () => {114 let element, docMock;115 beforeEach( () => {116 docMock = createDocumentMock();117 element = new EditableElement( docMock, 'div' );118 } );119 it( 'should be cloned properly', () => {120 const newElement = element._clone();121 expect( newElement.document ).to.equal( docMock );122 } );123 } );...
CustomerViews.js
Source:CustomerViews.js
...9 super(props);10 this.isFocused = false;11 }12 componentWillUpdate(){13 console.log("AllScreen -componentWillUpdate: Focused : " + this.props.navigation.isFocused());14 if( this.props.navigation.isFocused() === true && this.isFocused === false){15 this.isFocused = true;16 console.log("AllScreen focus received")17 this.props.screenProps.parent.props.customerActions.SearchCustomers("");18 }else if( this.props.navigation.isFocused() === false){19 this.isFocused = false;20 }21 }22 render() {23 return (24 <CustomerList filter='all' customerInfo={this.props.screenProps}/>25 );26 }27}28class WalkupScreen extends React.Component {29 constructor(props) {30 super(props);31 this.isFocused = false;32 }33 componentWillUpdate(){34 console.log("WalkupScreen -componentWillUpdate: Focused : " + this.props.navigation.isFocused());35 if( this.props.navigation.isFocused() === true && this.isFocused === false){36 this.isFocused = true;37 console.log("WalkupScreen focus received")38 this.props.screenProps.parent.props.customerActions.SearchCustomers("");39 }else if( this.props.navigation.isFocused() === false){40 this.isFocused = false;41 }42 }43 render() {44 return (45 <CustomerList filter='walkup' customerInfo={this.props.screenProps}/>46 );47 }48}49class ResellerScreen extends React.Component {50 constructor(props) {51 super(props);52 this.isFocused = false;53 }54 componentWillUpdate(){55 console.log("ResellerScreen -componentWillUpdate: Focused : " + this.props.navigation.isFocused());56 if( this.props.navigation.isFocused() === true && this.isFocused === false){57 this.isFocused = true;58 console.log("ResellerScreen focus received")59 this.props.screenProps.parent.props.customerActions.SearchCustomers("");60 }else if( this.props.navigation.isFocused() === false){61 this.isFocused = false;62 }63 }64 render() {65 return (66 <CustomerList filter='reseller' customerInfo={this.props.screenProps}/>67 );68 }69}70class CreditScreen extends React.Component {71 constructor(props) {72 super(props);73 this.isFocused = false;74 }75 componentWillUpdate(){76 console.log("CreditScreen -componentWillUpdate: Focused : " + this.props.navigation.isFocused());77 if( this.props.navigation.isFocused() === true && this.isFocused === false){78 this.isFocused = true;79 console.log("CreditScreen focus received")80 this.props.screenProps.parent.props.customerActions.SearchCustomers("");81 }else if( this.props.navigation.isFocused() === false){82 this.isFocused = false;83 }84 }85 render(){86 return (87 <CustomerList filter='credit' customerInfo={this.props.screenProps} />88 );89 }90}91export const CustomerViews = createBottomTabNavigator({92 All: {93 screen: AllScreen,94 navigationOptions: {95 tabBarLabel: 'All',...
CircleNav.js
Source:CircleNav.js
1import { useContext, useState } from "react";2import styled, { ThemeContext } from "styled-components";3import { CONTAINER_SIZING, PIXEL_SIZING } from "../../../utils/constants";4import { TextButton } from "../../core/Button";5import Text from "../../core/Text";6const CircleContainer = styled.div`7 position: fixed;8 bottom: ${PIXEL_SIZING.large};9 right: ${PIXEL_SIZING.large};10 height: ${CONTAINER_SIZING.miniscule};11 width: ${CONTAINER_SIZING.miniscule};12 border-radius: ${CONTAINER_SIZING.larger};13 background-color: ${({ theme }) => theme.colors.textPrimary};14 border: ${({ isFocused, theme }) => isFocused ? `2px solid ${theme.colors.primary}` : null};15 z-index: 110;16 overflow: hidden;17`;18const MenuContainer = styled.div`19 position: fixed;20 width: 100%;21 height: 100%;22 background-color: ${({ theme }) => theme.colors.invert};23 top: 24 left: 0;25 right: 0;26 z-index: 100;27`;28const SvgArrow = ({ style, invert, isFocused }) => {29 const theme = useContext(ThemeContext);30 return (31 <svg 32 viewBox="0 0 926.23699 573.74994"33 style={{ 34 height: 24,35 width: 24,36 x: 0,37 y: 0,38 transform: isFocused ? "translateY(9px)" : "translateY(30px)",39 transition: "transform 0.07s ease-out",40 ...style,41 }}42 >43 <g transform="translate(904.92214,-879.1482)">44 <path 45 d="46 m -673.67664,1221.6502 -231.2455,-231.24803 55.6165,47 -55.627 c 30.5891,-30.59485 56.1806,-55.627 56.8701,-55.627 0.6894,48 0 79.8637,78.60862 175.9427,174.68583 l 174.6892,174.6858 174.6892,49 -174.6858 c 96.079,-96.07721 175.253196,-174.68583 175.942696,50 -174.68583 0.6895,0 26.281,25.03215 56.8701,51 55.627 l 55.6165,55.627 -231.245496,231.24803 c -127.185,127.186452 -231.5279,231.248 -231.873,231.248 -0.3451,0 -104.688,53 -104.0616 -231.873,-231.248 z54 " 55 fill={theme.colors.primary}56 >57 </path>58 </g>59 </svg>60 );61}62export const CircleNav = ({ id, items, onChange }) => {63 const [isFocused, setIsFocused] = useState(false);64 return (65 <>66 <CircleContainer id={id} onClick={() => setIsFocused(!isFocused)} isFocused={isFocused}>67 <div style={{ height: "100%", width: "100%", position: "relative" }}>68 <div className={"center-absolute"} style={{ display: "grid", alignItems: "center", justifyItems: "center" }}>69 <SvgArrow isFocused={isFocused}/>70 <div style={{ transform: "rotate(180deg)", }}>71 <SvgArrow isFocused={isFocused}/>72 </div>73 </div>74 </div>75 </CircleContainer>76 {77 isFocused &&78 <MenuContainer>79 <div 80 className={"center-absolute"}81 style={{ 82 display: "grid",83 justifyItems: "center",84 rowGap: PIXEL_SIZING.large,85 }}86 >87 {88 items.map(({ label, value }) =>89 <TextButton 90 primary 91 onClick={() => {92 onChange(value);93 setIsFocused(false);94 }}95 >96 {label}97 </TextButton>98 )99 }100 </div>101 </MenuContainer>102 }103 </>104 )...
WithIsFocused.test.js
Source:WithIsFocused.test.js
1// @flow2import React from "react";3import { shallow } from "enzyme";4import { Text } from "react-native";5import withIsFocused from "./WithIsFocused";6const createNavigation = ({ isFocused }) => {7 const listeners = {};8 return {9 listeners,10 navigation: {11 isFocused,12 addListener: (type, callback) => {13 listeners[type] = callback;14 return {15 remove: () => {16 delete listeners[type];17 }18 };19 }20 }21 };22};23const Test = () => <Text>Hello</Text>;24it("intializes isFocused to props.navigation.isFocused", () => {25 const { navigation } = createNavigation({ isFocused: () => true });26 const WithIsFocusedComponent = withIsFocused(Test);27 const output = shallow(<WithIsFocusedComponent navigation={navigation} />);28 expect(output.find(Test).props()).toEqual({ isFocused: true, navigation });29});30it("sets state.isFocused to true when navigation emits willFocus", () => {31 const { navigation, listeners } = createNavigation({32 isFocused: () => false33 });34 const WithIsFocusedComponent = withIsFocused(Test);35 const output = shallow(<WithIsFocusedComponent navigation={navigation} />);36 listeners.willFocus();37 output.update();38 expect(output.find(Test).props()).toEqual({ isFocused: true, navigation });39});40it("sets state.isFocused to false when navigation emits willBlur", () => {41 const { navigation, listeners } = createNavigation({ isFocused: () => true });42 const WithIsFocusedComponent = withIsFocused(Test);43 const output = shallow(<WithIsFocusedComponent navigation={navigation} />);44 listeners.willBlur();45 output.update();46 expect(output.find(Test).props()).toEqual({ isFocused: false, navigation });47});48it("removes navigation listeners on umount", () => {49 const { navigation, listeners } = createNavigation({ isFocused: () => true });50 const WithIsFocusedComponent = withIsFocused(Test);51 const output = shallow(<WithIsFocusedComponent navigation={navigation} />);52 expect(Object.values(listeners).length).toBe(2);53 output.unmount();54 expect(Object.values(listeners).length).toBe(0);...
TabItem.js
Source:TabItem.js
1import React from 'react'2import {Text, StyleSheet, Pressable} from 'react-native'3import {4 IconHome,5 IconHomeActive,6 IconJersey,7 IconJerseyActive,8 IconProfile,9 IconProfileActive,10 IconNotification,11 IconNotificationActive,12} from '../assets'13import {colors, fonts} from '../utils'14export default function TabItem({15 isFocused,16 options,17 onPress,18 onLongPress,19 label,20}) {21 const Icon = () => {22 if (label === 'Home') {23 return isFocused ? <IconHomeActive /> : <IconHome />24 } else if (label === 'Jersey') {25 return isFocused ? <IconJerseyActive /> : <IconJersey />26 } else if (label === 'Profile') {27 return isFocused ? <IconProfileActive /> : <IconProfile />28 } else if (label === 'Notifications') {29 return isFocused ? <IconNotificationActive /> : <IconNotification />30 }31 }32 return (33 <Pressable34 android_ripple={{35 color: colors.secondary,36 borderless: true,37 }}38 accessibilityRole="button"39 accessibilityState={isFocused ? {selected: true} : {}}40 accessibilityLabel={options.tabBarAccessibilityLabel}41 testID={options.tabBarTestID}42 onPress={onPress}43 onLongPress={onLongPress}44 style={styles.container}>45 <Icon />46 <Text style={styles.text(isFocused)}>{label}</Text>47 </Pressable>48 )49}50const styles = StyleSheet.create({51 text: isFocused => ({52 color: isFocused ? colors.white : colors.secondary,53 fontSize: 11,54 marginTop: 4,55 fontFamily: isFocused ? fonts.primary.bold : fonts.primary.regular,56 }),57 container: {58 alignItems: 'center',59 },...
index.js
Source:index.js
1import React from 'react';2import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';3import {4 colors,5 IC_HomeOff,6 IC_HomeOn,7 IC_JerseyOff,8 IC_JerseyOn,9 IC_ProfileOff,10 IC_ProfileOn,11} from '../../../res';12const index = ({isFocused, options, onPress, onLongPress, label}) => {13 const Icon = ({label, isFocused}) => {14 switch (label) {15 case 'Home':16 return isFocused ? <IC_HomeOn /> : <IC_HomeOff />;17 case 'Jersey':18 return isFocused ? <IC_JerseyOn /> : <IC_JerseyOff />;19 case 'Profile':20 return isFocused ? <IC_ProfileOn /> : <IC_ProfileOff />;21 default:22 return <IC_HomeOn />;23 }24 };25 return (26 <TouchableOpacity27 key={index}28 accessibilityRole="button"29 accessibilityState={isFocused ? {selected: true} : {}}30 accessibilityLabel={options.tabBarAccessibilityLabel}31 testID={options.tabBarTestID}32 onPress={onPress}33 onLongPress={onLongPress}34 style={styles.container}>35 <Icon label={label} isFocused={isFocused} />36 <Text style={styles.label(isFocused)}>{label}</Text>37 </TouchableOpacity>38 );39};40export default index;41const styles = StyleSheet.create({42 container: {43 justifyContent: 'center',44 alignItems: 'center',45 },46 label: isFocused => ({47 color: isFocused ? colors.white : colors.blueSecondary,48 fontSize: 12,49 }),...
Using AI Code Generation
1describe('webdriver.io page', function() {2 it('should focus on the search box', function () {3 browser.setValue('#search_input_react', 'WebdriverIO');4 browser.pause(2000);5 var isFocused = browser.isFocused('#search_input_react');6 });7});
Using AI Code Generation
1it('should focus on the first element', () => {2 $('input[type="number"]').click()3 const focused = $('input[type="number"]').isFocused()4})5it('should display the element', () => {6 const displayed = $('input[type="number"]').isDisplayed()7})8it('should enable the element', () => {9 const enabled = $('input[type="number"]').isEnabled()10})11it('should exist the element', () => {12 const existing = $('input[type="number"]').isExisting()13})14it('should display the element in viewport', () => {15 const displayed = $('input[type="number"]').isDisplayedInViewport()16})17it('should wait for the element to be displayed', () => {18 $('input[type="number"]').waitForDisplayed()19})20it('should wait for the element to be enabled', () => {21 $('input[type="number"]').waitForEnabled()22})23it('should wait for the element to exist', () => {24 $('input[type="number"]').waitForExist()
Using AI Code Generation
1describe('Test', () => {2 it('should check if an element is focused or not', async () => {3 await browser.switchToFrame(0);4 let element = await $('input[type="text"]');5 await element.click();6 let isFocused = await element.isFocused();7 console.log(isFocused);8 await browser.switchToFrame(null);9 });10});
Using AI Code Generation
1describe('webdriver.io page', () => {2 it('should have the right title', () => {3 const title = browser.getTitle()4 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')5 })6 it('should have the right title', () => {7 const title = browser.getTitle()8 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')9 })10 it('should have the right title', () => {11 const title = browser.getTitle()12 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')13 })14 it('should have the right title', () => {15 const title = browser.getTitle()16 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')17 })18 it('should have the right title', () => {19 const title = browser.getTitle()20 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')21 })22 it('should have the right title', () => {23 const title = browser.getTitle()24 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')25 })26 it('should have the right title', () => {27 const title = browser.getTitle()28 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')29 })30 it('should have the right title', () => {31 const title = browser.getTitle()32 expect(title).toEqual('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')33 })34 it('should have the right title', () => {35 const title = browser.getTitle()36 expect(title).toEqual('WebdriverIO · Next
Using AI Code Generation
1describe('My Login application', () => {2 it('should login with valid credentials', () => {3 $('#user_login').setValue('username');4 $('#user_password').setValue('password');5 $('input[type="submit"]').click();6 const iconElement = $('.icon-user');7 iconElement.click();8 });9});
Using AI Code Generation
1it('should check if the element is focused', () => {2 const input = $('input');3 input.click();4 expect(input.isFocused()).toBe(true);5});6it('should check if the element exists', () => {7 const input = $('input');8 expect(input.isExisting()).toBe(true);9});10it('should check if the element is displayed', () => {11 const input = $('input');12 expect(input.isDisplayed()).toBe(true);13});14it('should check if the element is enabled', () => {15 const input = $('input');16 expect(input.isEnabled()).toBe(true);17});18it('should check if the element is selected', () => {19 const input = $('input');20 expect(input.isSelected()).toBe(true);21});22it('should check if the element is focused', () => {23 const input = $('input
Wondering what could be a next-gen browser and mobile test automation framework that is also simple and concise? Yes, that’s right, it's WebdriverIO. Since the setup is very easy to follow compared to Selenium testing configuration, you can configure the features manually thereby being the center of attraction for automation testing. Therefore the testers adopt WedriverIO to fulfill their needs of browser testing.
Learn to run automation testing with WebdriverIO tutorial. Go from a beginner to a professional automation test expert with LambdaTest WebdriverIO tutorial.
Running Your First Automation Script - Learn the steps involved to execute your first Test Automation Script using WebdriverIO since the setup is very easy to follow and the features can be configured manually.
Selenium Automation With WebdriverIO - Read more about automation testing with WebdriverIO and how it supports both browsers and mobile devices.
Browser Commands For Selenium Testing - Understand more about the barriers faced while working on your Selenium Automation Scripts in WebdriverIO, the ‘browser’ object and how to use them?
Handling Alerts & Overlay In Selenium - Learn different types of alerts faced during automation, how to handle these alerts and pops and also overlay modal in WebdriverIO.
How To Use Selenium Locators? - Understand how Webdriver uses selenium locators in a most unique way since having to choose web elements very carefully for script execution is very important to get stable test results.
Deep Selectors In Selenium WebdriverIO - The most popular automation testing framework that is extensively adopted by all the testers at a global level is WebdriverIO. Learn how you can use Deep Selectors in Selenium WebdriverIO.
Handling Dropdown In Selenium - Learn more about handling dropdowns and how it's important while performing automated browser testing.
Automated Monkey Testing with Selenium & WebdriverIO - Understand how you can leverage the amazing quality of WebdriverIO along with selenium framework to automate monkey testing of your website or web applications.
JavaScript Testing with Selenium and WebdriverIO - Speed up your Javascript testing with Selenium and WebdriverIO.
Cross Browser Testing With WebdriverIO - Learn more with this step-by-step tutorial about WebdriverIO framework and how cross-browser testing is done with WebdriverIO.
Get 100 minutes of automation test minutes FREE!!