Best JavaScript code snippet using testcafe
VerticalNavBar.js
Source:VerticalNavBar.js  
1import React, { useEffect, useMemo } from "react";2import { makeStyles /*, useTheme */ } from "@material-ui/core/styles";34// import LobbyIcon from "@material-ui/icons/Store";5// import LobbyIcon from "@material-ui/icons/Deck";6// import LobbyIcon from "@material-ui/icons/EventSeat";78import { useLocalStorage } from "react-use";910import _ from "lodash";1112import LobbyIcon from "@material-ui/icons/Weekend";13import MainStageIcon from "@material-ui/icons/DesktopMac";14import RoomsIcon from "../../Assets/Icons/Rooms";15import AttendeesIcon from "../../Assets/Icons/Person";16import NetworkingIcon from "../../Assets/Icons/Conversation1-1";17import ChatIcon from "../../Assets/Icons/Chat";18import PollsIcon from "../../Assets/Icons/Polls";19import BackstageIcon from "../../Assets/Icons/Backstage2";20import QnAIcon from "../../Assets/Icons/QnA";21import HelpIcon from "../../Assets/Icons/Help";22import Broadcast from "../../Assets/Icons/Broadcast2";2324import { useHover } from "react-use";25import { leaveCall } from "../../Modules/eventSessionOperations";26import { Box, Typography, Divider, Badge } from "@material-ui/core";27import VerticalNavBarContext, {28  VERTICAL_NAV_OPTIONS29} from "../../Contexts/VerticalNavBarContext";30import { useSelector, shallowEqual } from "react-redux";31import {32  getUserCurrentLocation,33  getSessionId,34  getUserGroup,35  getUserId,36  getFeatureDetails,37  isEventOwner,38  getUser39} from "../../Redux/eventSession";40import ChatMessagesContext, {41  CHAT_GLOBAL_NS42} from "../../Contexts/ChatMessagesContext";43import { FEATURES } from "../../Modules/features";44import PerfectScrollbar from "react-perfect-scrollbar";45import { ROLES } from "../../Modules/rolesOperations";4647export const DEAFULT_NAV_BAR = {48  [VERTICAL_NAV_OPTIONS.lobby]: {49    id: VERTICAL_NAV_OPTIONS.lobby,50    label: "Lobby",51    icon: LobbyIcon,52    order: 1,53    visible: true54  },55  [VERTICAL_NAV_OPTIONS.mainStage]: {56    id: VERTICAL_NAV_OPTIONS.mainStage,57    label: "Main Stage",58    icon: MainStageIcon,59    order: 2,60    visible: true61  },62  [VERTICAL_NAV_OPTIONS.rooms]: {63    id: VERTICAL_NAV_OPTIONS.rooms,64    label: "Rooms",65    icon: RoomsIcon,66    order: 3,67    visible: true68  },69  [VERTICAL_NAV_OPTIONS.networking]: {70    id: VERTICAL_NAV_OPTIONS.networking,71    label: "Networking",72    icon: NetworkingIcon,73    order: 4,74    visible: true75  },76  [VERTICAL_NAV_OPTIONS.attendees]: {77    id: VERTICAL_NAV_OPTIONS.attendees,78    label: "Attendees",79    icon: AttendeesIcon,80    order: 5,81    visible: true82  },83  divider: {84    id: "divider",85    label: "",86    icon: null,87    order: 6,88    visible: true89  },90  [VERTICAL_NAV_OPTIONS.chat]: {91    id: VERTICAL_NAV_OPTIONS.chat,92    label: "Chat",93    icon: ChatIcon,94    order: 7,95    visible: true96  },97  [VERTICAL_NAV_OPTIONS.qna]: {98    id: VERTICAL_NAV_OPTIONS.qna,99    label: "Q&A",100    icon: QnAIcon,101    order: 8,102    visible: false103  },104  [VERTICAL_NAV_OPTIONS.polls]: {105    id: VERTICAL_NAV_OPTIONS.polls,106    label: "Polls",107    icon: PollsIcon,108    order: 9,109    visible: true110  },111  [VERTICAL_NAV_OPTIONS.broadcasts]: {112    id: VERTICAL_NAV_OPTIONS.broadcasts,113    label: "Broadcast",114    icon: Broadcast,115    order: 10,116    visible: false117  },118  [VERTICAL_NAV_OPTIONS.backstage]: {119    id: VERTICAL_NAV_OPTIONS.backstage,120    label: "Backstage",121    icon: BackstageIcon,122    order: 11,123    visible: true124  }125};126127const useStyles = makeStyles((theme) => ({128  root: {129    display: "flex",130    flexDirection: "column",131    height: "100%"132  },133  menuItem: ({ selected, hovered, isCurrentLocation }) => ({134    padding: theme.spacing(1, 0, 1, 0),135    borderLeft: `4px solid ${136      isCurrentLocation137        ? theme.palette.secondary.light138        : selected139        ? theme.palette.primary.main140        : hovered141        ? theme.palette.background.default142        : "#fff"143    }`,144    backgroundColor: selected ? theme.palette.background.default : "inherit",145    "&:hover": {146      backgroundColor: theme.palette.background.default, //"rgba(0, 0, 0, 0.04)",147      cursor: "pointer"148    }149  }),150  itemInnerBox: ({ selected }) => ({}),151  itemIcon: ({ selected, hovered, isCurrentLocation }) => ({152    width: "100%",153    height: "100%",154    maxWidth: 32,155    maxHeight: 32,156    color: isCurrentLocation157      ? theme.palette.secondary.light158      : hovered || selected159      ? theme.palette.primary.main160      : theme.palette.primary.light161  })162}));163164const MenuIconContainer = ({165  icon,166  label,167  selected,168  isCurrentLocation,169  hasBadge = false,170  ...rest171}) => {172  const [isHovered, setIsHovered] = React.useState(false);173  const classes = useStyles({174    selected,175    hovered: isHovered,176    isCurrentLocation177  });178179  const Icon = icon;180181  const item = (hovered) => (182    <Box align="center" className={classes.menuItem} {...rest}>183      <Box className={classes.itemInnerBox}>184        <Box className={classes.itemIconBox}>185          <Badge color="secondary" variant="dot" invisible={!hasBadge}>186            <Icon className={classes.itemIcon} />187          </Badge>188        </Box>189        <Box className={classes.itemLabel}>190          <Typography variant="caption" color="textSecondary">191            {label}192          </Typography>193        </Box>194      </Box>195    </Box>196  );197198  const [hoverable, hovered] = useHover(item);199200  React.useEffect(() => {201    if (isHovered !== hovered) {202      setIsHovered(hovered);203    }204  }, [hovered, isHovered]);205206  return hoverable;207};208209const VerticalNavBar = (props) => {210  const classes = useStyles();211212  const {213    currentNavBarSelection,214    setCurrentNavBarSelection,215    setHasNavBarPaneOpen216  } = React.useContext(VerticalNavBarContext);217218  const sessionId = useSelector(getSessionId);219  const userGroup = useSelector(getUserGroup);220  const userId = useSelector(getUserId);221  const user = useSelector(getUser);222223  const backstageFeature = useSelector(224    getFeatureDetails(FEATURES.STREAMYARD_BACKSTAGE),225    shallowEqual226  );227228  const hasBackstage = useMemo(229    () =>230      user &&231      user.roles &&232      backstageFeature &&233      backstageFeature.enabled &&234      (user.roles.includes(ROLES.SPEAKER.key) ||235        user.roles.includes(ROLES.HOST.key)),236    [backstageFeature, user]237  );238239  const [lastNavBarSelection, setLastNavBarSelection] = React.useState(null);240241  const userCurrentLocation = useSelector(getUserCurrentLocation, shallowEqual);242243  const [currentLocation, setCurrentLocation] = React.useState(244    userCurrentLocation245  );246  const [lastCurrentSelection, setLastCurrentSelection] = React.useState(null);247248  const isOwner = useSelector(isEventOwner);249250  const [lastGlobalChatOpenCount, setLastGlobalChatOpenCount] = useLocalStorage(251    `veertly/chat/${CHAT_GLOBAL_NS}/${sessionId}/${userId}/count`,252    0,253    {254      raw: true255    }256  );257258  const [hasChatBadge, setHasChatBadge] = React.useState(false);259260  const { chatMessages } = React.useContext(ChatMessagesContext);261262  const customNavBarFeature = useSelector(263    getFeatureDetails(FEATURES.CUSTOM_NAV_BAR),264    shallowEqual265  );266  const navBarOptions = useMemo(() => {267    if (!customNavBarFeature) {268      return Object.values(DEAFULT_NAV_BAR);269    }270271    let result = { ...DEAFULT_NAV_BAR };272273    _.forEach(Object.values(customNavBarFeature), ({ id, label, visible }) => {274      if (result[id]) {275        result[id].label = label;276        result[id].visible = visible !== false;277      }278    });279280    return Object.values(result);281  }, [customNavBarFeature]);282283  useEffect(() => {284    if (currentNavBarSelection !== lastNavBarSelection) {285      if (286        lastNavBarSelection === VERTICAL_NAV_OPTIONS.chat &&287        currentNavBarSelection !== VERTICAL_NAV_OPTIONS.chat288      ) {289        // chat closed290        setLastGlobalChatOpenCount(chatMessages[CHAT_GLOBAL_NS].length);291      } else if (292        lastNavBarSelection !== VERTICAL_NAV_OPTIONS.chat &&293        currentNavBarSelection === VERTICAL_NAV_OPTIONS.chat294      ) {295        // chat opened296        setLastGlobalChatOpenCount(chatMessages[CHAT_GLOBAL_NS].length);297        setHasChatBadge(false);298      }299300      setLastNavBarSelection(currentNavBarSelection);301    }302  }, [303    chatMessages,304    currentNavBarSelection,305    lastNavBarSelection,306    setLastGlobalChatOpenCount307  ]);308309  useEffect(() => {310    if (chatMessages[CHAT_GLOBAL_NS].length > lastGlobalChatOpenCount) {311      // new msg312      if (313        currentNavBarSelection !== VERTICAL_NAV_OPTIONS.chat && // not on chat314        lastNavBarSelection !== VERTICAL_NAV_OPTIONS.chat // not previously on chat315      ) {316        setHasChatBadge(true);317      }318      if (currentNavBarSelection === VERTICAL_NAV_OPTIONS.chat) {319        setLastGlobalChatOpenCount(chatMessages[CHAT_GLOBAL_NS].length);320      }321    }322  }, [323    chatMessages,324    currentNavBarSelection,325    lastGlobalChatOpenCount,326    lastNavBarSelection,327    setLastGlobalChatOpenCount328  ]);329330  useEffect(() => {331    if (userCurrentLocation !== lastCurrentSelection) {332      setCurrentLocation(userCurrentLocation);333      setCurrentNavBarSelection(userCurrentLocation);334335      if (336        userCurrentLocation === VERTICAL_NAV_OPTIONS.lobby ||337        userCurrentLocation === VERTICAL_NAV_OPTIONS.mainStage338      ) {339        if (userGroup) {340          leaveCall(sessionId, userGroup, userId);341        }342      }343      if (userCurrentLocation === VERTICAL_NAV_OPTIONS.lobby) {344        setHasNavBarPaneOpen(false);345      } else {346        setHasNavBarPaneOpen(true);347      }348      setLastCurrentSelection(userCurrentLocation);349    }350  }, [351    lastCurrentSelection,352    sessionId,353    setCurrentNavBarSelection,354    setHasNavBarPaneOpen,355    userCurrentLocation,356    userGroup,357    userId358  ]);359360  const handleClick = (location) => (e) => {361    if (currentNavBarSelection !== location) {362      if (363        userCurrentLocation === VERTICAL_NAV_OPTIONS.lobby &&364        location === VERTICAL_NAV_OPTIONS.lobby365      ) {366        setHasNavBarPaneOpen(false);367      } else {368        setHasNavBarPaneOpen(true);369      }370      setCurrentNavBarSelection(location);371372      // if (373      //   userCurrentLocation === VERTICAL_NAV_OPTIONS.lobby &&374      //   location === VERTICAL_NAV_OPTIONS.mainStage375      // ) {376      //   setUserCurrentLocation(sessionId, VERTICAL_NAV_OPTIONS.mainStage);377      // }378379      // }380    } else {381      // if (location !== VERTICAL_NAV_OPTIONS.lobby) {382      setCurrentNavBarSelection(null);383      setHasNavBarPaneOpen(false);384      // }385    }386  };387388  return (389    <PerfectScrollbar>390      <div className={classes.root}>391        {navBarOptions.map(({ icon, label, id, visible }) => {392          if (id === VERTICAL_NAV_OPTIONS.backstage && !hasBackstage) {393            return null;394          }395396          if (id === "divider" && visible) {397            return <Divider key="divider" />;398          } else if (id === VERTICAL_NAV_OPTIONS.broadcasts) {399            if (isOwner) {400              return (401                <MenuIconContainer402                  key={id}403                  icon={icon}404                  label={label}405                  selected={currentNavBarSelection === id}406                  onClick={handleClick(id)}407                  isCurrentLocation={currentLocation === id}408                />409              );410            }411          } else if (visible) {412            return (413              <Box key={id}>414                {id === VERTICAL_NAV_OPTIONS.backstage && <Divider />}415                <MenuIconContainer416                  icon={icon}417                  label={label}418                  selected={currentNavBarSelection === id}419                  onClick={handleClick(id)}420                  isCurrentLocation={currentLocation === id}421                  hasBadge={422                    id === VERTICAL_NAV_OPTIONS.chat ? hasChatBadge : false423                  }424                />425              </Box>426            );427          }428          return null;429        })}430431        <div style={{ flexGrow: 1 }}></div>432        <MenuIconContainer433          icon={HelpIcon}434          label="Help"435          selected={currentNavBarSelection === VERTICAL_NAV_OPTIONS.help}436          onClick={handleClick(VERTICAL_NAV_OPTIONS.help)}437        />438      </div>439    </PerfectScrollbar>440  );441};442
...world.js
Source:world.js  
1// -*- Mode: js; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*-2//3// Copyright (c) 2012 Giovanni Campagna <scampa.giovanni@gmail.com>4//5// Gnome Weather is free software; you can redistribute it and/or modify6// it under the terms of the GNU General Public License as published by the7// Free Software Foundation; either version 2 of the License, or (at your8// option) any later version.9//10// Gnome Weather is distributed in the hope that it will be useful, but11// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY12// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License13// for more details.14//15// You should have received a copy of the GNU General Public License along16// with Gnome Weather; if not, write to the Free Software Foundation,17// Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA18const GLib = imports.gi.GLib;19const GObject = imports.gi.GObject;20const GWeather = imports.gi.GWeather;21const Util = imports.misc.util;22var WorldModel = GObject.registerClass({23    Signals: {24        'current-location-changed': { param_types: [ GWeather.Info ] },25        'location-added': { param_types: [ GWeather.Info, GObject.Boolean ] },26        'location-removed': { param_types: [ GWeather.Info ] }27    },28    Properties: {29        'loading': GObject.ParamSpec.boolean('loading', '', '', GObject.ParamFlags.READABLE, false)30    },31}, class WorldModel extends GObject.Object {32    _init(world, enableGtk) {33        super._init();34        this._world = world;35        this._settings = Util.getSettings('org.gnome.Weather');36        this._providers = Util.getEnabledProviders();37        this._loadingCount = 0;38        this._currentLocationInfo = null;39        this._infoList = [];40    }41    get length() {42        return this._infoList.length + (this._currentLocationInfo ? 1 : 0);43    }44    getAll() {45        if (this._currentLocationInfo)46            return [this._currentLocationInfo].concat(this._infoList);47        else48            return [].concat(this._infoList);49    }50    getAtIndex(index) {51        if (this._currentLocationInfo) {52            if (index == 0)53                return this._currentLocationInfo;54            else55                index--;56        }57        return this._infoList[index];58    }59    getCurrentLocation() {60        return this._currentLocationInfo;61    }62    currentLocationChanged(location) {63        if (this._currentLocationInfo)64            this._removeLocationInternal(this._currentLocationInfo, false);65        let info;66        if (location)67            info = this.addNewLocation(location, true);68        else69            info = null;70        this.emit('current-location-changed', info);71    }72    getRecent() {73        if (this._infoList.length > 0)74            return this._infoList[0];75        else76            return null;77    }78    load () {79        let locations = this._settings.get_value('locations').deep_unpack();80        if (locations.length > 5) {81            locations = locations.slice(0, 5);82            this._settings.set_value('locations', new GLib.Variant('av', locations));83        }84        let info = null;85        for (let i = locations.length - 1; i >= 0; i--) {86            let variant = locations[i];87            let location = this._world.deserialize(variant);88            info = this._addLocationInternal(location, false);89        }90    }91    _updateLoadingCount(delta) {92        let wasLoading = this._loadingCount > 0;93        this._loadingCount += delta;94        let isLoading = this._loadingCount > 0;95        if (wasLoading != isLoading)96            this.notify('loading');97    }98    updateInfo(info) {99        if (info._loadingId)100            return;101        info._loadingId = info.connect('updated', (info) => {102            info.disconnect(info._loadingId);103            info._loadingId = 0;104            this._updateLoadingCount(-1);105        });106        info.update();107        this._updateLoadingCount(+1);108    }109    get loading() {110        return this._loadingCount > 0;111    }112    addNewLocation(newLocation, isCurrentLocation) {113        if (!isCurrentLocation) {114            for (let info of this._infoList) {115                let location = info.location;116                if (location.equal(newLocation)) {117                    this.moveLocationToFront(info);118                    return info;119                }120            }121        }122        let info = this._addLocationInternal(newLocation, isCurrentLocation);123        if (!isCurrentLocation)124            this._queueSaveSettings();125        return info;126    }127    _queueSaveSettings() {128        if (this._queueSaveSettingsId)129            return;130        let id = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 10, () => {131            this._queueSaveSettingsId = 0;132            this._saveSettingsInternal();133            return false;134        });135        this._queueSaveSettingsId = id;136    }137    _saveSettingsInternal() {138        let locations = [];139        for (let i = 0; i < this._infoList.length; i++) {140            if (!this._infoList[i]._isCurrentLocation)141                locations.push(this._infoList[i].location.serialize());142        }143        this._settings.set_value('locations', new GLib.Variant('av', locations));144    }145    saveSettingsNow() {146        if (!this._queueSaveSettingsId)147            return;148        GLib.source_remove(this._queueSaveSettingsId);149        this._queueSaveSettingsId = 0;150        this._saveSettingsInternal();151    }152    moveLocationToFront(info) {153        if (this._infoList.length == 0 || this._infoList[0] == info)154            return;155        this._removeLocationInternal(info, true);156        this._addInfoInternal(info, info._isCurrentLocation);157        // mark info as a manually chosen location so that we158        // save it159        info._isCurrentLocation = false;160        this._queueSaveSettings();161    }162    _removeLocationInternal(oldInfo, skipDisconnect) {163        if (oldInfo._loadingId && !skipDisconnect) {164            oldInfo.disconnect(oldInfo._loadingId);165            oldInfo._loadingId = 0;166            this._updateLoadingCount(-1);167        }168        if (oldInfo == this._currentLocationInfo)169            this._currentLocationInfo = null;170        for (let i = 0; i < this._infoList.length; i++) {171            if (this._infoList[i] == oldInfo) {172                this._infoList.splice(i, 1);173                break;174            }175        }176        this.emit('location-removed', oldInfo);177    }178    _addLocationInternal(newLocation, isCurrentLocation) {179        for (let i = 0; i < this._infoList.length; i++) {180            let info = this._infoList[i];181            if (info.get_location().equal(newLocation))182                return info;183        }184        let info = new GWeather.Info({185            application_id: pkg.name,186            contact_info: 'https://gitlab.gnome.org/GNOME/gnome-weather/-/raw/master/gnome-weather.doap',187            location: newLocation,188            enabled_providers: this._providers189        });190        this._addInfoInternal(info, isCurrentLocation);191        return info;192    }193    _addInfoInternal(info, isCurrentLocation) {194        info._isCurrentLocation = isCurrentLocation;195        this._infoList.unshift(info);196        this.updateInfo(info);197        if (isCurrentLocation)198            this._currentLocationInfo = info;199        this.emit('location-added', info, isCurrentLocation);200        if (this._infoList.length > 5) {201            let oldInfo = this._infoList.pop();202            this._removeLocationInternal(oldInfo);203        }204    }...index.js
Source:index.js  
...31export function startHeartbeat (heartbeatUrl, createXHR) {32    function heartbeat () {33        sendXHR(heartbeatUrl, createXHR)34            .then(status => {35                if (status.code === STATUS.closing && !isCurrentLocation(status.url)) {36                    stopInitScriptExecution();37                    document.location = status.url;38                }39            });40    }41    window.setInterval(heartbeat, HEARTBEAT_INTERVAL);42    heartbeat();43}44function executeInitScript (initScriptUrl, createXHR) {45    if (!allowInitScriptExecution)46        return;47    sendXHR(initScriptUrl, createXHR)48        .then(res => {49            if (!res.code)50                return null;51            /* eslint-disable no-eval,  no-restricted-globals*/52            return sendXHR(initScriptUrl, createXHR, 'POST', JSON.stringify(eval(res.code)));53            /* eslint-enable no-eval, no-restricted-globals */54        })55        .then(() => {56            window.setTimeout(() => executeInitScript(initScriptUrl, createXHR), 1000);57        });58}59export function startInitScriptExecution (initScriptUrl, createXHR) {60    allowInitScriptExecution = true;61    executeInitScript(initScriptUrl, createXHR);62}63export function stopInitScriptExecution () {64    allowInitScriptExecution = false;65}66export function redirect (command) {67    stopInitScriptExecution();68    document.location = command.url;69}70export function checkStatus (statusUrl, createXHR, opts) {71    const { manualRedirect } = opts || {};72    return sendXHR(statusUrl, createXHR)73        .then(res => {74            const redirecting = (res.cmd === COMMAND.run || res.cmd === COMMAND.idle) && !isCurrentLocation(res.url);75            if (redirecting && !manualRedirect)76                redirect(res);77            return { command: res, redirecting };78        });...WeatherContainer.js
Source:WeatherContainer.js  
1import React, { useContext, useEffect, useState } from 'react'2import { getUrls } from '../util/urls'3import { get } from '../util/fetchAPI'4import UnitSwitch from './UnitSwitch'5import SwitchLocation from './SwitchLocation'6import { getCurrentLocation } from '../util/getCurrentLocation'7import CurrentLocation from './CurrentLocation'8import { UnitContext } from '../context/UnitContext'9import '../styles/weatherContainer.css'10import CurrentWeather from './CurrentWeather'11import { formatForecastData } from '../util/formatForecastData'12import Forecast from './Forecast/Forecast'13import { getData } from '../util/getData'14import { LocalStorage } from '../util/LocalStorage'15const storage = new LocalStorage()16export default function WeatherContainer() {17    const [isCurrentLocation, setIsCurrentLocation] = useState(false)18    const { unit, setUnit } = useContext(UnitContext)19    const [weatherObj, setWeatherObj] = useState(null)20    const [forecastObj, setForecastObj] = useState(null)21    const [searchObj, setSearchObj] = useState({ location: '', type: '' })22    const currentLocationClick = () => {23        getCurrentLocation().then(data => {24            if (!data) return25            setSearchObj({ type: 'cord', location: data })26            setIsCurrentLocation(true)27            storage.remove()28        }29        )30    }31    useEffect(() => {32        let data = storage.get()33        if (data) {34            setSearchObj(data)35        }36        else currentLocationClick()37    }, [])38    useEffect(() => {39        const runner = async () => {40            try {41                const { location, type } = searchObj42                if (!location || !type) return43                setWeatherObj(null)44                setForecastObj(null)45                // current46                const url = getUrls[type](location, unit)47                setWeatherObj(await get(url))48                // forecast49                const forecastUrl = getUrls[type](location, unit, true)50                const data = formatForecastData(await get(forecastUrl))51                setForecastObj(data)52            } catch (error) {53                alert(error)54            }55        }56        runner()57    }, [unit, searchObj])58    const getLocation = (weatherObj) => {59        const name = getData.name(weatherObj)60        if (name) return name;61        return getData.coord(weatherObj)62    }63    return (64        <div className='weatherCon'>65            <UnitSwitch setUnit={setUnit}></UnitSwitch>66            <SwitchLocation setSearchObj={setSearchObj} searchObj={searchObj} setIsCurrentLocation={setIsCurrentLocation}></SwitchLocation>67            <CurrentLocation isCurrentLocation={isCurrentLocation} currentLocationClick={currentLocationClick} location={weatherObj && getLocation(weatherObj)} />68            <CurrentWeather weatherObj={weatherObj} />69            <Forecast forecastObj={forecastObj} />70        </div>71    )...Map.js
Source:Map.js  
1import React, { Component } from 'react';2import './Map.css';3import PropTypes from "prop-types";4import Fire from '../Fire/index';5class Map extends Component {6    placeMarker(location, title, isCurrentLocation) {7      const google = window.google;8      let marker = new google.maps.Marker({9        position: location,10        title: title,11        map: this.map,12      });13      this.state.markers.push(marker)14      let newLocation = {lat: location.lat, lng: location.lng}15      let infowindow = new google.maps.InfoWindow({16        content: title,17        position: newLocation,18        pixelOffset: new google.maps.Size(-1.5, -40),19      });20      if (isCurrentLocation === true) {21        infowindow.open(this.map);22      }23      google.maps.event.addListener(marker , 'click', function(){24        infowindow.open(this.map);25      });26    }27    constructor(props) {28      super(props)29      this.placeMarker = this.placeMarker.bind(this)30      this.clearMarkers = this.clearMarkers.bind(this)31      this.placeMarkers = this.placeMarkers.bind(this)32      this.state = {results: props.results, markers: []}33    }34    componentWillMount(){35        /* Create reference to messages in Firebase Database */36        let messagesRef = Fire.database().ref('test_data').limitToLast(100);37        messagesRef.on('child_added', snapshot => {38            /* Update React state when message is added at Firebase Database */39            const message = snapshot.val();40            this.setState({ results: [message].concat(this.state.results) });41            //console.log(this.state.results)42        });43    }44    componentDidMount() {45      const google = window.google;46      let center = {47        lat: 45,48        lng: 0,49      }50      this.map = new google.maps.Map(this.refs.map, {51        mapTypeControl: false,52        fullscreenControl: false,53        streetViewControl: false,54        center: center,55        zoom: 1.556      });57    }58    render() {59        this.clearMarkers()60        this.placeMarkers()61        return (62          <div ref="map" className="map"></div>63        );64    }65    placeMarkers() {66      let results = this.state.results67      //console.log(results.length)68      for(let i = 0; i < results.length; i++) {69        let coordinates = {70          lat: results[i].lat,71          lng: results[i].lon72        };73        this.placeMarker(coordinates, results[i].name, false)74      }75    }76    clearMarkers(map) {77      let markers = this.state.markers78      for(let i = 0; i < markers.length; i++) {79        markers[i].setMap(null)80      }81    }82}83Map.defaultProps = {84    title: "TÃtulo"85};86Map.propTypes = {87    title: PropTypes.string.isRequired88};...link.js
Source:link.js  
1import React, { memo, useMemo } from 'react';2import isEqual from 'react-fast-compare';3import { Box, mergeClass, Text } from 'goods-core';4import { useParsedLocation } from 'src/hooks/parsed-location';5/**6 *7 * @param {React.MouseEvent<HTMLAnchorElement>} e8 */9function isModifiedEvent(e) {10  return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);11}12/** @type {React.NamedExoticComponent<import('./link').LinkProps>} */13const Link = memo(14  ({15    to = '#',16    target = '_self',17    method,18    className,19    c,20    rule = 'body',21    dRule,22    fontFam,23    fSize,24    weight,25    lineHeight,26    letterSpace,27    textAlign,28    onClick,29    children,30    ...props31  }) => {32    const { getHref, goTo, search, pathname } = useParsedLocation();33    const { href, isCurrentLocation, isExternalLink } = useMemo(() => {34      const _href = getHref(to);35      return {36        href: _href,37        isCurrentLocation: _href === `${pathname}${search}`,38        isExternalLink: ['http', 'tel', 'mailto'].some(prefix =>39          (_href || '').startsWith(prefix)40        ),41      };42    }, [to, search, pathname]);43    /** @param {React.MouseEvent} e */44    function _onClick(e) {45      if (isCurrentLocation) {46        if (isModifiedEvent(e)) return;47        e.preventDefault();48        return;49      }50      try {51        if (typeof onClick === 'function') onClick(e);52      } catch (error) {53        e.preventDefault();54        throw error;55      }56      if (!href) {57        e.preventDefault();58        return;59      }60      if (61        !e.defaultPrevented &&62        e.button === 0 &&63        (!target || target === '_self') &&64        !isModifiedEvent(e) &&65        !isExternalLink66      ) {67        e.preventDefault();68        goTo(href, { method });69      }70    }71    return (72      <Box73        cursor='pointer'74        b='none'75        outline='none'76        className={mergeClass('link', className)}77        {...props}78        as='a'79        href={href}80        target={target}81        onClick={_onClick}82      >83        {typeof children === 'string' || typeof children === 'number' ? (84          <Text85            as='span'86            rule={rule}87            dRule={dRule}88            fontFam={fontFam}89            c={c}90            textAlign={textAlign}91            {...(fSize && { fSize })}92            {...(weight && { weight })}93            {...(lineHeight && { lineHeight })}94            {...(letterSpace && { letterSpace })}95          >96            {children}97          </Text>98        ) : (99          children100        )}101      </Box>102    );103  },104  isEqual105);...geolocation.js
Source:geolocation.js  
1import { API_KEY } from '../config.js';2import {getWeather} from './getWeather.js';3import {hidePreloader} from './preloader.js';4import { setWeather } from './setWeather.js';5export let isGeoError = false;6export let isCurrentLocation = false;7let currentGeoURL = ``,8    cachedGeo = {};9localStorage.getItem('cachedGeo') ? 10    cachedGeo = JSON.parse(localStorage.getItem('cachedGeo')) : 11    localStorage.setItem('cachedGeo', JSON.stringify({}));12let geoOptions = {13    enableHighAccuracy: false,14    timeout: 10 * 1000,15    maximumAge: 5 * 60 * 100016}17export const falseCurrentLocation = () => {18    isCurrentLocation = false;19}20function getCurrentLocation (options = {}) {21    return new Promise ((resolve, reject) => {22        navigator.geolocation.getCurrentPosition(resolve, reject, options);23    })24};25const fetchCoordinates = async () => {26    if (cachedGeo.isCached){27        // getWeather(cachedGeo.url);28        setWeather(cachedGeo.temp, 29            cachedGeo.tempMax, 30            cachedGeo.tempMin, 31            cachedGeo.cityName, 32            cachedGeo.condition, 33            cachedGeo.id);34            hidePreloader();35    } 36    try {   37        isCurrentLocation = true;38        const {coords} = await getCurrentLocation(geoOptions);39        const {latitude, longitude} = coords;40        currentGeoURL = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${API_KEY}`;41        getWeather(currentGeoURL);42        cachedGeo.isCached = true;43        cachedGeo.url = currentGeoURL;44        localStorage.setItem('cachedGeo', JSON.stringify(cachedGeo));45        // isCurrentLocation = false;46   47    } catch (error) {48        isGeoError = true;49        const message = document.querySelector('.geolocation-message');50        message.hidden = false;51        console.error('Error CODE: '+ error.code + '. MESSAGE: ' + error.message);52        currentGeoURL = `http://api.openweathermap.org/data/2.5/weather?id=5128581&units=metric&appid=${API_KEY}`;53        getWeather(currentGeoURL);54    }55}...NavMain.js
Source:NavMain.js  
...10    11    return (12        <div>13           {14        isCurrentLocation('/')? <NavBar/>: isCurrentLocation('/cart')? <NavBar/>: <NavBarRegular/>15    } 16        </div>17    )18}...Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button')5        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6    await t.expect(t.ctx.currentLocation).contains('thank-you');7});8import { Selector } from 'testcafe';9test('My first test', async t => {10        .typeText('#developer-name', 'John Smith')11        .click('#submit-button')12        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');13    await t.expect(t.ctx.currentLocation).contains('thank-you');14});Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5    const getLocation = ClientFunction(() => document.location.href);6});Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My test', async t => {3    const getLocation = ClientFunction(() => document.location.href);4    await t.expect(getLocation()).contains('example');5});6test('My test', async t => {7});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3    console.log(await t.eval(() => window.location.href));4    console.log(await t.eval(() => window.location.pathname));5    console.log(await t.eval(() => window.location));6    console.log(await t.eval(() => window.location.toString()));7    console.log(await t.eval(() => window.location.hash));8    console.log(await t.eval(() => window.location.search));9    console.log(await t.eval(() => window.location.origin));10    console.log(await t.eval(() => window.location.host));11});12const item = Selector('.item').withAttribute('id', 'item-1');13await t.click(item);14const item = Selector('.item').withAttribute('id', 'item-1');15await t.click(item.id);16const item = Selector('.item').withAttribute('id', 'item-1');17await t.click(item.getAttribute('id'));18const item = Selector('.item').withAttribute('id', 'item-1');19await t.click(item.data.id);20const item = Selector('.item').withAttribute('id', 'item-1');21await t.click(item.data('id'));22const item = Selector('.item').withAttribute('id', 'item-1');23await t.click(item.data().id);24const item = Selector('.item').withAttribute('id',Using AI Code Generation
1import { Selector } from 'testcafe';2test('My test', async t => {3        .expect(Selector('h1').innerText).eql('Example Domain')4        .expect(Selector('h1').isCurrentLocation).ok();5});6const puppeteer = require('puppeteer');7const assert = require('assert');8(async () => {9    const browser = await puppeteer.launch();10    const page = await browser.newPage();11    await page.waitForSelector('h1');12    const h1 = await page.$('h1');13    const h1Text = await page.evaluate(h1 => h1.innerText, h1);14    assert.equal(h1Text, 'Example Domain');15    const isCurrentLocation = await page.evaluate(() => {16    });17    assert.ok(isCurrentLocation);18    await browser.close();19})();20const playwright = require('playwright');21const assert = require('assert');22(async () => {23    const browser = await playwright.chromium.launch();24    const context = await browser.newContext();25    const page = await context.newPage();26    await page.waitForSelector('h1');27    const h1 = await page.$('h1');28    const h1Text = await page.evaluate(h1 => h1.innerText, h1);29    assert.equal(h1Text, 'Example Domain');30    const isCurrentLocation = await page.evaluate(() => {31    });32    assert.ok(isCurrentLocation);33    await browser.close();34})();35const assert = require('assert');36const { remote } = require('webdriverio');37(async () => {38    const browser = await remote({39        capabilities: {40        }41    });42    await browser.waitForExist('h1');43    const h1Text = await browser.getText('h1');44    assert.equal(h1Text, 'Example Domain');45    const isCurrentLocation = await browser.execute(() => {Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('test', async t => {3    const isCurrentLocation = ClientFunction(() => window.location.href);4    await t.expect(isCurrentLocation()).contains('example');5});6import { ClientFunction } from 'testcafe';7test('test', async t => {8    const isCurrentLocation = ClientFunction(() => window.location.href);9    await t.expect(isCurrentLocation()).contains('example');10});11import { ClientFunction } from 'testcafe';12test('test', async t => {13    const isCurrentLocation = ClientFunction(() => window.location.href);14    await t.expect(isCurrentLocation()).contains('example');15});16import { ClientFunction } from 'testcafe';17test('test', async t => {18    const isCurrentLocation = ClientFunction(() => window.location.href);19    await t.expect(isCurrentLocation()).contains('example');20});21import { ClientFunction } from 'testcafe';22test('test', async t => {23    const isCurrentLocation = ClientFunction(() => window.location.href);24    await t.expect(isCurrentLocation()).contains('example');25});26import { ClientFunction } from 'testcafe';27test('test', async t => {28    const isCurrentLocation = ClientFunction(() => window.location.href);29    await t.expect(isCurrentLocation()).contains('example');30});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My Test', async t => {3    const getLocation = Selector('#populate').value;4});5import { Selector } from 'testcafe';6test('My Test', async t => {7    await t.click('#populate');8    const getLocation = Selector('#populate').value;9});10If you need to get the current URL, use the t.eval() method instead:11import { Selector } from 'testcafe';12test('My Test', async t => {13    const getLocation = await t.eval(() => window.location.href);14});Using AI Code Generation
1import { Selector, t } from 'testcafe';2import { ClientFunction } from 'testcafe';3const getLocation = ClientFunction(() => document.location.href);4test('Test', async t => {5    .expect(getLocation()).contains('localhost:3000');6});7import { Selector, t } from 'testcafe';8import { ClientFunction } from 'testcafe';9const getLocation = ClientFunction(() => document.location.href);10test('Test', async t => {11});12import { Selector, t } from 'testcafe';13import { ClientFunction } from 'testcafe';14const getLocation = ClientFunction(() => document.location.href);15test('Test', async t => {16});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#lst-ib', 'testcafe')4        .click('.jsb > center:nth-child(1) > input:nth-child(1)')5        .expect(Selector('a').withText('TestCafe').exists).ok()6        .expect(Selector('a').withText('TestCafe').isCurrentLocation()).ok();7});Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
