cant save data to firebase realtime database

I cant save any data to my firebase database.

I dont get any errors on the site, but no matter what i do, the when i look in the firebase its only null and never change.

here is my code.
HTML

<html>
    <head>
        <title>Testing Site</title>
        <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-app.js" type="module"></script>
        <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-database.js" type="module"></script>
        <script src="func2.js" type="module"></script>       <!--  your js file here -->
    </head>
    <body>
        <form>
            <div id="buildingDiv">
            <h1 id="SellTitle" class="centerAlian">קבלו הצעת מחיר משוערת</h1>                                                     <!--  id for Or  הוא מציק לי -->
            מספר קומות: <input type="text" id="floorNum" name="floorNum"> </br>
            גודל קומה:  
            <select id="floorSize" name="floorSize">
                <option value="Empty"> -- בחר אופציה -- </option>
                <option value="Small">קטן</option>
                <option value="Medium">בינוני</option>
                <option value="Large">גדול</option>
            </select></br></br>  

            מספר לובים: <input type="text" id="lobbyNum" name="lobbyNum"> </br>
            גודל לובי: 
            <select id="lobbySize" name="lobbySize">
                <option value="Empty"> -- בחר אופציה -- </option>
                <option value="Small">קטן</option>
                <option value="Medium">בינוני</option>
                <option value="Large">גדול</option>
            </select></br></br>

            מספר חלונות: <input type="text" id="windowsNum" name="windowsNum"> </br></br>

            האם יש חניון?:
            <select id="parkingLot" name="parkingLot">
                <option value="No">לא</option>
                <option value="Yes">כן</option>
            </select> </br>
            גודל חניון:        <!-- Show only if the select on yes -->
            <select id="parkingSize" name="parkingSize">
                <option value="Empty"> -- בחר אופציה -- </option>
                <option value="Small">קטן</option>
                <option value="Medium">בינוני</option>
                <option value="Large">גדול</option>
            </select></br></br>


            האם יש חדר אשפה?:
            <select id="garbageRoom" name="garbageRoom">
                <option value="No">לא</option>
                <option value="Yes">כן</option>
            </select> </br>
            גודל חדר אשפה:       <!-- Show only if the select on yes -->
            <select id="garbageSize" name="garbageSize">
                <option value="Empty"> -- בחר אופציה -- </option>
                <option value="Small">קטן</option>
                <option value="Medium">בינוני</option>
                <option value="Large">גדול</option>
            </select></br></br>

            
            האם יש גינה?:
            <select id="garden" name="garden">
                <option value="No">לא</option>
                <option value="Yes">כן</option>
            </select> </br>
            גודל גינה:              <!-- Show only if the select on yes -->
            <select id="gardenSize" name="gardenSize">
                <option value="Empty"> -- בחר אופציה -- </option>
                <option value="Small">קטן</option>
                <option value="Medium">בינוני</option>
                <option value="Large">גדול</option>
            </select></br></br>

            תדירות ניקיון: </br>
            <input type="radio" id="onceAWeek" name="cleaningFrequency" value="OnceAWeek"> פעם בשבוע</br>
            <input type="radio" id="twiceAWeek" name="cleaningFrequency" value="TwiceAWeek"> פעמיים בשבוע </br>
            <input type="radio" id="ThreeAWeek" name="cleaningFrequency" value="ThreeAWeek"> שלוש פעמים בשבוע</br></br>
            <button type="button" class="centerAlian">קבל הצעת מחיר משוערת</button>              <!-- Add onclick function, the next p tag is for the results (unhide and put result)-->
            <p style="visibility: visible;" id="priceResult" class="centerAlian"></p>מחיר כלשהו</p>
            </div>


            <div id="clientDiv">
            <h1>פרטי לקוח</h1>
            עיר: 
            <select id="city" name="city">
                <option value="Akko">עכו</option>       
                <option value="Nahariya">נהריה</option>
            </select></br></br>

            רחוב: <input type="text" id="street" name="street"> </br></br>

            מספר ביניין: <input type="text" id="buildingNum" name="buildingNum"> </br></br>
            <div id="person1Div">
            <h3>איש קשר 1</h3>
            שם פרטי: <input type="text" id="fName1" name="fName1"></br></br>
            שם משפחה: <input type="text" id="lName1" name="lName1"></br></br>
            מספר טלפון: <input type="text" id="phone1" name="phone1"></br></br>
            Email: <input type="text" id="email1" name="email1"></br></br>
            </div>
            <div id="person2Div">
            <h3 id="person2Title">איש קשר 2</h3>
            שם פרטי: <input type="text" id="fName2" name="fName2"></br></br>
            שם משפחה: <input type="text" id="lName2" name="lName2"></br></br>
            מספר טלפון: <input type="text" id="phone2" name="phone2"></br></br>
            Email: <input type="text" id="email2" name="email2"></br></br>
            </div>
            </div>
            </br>
            בקשות מיוחדות:</br> <textarea name="specialRequest" rows="8" cols="50">הכנס את הבקשה שלך</textarea> </br></br>

            <button type="button" onclick="ordernow()">שליחת טופס</button>                         <!-- Add onclick function -->
            <button type="button" onclick="">ניקוי טופס</button>                         <!-- Add onclick function -->
        </form>
    </body>
</html>

**
JS**

// firebase server data
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.8.0/firebase-app.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/10.8.0/firebase-database.js";
const firebaseConfig = {
  apiKey: "***************************,
  authDomain: "***************************,
  databaseURL: "***************************",
  projectId: "***************************",
  storageBucket: "***************************",
  messagingSenderId: "***************************",
  appId: "***************************"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
// Initialize Realtime Database and get a reference to the service


function ordernow(){
  // Get all items
  var floorNum = document.getElementById('floorNum').value;
  var floorSize = document.getElementById('floorSize').value;
  var lobbyNum = document.getElementById('lobbyNum').value;
  var lobbySize = document.getElementById('lobbySize').value;
  var windowsNum = document.getElementById('windowsNum').value;
  var parkingLot = document.getElementById('parkingLot').value;
  var parkingSize = document.getElementById('parkingSize').value;
  var garbageRoom = document.getElementById('garbageRoom').value;
  var garbageSize = document.getElementById('garbageSize').value;
  var garden = document.getElementById('garden').value;
  var gardenSize = document.getElementById('gardenSize').value;
  var onceAWeek = document.getElementById('onceAWeek').checked;
  var twiceAWeek = document.getElementById('twiceAWeek').checked;
  var ThreeAWeek = document.getElementById('ThreeAWeek').checked;
  var CleaningPerWeek = onceAWeek ? "lowonceAWeek" : (twiceAWeek ? "twiceAWeek" : (ThreeAWeek ? "ThreeAWeek" : "none"));
  var city = document.getElementById('city').value;
  var street = document.getElementById('street').value;
  var buildingNum = document.getElementById('buildingNum').value;
  var fName1 = document.getElementById('fName1').value;
  var lName1 = document.getElementById('lName1').value;
  var phone1 = document.getElementById('phone1').value;
  var email1 = document.getElementById('email1').value;
  var fName2 = document.getElementById('fName2').value;
  var lName2 = document.getElementById('lName2').value;
  var phone2 = document.getElementById('phone2').value;
  var email2 = document.getElementById('email2').value;

  set(ref(db, 'client/' + phone1), {
  Contact1: {FirstName: fName1, LastName:lName1, PhoneNumber: phone1,email: email1},
  Contact2: {FirstName: fName2, LastName:lName2, PhoneNumber: phone2,email: email2},
  Address: {City: city, sStreet: street, BuildingNum: buildingNum},
  BuildingData: {Floors: floorNum,FloorSize: floorSize,Lobbys: lobbyNum,Lobbysize: lobbySize,
  Winows: windowsNum, ParkingLot: parkingLot, ParkingLotSize: parkingSize, GarbageRoom: garbageRoom,
  GarbageRoomSize: garbageSize,Garden: garden,GardenSize: gardenSize},
  CleaningPerWeek:CleaningPerWeek
})
.then(() => {
  console.log('Data successfully written to Firebase');
})
.catch((error) => {
  console.error('Error writing to Firebase: ', error);
});
}

3d-force-graph bidirectional links

I have the following graph

const gData = {
    nodes: [{ id: 2 }, { id: 3 }],
    links: [
        { source: 2, target: 3 },
        { source: 3, target: 2 }]
};

const Graph = ForceGraph3D()
    (document.getElementById('3d-graph'))
    .graphData(gData)
    .linkDirectionalArrowLength(3.5)
    .linkDirectionalArrowRelPos(1)
    .linkCurvature(0.2);

As you can see I have 2 nodes and 2 links.

Those links are directional (I mean that visually they are represented with an arrow from source to target)

The problem is when we are going through big graphs, those directional links pose a problem.

I want to make them bidirectional. If there is a link from A to B and B to A (like in the example) I want one link but with 2 tips on the arrow.

I know that if I go for

.linkCurvature(0);

visually there will be only one link but actually, there are still 2 on each other.

Here is a codepen:
Graph

Angular reusable component

I’m creating a foreign language learning app in Angular 15. I have a lot of pages/components with different content. I thought that I will add a possibility of adjusting the font type, size etc for each page/component. I do not want to repeat the same code on each of the pages and thought that it would be best to create a separate component called reading.settings. But now my question is how can component reading.settings be able to change font size, font type on a different component? Does anyone have an idea how to implement something like this? Thank you in advance for any answers

Is it possible to do with Input and Output? If so then how?

TypeError: (0 , html_to_docx__WEBPACK_IMPORTED_MODULE_0__.HTMLtoDOCX) is not a function

I used the html-to-docx module to generate a content on the website to a docx file. After running this, this error appears here

✓ Compiled /api/convert in 420ms (86 modules)
⨯ src/pages/api/convert.js (4:19) @ req
⨯ TypeError: (0 , html_to_docx__WEBPACK_IMPORTED_MODULE_0__.HTMLtoDOCX) is not a function
at handler (webpack-internal:///(api)/./src/pages/api/convert.js:9:67)

this is pages/api/covert.js

import { HTMLtoDOCX } from "html-to-docx";

export default async function handler(req, res) {
  await HTMLtoDOCX(req.body, null, {
    table: { row: { cantSplit: true } },
    footer: true,
    pageNumber: true,
  });
}

Please tell me how to fix this error or explain me an alternative way to convert the html code into a docx

Alpine js not defind type

Im trying to build out the second part of this tutorial https://joeyfarruggio.com/wordpress/skeleton-loader/.
First part is working well, however now i try and add the second part for a load more button, im starting to get a few errors that im trying to fix.

on page load im seeings

cdn.min.js:5 Uncaught ReferenceError: category is not defined
at [Alpine] category == 835 ? ‘active’ : ” (eval at (cdn.min.js:5:665), :3:33)
at cdn.min.js:5:1068
at fr (cdn.min.js:1:6642)
at cdn.min.js:5:31317
at r (cdn.min.js:5:16370)
at Object.Zr [as effect] (cdn.min.js:5:16158)
at N (cdn.min.js:1:398)
at cdn.min.js:1:511
at Function.xn (cdn.min.js:5:31311)
at r (cdn.min.js:5:2273)

and on category click, im getting

Alpine Expression Error: filterPosts is not defined

Expression: “filterPosts(835)”

<a hreff @click=​”filterPosts(835)​” class=​”active”>​cat b​​
te @ cdn.min.js:1
(anonymous) @ cdn.min.js:5
Promise.catch (async)
(anonymous) @ cdn.min.js:5
fr @ cdn.min.js:1
(anonymous) @ cdn.min.js:5
o @ cdn.min.js:5
(anonymous) @ cdn.min.js:5
(anonymous) @ cdn.min.js:5

This is the code i have tried, I cant see why category is not defined and filterPost not defind. Ive been at this hours any help is much appreciated.

<?php /* Template Name: test */ 
?>
<html>
<head>
     <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
     <script>

document.addEventListener('alpine:init', () => {

Alpine.data("filterPosts", (adminURL) => ({
posts: null,
    category: null,
    showDefault: true,
    showFiltered: false,
    loading: false,
    offset: 0,
    loadingNew: false, // <--- defaults to false
    loadingMore: false, // <--- defaults to false

filterPosts(id) {
    this.loadingNew = true;
    this.showFiltered = true;
    this.category = id;
    this.offset = 0; // <-- reset offset to zero
    this.fetchPosts();
},
    
    loadMore() {
    this.loadingMore = true;
        this.offset += 10;
        this.showFiltered = true;
        this.fetchPosts(true);
},

// append defaults to false 
    fetchPosts(append = false) {
        var formData = new FormData();
        formData.append("action", "ajaxPosts");
        formData.append("offset", this.offset); // <-- Add new data to the form

        ...

        fetch(adminURL, {
            method: "POST",
            body: formData,
        })
        .then((res) => res.json())
        .then((res) => {
            if (append) {
                // Appends posts to the end of existing posts data
                this.posts = this.posts.concat(res.posts);
            } else {
                // Resets the posts data with new data
                this.posts = res.posts;
            }

            this.loading = false;
        });
    },
    getTotal() {
    var formData = new FormData();
    formData.append("action", "filterPosts");

    fetch(adminURL, {
        method: "POST",
        body: formData,
    })
    .then((res) => res.json())
    .then((res) => {
        this.total = res.total;
    });
},

init() {
    this.getTotal();
}
}));
})

    
     </script>
</head>
<body>
    <div x-data="filterPosts('<?php echo admin_url('admin-ajax.php'); ?>')">
        
        
<section <?php theme_section_attr_id() ?> <?php theme_section_attr_class('main-section js-posts') ?>>
  <div class="container">
    <div class="heading mx-0">
      <?php $before_title = get_sub_field('before_title');
      if ($before_title) : ?>
        <strong class="sub-title"><?php echo $before_title ?></strong>
      <?php endif ?>
      <?php $title = get_sub_field('title');
      if ($title) : ?>
        <h2><?php echo $title ?></h2>
      <?php endif ?>
    </div>

      <div class="head js-posts-search-text">
        <?php if ($search_value) : ?>
          <h2 class="h5 fw-semibold"><?php printf(__('Showing results for “%s”', 'base'), $search_value) ?></h2>
        <?php endif ?>
      </div>
      
<!--alipne js dynamic post start-->
    <div class="has-filter row flex-md-row-reverse">
        <div class="col-md-8 col-lg-9 js-posts-holder">
                <!-- Posts Column -->
            <div x-show.important="showDefault" class="row cards-area js-posts-items">
                <!-- Default posts query -->
                <?php get_template_part( 'template-parts/posts-filter/default-query' ); ?>
            </div>
             <!-- Load More Posts -->
  <!-- Load More Posts -->
<div @click="loadMore()" x-show="total > (limit + offset)" class="text-center mt-12">
    <button class="border border-solid border-slate-700 text-slate-100 hover:bg-slate-800 px-4 py-2">
        Load More
    </button>
</div>
                <!-- Filtered posts -->
            <div x-show.important="showFiltered" x-html="posts" class="row cards-area js-posts-items">
                <!-- Default posts query -->
            </div>
            
             <template x-if="loadingNew || loadingMore">
        <div class="grid grid-cols-2 gap-6">
            <template x-for="i in 4">
                <div>
                    <div class="h-52 w-full bg-slate-200 rounded-lg"></div>
                    <div class="h-8 w-1/2 bg-slate-200 rounded-lg mt-4"></div>
                </div>
            </template>
        </div>
    </template>
        </div>
                
        <!-- Filtered posts -->
        <div class="col-md-4 col-lg-3">
             <aside class="sidebar">
                 <div class="widget widget-filter">
                     <button class="widget-title">Explore Topics</button>
                     <svg class="separator" viewBox="0 0 238 11" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
                <line opacity="0.3" y1="0.5" x2="101.942" y2="0.5" stroke="#3CD5AF"></line>
                <line opacity="0.3" y1="10.5" x2="237.5" y2="10.5" stroke="#3CD5AF"></line>
              </svg>
            <?php 
                $categories = get_categories();
                if ( ! empty( $categories ) ) : 
            ?>
            <ul class="filter-list">
                <?php foreach ( $categories as $category ) :
                
                // Skip "Uncategorized" category
                if ($category->name == 'Uncategorized') continue; ?>    
        
                   <li :class=" category == <?php echo $category->term_id; ?> ? 'active' : ''">
            <a hreff="" @click="filterPosts(<?= $category->term_id; ?>)"><?= esc_html( $category->name ); ?></button>
        </li>
                
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>
            </div>
</aside>
        <!-- Filtered end -->
          </div>   
    </div>
    </div>
<!--alipne js dynamic post end-->

</section>
</div>

</body>
</html>







IOnic Storage forEach returns nor all entries

I’m using the ionic storage.
In the storage I have 41 entries. Now I would like to read them all into an array. Furthermore, I’d like to filter some out.
My code is the following:

async getEntries() {
 this.trackingEntries = [];
 let promise = new Promise((resolve, reject) => {
  this.storage.forEach((value, key, index) => {
    if (key != "Options0" && key != "Options1" && key != "Options2" && key != "Options3" && key != "welcome" && key != "LockedOptions") {
      this.trackingEntries.push(value);
      console.log(index, value)
    }
  }).then(() => {
    console.log(this.trackingEntries)
    resolve(this.trackingEntries.length);
  });
});
return promise;
}

My problem is, that the function returns different values. Sometimes 33, sometimes 38 and so on.
Can somebody help me to fix this?

What causes “filterSelection is not defined” whenever I try to press a button on this html script?

I have been trying to work on a media database built on HTML, Javascript and MySQL, but the buttons used to filter different media types don’t work. Anytime I try to activate the site, the debug console gives me an error.

Here is the main code and the part this code has a problem with:

<div id="Category">
  <div id="myBtnContainer">
    <button class="btn active" onclick="filterSelection('all')"> Show all</button>
    <button class="btn" onclick="filterSelection('pictures')"> Pictures</button>
    <button class="btn" onclick="filterSelection('videos')"> Videos</button>
    <button class="btn" onclick="filterSelection('pdf')"> PDF</button>
  </div>
</div>

Here is the portion of the code, which does have the “filterSelection” defined.

<script src="scripts/require.js">
    filterSelection("all")
    const mysql = require('mysql');

    const servername = "localhost";
    const username = "root";
    const password = "";
    const dbname = "Database";

    function filterSelection (category) {
  var elements = document.getElementsByClassName("filterDiv");
  if (category == "all") {
    category = "";
  }
    for (var i = 0; i < elements.length; i++) {
            removeClass(elements[i], "show");
        if (elements[i].className.indexOf(category) > -1) {
            addClass(elements[i], "show");
        }
    }
    }

    function addClass(element, name) {
  var arr1 = element.className.split(" ");
  var arr2 = name.split(" ");
  for (var i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {
      element.className += " " + arr2[i];
    }
  }
}

    function removeClass(element, name) {
    var arr1 = element.className.split(" ");
    var arr2 = name.split(" ");
    for (var i = 0; i < arr2.length; i++) {
        while (arr1.indexOf(arr2[i]) > -1) {
        arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
  }
    element.className = arr1.join(" ");
}

var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
    // Create connection
    const conn = mysql.createConnection({
    host: servername,
    user: username,
    password: password,
    database: dbname
    });

    // Check connection
    conn.connect((err) => {
    if (err) {
        console.error("Connection failed: " + err.stack);
        return;
    }
    console.log("Connected as id " + conn.threadId);
    });

    const sql = "SELECT * FROM files";
    conn.query(sql, (err, result, fields) => {
        if (err) throw err;
        if (result.length > 0) {
        // output data of each row
        result.forEach((row) => {
        console.log(`<a href='material/${row.name}'>${row.name}</a><br>`);
        });
    } else {
        console.log("0 results");
    }
    });

    conn.end();

    </script>

Here is the error Debug console gives out whenever I try to press one of the buttons

Uncaught ReferenceError ReferenceError: filterSelection is not defined

I’ve tried putting the div code both above and below the portion, and also try to put the portion on its own file but then “require” does not work. Even if it had worked I’m sure the “Uncaught ReferenceError ReferenceError: filterSelection is not defined” error would have still happened.

Close React Tooltip at Escape character

Requirement: I am using @react-tooltip 4.2, I need to close it when the user presses escape.

Unsuccessful Attempt:

<ReactTooltip id={ "tooltip" } effect="solid" role="status" globalEventOff={ ['click', 'escape'] } eventOff="escape">
     Some Content
</ReactTooltip>

What am I doing wrong?

I get a 401 message woocommerce_rest_cannot_view

Using Postman with Bearer authorization and using the follwoing url https://website.nl/wp-json/wc/v3/orders, I get this error message:

{
    "code": "woocommerce_rest_cannot_view",
    "message": "Je kunt gegevensbronnen niet weergeven.",
    "data": {
        "status": 401
    }
}

This is the code I want to use:

function fetchOrderData(orderNumber) {
    return new Promise(function(resolve, reject) {
        var apiUrl = 'https://website.nl/wp-json/wc/v3/orders?order_number=' + orderNumber;
        fetch(apiUrl, {
            headers: {
                'Authorization': 'Bearer token'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch order details');
            }
            return response.json();
        })
        .then(orderDetails => {
            if (orderDetails && orderDetails.length > 0) {
                var customerInfo = orderDetails[0].billing;
                resolve(customerInfo);
            } else {
                reject(new Error('Order not found'));
            }
        })
        .catch(error => {
            console.error('Error fetching order data:', error);
            reject(error);
        });
    });
}

The user is the ‘shopmanager’ with the Bearer authorization. No specific settings set in Woocommerce.
I make use of a nginx server.

I checked many things like: Bearer Token, token permissions, API Endpoint URL, API version, plugin conflicts, etc.

How can i solve the 401 error? Looking forward for the solution.

Highcharts xaxis start from 0

I have the following Highchart:
Current Chart

I want to start the dates from the 1st point at 0,0 so that it looks like this:
enter image description here

Here is a fiddle: https://jsfiddle.net/87230rms/

HTML:

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/variwide.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
    <div id="container"></div>
</figure>

JS:

Highcharts.chart('container', {
  yAxis: {
    min: 0
  },

  xAxis: [
    {
      categories: ["01-23","02-23","03-23","04-23"]
    }
  ],    

  legend: {
    enabled: false
  },

  series: [
    {
      data: [10,20,30,40]
    }
  ]
});

Prevent React from closing the HTML modal dialog

I am trying to prevent the modal window from closing if the status of the createAsyncSomething operation is error, however, it does close for some reason. I have researched some options, and attempted to wrap the handleSubmit function with the useCallback hook, and memoise the Modal component itself, which did not help. The component still closes the modal window during submission, even though the closeModal function is not triggered within the modal.

export const SomeComponent = () => {
  const modalRef = useRef<HTMLDialogElement>(null);

  const handleSubmit = async () => {
    try {
      ...

      const status = await createAsyncSomething({ input: inputData });

      if (status === Status.Error) {
        setShouldCloseModal(false);
        return;
      }

      setShouldCloseModal(true);
      handleResetFormValues();
      handlePageReload();
    } catch (err) {
      setShouldCloseModal(false);
    }
  };

  const handleFormSubmit = useCallback(() => handleSubmit, [])

  const renderForm = () => {
    switch (selectedForm) {
      case ...:
        return (
          <SomeComponent
            formData={formData}
            onChange={handleChange}
          />
        );
      case ...:
        return (
          <SomeComponent
            formData={formData}
            onChange={handleChange}
          />
        );
      default:
        return (
          <SomeComponent />
        );
    }
  };

  const modal = useMemo(() => (
    <Modal
        onConfirmClick={() => handleFormSubmit()}
        focusOnModal={false}
        shouldCloseOnConfirm={shouldCloseModal}
        isAccessible
      >
        <div className="" />
        {renderForm()}
      </Modal>
  ), [apiTypeOptions, dataStreamTypeOptions, handleFormSubmit, renderForm, shouldCloseModal, t])

  return (
    <Fragment>
      <div>
        <Button
          // Button to open the modal window
          onClick={() => modalRef.current?.showModal()}
        />
      </div>
      {modal}
    </Fragment>
  );
};

export default;

Custom modal component:

export const Modal = forwardRef<HTMLDialogElement, Readonly<ModalProps>>(
  (
    {
      onConfirmClick,
      isAccessible,
      shouldCloseOnConfirm = true
    },
    ref
  ) => {
    const formRef = useRef<HTMLFormElement>(null);

    useEffect(() => {
      if (handleBodyAreaClick) {
        const handleClickOutside = (event) => {
          if (
            typeof ref === 'object' &&
            ref?.current &&
            formRef?.current &&
            !formRef.current.contains(event.target)
          ) {
            if (shouldCloseOnConfirm) {
              ref.current.close();
            }
          }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
          document.removeEventListener('mousedown', handleClickOutside);
        };
      }
    }, [ref, handleBodyAreaClick, shouldCloseOnConfirm]);

    useEffect(() => {
      if (!onCancelClick) return;
      const handleKeyDown = (event) => {
        if (event.key === 'Escape') {
          onCancelClick();
        }
      };
      document.addEventListener('keydown', handleKeyDown);
      return () => {
        document.removeEventListener('keydown', handleKeyDown);
      };
    }, [onCancelClick]);

    const closeModal = () => {
      console.log('closing');
      if (typeof ref === 'object' && ref?.current) {
        // Is not triggered on clicking submit
        ref.current.close();
      }
    };

    return (
      <BaseModal
        isAccessible={isAccessible}
      >
        <form
          ref={formRef}
          method="dialog"
        >
          <div>
            <button
              data-testid={`${dataTestId}-close`}
              onClick={() => {
                closeModal();
                onCancelClick?.();
              }}
            >
            </button>
          </div>
          {children}
          <div className="flex gap-2 justify-end">
            <Button
              type="reset"
              onClick={() => {
                closeModal();
                onCancelClick?.();
              }}
            />
            <Button
              type="submit"
              onClick={() => {
                onConfirmClick();
                if (shouldCloseOnConfirm) {
                  console.log('closing');
                  closeModal();
                }
              }}
            />
          </div>
        </form>
      </BaseModal>
    );
  }
);

Is there a way to hide an HTML element from a user yet let the JS think it is visible?

I am trying to implement a feature that hides a portion of a web UI whose rendering I have no control of (in the context of a browser extension – I don’t have access to the host page’s code), but in the hidden part I need the normal behaviour to happen, and I think it only happens when that area of the page I’m hiding (with a position absolute div with large z-index) is detected as being visible by the JS (think infinite scrolling for instance, I think they can work like that).

Do you know of a way to hide a part of an UI from humans while making the JS believe it is actually visible?

How to create Roster in PHP?

I want to develop Student Result System System using PHP. My aim is to create a database table that displays a roster. Data values are fetched from tables of 1st semester and 2nd semester. Please help me how to create this database table.

I tried to join tables however, I can not do like that.
What I want looks like the following table.

enter image description here