I need a regular expression that follows these conditions: [closed]

  • False if the string contains only numbers (e.g., 12345).
  • False if the string contains only special characters (e.g., !@#$%).
  • True if the string contains only letters (e.g., hello).
  • True if the string contains both letters and special characters (e.g., hello!).
  • True if the string contains both letters and numbers (e.g., hello123).
  • False if the string contains only numbers and special characters together (e.g., 123!).
  • False if the string consists only of spaces or is empty.

To match the conditions described, you can use the following regular expression:

/^(?![d]+$)(?![^ws]+$)(?!d.*[^ws]+$)(?!s+$).+$/

Breakdown of conditions:

  • Just numbers: 12345 → False
  • Just special characters: !@#$% → False
  • Just letters: hello → True
  • Letters with special characters: hello! → True
  • Letters with numbers: hello123 → True
  • Numbers with special characters: 123! → False
  • Only spaces: → False

Overriding hover effects in Web Forms with JavaScript

I am working with a web form where the (table header) elements in a grid change color when I hover over them. However, the hover color stays even after I move the mouse away. This behavior is caused by a method in an internal JavaScript library that adds a class (sf_th_hover) on hover and keeps it active. The hover effect occurs mostly, but not always. I cannot modify the library code directly, so I’m trying to override this behavior using custom JavaScript.

Attempt 1

I tried to remove the hover effect with this code but it was only run when the site was loaded.

document.addEventListener("DOMContentLoaded", function ()
{
    console.log("Fix für sf_th_hover aktiv!");

    function removeHoverEffect()
    {
        document.querySelectorAll(".sf_th_hover").forEach(header =>
        {
            header.addEventListener("mouseleave", function ()
            {
                this.classList.remove("sf_th_hover");
                console.log("sf_th_hover entfernt:", this);
            });
        });
    }

    removeHoverEffect();

    new MutationObserver(mutations =>
    {
        mutations.forEach(mutation =>
        {
            mutation.addedNodes.forEach(node => {
                if (node.nodeType === 1 && node.classList.contains("sf_th_hover"))
                {
                    console.log("Neues sf_th_hover gefunden:", node);
                    node.addEventListener("mouseleave", function ()
                    {
                        this.classList.remove("sf_th_hover");
                        console.log("sf_th_hover entfernt (durch MutationObserver):", this);
                    });
                }
            });
        });
    }).observe(document.body, { childList: true, subtree: true });
});

These logs (for example sf_th_hover entfernt) were never reached.

Attempt 2

I tried to remove the class.

$(document).on("mouseenter", "th", function () {
    $(this).removeClass("sf_th_hover");
    console.log("Fix: sf_th_hover wurde entfernt!");
});

$(document).off("mousemove", "th");

But an error occured:

Uncaught TypeError: $(…).on is not a function

which refers to the line $(document).on("mouseenter", "th", function () {.

I cannot include jQuery, as it breaks the page.

I’m not familiar with JavaScript. I appreciate the help.


The code in the grid is this:
original events

_mouseMove = function () {
                    var _e = $(this);
                    if (this.tagName != 'th') $(this).parents('th:first');
                    _e.toggleClass('sf_th_hover');
                },

And the problem is that it shouldn’t use toggle as far as I understand the situation.

How to pass an array from Javascript to admin-ajax.php using Fetch for processing

I have been struggling these days when passing an array of data in WordPress for processing in admin-ajax.php. I have added a button in the woocommerce hook ‘woocommerce_after_shop_loop_item’ that contains a data-product_id with a class of compare-button. My problem is that I am getting a sort of ‘many times’ stringified array (with escaped quotes, pictures shown). My goal is to pass an array of clicked products Ids to admin-ajax.php and there process this array. I can’t do it probably due to the format of the array as string. If I use json_decode I also get an error (while this way it works if tested in localhost not in WordPress envirennment). If I json decode it first and check if an ID is in the array again it is not working. What I am I doing wrong?


function ps_compare_products_add_enqueue(){
    wp_enqueue_script('ps_script1', plugin_dir_url(__FILE__).'../script/script.js');
    wp_localize_script('ps_script1','ps_object', array(
      "ajax_url" => admin_url("admin-ajax.php")
   ));
 }

function process_array_ids(){

  if(isset($_POST['my_string_array']) && !empty($_POST['my_string_array'])){
    $array = $_POST['my_string_array'];
    //$array = json_decode($array); // if I add this I get null in my console which in not wordpress environment works
    echo json_encode($array); // the only way I found to send back the array but in string format again
    
  }

  wp_die();
}

add_action('wp_enqueue_scripts','ps_compare_products_add_enqueue');

add_action('wp_ajax_my_array_ids_action', 'process_array_ids');

add_action('wp_ajax_nopriv_my_array_ids_action', 'process_array_ids');

```Javascript

document.addEventListener('DOMContentLoaded', function() {
    let compareProducts = []
    var compareButtons = document.querySelectorAll('.compare-button');
    document.addEventListener('click', (e) => {
        if(e.target.matches('.compare-button')){
            var productId = e.target.dataset.product_id; 
            if (!compareProducts.includes(productId)) {
                compareProducts.push(productId);
            }
            fetch_my_array(ps_object.ajax_url, 'POST', compareProducts)
        }
    });
})

async function fetch_my_array(url, post, myArray){
    let myForm = new FormData()
    let my_string_array = JSON.stringify(myArray)
    myForm.append('action', 'my_array_ids_action')
    myForm.append('my_string_array', my_string_array)
   
    const options={
        method: post,
        body: myForm
    }
    const response = await fetch(url, options)
    let result =  await response.json()
    console.log(response)
    console.log(result)
    // console.log(JSON.parse(result.replaceAll('\"','')))

}

How to place divs in the certain way?

how can I center 2 divs in this way ?
link to example

Here is a link to image showhing how it should work regarding to page relative size

How can realize this behavior without using JS, only CSS? If it is impossible, then how to realize it with JS ?

X is size of square div.

On picture there is two examples:
Red frames are pages and black frames are divs.

React native with jest Cannot use import statement outside a module

I’m using react native 0.73.0, react 18.2.0, jest 29.6.3, and @testing-library/react-native 12.4.3. When I run command npx jest src/components/ActionButton/__tests__/ActionButton.test.js --detectOpenHandles it gives me error
`ActionButton › Check render props › should call onPress

Trying to detect host component names triggered the following error:

Cannot use import statement outside a module

There seems to be an issue with your configuration that prevents React Native Testing Library from working correctly.
Please check if you are using compatible versions of React Native and React Native Testing Library.`

my jest config is in package.json,

“jest”: {
“preset”: “react-native”,
“setupFilesAfterEnv”: [
“./setupTests.js”
],
“transform”: {
“^.+.js$”: “babel-jest”
},
“setupFiles”: [
“./jest-setup.js”
],
“transformIgnorePatterns”: [
“node_modules/(?!(jest-)?react-native|@?react-navigation|@react-native-community|react-native-unimodules|@unimodules/.*|unimodules|@unimodules/react-native-adapter|@react-native/js-polyfills|@testing-library/react-native)”
],
“moduleDirectories”: [
“src”,
“node_modules”
],
“moduleNameMapper”: {
“react-native-extended-stylesheet”: “mocks/react-native-extended-stylesheet.js”
},
“moduleFileExtensions”: [
“js”,
“jsx”,
“json”,
“node”
]
}

my test case looks good too, but I’m not sure what’s the problem

import React from 'react';
import {render, fireEvent} from '@testing-library/react-native';
import {ActionButton} from '../ActionButton';

describe('ActionButton', () => {
  describe('Rendering', () => {
    it('should match to snapshot', () => {
      const {toJSON} = render(<ActionButton icon="card" title="Title" />);
      expect(toJSON()).toMatchSnapshot();
    });
  });

  describe('Check render props', () => {
    const title = 'Test';
    const icon = 'card';
    const mockFn = jest.fn();

    it('should render correct title', () => {
      const {getByText} = render(
        <ActionButton icon={icon} title={title} onPress={mockFn} />,
      );
      const titleElement = getByText(title);
      expect(titleElement).toBeTruthy();
    });

    it('should render correct icon', () => {
      const {getByProps} = render(
        <ActionButton icon={icon} title={title} onPress={mockFn} />,
      );
      const iconElement = getByProps({name: icon});
      expect(iconElement).toBeTruthy();
    });

    it('should call onPress', () => {
      const {getByTestId} = render(
        <ActionButton icon={icon} title={title} onPress={mockFn} />,
      );
      const button = getByTestId('action-button'); // Assuming you're using testID to identify the button
      fireEvent.press(button);
      expect(mockFn).toHaveBeenCalledTimes(1);
    });
  });
});

Troubleshooting Steps I’ve Tried:

  1. Verified that @testing-library/react-native is correctly installed.
  2. Ensured babel-jest is being used for transforming files.
  3. Checked transformIgnorePatterns to ensure it’s correctly set up for node_modules.
  4. Confirmed that I’m using the correct versions of React Native and React Native Testing Library.

Questions:

  1. Why is Jest throwing the “Cannot use import statement outside a module” error?
  2. Do I need to modify my Jest configuration further to properly transform dependencies?
  3. Could this be related to an issue with how the ActionButton component is imported?

How to get a class from the constructor of an anonymous class inside it in JS

I have this situation in JS:

class Outer{
    constructor() {
        this.fruit = "orange";
        let inner = new this.Inner();
    }
    Inner = class{
        constructor() {
            // here
        }
    }
}
let outer = new Outer();

From the constructor of the class Inner, how can I get the outer class, as if this was used in the outer constructor?

Sure, I could pass the outer class as a parameter into the inner class’ constructor, or put the outer class in a variable, but is there some actual clean method?

Parsing error: “parserOptions.project”. After migrating eslint to 9.x

On an existing project, migrated Eslint from 8.x to 9.x following https://eslint.org/docs/latest/use/migrate-to-9.0.0

After completing migration and running npx eslint getting following error

0:0  error  Parsing error: "parserOptions.project" has been provided for @typescript-eslint/parser.
The file was not found in any of the provided project(s): eslint.config.cjs

Tried to include this file in tsconfig.json, and eslintignore but dint work.

Registering a plain JS object as Vue component: “Failed to resolve component:”

I new to Vue.js and want to have an app with a component that can be reused. My HTML looks like this:

<body>
  <!-- all component templates will be here, this is a single page app -->
  <div>
    <!-- This is the current root component of the app -->
    <template id="vue-select-station-template">
      <div class="form-like">
        <div class="field-label">
          <label>Field 1</label>
        </div>
        <AutoCompleteComponent class="field-field" :suggestions="cities" :selection.sync="selectedCity" />
        <div class="field-label">
          <label>Field 2</label>
        </div>
        <div class="field-field">
          <select id="field_2"></select>
        </div>
      </div>
    </template>
    <!-- This should be instantiated into AutoCompleteComponent -->
    <template id="vue-auto-complete-template">
      <div style="position:relative" v-bind:class="{'open':openSuggestion}">
        <input class="form-control" type="text" v-model="selection" @keydown.enter='enter' @keydown.down='down'
          @keydown.up='up' @input='change' />
        <ul class="dropdown-menu" style="width:100%">
          <li v-for="suggestion in matches" v-bind:class="{'active': isActive($index)}"
            @click="suggestionClick($index)">
            <a href="#">{{ suggestion }}</a>
          </li>
        </ul>
      </div>
    </template>
  </div>
  <script type="module" src="js/gui/gui_main.js"></script>
  <div id="vue-app"></div>
</body>

And for the AutoCompleteComponent I have AutoCompleteComponent.js:

const AutoCompleteComponent = {
    data: {
        open: false,
        current: 0
    },
    methods: {
        ... omitted for brevity ...
    
    },
    computed: {
    
        //Filtering the suggestion based on the input
        matches() {
            return this.suggestions.filter((str) => {
                return str.indexOf(this.selection) >= 0;
            });
        },
    
        //The flag
        openSuggestion() {
            return this.selection !== "" &&
                   this.matches.length != 0 &&
                   this.open === true;
        }
    },
    template: "#vue-auto-complete-template"
}

export default AutoCompleteComponent;

I tried two ways of adding it to the main app, neither works:

import AutoCompleteComponent from "./AutoCompleteComponent.js";
import * as vue_core from "/node_modules/vue/dist/vue.esm-browser.js"

const app = {
  data() {
    return {
      message: 'Hello Vue!',
      cities: ["Prague", "Brno", "Krakow", "Berlin"],
      selectedCity: ""
    };
  },
  template: "#vue-select-station-template",
  // this is what makes more sense to me, registering it before calling createApp
  components: {AutoCompleteComponent}
};
const vueApp = vue_core.createApp(app);
// tried this too, it did not help
vueApp.component("AutoCompleteComponent", AutoCompleteComponent);
vueApp.mount('#vue-app');

The error I get:

[Vue warn]: Failed to resolve component: autocompletecomponent
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. 
  at <App>

I want all of this to be plain JS and HTML without any transpiling, which is why I use the packaged Vue and directly added an exception to the HTTP server to allow loading it from node_modules.

getting NaN value some times and some times not

I get NaN value when I try to show the value of (item.total_amount,item.price,item.addtional_price) in ejs page but when I debug the variables some time I get the value and some time not!!
this is the nodejs code

const getCustomers = async (req) => {
    const name = req.query.name || null;
  
    try {
      let query = `
        SELECT 
          customers.id AS customer_id,
          customers.name AS customer_name,
          customers.phone AS customer_phone,
          SUM(receipt_vouchers.amount) AS total_amount,
          reservations.price,
          reservations.addtional_price
        FROM 
          customers
        LEFT JOIN 
          receipt_vouchers 
          ON receipt_vouchers.customer_id = customers.id
        LEFT JOIN 
          reservations 
          ON reservations.customer_id = customers.id
      `;
  
      let params = [];
  
      // If a name is provided, add a WHERE clause to filter by customer name
      if (name) {
        query += ` WHERE customers.name ILIKE $1`;
        params.push(`%${name}%`);
      }
  
      // Group by customer and reservation columns to avoid aggregation on reservations values
      query += `
        GROUP BY 
          customers.id, 
          customers.name, 
          customers.phone, 
          reservations.price, 
          reservations.addtional_price
      `;
  
      // Execute the query
      const result = await db.query(query, params);
      return result.rows;
    } catch (error) {
      console.error("Error fetching customers:", error);
      throw error;
    }
  };


app.get("/customers", async (req, res) => {
    try {
        const customers = await getCustomers(req);
        console.log(customers.map(row => row));
        res.render("customers.ejs", { // Ensure the template path is correct
            data: customers
        });
    } catch (error) {
        console.error("Error in /customers route:", error); // Debugging
        res.status(500).json({ error: "Internal Server Error" }); // Handle errors
    }
});

and this is the ejs part

<tbody id="tableBody">
          <% if (data.length > 0) { %>
            <% data.forEach(function(item) {
                console.log("total_amount:", item.total_amount);
                console.log("price:", item.price);
                console.log("additional_price:", item.additional_price);
                let theAmount = parseInt(item.total_amount);
                let thePrice = parseInt(item.price) ;
                let theAdditionalPrice = parseInt(item.additional_price);

                 let total = thePrice + theAdditionalPrice;
                 let balance = total - theAmount;
            %>
              <tr>
                <td><%= item.customer_id %></td>
                <td><%= item.customer_name %></td>
                <td><%= item.customer_phone %></td>
                <td><%= item.total_amount %></td>
                <td><%= total %></td>
                <td><%= balance %></td>
        

and this is the value of debugging

total_amount: null
price: null
additional_price: undefined
total_amount: null
price: null
additional_price: undefined
total_amount: 322523.00
price: 2938429
additional_price: undefined
total_amount: null
price: null
additional_price: undefined
total_amount: 3999.00
price: null
additional_price: undefined
total_amount: 83834.00
price: 39382
additional_price: undefined
total_amount: 2000.00
price: null
additional_price: undefined
total_amount: 10000.00
price: 100000
additional_price: undefined
total_amount: null
price: null
additional_price: undefined

some time is get the value and some time not !!!

I try to change the data type coz I got the data from data base so I change to parseInt & parseFloat but i still getting the same value Nan
I asked AI to solve this problem it suggest to add ( parseFloat(item.additional_price)||0 ) but this will give me a wrong value (0) while I want a real value (not 0)

Load GA4 script from specific component in angular

I am working with angular v12 to build a web page that will be user with different clients, and i can tell the difference between clients based on a query param (realm) which is unique per client, and based on this realm param i get data from back end like custom font colors, users, etc…

Now i want to collect information for users that access only a specific page of the website via google analytics, but these information is not gathered by me, each client can insert his measurement id for his google analytics website and then information for users coming to there realms are gathered by them.

I have a question regarding this, first one is that i tried loading the gtag.js script dynamically from within the component and get the measurement id specifically for that realm, but was faced with some issues like analytics is not able to link the data stream to the web page, (i think its something cause its not finding it in the index.html like when adding meta tags for SEO – correct me if i am wrong -)

This is analytics.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AnalyticsService {
  private isLoaded = false;

  constructor() {}

  loadGoogleAnalytics(measurementId: string): void {
    console.log('hi loadGoogleAnalytics', measurementId);
    if (!measurementId || this.isLoaded) {
      return;
    }

    this.isLoaded = true;

    // Create script tag
    const script = document.createElement('script');
    script.async = true;
    script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
    document.head.appendChild(script);

    // Initialize GA
    script.onload = () => {
      (window as any).dataLayer = (window as any).dataLayer || [];
      function gtag(...args: any[]) {
        (window as any).dataLayer.push(args);
      }
      (window as any).gtag = gtag;

      gtag('js', new Date());
      gtag('config', measurementId);
      this.trackPageView();
    };
  }

  trackPageView(): void {
    console.log('Tracking page view:', window.location.hash);
    if ((window as any).gtag) {
      (window as any).gtag('event', 'page_view', {page_title: document.title, page_path: window.location.hash });
    }
  }  
}

google analytics test tag

so what is a suggested solution to solve this issue?

How to make select cell focused in jquery datatable

Im using Jquery data table

im using 3 fixedColumn when i press shift+tab from end row its navigating each cell but some cell are not focusable its showing half field which difficult identify which field user are entering. how to make focusable input field jquery data table?

Please refer below shift+tab video issue
enter image description here

$(document).ready(function() {
  let data = [];
  for (let i = 1; i <= 100; i++) {
    let row = [];
    for (let j = 1; j <= 20; j++) {
      row.push(`<input type='text' value='Row ${i} Col ${j}'>`);
    }
    data.push(row);
  }

  $('#example').DataTable({
    data: data,
    scrollX: true,
    scrollCollapse: true,
    paging: false,
    fixedColumns: {
      left: 3
    }
  });
});
<link rel="stylesheet" href="https://cdn.datatables.net/2.2.2/css/dataTables.dataTables.css">
<link rel="stylesheet" href="https://cdn.datatables.net/fixedcolumns/5.0.4/css/fixedColumns.dataTables.css">
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script src="https://cdn.datatables.net/2.2.2/js/dataTables.js"></script>
<script src="https://cdn.datatables.net/fixedcolumns/5.0.4/js/dataTables.fixedColumns.js"></script>

<table id="example" class="display nowrap" style="width:100%">
  <thead>
    <tr>
      <th>Fixed 1</th>
      <th>Fixed 2</th>
      <th>Fixed 3</th>
      <th>Column 4</th>
      <th>Column 5</th>
      <th>Column 6</th>
      <th>Column 7</th>
      <th>Column 8</th>
      <th>Column 9</th>
      <th>Column 10</th>
      <th>Column 11</th>
      <th>Column 12</th>
      <th>Column 13</th>
      <th>Column 14</th>
      <th>Column 15</th>
      <th>Column 16</th>
      <th>Column 17</th>
      <th>Column 18</th>
      <th>Column 19</th>
      <th>Column 20</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

How to include Look Up values from One SharePoint list to another list while formatting a list view using json code

I have a SharePoint list [Project List] with few columns like Title,Project Start Date and Project end date.In another SharePoint list [Project Task list] and I have to format the list view to a Gantt chart view with JSON code.But Here, my problem is to include the Project Start Date and Project End Date columns from the Project list as look up columns.How to include them in Json code of mine?

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/row-formatting.schema.json",
  "hideSelection": true,
  "hideColumnHeader": true,
  "rowFormatter": {
    "elmType": "div",
    "style": {
      "height": "=if(@rowIndex == 0, '88px', '52px')",
      "display": "block",
      "width": "100%",
      "position": "sticky"
    },
    "attributes": {
      "class": "ms-bgColor-neutralLighter--hover"
    },
    "children": [
      {
        "elmType": "div",
        "attributes": {
          "class": "ms-bgColor-themePrimary"
        },
        "style": {
          "width": "100%",
          "display": "=if(@rowIndex == 0, 'flex', 'none')",
          "height": "36px",
          "padding": "0",
          "font-weight": "bold",
          "border-radius": "6px 6px 0 0"
        },
        "children": [
          {
            "elmType": "div",
            "txtContent": "Milestone Chart",
            "style": {
              "width": "220px",
              "text-align": "left",
              "padding-left": "0.4em",
              "box-sizing": "border-box"
            },
            "attributes": {
              "class": "ms-fontSize-16 ms-fontColor-white"
            }
          },
          {
            "elmType": "div",
            "style": {
              "flex-grow": "1",
              "height": "100%",
              "position": "relative"
            },
            "children": [
              {
                "elmType": "div",
                "txtContent": "=**toLocaleDateString([$ProjectStart])"**,
                "style": {
                  "position": "absolute",
                  "padding": "14px 4px 0 4px",
                  "height": "22px",
                  "border-radius": "6px 6px 0 0"
                },
                "attributes": {
                  "title": "='Project Start: ' + **toLocaleDateString([$ProjectStart])**",
                  "class": "ms-bgColor-themeDarker ms-fontSize-14 ms-fontColor-white"
                }
              },
              {
                "elmType": "div",
                "txtContent": "=toLocaleDateString([$ProjectDue])",
                "style": {
                  "position": "absolute",
                  "right": "0",
                  "padding": "14px 4px 0 4px",
                  "height": "22px",
                  "border-radius": "6px 6px 0 0"
                },
                "attributes": {
                  "title": "='Project Finish: ' + toLocaleDateString([$ProjectDue])",
                  "class": "ms-bgColor-themeDarker ms-fontSize-14 ms-fontColor-white"
                }
              },
              {
                "elmType": "span",
                "txtContent": "=toLocaleDateString( @now)",
                "style": {
                  "position": "relative",
                  "width": "90px",
                  "z-index": "100",
                  "display": "=if([$ProjectDue] < @now , 'none', 'block')",
                  "left": "=floor( (Number(@now)-Number([$ProjectStart])) / (Number([$ProjectDue])-Number([$ProjectStart])) * 100 ) + '%'",
                  "background-color": "#e1dfdd",
                  "text-align": "center",
                  "padding": "0 3px",
                  "margin": "0 0 0 3px"
                }
              },
              {
                "elmType": "span",
                "attributes": {
                  "class": "ms-fontColor-gray40"
                },
                "style": {
                  "position": "relative",
                  "display": "=if( [$ProjectDue] < @now , 'none', 'block')",
                  "top": "-1.3em",
                  "z-index": "1",
                  "border-left": "5px solid",
                  "height": "800px",
                  "width": "0.1em",
                  "left": "=  (Number(@now)-Number([$ProjectStart])) /  (Number([$ProjectDue])-Number([$ProjectStart]))  * 100  + '%' "
                }
              }
            ]
          }
        ]
      }

vertical surface detection in webxr in andriod webar

I have this webxr code, it is detecting the floor (horizontal surface) correctly (after taking sometime) but its failing when I move my camera towards the wall. I am using chrome on andriod. What I am doing wrong? Is there a way to detect vertical surfaces.

WebXR AR Surface Detection

Start AR

let scene, camera, renderer, xrSession, xrRefSpace;
let hitTestSource = null;
let reticle = null;
let glbModel = null;

    // Load GLB model
    function loadModel() {
        return new Promise((resolve, reject) => {
            const loader = new THREE.GLTFLoader();
            loader.load(
                'ac.glb', // Replace with your GLB file path
                (gltf) => {
                    glbModel = gltf.scene;
                    // Scale your model if needed
                    glbModel.scale.set(1, 1, 1);
                    resolve(glbModel);
                },
                (xhr) => {
                    console.log((xhr.loaded / xhr.total * 100) + '% loaded');
                },
                (error) => {
                    console.error('Error loading model:', error);
                    reject(error);
                }
            );
        });
    }

    async function initAR() {
        if (!navigator.xr) {
            alert("WebXR not supported on this device!");
            return;
        }

        try {
            // Load model before starting AR
            await loadModel();

            const session = await navigator.xr.requestSession("immersive-ar", {
                requiredFeatures: ["hit-test", "local-floor"],
                optionalFeatures: ["dom-overlay"],
                domOverlay: { root: document.body }
            });

            session.addEventListener("end", () => {
                xrSession = null;
                document.getElementById("startAR").style.display = "block";
            });

            session.addEventListener("select", placeObjectAtReticle);

            xrSession = session;
            document.getElementById("startAR").style.display = "none";
            setupXRScene(session);
        } catch (err) {
            console.error("WebXR session failed:", err);
            alert("Error starting AR: " + err.message);
        }
    }

    function setupXRScene(session) {
        const canvas = document.createElement("canvas");
        document.body.appendChild(canvas);
        const gl = canvas.getContext("webgl", { xrCompatible: true });

        renderer = new THREE.WebGLRenderer({ 
            alpha: true, 
            canvas: canvas, 
            context: gl 
        });
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.xr.enabled = true;
        renderer.xr.setSession(session);

        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 100);

        // Improved reticle
        reticle = new THREE.Group();
        
        const reticleRing = new THREE.Mesh(
            new THREE.RingGeometry(0.15, 0.2, 32),
            new THREE.MeshBasicMaterial({ 
                color: 0x00ff00,
                side: THREE.DoubleSide,
                transparent: true,
                opacity: 0.8,
                depthTest: false
            })
        );
        
        reticle.add(reticleRing);
        reticle.visible = false;
        scene.add(reticle);

        // Multiple hit test sources
        /*session.requestReferenceSpace("viewer").then((viewerRefSpace) => {
            Promise.all([
                session.requestHitTestSource({
                    space: viewerRefSpace,
                    offsetRay: new XRRay()
                }),
                session.requestHitTestSource({
                    space: viewerRefSpace,
                    offsetRay: new XRRay({
                        direction: { x: 0, y: -0.5, z: -1 }
                    })
                }),
                session.requestHitTestSource({
                    space: viewerRefSpace,
                    offsetRay: new XRRay({
                        direction: { x: 0, y: 0, z: -1 }
                    })
                })
            ]).then(sources => {
                hitTestSource = sources;
                console.log("Hit test sources created successfully");
            }).catch(err => {
                console.error("Hit test source creation failed:", err);
            });
        });*/
        
        ////another method
        session.requestReferenceSpace("viewer").then((viewerRefSpace) => {
        Promise.all([
                // Default downward hit test (for floors)
                session.requestHitTestSource({
        space: viewerRefSpace,
        offsetRay: new XRRay({ origin: {x: 0, y: 0, z: 0}, direction: {x: 0, y: -0.5, z: -1} })
    }),
    // Forward ray for detecting walls
    session.requestHitTestSource({
        space: viewerRefSpace,
        offsetRay: new XRRay({ origin: {x: 0, y: 1.5, z: 0}, direction: {x: 0, y: 0, z: -1} }) // Ray at eye level
    })
]).then(sources => {
    hitTestSource = sources;
    console.log("Hit test sources created successfully");
}).catch(err => {
    console.error("Hit test source creation failed:", err);
});

});

        ///////////
        
        
        
        
        

        session.requestReferenceSpace("local").then((refSpace) => {
            xrRefSpace = refSpace;
            session.requestAnimationFrame(onXRFrame);
        });
    }

    function onXRFrame(time, frame) {
        frame.session.requestAnimationFrame(onXRFrame);
        
        if (!frame || !xrRefSpace || !hitTestSource) return;
        
        const pose = frame.getViewerPose(xrRefSpace);
        
        if (pose) {
            let hitPose = null;
            
            // Check all hit test sources
            for (let source of hitTestSource) {
                const hitTestResults = frame.getHitTestResults(source);
                if (hitTestResults.length > 0) {
                    hitPose = hitTestResults[0].getPose(xrRefSpace);
                    break;
                }
            }
            
            if (hitPose) {
                reticle.visible = true;
                
                const matrix = new THREE.Matrix4();
                matrix.fromArray(hitPose.transform.matrix);
                
                const position = new THREE.Vector3();
                const quaternion = new THREE.Quaternion();
                const scale = new THREE.Vector3();
                matrix.decompose(position, quaternion, scale);
                
                reticle.position.copy(position);
                reticle.quaternion.copy(quaternion);
                
                // Calculate surface orientation
                const normal = new THREE.Vector3(0, 1, 0);
                normal.applyQuaternion(quaternion);
                const angleWithVertical = normal.angleTo(new THREE.Vector3(0, 1, 0)) * (180 / Math.PI);
                
                // Update reticle color
                const reticleMaterial = reticle.children[0].material;
                if (angleWithVertical < 20) {
                    reticleMaterial.color.setHex(0x00ff00); // Green for horizontal
                } else if (angleWithVertical > 70) {
                    reticleMaterial.color.setHex(0x0000ff); // Blue for vertical
                } else {
                    reticleMaterial.color.setHex(0xffff00); // Yellow for angled
                }
            } else {
                reticle.visible = false;
            }
        }
        
        renderer.render(scene, camera);
    }

    function placeObjectAtReticle() {
        if (!reticle.visible || !glbModel) return;
        
        const modelClone = glbModel.clone();
        modelClone.position.copy(reticle.position);
        modelClone.quaternion.copy(reticle.quaternion);
        
        scene.add(modelClone);
    }

    document.getElementById("startAR").addEventListener("click", initAR);
</script>

Clear react dropdown using javascript dev tools

I am trying to figure out how to clear a dropdown on a website (Atlassian’s Jira’s issue creation form) using plain javascript in the chrome dev tools (with the goal of moving the code over to a userscript like tampermonkey). The page seems to be written in react and I think it’s using react-select for the dropdown. What I can’t figure out is how to click on the little “X” to clear the dropdown once an item is selected. This is a dropdown field that only accepts 1 value (so not multi select/don’t have to worry about multiple X boxes).

I tried grabbing the element and calling .click()/onClick() which didn’t work. Some posts I saw mention using react’s ref but I do not have control over how this page is set up so I don’t think it can be used. I also tried calling the mousedown/mouseup/click events and dispatching those but didn’t seem to do anything.