Best JavaScript code snippet using playwright-internal
OrganizationForms.jsx
Source:OrganizationForms.jsx  
1import React from "react";2import LocationMapModal from "../locations/LocationMapModal";3import {4  Form,5  Label,6  FormGroup,7  Button,8  Row,9  Col,10  Card,11  CardBody,12} from "reactstrap";13import { Formik, Field } from "formik";14import { AddOrganizationSchema } from "./AddOrganizationSchema";15import {16  mergeLocationData,17  getLocationQuery,18  verifyGeoLocation,19  isLocationValid,20} from "../../services/locationFormService";21import { getTypes } from "../../services/locationService";22import debug from "sabio-debug";23import PropTypes from "prop-types";24import Swal from "sweetalert2";25import {26  addOrganization,27  getOrganizationTypes,28  updateOrganization,29} from "../../services/organizationService";30import fileUploadService from "../../services/fileUploadService";3132const _logger = debug.extend("LocationForm");33const feedback = "input-feedback text-danger pl-2";3435// for update protocols look at initiialValues in Formik3637class OrganizationForms extends React.Component {38  constructor(props) {39    super(props);40    this.state = {41      organizationTypes: [],42      mappedOrganizationTypes: [],43      formData: {44        organizationTypeId: "",45        name: "",46        description: "",47        logo: "",48        businessPhone: "",49        siteUrl: "",50        employeesNumber: 0,51        locationId: 0,52        lineOne: "",53        lineTwo: "",54        city: "",55        stateId: 0,56        zip: "",57        locationTypeId: 0,58        acceptLocation: false,59      },60      isAddressVerifying: false,61      isAddressVerified: false,62      isMapShown: false,63    };64  }6566  componentDidMount() {67    this.getSelectTypes();68  }6970  getSelectTypes = () => {71    debugger;72    let data = { ...this.state.formData };73    if (this.props.match.params.id && this.props.location.state) {74      const {75        id,76        organizationType,77        name,78        description,79        logo,80        location,81        businessPhone,82        siteUrl,83        employeesNumber,84      } = this.props.location.state;85      const { lineOne, lineTwo, city, stateId, zip, locationTypeId } = location;86      data = {87        ...this.state.formData,88        id,89        organizationTypeId: organizationType.id,90        name,91        description,92        logo,93        businessPhone,94        siteUrl,95        employeesNumber,96        locationId: location.id,97        lineOne,98        lineTwo,99        city,100        stateId,101        zip,102        locationTypeId,103      };104    }105106    let orgTypes = null;107108    getOrganizationTypes()109      .then((response) => {110        orgTypes = response.items;111        return getTypes();112      })113      .then((response) => {114        const { states, locationTypes } = response.item;115        this.setState((prevState) => {116          return {117            ...prevState,118            states,119            locationTypes,120            mappedStates: states.map(this.mapSelectOptions),121            mappedLocationTypes: locationTypes.map(this.mapSelectOptions),122            formData: data,123            organizationTypes: orgTypes,124            mappedOrganizationTypes: orgTypes.map(this.mapOrganizationOptions),125          };126        });127      })128      .catch(this.onGetTypesFail);129  };130131  onGetTypesFail = (error) => {132    _logger("onGetTypesFail", error);133  };134135  mapOrganizationOptions = (type) => {136    return (137      <option key={type.id} value={type.id}>138        {type.name}139      </option>140    );141  };142143  onUploadFile = (e, values, setValues) => {144    const files = e.target.files;145    const data = new FormData();146    data.append("files", files[0]);147    fileUploadService148      .upload(data)149      .then((response) => {150        const logo = response.items[0].url;151        _logger(logo);152        this.setState(153          (prevState) => {154            return {155              ...prevState,156              formData: {157                ...prevState.formData,158                logo: response.items[0].url,159              },160            };161          },162          () => {163            setValues({164              ...values,165              logo,166            });167          }168        );169      })170      .catch(this.onFileUploadError);171  };172173  onFileUploadError = (response) => {174    _logger(response);175  };176177  onAddOrganizationSuccess = (response) => {178    _logger(response);179    Swal.fire("Success!", "Organization has been added", "success");180    this.props.history.push("/organizations");181  };182183  onUpdateOrganizationSuccess = (response) => {184    _logger(response);185    Swal.fire("Success!", "Organization has been updated", "success");186    this.props.history.push("/organizations");187  };188189  addLocation = (address, setFieldValue) => {190    Object.keys(address).forEach((key) => {191      setFieldValue(key, address[key]);192    });193  };194195  mapSelectOptions = (type) => {196    return (197      <option key={type.id} value={type.id}>198        {type.name}199      </option>200    );201  };202203  toggleMap = () => {204    this.setState((prevState) => {205      return {206        ...prevState,207        isMapShown: !this.state.isMapShown,208      };209    });210  };211212  resetAddressVerified = () => {213    this.setState((prevState) => {214      return {215        ...prevState,216        isAddressVerified: false,217        isAddressVerifying: false,218      };219    });220  };221222  onSetValidLocationToFormFail = (e) => {223    _logger("putValidLocationInState: fail", e);224  };225226  handleVerify = (values, setSubmitting, setValues) => {227    const statesArray = this.state.states;228    const setValidLocationFormData = (validLocationData) => {229      return new Promise((resolve, reject) => {230        if (validLocationData) {231          const mergedData = { ...values, ...validLocationData };232          setValues(mergedData);233          resolve("Able to set valid location data to form");234        } else {235          reject(236            "validLocationData is undefined, unable to set values of location fields in Formik"237          );238        }239      });240    };241242    const setSubmittingToFalse = () => {243      setSubmitting(false);244    };245246    const onVerifyGeoLocationFail = (e) => {247      setSubmittingToFalse();248      this.resetAddressVerified();249      return e;250    };251252    const putValidLocationInState = (results) => {253      const onSetValidLocationFormDataSuccess = () => {254        this.setState((prevState) => {255          return {256            ...prevState,257            isMapShown: false,258            formattedAddress: results.formattedAddress,259            validAddress: results.validAddress,260            isAddressVerified: true,261            isAddressVerifying: false,262          };263        }, setSubmittingToFalse);264      };265266      return setValidLocationFormData(results.newFormAddress)267        .then(onSetValidLocationFormDataSuccess)268        .catch(this.onSetValidLocationToFormFail);269    };270271    const onCatch = (e) => {272      setSubmittingToFalse();273      _logger("tryCatchSequence; fail", e);274    };275276    const tryCatchSequence = () => {277      try {278        verifyGeoLocation(getLocationQuery(values, statesArray))279          .then((response) => {280            return mergeLocationData(response, values, statesArray);281          })282          .then(putValidLocationInState)283          .catch(onVerifyGeoLocationFail);284      } catch (e) {285        onCatch(e);286      }287    };288289    this.setState((prevState) => {290      return {291        ...prevState,292        isAddressVerifying: true,293        isAddressVerified: false,294      };295    }, tryCatchSequence);296  };297298  handleNotValidSubmit = (e, setTouched) => {299    e.preventDefault();300    const touchedFields = {};301    Object.keys(this.state.formData).forEach((key) => {302      touchedFields[key] = true;303    });304    Swal.fire(305      "Uh Oh!",306      "There are issues with your form, verify inputs and all required fields are filled",307      "error"308    );309    setTouched(touchedFields);310  };311312  handleSubmit = (values, { setSubmitting }) => {313    _logger("handleSubmit", values);314    values.organizationTypeId = parseInt(values.organizationTypeId);315    values.employeesNumber = parseInt(values.employeesNumber);316    values.latitude = this.state.validAddress.latitude;317    values.longitude = this.state.validAddress.longitude;318319    if (this.props.match.params.id) {320      updateOrganization(values)321        .then(this.onUpdateOrganizationSuccess)322        .catch((error) => {323          _logger("Update organization failed", error);324          Swal.fire("Error", "Could not update Organization", "error");325          setSubmitting(false);326        });327    } else {328      addOrganization(values)329        .then(this.onAddOrganizationSuccess)330        .catch((error) => {331          _logger("Add organization failed", error);332          Swal.fire("Error", "Could not add Organization", "error");333          setSubmitting(false);334        });335    }336  };337338  render() {339    return (340      <React.Fragment>341        <div className="app-main__inner p-0">342          <div className="app-inner-layout chat-layout">343            <div className="app-inner-layout__header text-white bg-alternate">344              <div className="app-page-title">345                <div className="page-title-wrapper">346                  <div className="page-title-heading">347                    <div className="page-title-icon bg-happy-fisher">348                      <i className="pe-7s-folder text-white"></i>349                    </div>350                    <div>351                      Organizations352                      <div className="page-title-subheading">353                        Organization Listing354                      </div>355                    </div>356                  </div>357                  {/* <div className="page-title-actions">358                    <button359                      className="ladda-button btn btn-pill btn-wide btn-alternate"360                      onClick={handleAdd}361                      data-style="expand-right"362                    >363                      <i className="pe-7s-plus mr-2"> </i>364                      <span className="ladda-label">Add Organization</span>365                      <span className="ladda-spinner"></span>366                    </button>367                  </div> */}368                </div>369              </div>370            </div>371          </div>372        </div>373        <div>374          <img375            className="mb-1 mt-1"376            style={{ maxHeight: 300 }}377            src={this.state.formData.logo && this.state.formData.logo}378            alt="logo"379          />380        </div>381        {this.state.isAddressVerified &&382          this.state.validAddress &&383          this.state.validAddress.latitude &&384          this.state.validAddress.longitude &&385          this.state.formattedAddress && (386            <LocationMapModal387              lat={this.state.validAddress.latitude}388              lng={this.state.validAddress.longitude}389              formattedAddress={this.state.formattedAddress}390              isMapShown={this.state.isMapShown}391              toggleMap={this.toggleMap}392            />393          )}394        <Formik395          enableReinitialize={true}396          validationSchema={AddOrganizationSchema} //org schema?397          initialValues={this.state.formData}398          // For updating utlize the following initialValues prop399          // initialValues={this.props.updateData || this.state.formData}400          onSubmit={this.handleSubmit}401        >402          {(formikProps) => {403            const {404              values,405              touched,406              errors,407              handleSubmit,408              isSubmitting,409              isValid,410              setTouched,411              setSubmitting,412              setValues,413            } = formikProps;414            return (415              <Form416                onSubmit={417                  isValid418                    ? handleSubmit419                    : (e) => {420                        this.handleNotValidSubmit(e, setTouched);421                      }422                }423              >424                <Card className="col-md-9 my-3">425                  <CardBody>426                    <h5 className="card-title">Locations</h5>427                    <Row form className="mt-n1">428                      <Col>429                        <FormGroup>430                          <Label>Address</Label>431                          <Field432                            value={values.lineOne}433                            name="lineOne"434                            id="lineOne"435                            placeholder="1234 Main St"436                            type="text"437                            className={438                              errors.lineOne && touched.lineOne439                                ? "form-control error"440                                : "form-control"441                            }442                            autoComplete="on"443                          />444                          <span className={feedback}>445                            {errors.lineOne &&446                              touched.lineOne &&447                              `${errors.lineOne}`}448                          </span>449                        </FormGroup>450                      </Col>451                    </Row>452                    <Row form className="mt-n1">453                      <Col>454                        <FormGroup>455                          <Label htmlFor="locationLineTwo2">Address 2</Label>456                          <Field457                            value={values.lineTwo}458                            name="lineTwo"459                            id="locationLineTwo2"460                            placeholder="Apartment, studio, or floor"461                            type="text"462                            className={463                              errors.name && touched.name464                                ? "form-control error"465                                : "form-control"466                            }467                            autoComplete="on"468                          />469                          <span className={feedback}>470                            {errors.lineTwo &&471                              touched.lineTwo &&472                              `${errors.lineTwo}`}473                          </span>474                        </FormGroup>475                      </Col>476                    </Row>477                    <Row form className="mt-n1">478                      <Col md={3}>479                        <FormGroup>480                          <Label htmlFor="locationCity2">City</Label>481                          <Field482                            value={values.city}483                            name="city"484                            id="locationCity2"485                            type="text"486                            className={487                              errors.city && touched.city488                                ? "form-control error"489                                : "form-control"490                            }491                            autoComplete="on"492                          />493                          <span className={feedback}>494                            {errors.city && touched.city && `${errors.city}`}495                          </span>496                        </FormGroup>497                      </Col>498                      <Col md={3}>499                        <FormGroup>500                          <Label htmlFor="locationStates">States</Label>501                          <Field502                            value={values.stateId}503                            name="stateId"504                            component="select"505                            id="locationStates"506                            className={507                              errors.stateId && touched.stateId508                                ? "form-control error"509                                : "form-control"510                            }511                            autoComplete="on"512                          >513                            <option value="0"></option>514                            {this.state.mappedStates}515                          </Field>516                          <span className={feedback}>517                            {errors.stateId &&518                              touched.stateId &&519                              `${errors.stateId}`}520                          </span>521                        </FormGroup>522                      </Col>523                      <Col md={3}>524                        <FormGroup>525                          <Label>Zip</Label>526                          <Field527                            value={values.zip}528                            name="zip"529                            id="locationZip2"530                            type="text"531                            className={532                              errors.zip && touched.zip533                                ? "form-control error"534                                : "form-control"535                            }536                            autoComplete="on"537                          />538                          <span className={feedback}>539                            {errors.zip && touched.zip && `${errors.zip}`}540                          </span>541                        </FormGroup>542                      </Col>543                      <Col md={3}>544                        <FormGroup>545                          <Label>Location Type</Label>546                          <Field547                            value={values.locationTypeId}548                            name="locationTypeId"549                            component="select"550                            id="locationType2"551                            className={552                              errors.locationTypeId && touched.locationTypeId553                                ? "form-control error"554                                : "form-control"555                            }556                          >557                            <option value="0"></option>558                            {this.state.mappedLocationTypes}559                          </Field>560                          <span className={feedback}>561                            {errors.locationTypeId &&562                              touched.locationTypeId &&563                              `${errors.locationTypeId}`}564                          </span>565                        </FormGroup>566                      </Col>567                    </Row>568                    <Row form>569                      <FormGroup className="pr-2">570                        <Button571                          type="button"572                          color="secondary"573                          onClick={() => {574                            this.handleVerify(values, setSubmitting, setValues);575                          }}576                          disabled={577                            isSubmitting ||578                            this.state.isAddressVerifying ||579                            !isLocationValid(errors, values)580                          }581                        >582                          Verify583                        </Button>584                      </FormGroup>585                      <FormGroup className="pr-2">586                        <Button587                          className="ml-2"588                          type="button"589                          color="success"590                          onClick={this.toggleMap}591                          disabled={592                            isSubmitting ||593                            this.state.isAddressVerifying ||594                            !isLocationValid(errors, values) ||595                            !this.state.isMapShown596                          }597                        >598                          View Map599                        </Button>600                      </FormGroup>601                      <FormGroup className="inline-block pl-2 float-left">602                        <Label className="pt-2 pb-2">603                          <Field604                            name="acceptLocation"605                            type="checkbox"606                            id="acceptLocation"607                            disabled={!this.state.validAddress}608                            value={values.acceptLocation}609                            className={610                              errors.acceptLocation && touched.acceptLocation611                                ? "form-control error"612                                : "form-control"613                            }614                            style={{615                              width: "22px",616                              height: "22px",617                              display: "inline-block",618                            }}619                          />620                          <span className="pl-2">621                            Accept Address622                            <div className="input-feedback text-danger pl-2">623                              {errors.acceptLocation &&624                                touched.acceptLocation &&625                                `${errors.acceptLocation}`}626                            </div>627                          </span>628                        </Label>629                      </FormGroup>630                    </Row>631                    {/* </CardBody>632                </Card>633                <Card className="main-card my-3 card col-md-9">634                  <CardBody> */}635                    <h5 className="card-title">Organization</h5>636                    <FormGroup>637                      <Label>Organization Types</Label>638                      <Field639                        value={values.organizationTypeId}640                        name="organizationTypeId"641                        component="select"642                        id="organizationTypeId"643                        className={644                          errors.organizationTypeId &&645                          touched.organizationTypeId646                            ? "form-control error"647                            : "form-control"648                        }649                        autoComplete="on"650                      >651                        <option value="0"></option>652                        {this.state.mappedOrganizationTypes}653                      </Field>654                      <span className={feedback}>655                        {errors.organizationTypeId &&656                          touched.organizationTypeId &&657                          `${errors.organizationTypeId}`}658                      </span>659                    </FormGroup>660                    <FormGroup>661                      <Label htmlFor="organizationName">662                        Organization Name663                      </Label>664                      <Field665                        value={values.name}666                        name="name"667                        id="organizationName"668                        placeholder="Business Name"669                        type="text"670                        className={671                          errors.name && touched.name672                            ? "form-control error"673                            : "form-control"674                        }675                        autoComplete="on"676                      />677                      <span className={feedback}>678                        {errors.name && touched.name && `${errors.name}`}679                      </span>680                    </FormGroup>681                    <FormGroup>682                      <Label htmlFor="description">Description</Label>683                      <Field684                        value={values.description}685                        name="description"686                        id="description"687                        placeholder="Description"688                        type="text"689                        className={690                          errors.description && touched.description691                            ? "form-control error"692                            : "form-control"693                        }694                        autoComplete="on"695                      />696                      <span className={feedback}>697                        {errors.description &&698                          touched.description &&699                          `${errors.description}`}700                      </span>701                    </FormGroup>702                    <FormGroup>703                      <Label>Logo</Label>704                      <input705                        multiple706                        name="file"707                        type="file"708                        className="form-control-file"709                        onChange={(e) => {710                          this.onUploadFile(e, values, setValues);711                        }}712                        values={values.logo}713                      />714                    </FormGroup>715                    <FormGroup>716                      <Label htmlFor="businessPhone">717                        Business Phone Number718                      </Label>719                      <Field720                        value={values.businessPhone}721                        name="businessPhone"722                        id="businessPhone"723                        placeholder="Business Phone"724                        type="text"725                        className={726                          errors.businessPhone && touched.businessPhone727                            ? "form-control error"728                            : "form-control"729                        }730                        autoComplete="on"731                      />732                      <span className={feedback}>733                        {errors.businessPhone &&734                          touched.businessPhone &&735                          `${errors.businessPhone}`}736                      </span>737                    </FormGroup>738                    <FormGroup>739                      <Label htmlFor="organizationWebsite">740                        Organization Website741                      </Label>742                      <Field743                        value={values.siteUrl}744                        name="siteUrl"745                        id="siteUrl"746                        placeholder="Site Url"747                        type="text"748                        className={749                          errors.siteUrl && touched.siteUrl750                            ? "form-control error"751                            : "form-control"752                        }753                        autoComplete="on"754                      />755                      <span className={feedback}>756                        {errors.siteUrl &&757                          touched.siteUrl &&758                          `${errors.siteUrl}`}759                      </span>760                    </FormGroup>761                    <FormGroup>762                      <Label htmlFor="numberOfEmployees">763                        Number of Employees764                      </Label>765                      <Field766                        value={values.employeesNumber}767                        name="employeesNumber"768                        id="employeesNumber"769                        placeholder="Number of Employees"770                        type="text"771                        className={772                          errors.employeesNumber && touched.employeesNumber773                            ? "form-control error"774                            : "form-control"775                        }776                        autoComplete="on"777                      />778                      <span className={feedback}>779                        {errors.employeesNumber &&780                          touched.employeesNumber &&781                          `${errors.employeesNumber}`}782                      </span>783                    </FormGroup>784                    <FormGroup style={{ display: "none" }}>785                      <Label htmlFor="locationId">LocationId</Label>786                      <Field787                        value={values.locationId}788                        name="locationId"789                        id="locationId"790                        placeholder="Location Id"791                        type="text"792                        className={793                          errors.locationId && touched.locationId794                            ? "form-control error"795                            : "form-control"796                        }797                        autoComplete="on"798                      />799                      <span className={feedback}>800                        {errors.locationId &&801                          touched.locationId &&802                          `${errors.locationId}`}803                      </span>804                    </FormGroup>805806                    <Button807                      color="primary"808                      type="submit"809                      disabled={isSubmitting}810                    >811                      Submit812                    </Button>813                  </CardBody>814                </Card>815              </Form>816            );817          }}818        </Formik>819      </React.Fragment>820    );821  }822}823824OrganizationForms.propTypes = {825  mappedStates: PropTypes.arrayOf(PropTypes.object),826  mappedLocationTypes: PropTypes.arrayOf(PropTypes.object),827  history: PropTypes.shape({828    push: PropTypes.func,829  }),830  match: PropTypes.shape({831    params: PropTypes.shape({832      id: PropTypes.string,833    }),834  }),835  location: PropTypes.shape({836    state: PropTypes.shape({837      id: PropTypes.number,838      organizationType: PropTypes.shape({ id: PropTypes.number }),839      name: PropTypes.string,840      description: PropTypes.string,841      logo: PropTypes.string,842      locationId: PropTypes.number,843      businessPhone: PropTypes.string,844      siteUrl: PropTypes.string,845      employeesNumber: PropTypes.number,846      location: {847        city: PropTypes.string,848        latitude: PropTypes.number,849        lineOne: PropTypes.string,850        lineTwo: PropTypes.string,851        longitude: PropTypes.number,852        stateId: PropTypes.number,853        zip: PropTypes.string,854        locationTypeId: PropTypes.number,855      },856    }),857  }),858};859
...LocationForm.jsx
Source:LocationForm.jsx  
1import React from "react";2import LocationMapModal from "./LocationMapModal";3import {4  Form,5  Label,6  FormGroup,7  Button,8  Row,9  Col,10  Card,11  CardBody,12} from "reactstrap";13import { Formik, Field } from "formik";14import { addLocationSchema } from "./addLocationSchema";15import {16  mergeLocationData,17  getLocationQuery,18  verifyGeoLocation,19  isLocationValid,20} from "../../services/locationFormService";21import { getTypes } from "../../services/locationService";22import debug from "sabio-debug";23import PropTypes from "prop-types";24import Swal from "sweetalert2";2526const _logger = debug.extend("LocationForm");2728class LocationForm extends React.Component {29  constructor(props) {30    super(props);31    this.state = {32      formData: {33        lineOne: "",34        lineTwo: "",35        city: "",36        stateId: 0,37        zip: "",38        locationTypeId: 0,39        acceptLocation: false,40        example: "",41      },42      isAddressVerifying: false,43      isAddressVerified: false,44      isMapShown: false,45    };46  }4748  componentDidMount() {49    this.getSelectTypes();50  }5152  getSelectTypes = () => {53    getTypes().then(this.onGetTypesSuccess).catch(this.onGetTypesFail);54  };5556  onGetTypesSuccess = (response) => {57    const { states, locationTypes } = response.item;58    this.setState((prevState) => {59      return {60        ...prevState,61        states,62        locationTypes,63        mappedStates: states.map(this.mapSelectOptions),64        mappedLocationTypes: locationTypes.map(this.mapSelectOptions),65      };66    });67  };6869  onGetTypesFail = (error) => {70    _logger("onGetTypesFail", error);71  };7273  mapSelectOptions = (type) => {74    return (75      <option key={`${type.id}.${type.name}`} value={type.id}>76        {type.name}77      </option>78    );79  };8081  toggleMap = () => {82    this.setState((prevState) => {83      return {84        ...prevState,85        isMapShown: !this.state.isMapShown,86      };87    });88  };8990  resetAddressVerified = () => {91    this.setState((prevState) => {92      return {93        ...prevState,94        isAddressVerified: false,95        isAddressVerifying: false,96      };97    });98  };99100  onSetValidLocationToFormFail = (e) => {101    _logger("putValidLocationInState: fail", e);102  };103104  handleVerify = (values, setSubmitting, setValues) => {105    const statesArray = this.state.states;106    const setValidLocationFormData = (validLocationData) => {107      return new Promise((resolve, reject) => {108        if (validLocationData) {109          const mergedData = { ...values, ...validLocationData };110          setValues(mergedData);111          resolve("Able to set valid location data to form");112        } else {113          reject(114            "validLocationData is undefined, unable to set values of location fields in Formik"115          );116        }117      });118    };119120    const setSubmittingToFalse = () => {121      setSubmitting(false);122    };123124    const onVerifyGeoLocationFail = (e) => {125      setSubmittingToFalse();126      this.resetAddressVerified();127      return e;128    };129130    const putValidLocationInState = (results) => {131      const onSetValidLocationFormDataSuccess = () => {132        this.setState((prevState) => {133          return {134            ...prevState,135            isMapShown: false,136            formattedAddress: results.formattedAddress,137            validAddress: results.validAddress,138            isAddressVerified: true,139            isAddressVerifying: false,140          };141        }, setSubmittingToFalse);142      };143144      return setValidLocationFormData(results.newFormAddress)145        .then(onSetValidLocationFormDataSuccess)146        .catch(this.onSetValidLocationToFormFail);147    };148149    const onCatch = (e) => {150      setSubmittingToFalse();151      _logger("tryCatchSequence; fail", e);152    };153154    const tryCatchSequence = () => {155      try {156        verifyGeoLocation(getLocationQuery(values, statesArray))157          .then((response) => {158            return mergeLocationData(response, values, statesArray);159          })160          .then(putValidLocationInState)161          .catch(onVerifyGeoLocationFail);162      } catch (e) {163        onCatch(e);164      }165    };166167    this.setState((prevState) => {168      return {169        ...prevState,170        isAddressVerifying: true,171        isAddressVerified: false,172      };173    }, tryCatchSequence);174  };175176  handleNotValidSubmit = (e, setTouched) => {177    e.preventDefault();178    const touchedFields = {};179    Object.keys(this.state.formData).forEach((key) => {180      touchedFields[key] = true;181    });182    Swal.fire(183      "Uh Oh!",184      "There are issues with your form, verify inputs and all required fields are filled",185      "error"186    );187    setTouched(touchedFields);188  };189190  handleSubmit = (values, { setSubmitting }) => {191    _logger("handleSubmit", values);192    // when ajax call is succesful do a this.state.history.push("/somewhere") to redirect193    // get latitude and longitude from verifiedAddress in state. NOT FROM VALUES!194    Swal.fire("Submit success", "Successfully submitted", "success");195    //use setsubmtiting to false when ajax call fails196    setSubmitting(false);197  };198199  render() {200    return (201      <React.Fragment>202        {this.state.isAddressVerified &&203          this.state.validAddress &&204          this.state.validAddress.latitude &&205          this.state.validAddress.longitude &&206          this.state.formattedAddress && (207            <LocationMapModal208              lat={this.state.validAddress.latitude}209              lng={this.state.validAddress.longitude}210              infoWindowContent={this.state.formattedAddress}211              isMapShown={this.state.isMapShown}212              toggleMap={this.toggleMap}213            />214          )}215        <Formik216          enableReinitialize={true}217          validationSchema={addLocationSchema}218          initialValues={this.state.formData}219          onSubmit={this.handleSubmit}220        >221          {(formikProps) => {222            const {223              values,224              touched,225              errors,226              handleSubmit,227              isSubmitting,228              isValid,229              setSubmitting,230              setValues,231              setTouched,232            } = formikProps;233            return (234              <Form235                onSubmit={236                  isValid237                    ? handleSubmit238                    : (e) => {239                        this.handleNotValidSubmit(e, setTouched);240                      }241                }242              >243                <Card className="col-md-9 my-3">244                  <CardBody>245                    <h5 className="card-title">Locations</h5>246                    <Row form>247                      <Col>248                        <FormGroup>249                          <Label>Address</Label>250                          <Field251                            value={values.lineOne}252                            name="lineOne"253                            id="lineOne"254                            placeholder="1234 Main St"255                            type="text"256                            className={257                              errors.lineOne && touched.lineOne258                                ? "form-control error"259                                : "form-control"260                            }261                            autoComplete="on"262                          />263                          <span className="input-feedback text-danger pl-2">264                            {errors.lineOne &&265                              touched.lineOne &&266                              `${errors.lineOne}`}267                          </span>268                        </FormGroup>269                      </Col>270                    </Row>271                    <Row form className="mt-n1">272                      <Col>273                        <FormGroup>274                          <Label htmlFor="locationLineTwo2">Address 2</Label>275                          <Field276                            value={values.lineTwo}277                            name="lineTwo"278                            id="locationLineTwo2"279                            placeholder="Apartment, studio, or floor"280                            type="text"281                            className={282                              errors.name && touched.name283                                ? "form-control error"284                                : "form-control"285                            }286                            autoComplete="on"287                          />288                          <span className="input-feedback text-danger pl-2">289                            {errors.lineTwo &&290                              touched.lineTwo &&291                              `${errors.lineTwo}`}292                          </span>293                        </FormGroup>294                      </Col>295                    </Row>296                    <Row form className="mt-n1">297                      <Col md={3}>298                        <FormGroup>299                          <Label htmlFor="locationCity2">City</Label>300                          <Field301                            value={values.city}302                            name="city"303                            id="locationCity2"304                            type="text"305                            className={306                              errors.city && touched.city307                                ? "form-control error"308                                : "form-control"309                            }310                            autoComplete="on"311                          />312                          <span className="input-feedback text-danger pl-2">313                            {errors.city && touched.city && `${errors.city}`}314                          </span>315                        </FormGroup>316                      </Col>317                      <Col md={3}>318                        <FormGroup>319                          <Label htmlFor="locationStates">States</Label>320                          <Field321                            value={values.stateId}322                            name="stateId"323                            component="select"324                            id="locationStates"325                            className={326                              errors.stateId && touched.stateId327                                ? "form-control error"328                                : "form-control"329                            }330                            autoComplete="on"331                          >332                            <option value="0"></option>333                            {this.state.mappedStates}334                          </Field>335                          <span className="input-feedback text-danger pl-2">336                            {errors.stateId &&337                              touched.stateId &&338                              `${errors.stateId}`}339                          </span>340                        </FormGroup>341                      </Col>342                      <Col md={3}>343                        <FormGroup>344                          <Label>Zip</Label>345                          <Field346                            value={values.zip}347                            name="zip"348                            id="locationZip2"349                            type="text"350                            className={351                              errors.zip && touched.zip352                                ? "form-control error"353                                : "form-control"354                            }355                            autoComplete="on"356                          />357                          <span className="input-feedback text-danger pl-2">358                            {errors.zip && touched.zip && `${errors.zip}`}359                          </span>360                        </FormGroup>361                      </Col>362                      <Col md={3}>363                        <FormGroup>364                          <Label>Location Type</Label>365                          <Field366                            value={values.locationTypeId}367                            name="locationTypeId"368                            component="select"369                            id="locationType2"370                            className={371                              errors.locationTypeId && touched.locationTypeId372                                ? "form-control error"373                                : "form-control"374                            }375                          >376                            <option value="0"></option>377                            {this.state.mappedLocationTypes}378                          </Field>379                          <span className="input-feedback text-danger pl-2">380                            {errors.locationTypeId &&381                              touched.locationTypeId &&382                              `${errors.locationTypeId}`}383                          </span>384                        </FormGroup>385                      </Col>386                    </Row>387                    <Row form>388                      <FormGroup className="pr-2">389                        <Button390                          type="button"391                          color="secondary"392                          onClick={() => {393                            this.handleVerify(values, setSubmitting, setValues);394                          }}395                          disabled={396                            isSubmitting ||397                            this.state.isAddressVerifying ||398                            !isLocationValid(errors, values)399                          }400                        >401                          Verify402                        </Button>403                      </FormGroup>404                      <FormGroup className="pr-2">405                        <Button406                          className="ml-2"407                          type="button"408                          color="success"409                          onClick={this.toggleMap}410                          disabled={411                            isSubmitting ||412                            this.state.isAddressVerifying ||413                            !isLocationValid(errors, values) ||414                            !this.state.isMapShown415                          }416                        >417                          View Map418                        </Button>419                      </FormGroup>420                      <FormGroup className="inline-block pl-2 float-left">421                        <Label className="pt-2 pb-2">422                          <Field423                            name="acceptLocation"424                            type="checkbox"425                            id="acceptLocation"426                            disabled={!this.state.validAddress}427                            value={values.acceptLocation}428                            className={429                              errors.acceptLocation && touched.acceptLocation430                                ? "form-control error"431                                : "form-control"432                            }433                            style={{434                              width: "22px",435                              height: "22px",436                              display: "inline-block",437                            }}438                          />439                          <span className="pl-2">440                            Accept Address441                            <div className="input-feedback text-danger pl-2">442                              {errors.acceptLocation &&443                                touched.acceptLocation &&444                                `${errors.acceptLocation}`}445                            </div>446                          </span>447                        </Label>448                      </FormGroup>449                    </Row>450451                    <Row>452                      <Col>453                        <FormGroup>454                          <Label>Example</Label>455                          <Field456                            value={values.example}457                            name="example"458                            id="example"459                            placeholder="1234 Main St"460                            type="text"461                            className={462                              errors.example && touched.example463                                ? "form-control error"464                                : "form-control"465                            }466                            autoComplete="on"467                          />468                          <span className="input-feedback text-danger pl-2">469                            {errors.example &&470                              touched.example &&471                              `${errors.example}`}472                          </span>473                        </FormGroup>474                        <Row form>475                          <Col>476                            <Button477                              color="primary"478                              type="submit"479                              disabled={isSubmitting}480                            >481                              Submit482                            </Button>483                          </Col>484                        </Row>485                      </Col>486                    </Row>487                  </CardBody>488                </Card>489              </Form>490            );491          }}492        </Formik>493      </React.Fragment>494    );495  }496}497498LocationForm.propTypes = {499  mappedStates: PropTypes.arrayOf(PropTypes.object),500  mappedLocationTypes: PropTypes.arrayOf(PropTypes.object),501};502
...browserContext.js
Source:browserContext.js  
...374    if (!browserOptions.proxy && browserOptions.isChromium && os.platform() === 'win32') throw new Error(`Browser needs to be launched with the global proxy. If all contexts override the proxy, global proxy will be never used and can be any string, for example "launch({ proxy: { server: 'http://per-context' } })"`);375    options.proxy = normalizeProxySettings(options.proxy);376  }377  if ((0, _utils.debugMode)() === 'inspector') options.bypassCSP = true;378  verifyGeolocation(options.geolocation);379}380function verifyGeolocation(geolocation) {381  if (!geolocation) return;382  geolocation.accuracy = geolocation.accuracy || 0;383  const {384    longitude,385    latitude,386    accuracy387  } = geolocation;388  if (longitude < -180 || longitude > 180) throw new Error(`geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.`);389  if (latitude < -90 || latitude > 90) throw new Error(`geolocation.latitude: precondition -90 <= LATITUDE <= 90 failed.`);390  if (accuracy < 0) throw new Error(`geolocation.accuracy: precondition 0 <= ACCURACY failed.`);391}392function normalizeProxySettings(proxy) {393  let {394    server,...javascript.js
Source:javascript.js  
...255    setTimeout(() => cityInputEl.attr('placeholder', 'Enter City'), 2000);256  }257});258// Modal Functions259function verifyGeolocation() {260  var myModal = new bootstrap.Modal(document.getElementById('myModal'))261  myModal.show()262  263  // Modal Geolocation Allow Event264  var allowGeolocationBtn = $('#allow');265  var myModalEl = $('#myModal')266  var closeGeolocationBtn = $('#close');267  268  myModalEl.on('hidden.bs.modal', function (event) {269    myModal.hide()270  });271  272  allowGeolocationBtn.on('click', function (event) {273    // Check if the User allows finding location to get current weather274    if(!navigator.geolocation) {275      // Default Location276      console.log('Geolocation is not supported by your browser.')277  278    } else {279      // Use User's current location280      navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);281    }282  });283  closeGeolocationBtn.on('click', function (event) {284    myModal.hide();285  })286};287// Geolocation functions288function geolocationSuccess(position) {289  user.lat = position.coords.latitude;290  user.lon = position.coords.longitude;291  $('#modal-txt').text(`Lat: ${user.lat}, Lon: ${user.lon}`)292  oneCallRequest(user.lat, user.lon);293}294function geolocationError() {295  console.log('Unable to retrieve your location');296  cityContainer.text("Allow Geolocation for your location's current weather.");297}298// Get existing search data on load299var user = load();300console.log(user)301if (null === user) {302  user = new User();303  verifyGeolocation();304} else {305  user.searchedCities.forEach(city => {306    createCitySearchBtn(city);307  });308  getCoords(user.lastCitySearched)...weather.js
Source:weather.js  
2    Plugin used: http://simpleweatherjs.com/3    Notes: DO NOT USE 'location'4*/5$(document).ready(function () {6    verifyGeolocation();7    loadSettings();8    $('#weather_switch').hide();9    $('#weather_input_location').hide();10    11    $('#weather_location').hover(function() {12        $('#weather_input_location').show();13        $('#weather_switch').show();14    });15    16    $('#weather_input_location').mouseout(function() {17        $('#weather_input_location').hide();18        $('#weather_switch').hide();19    });20    21    22    $('#weather_onoff').change(function() {23        chrome.storage.sync.get('set_location', function(data) {24            var result = data.set_location;25            setWeather(result);26        });27    });28    $('#weather_input_location').keypress(function(pressedKey) {29        if (pressedKey.which === 13) {30            var data = $('#weather_input_location').val();31            if (data.toUpperCase() === 'DEFAULT') {32                setWeather(null);33                var data = { set_location: null};34                chrome.storage.sync.set(data);35            }36            else if (data !== '' && isValidLocation(data)) {37                setWeather(data);38            }39        }40    });41});42function verifyGeolocation() {43    if ("geolocation" in navigator) {44        $('#weather').show();45    }46    else {47        $('#weather').hide();48    }49}50/* Call initial setWeather() here due to asynchronicity of storage functions */51function loadSettings() {52    chrome.storage.sync.get('metric', function(metricSetting) {53        currentMetric = metricSetting.metric;54        chrome.storage.sync.get('set_location', function(locationSetting) {55            setLocation = locationSetting.set_location;56            if (currentMetric === 'fahrenheit') {...geolocation_component.js
Source:geolocation_component.js  
1define(function(require) {2    var context = require('context'),3    4    GeolocationComponent = {5        verifyGeolocation: function() {6            if (navigator.geolocation) {7                navigator.geolocation.getCurrentPosition(function(position) {8                    this.addGeolocationToForm(position);9                }.bind(this), function(error) {10                    this.handleGeolocationError(error);11                }.bind(this));12            } else {13              console.log('Geolocation is not supported by this browser.');14            }15        },16        addGeolocationToForm: function(position) {17            if (position.coords !== undefined) {18                $.each(position.coords, function(key, value) {19                    this.$('form input[name="exif[' + key + ']"]').val(value);20                }.bind(this));21            }22            if (position.timestamp !== undefined) {23                this.$('form input[name="exif[timestamp]"]').val(position.timestamp);24            }25        }.bind(this),26        handleGeolocationError: function(error) {27            switch(error.code) {28                case error.PERMISSION_DENIED:29                    console.log("User denied the request for Geolocation.");30                    break;31                case error.POSITION_UNAVAILABLE:32                    console.log("Location information is unavailable.");33                    break;34                case error.TIMEOUT:35                    console.log("The request to get user location timed out.");36                    break;37                case error.UNKNOWN_ERROR:38                    console.log("An unknown error occurred.");39                    break;40            }41        }42    };43    return GeolocationComponent;...edit.js
Source:edit.js  
...14            this.listenTo(context, 'list:activity:started', this.starting);15        },16        render: function() {17            if (window.bootstrap.canEnableGeolocation === true) {18                this.verifyGeolocation();19            }20            this.$jobs = this.$('#jobs');21            this.$jobs.empty();22            this.model.jobs.forEach(function(job) {23                this.$jobs.append(new JobView({model: job, collection: job.required_tasks}).render().$el);24            }, this);25            return this;26        },27        submit: function (e) {28            e.preventDefault();29            this.$(".checkin-form-btn").prop('disabled', true);30            this.$(".checkin-form-btn i").removeClass('ic_check').addClass("ic-spin ic_processing");31            this.$('.actions-section form').submit();32        },...job.js
Source:job.js  
...10        template: Templates['thirdchannel/checkins/list/job'],11        initialize: function() {12            if (this.model.canEnableGeolocation === true) {13                setTimeout(function() {14                    this.verifyGeolocation();15                }.bind(this), 100);16            }17        },18        render: function() {19            this.$el.html(this.template(this.model));20            return this;21        },22        startJob: function (e) {23            e.preventDefault();24            if (!this.inprogress) {25                this.inprogress = true;26                this.$('form').submit();27            }28        }...Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch({ headless: false, slowMo: 500 });4  const context = await browser.newContext();5  const page = await context.newPage();6  await page.verifyGeolocation({ latitude: 37.422, longitude: -122.084 });Using AI Code Generation
1const { chromium } = require('playwright');2const assert = require('assert').strict;3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.waitForSelector('text="Your location"');8  await page.click('text="Your location"');9  const geolocation = await page.context().permissions().geolocation();10  assert.strictEqual(geolocation.state, 'granted');11  await page.close();12  await context.close();13  await browser.close();14})();15const { chromium } = require('playwright');16const { verifyGeolocation } = require('playwright-internal-api');17(async () => {18  const browser = await chromium.launch();19  const context = await browser.newContext();20  const page = await context.newPage();21  await page.waitForSelector('text="Your location"');22  await page.click('text="Your location"');23  const geolocation = await verifyGeolocation(page);24  console.log(geolocation);25  await page.close();26  await context.close();27  await browser.close();28})();Using AI Code Generation
1const { _verifyGeolocation } = require('playwright/lib/server/chromium/crBrowser');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  const geolocation = { longitude: 12.492507, latitude: 41.889938 };8  await _verifyGeolocation(geolocation);9  await browser.close();10})();11#### geolocation.set(options)12const geolocation = { longitude: 12.492507, latitude: 41.889938 };13await context.setGeolocation(geolocation);14#### geolocation.clear()15await context.setGeolocation(null);Using AI Code Generation
1const geolocation = {latitude: 51.508, longitude: 0.11};2await context.grantPermissions(['geolocation']);3await context.setGeolocation(geolocation);4await page.waitForSelector('text="Your location"');5const result = await page.$eval('text="Your location"', el => el.textContent);6expect(result).toContain('51.508, 0.11');Using AI Code Generation
1const { verifyGeolocation } = require('@playwright/test');2await verifyGeolocation({latitude: 12.34, longitude: 56.78});3const { verifyGeolocation } = require('playwright-internal-api');4await verifyGeolocation({latitude: 12.34, longitude: 56.78});5### verifyGeolocation(options)6[MIT](LICENSE)Using AI Code Generation
1const { verifyGeolocation } = require('@playwright/test/lib/server/geolocation');2await verifyGeolocation({latitude: 50, longitude: 50});3### BrowserContext.overridePermissions(origin, permissions)4await context.overridePermissions('*', ['geolocation']);5### BrowserContext.setDefaultTimeout(timeout)6await context.setDefaultTimeout(10000);7### BrowserContext.setDefaultNavigationTimeout(timeout)8await context.setDefaultNavigationTimeout(0);9### BrowserContext.setDefaultLoadTimeout(timeout)10await context.setDefaultLoadTimeout(0);11### BrowserContext.setDefaultIdleTimeout(timeout)LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
