custom contact form google sheet

i tryed this code its almost working. but there is an issue with this code.

whats not working

without uploading file the send button not working.

trying to acheive

all input field should have required(name,email,phone,message).
but uploading file must be optional field.

Addditiional : i tryed to add feature like auto sending email to receiver after user submit form successfully. but i unable to code that part,if someone know how to do that is most welcome to add this auto email feature.

here is code i tryed [ (code.gs), (index.html), (library id) ]

library id

 1CcBYkrGSeBRgphHUE92vWInyULOcJ1Ub6eFUR0_gI1h9I6whLjXtDA-P

code.gs

function doGet() {
  return HtmlService.createTemplateFromFile('index').evaluate()
  .addMetaTag('viewport', 'width=device-width, initial-scale=1')
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}

var url = 'google sheet url here'
var sh = 'sheet1'<!-- current google sheet name here -->
var folderId = 'google drive folder id here'

function processForm(formdata){
  var superscript = SuperScript.initSuper(url,sh)
  
  var formObject = {}
  formdata.forEach(element => formObject[element.name] = element.value),
  formdata.forEach(element => formObject[element.message] = element.value)
  formdata.forEach(element => formObject[element.email] = element.value)
  formdata.forEach(element => formObject[element.phone] = element.value)

  var file = superscript.uploadFile(folderId,formObject.myfile.data,formObject.myfilename)
  var ss= SpreadsheetApp.openByUrl(url);
  var ws=ss.getSheets()[0]
   ws.appendRow([
     new Date(),
    formObject.name,
    "'"+formObject.message,
    formObject.email,
    formObject.phone,
    file.getUrl()
  ]);
  };

index.html

<!DOCTYPE html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
        integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  
  
</head>
<body>
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-5 col-md-8 mx-auto shadow border bg-white p-4 rounded">
                <nav class="navbar navbar-dark bg-primary">
                    <a class="navbar-brand" href="#" fw-bold mb-3>WRITE YOUR QUERY / Message</a>
                </nav>
                <br>
                <form id="myForm" onsubmit="handleFormSubmit()">
                    <div id="form_alerts"></div>
                    <div class="form-group mb-3">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" placeholder="Enter your Name here|" name="name"required>
            </div>

            <div class="form-group mb-3">
            <label for="email" >Email</label>
                        <input type="email"  class="form-control" id="email"
            placeholder="Enter your email address here|" name="email" required>
            </div>

            <div class="form-group mb-3">
           <label for="phone">phone number</label><br><br>
  <input type="tel" id="phone" class="form-control" name="phone" placeholder="Enter your phone number here with country code." pattern="[+]{1}[0-9]{2}[0-9]{10}" required><br><br>
  <small>Format: +919234567898</small><br><br>
            </div>

            <div class="form-group mb-3">
              <label for="message">Message</label>
    <textarea class="form-control" id="message" placeholder="Write your message here|" name="message" required ></textarea>
              </div>

                         <div class="form-group mb-3">
                            <label for="uploadFile">Upload File</label>
                            <input type="file" class="form-control" File="file" id="file">
                            </div>
                            <button type="submit" class= "btn btn-primary btn-block">SEND</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
  <script>
        function preventFormSubmit() {
                var forms = document.querySelectorAll('form');
                for (var i = 0; i < forms.length; i++) {
                    forms[i].addEventListener('submit', function (event) {
                        event.preventDefault();
                    });
                }
            }
            window.addEventListener('load', preventFormSubmit);
            function handleFormSubmit() {
                var formdata = $('#myForm').serializeArray()
                formdata.push({
                  name: 'myfile',
                  value: myfile
                })
                google.script.run.withSuccessHandler(success).processForm(formdata);
            }
            function success(){
                 document.getElementById("myForm").reset()
                 Swal.fire({
                  position: 'center',
                  icon: 'success',
                  title: 'sended sucessfully be ready we will contact you shortly',
                  showConfirmButton: true,
      
                })
            }
        var myfile ={},file, reader = new FileReader();
      reader.onloadend = function(e) {
          myfile.data = e.target.result
          myfile.name = file.name
          console.log(myfile)
      };
     $('#file').change(function(){
       file = $('#file')[0].files[0]
        reader.readAsDataURL(file);
     })
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="sweetalert2.all.min.js"></script>
</body>
</html>

Turbo causes full refresh when adding JS per page

According to the Turbo documentation here: https://turbo.hotwired.dev/handbook/building#working-with-script-elements adding JS files into a page’s <head> that are not present on the current page should cause a Turbo to merge the <head> and load the code. Quoting the documentation:

When you navigate to a new page, Turbo Drive looks for any
elements in the new page’s which aren’t present on the current
page. Then it appends them to the current where they’re loaded
and evaluated by the browser. You can use this to load additional
JavaScript files on-demand.

We add these files in the views like:

<%= content_for :head do %>
  <%= javascript_include_tag 'example', 'data-turbo-track': 'reload' %>
<% end %>

However when doing this Turbo always does a full page refresh. This seems to conflict with what the documentation says around merging the heads and loading the files as needed. We have this approach in a lot of our views which makes Turbo almost pointless as it means the page is being fully reloaded between views. The fingerprints of the files are the same so in theory it shouldn’t be doing a full re-load (it doesn’t need to load new JS)

Node.js Express app not rendering HTML file; only shows a blank page

Body: I am developing a simple Node.js application using Express. My goal is to serve an HTML file located in the views folder, but when I access the page, it shows a blank screen without any content.

Code:

const express = require('express');
const path = require('path');

const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'views', 'index.html'));
});

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});

HTML File (views/index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Page</title>
</head>
<body>
    <h1>Hello World!</h1>
    <p>This is a test page.</p>
</body>
</html>

Error Messages: I do not see any error messages in the terminal or the browser console.

What I’ve Tried:

I ensured that the server is running and that I can access http://localhost:3000/.
I checked the file paths to ensure they are correct.
I tried using a simple HTML file to see if it renders anything.
I am using Windows 10 (Crack Version) and wondering if it might affect the application.
Expected vs. Actual Behavior:

Expected: The browser should display “Hello World!” and the text “This is a test page.”
Actual: The page is blank with no content displayed.
Environment:

OS: Windows 10 (Crack Version)
Node.js version: 20.17.0
Express version: 4.21.1

Firefox not being helpful by reloading iframe

I want a web page to periodically check for some condition by connecting to a server.
If the condition occurs, it should post a notice, and play a sound.

In order to play the sound, there has to be some user interaction, so I ask the user
to click the page to get the whole thing going, which I call launching.

In order to repeatedly check for the condition, I need to refresh the page.
But that would require the user to click again (repeatedly), so I use an
iframe and refresh that. And it works.

However … in Firefox (only, apparently), if I refresh the parent page itself
(for whatever reason), then Firefox “helpfully” reloads the iframe automatically,
and does the launch right away. Then the sound doesn’t play.

I’m looking to avoid having to remember to do
a hard refresh on the parent page, or remembering to click after I do a soft
refresh, and haven’t found one. Chrome browser doesn’t do this, but I prefer
using Firefox.

Here is what I’ve tried, which isn’t working.

<script>
var launched = false;
function launch()
{
 console.log("Launching: launched = " + launched);
 if (!launched)
   {
    document.getElementById("framex").src = "checkalive1.shtml";
    launched = true;
   }
}
function virginstate()
{
 console.log("virginstate called with launched = " + launched);
 document.getElementById("framex").src = "";
 launched = false;
}
</script>

<body onload="virginstate()" onclick="launch()">
<iframe id="framex" src=""> </iframe>
</body>

and in the browser console:

virginstate called with launched = false

Autoplay is only allowed when approved by the user, 
the site is activated by the user, or media is muted.


checkalive1.shtml:168:7 Uncaught (in promise) DOMException: 
The play method is not allowed by the user agent or the platform 
in the current context, possibly because the user denied permission.

Trying to access a specific route but its getting redirected on / home route after deployement on Vercel [duplicate]

I have three routes in React: ‘/’, ‘/login’, and ‘/edit-user’, where the login route is public, and the other two are protected. I’ve created a protected layout component and an authentication handler in React. The authentication handler checks the uid and sets it in session storage. Based on that, we update the isAuthenticated state.

Everything works fine locally, but after deployment, when isAuthenticated is true, and I try to access any private route, it redirects me to the / (home) route.

App.tsx

import { useState } from "react";
import Home from "./pages/Home";
import Auth from "./pages/Auth";
import ProtectedLayout from "./routes/ProtectedLayout";
import AuthenticationHandler from "./components/Auth/AuthenticationHandler";
import Onboarding from "./pages/Onboarding";

const App: React.FC = () => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
  return (
    <Router>
      {/* Handle authentication within the Router context */}
      <AuthenticationHandler setIsAuthenticated={setIsAuthenticated} />

      <Routes>
        {/* Public Route */}
        <Route path="/login" element={<Auth />} />
          
        {/* Protected Layout */}
        <Route element={<ProtectedLayout isAuthenticated={isAuthenticated} />}>
          <Route path="/" element={<Home />} />
          <Route path="/edit-user" element={<Onboarding />} />
        </Route>
      </Routes>
    </Router>
  );
};

export default App;

ProtectedLayout.tsx


interface ProtectedLayoutProps {
  isAuthenticated: boolean | null;
}

const ProtectedLayout: React.FC<ProtectedLayoutProps> = ({ isAuthenticated }) => {
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return (
    <div>
      <Outlet />
    </div>
  );
};

export default ProtectedLayout;

AuthenticationHandler.tsx

import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

interface Props {
  setIsAuthenticated: (authState: boolean) => void;
}

const AuthenticationHandler: React.FC<Props> = ({ setIsAuthenticated }) => {
  const navigate = useNavigate();

  useEffect(() => {
    const checkAuthentication = () => {
      const urlParams = new URLSearchParams(window.location.search);
      const bbuid = urlParams.get("bbuid");

      if (bbuid) {
        sessionStorage.setItem("bbuid", bbuid);

        navigate(window.location.pathname, { replace: true });

        setIsAuthenticated(true);
      } else if (sessionStorage.getItem("bbuid")) {
        setIsAuthenticated(true);
        
        if (window.location.pathname === "/login") {
          navigate("/", { replace: true });
}      } else {
        setIsAuthenticated(false);
      }
    };

    checkAuthentication();
  }, [navigate, setIsAuthenticated]);

  return null; 
};

export default AuthenticationHandler;

How can I resolve this

Why is my function not writing the data onto my firebase realtime database

Firebase createUserWithEmailAndPassword Works but set() to Realtime Database Fails
I have a Firebase project where I need to register a user using Firebase Authentication, then immediately write the user’s data to the Firebase Realtime Database.

Here’s the structure of my registration function:


export function registerbtn(register, emailinput, passwordinput) {
    register.preventDefault();
    console.log(passwordinput, emailinput);
    const email = emailinput.value;
    const password = passwordinput.value;

    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            // Signed up
            const user = userCredential.user;
            writeUserData(user);  // Writing user data to Firebase DB
            const provider = "local";
            getUserDetails(user);
            saveUserdetails(user, provider);

            window.alert(email + password);
            window.location.href = accountredirect;
            return user;

        })
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(errorMessage + errorCode);
            document.getElementById('error-text').innerHTML = errorCode;
        });
}

I also have a writeUserData function that writes the newly registered user’s data to Firebase Realtime Database:


function writeUserData(user) {
    const userId = user.uid;
    const info = "value";

    // Update the user's data in the database
    const db = getDatabase();
    set(ref(db, 'users/' + userId), {
        username: info,
        email: info,
        profile_picture: info
    })
    .then(() => {
        console.log("User data updated successfully!");
    })
    .catch((error) => {
        console.error("Error updating user data: ", error);
    });
}

The Issue:
Everything inside the registerbtn function works fine, except for the writeUserData function. It doesn’t write to the database, and the console logs show no errors related to Firebase database. However, if I call the writeUserData function separately or outside of the registration process, it works perfectly and writes the data to Firebase.

I’ve tried putting the writeUserData function inside and outside the .then() block, and even exporting/importing it, but the issue persists.

My Firebase Configuration:


import {
    initializeApp
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-app.js";


import {
    getAuth, signOut, signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, createUserWithEmailAndPassword, onAuthStateChanged
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-auth.js";


import {
    getAnalytics
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-analytics.js";


import {
    getDatabase, onValue, child, ref, set, get
} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-database.js";


// TODO: Add SDKs for Firebase products that you want to use

// https://firebase.google.com/docs/web/setup#available-libraries


// Your web app's Firebase configuration

// For Firebase JS SDK v7.20.0 and later, measurementId is optional

const firebaseConfig = {

    apiKey: "AIza**************",

    authDomain: "wespot-website.firebaseapp.com",

    databaseURL: "https://wespot-website-default-rtdb.europe-west1.firebasedatabase.app",

    projectId: "wespot-website",

    storageBucket: "wespot-website.appspot.com",

    messagingSenderId: "864768589048",

    appId: "1:864768589048:web:f76790c9abfa6b2e594f0d",

    measurementId: "G-0ZD710W4YE"

};


// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const database = getDatabase();
const auth = getAuth();
export const provider = new GoogleAuthProvider();
const accountredirect = "../index.html";

Steps I’ve Tried:
Logging the user object: To ensure the user object is populated, I added console logs, and it shows the correct user UID.

Firebase Rules: I’ve checked my Firebase Realtime Database rules and made sure they allow authenticated users to write.

Firebase Authentication works fine and the user is successfully created.
Database writes only fail when the writeUserData function is called right after the user registration.
There are no errors in the console, making it hard to trace the issue.
Question:
Why is writeUserData(user) failing when called after createUserWithEmailAndPassword but works perfectly fine when called separately? Could it be a timing issue, or am I missing something else?

Any help or insight would be appreciated!

AgGrid angular scrollbarWidth only applying to the horizontal scroller

AgGrid has a parameter called scrollbarWidth which I can pass into the grid as a number. I was hoping it would alter the width of both the horizontal and vertical scrollbars but it only seems to affect the horizontal scroll width. The vertical scroller seems to stay the same

<ag-grid-angular
  #agGrid
  style="width: 400px; height: 400px;"
  id="myGrid"
  class="ag-theme-balham"
  [columnDefs]="columnDefs"
  [defaultColDef]="defaultColDef"
  [rowData]="rowData"
  (gridReady)="onGridReady($event)"
  [scrollbarWidth]="8"
>
</ag-grid-angular>

My goal was to change the scroller width for both horizontal and vertical and get both of them same width.

Tried my best to create a demo of the issue I have.

Help is much appreciated, Thanks

vis.js timeline element set content same size as outer element

in vis.js timeline you can set the own elements to overflow the item box like in this example.
Is there also an way that my custom element is exactly the same size as the VISIBLE item box on the screen?
By default it is the same size which is good until the item leaves the visible page on the left/right. After that a translateX() gets added to the own content which moves my progressbar out of the container.
enter image description here
enter image description here
enter image description here

What I want:

enter image description here

Is there a way to achieve this without doing hacky things? I calculate the negative translate(X) on every event and with an interval right now which is just bad.

Thank you very much 🙂

Authentication Cookie Not Sent with Axios Request in Browser

I’m having trouble with cookie-based authentication in my Django + React app. I’ve set the cookie on the backend, but it’s not being sent with subsequent requests from the frontend React (Using Vite) app running on Google Chrome.

I’m trying to implement authentication using cookies in a Django backend using Simple JWT. After a successful login, I set an authentication cookie (“CAT”) in Django. Here’s the code I use to set the cookie:

final_response.set_cookie(
    "CAT",
    combined_token,
    httponly=True,
    secure=False,
    samesite="None",
    max_age=86400,
    path="/",
)
return final_response

Setting.py at the Django server:

CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = ["http://localhost:5173/"]
CORS_ALLOW_CREDENTIALS = True
SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin"

I can see the cookie stored in Chrome after logging in:
enter image description here

However, when my React app makes subsequent requests, the browser doesn’t seem to include the cookie, and I get an authentication failure (“Cookie not found”). Here’s my Axios request setup in the React app:

try {
  const auth_response = await axios.get(
    "http://my-django-server/api/auth/auth-checker",
    {
      headers: {
        "Content-Type": "application/json",
      },
      withCredentials: true,
      timeout: 5000,
    }
  );
  console.log(auth_response?.data);
  if (auth_response?.status === 200) {
    navigate("/profile");
  } else {
    console.error("Unauthorized access. Please try again.");
  }
} catch (error) {
  console.error("An error occurred. Please try again.", error);
}

Manual authentication works:
Interestingly, when I manually set the cookie in an Axios request from the terminal, the request works as expected and I get an authenticated response. However, in the browser, it fails.

getRegularHeader(port: string): Record<string, string> {
    return {
      "Content-Type": "application/json",
      Origin: `http://localhost:${port}`,
    };
  }

const token = readlineSync.question("Enter CAT token: ");
        try {
          const response = await axios.get(url, {
            headers: { ...this.getRegularHeader(port), Cookie: `CAT=${token}` },
            withCredentials: true,
            timeout: 5000,
          });
          return response;
        } catch (error) {
          console.error(`Failed to authenticate: ${error}`);
          return null;
        }

There is also a message from Google Chrome:
enter image description here

What I’ve Tried:

  • Checked in both Chrome and Edge with the same result.
  • Verified that withCredentials: true is set in the Axios request.
  • Attempted different cookie settings (e.g., SameSite=None, Secure=False).

Questions:

  • Why are the browsers not sending the cookie with my requests?
  • Are there any specific settings or configurations I might be missing in either Django or React?

Axios invalid URL but url is correct

I just can’t send request
This code perfectly works:

    const data = new FormData()
    data.append('file', event.target!.files![0])

    const xhr = new XMLHttpRequest()

    xhr.addEventListener('readystatechange', function () {
      if (this.readyState === 4) {
        console.log(this.responseText)
      }
    })

    xhr.open('POST', 'http://localhost:9095/upload')

    xhr.send(data)

but this do not, I executed both in the same project during the same event:

    const formData = new FormData()
    formData.append('file', event.target!.files![0])
    const response = await axios({
      method: 'post',
      url: 'http://localhost:9095/upload',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    console.log(response.data)

ERROR:

ncaught (in promise) SyntaxError: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
    at dispatchXhrRequest (axios.js?v=cf8614a3:1572:13)
    at new Promise (<anonymous>)
    at xhr (axios.js?v=cf8614a3:1557:10)
    at Axios.dispatchRequest (axios.js?v=cf8614a3:2012:10)
    at async Axios.request (axios.js?v=cf8614a3:2118:14)
    at async handleFileUpload (fileButton.tsx:18:22)
    at Axios.request (axios.js?v=cf8614a3:2122:41)
    at async handleFileUpload (fileButton.tsx:18:22)

P.S. I use react ts + axios 1.7.3

Unable to control a React Aria component

I’m trying to build a custom Accordion component with (Adobe) React Aria. I’m building it on top of the Disclosure and DisclosureGroup components.

import { tv } from "tailwind-variants";
import { motion } from "framer-motion";
import {
  UNSTABLE_Disclosure as DisclosureItem,
  UNSTABLE_DisclosureGroup as Disclosure,
  UNSTABLE_DisclosurePanel as DisclosurePanel,
  DisclosureGroupProps as DisclosureProps,
  DisclosureProps as DisclosureItemProps
} from "react-aria-components";
import ChevronLeft from "@spectrum-icons/workflow/ChevronLeft";
import { useButton, AriaButtonOptions, ButtonAria } from "@react-aria/button";

export const accordion = tv({
  slots: {
    accordion: "p-2",
    item: "",
    header: "flex flex-row"
  },
  variants: {
    colorMode: {
      dark: { accordion: "bg-slate-900 text-white" },
      light: { accordion: "text-slate-800" }
    }
  }
});

export type AccordionProps = Omit<DisclosureProps, "id" | "style" | "isDisabled" | "className"> & Options;

export const Accordion = forwardRef(
  (
    {
      children,
      allowsMultipleExpanded,
      expandedKeys,
      defaultExpandedKeys,
      onExpandedChange,
      className,
      id,
      isVisible,
      borderRadius,
      isLoading,
      error,
      isDisabled
    }: AccordionProps,
    ref: React.LegacyRef<HTMLDivElement>
  ) => {
    return (
      <Disclosure
        ref={ref}
        allowsMultipleExpanded={allowsMultipleExpanded}
        expandedKeys={expandedKeys}
        defaultExpandedKeys={defaultExpandedKeys}
        onExpandedChange={onExpandedChange}
        className={accordion().accordion({ colorMode: "light", class: className })}
        id={id}
        isDisabled={isDisabled}
      >
        {children}
      </Disclosure>
    );
  }
);

export type AccordionItemProps = Omit<DisclosureItemProps, "id" | "style" | "isDisabled" | "className"> & Options;

export const AccordionItem = forwardRef(
  (
    {
      children,
      onExpandedChange,
      className,
      isExpanded,
      defaultExpanded,
      slot,
      id,
      isVisible,
      borderRadius,
      isLoading,
      error,
      isDisabled
    }: AccordionItemProps,
    ref: React.LegacyRef<HTMLDivElement>
  ) => {
    return (
      <DisclosureItem
        ref={ref}
        onExpandedChange={onExpandedChange}
        className={accordion().item({ class: className })}
        isExpanded={isExpanded}
        defaultExpanded={defaultExpanded}
        slot={slot}
        id={id}
        isDisabled={isDisabled}
      >
        {children}
      </DisclosureItem>
    );
  }
);

export type AccordionHeaderProps<T extends ElementType> = {
  children: React.ReactNode;
  iconProps?: AriaButtonOptions<T>;
} & Options;

export const AccordionHeader = forwardRef(
  (
    {
      children,
      iconProps,
      id,
      className,
      isVisible,
      borderRadius,
      isLoading,
      error,
      isDisabled
    }: AccordionHeaderProps<"button">,
    ref
  ) => {
    const { buttonProps } = useButton(iconProps || { elementType: "button" }, ref as RefObject<HTMLButtonElement>);

    // @ts-ignore
    // Type conversion for framer-motion is nessecary so defination is removed
    const ariaButtonProps: Omit<ButtonAria<HTMLAttributes<unknown>>, "defination"> & { defination: undefined } = {
      defination: undefined,
      onAnimationStart: undefined,
      ...buttonProps
    };
    return (
      <div className={accordion().header({ class: className })}>
        <div>{children}</div>
        <motion.button {...ariaButtonProps} disabled={isDisabled} className="ml-auto">
          <ChevronLeft width={25} />
        </motion.button>
      </div>
    );
  }
);

export const AccordionContent = forwardRef(({ children }: { children: React.ReactNode }, ref) => {
  return <DisclosurePanel>{children}</DisclosurePanel>;
});

Please note that I have rearranged the names of the Disclosure from React Aria to better fit my use cases:

  • Disclosure is now DisclosureItem
  • DisclosureGroup is now Disclosure
  • DisclosurePanel is now DisclosureProps

This new accordion component is used like so:

<Accordion>
      <AccordionItem isExpanded>
        <AccordionHeader>
          test
        </AccordionHeader>
        <AccordionContent>
          Hello, World
        </AccordionContent>
      </AccordionItem>
</Accordion>

As you can see I am trying to control one of the AccordionItems however when I preview the component all it is not expanded:

Current

Current

Expected

Expected

I look at the DOM shows that even when isExpanded is true hidden is still applied to the AccordionContent div:

<div class="p-2 text-slate-800" data-rac="">
  <div class="react-aria-Disclosure" data-rac="">
    <div class="flex flex-row">
      <div>test</div>
      <button type="button" class="ml-auto">
        <svg
          viewBox="0 0 36 36"
          class="wBx8DG_spectrum-Icon wBx8DG_spectrum-Icon--sizeM"
          focusable="false"
          aria-hidden="true"
          role="img"
          style="width: 25px"
        >
          <path
            fill-rule="evenodd"
            d="M12,18v0a1.988,1.988,0,0,0,.585,1.409l7.983,7.98a2,2,0,1,0,2.871-2.772l-.049-.049L16.819,18l6.572-6.57a2,2,0,0,0-2.773-2.87l-.049.049-7.983,7.98A1.988,1.988,0,0,0,12,18Z"
          ></path>
        </svg>
      </button>
    </div>
   <!-- Here ⬇️ -->
    <div
      id="react-aria3890111277-:r2:"
      role="group"
      aria-labelledby="react-aria3890111277-:r1:"
      hidden=""
      class="react-aria-DisclosurePanel"
      data-rac=""
    >
      Hello, World
    </div>
  </div>
</div>

Removing hidden shows the element. So my question is how do I do this with RA?

bundle unused functions in vite js

hi I’m using vite for bundle my javascript codes and moudules in vanilla js

it’s ok when i run in dev mode
but when i build the code there is two problems

first
i have some functions that aren’t called directly in code and when i build the code they aren’t export to final js file

this is how i call my function in a loob

eval(routes[routesKey]+'(fn(currentRoute))')

and the secound problem is i have some html files and i use them by a fetch in my code and after build the html files are not in dist directory

export function home(pathData){
document.querySelector('title').innerText = "Home"
fetch("/pages/home.html").then(response => {return response.text()} ).then(text =>{
    document.getElementById('main').innerHTML = text
})

}

why does my marker appear in the layerswitcher under a number

I receive the list of layers to use in a json.
To add them, I browse the json and add the layers in the overlaylayers.
Then, I want to materialize the coordinates passed to the page with a marker.
It is displayed correctly but instead of finding the name of the marker “Position” in the layerSwitcher, there is a number.
Below is the code to use.
Any idea?

jsonData.Layers.forEach(layer => {
    console.log("2 "+layer.Layer.nom);  // Affiche le nom de chaque layer

    index = index + 1;
    const layerKey = `lyr${index}`; // Créer une clé dynamique
    let [unLayer,unNom,unVisible]=createLayer(layer.Layer);
    theLayers[index]=unLayer;
    theLayersSwitcher[index]= {layer : unLayer, config : {title : unNom,description : unNom,visibility : unVisible}};

    theLayersNom[index]=unNom;
    theLayersVisible[index]=unVisible;

    if (layer.Layer.inUse==1)
    {
        overlayLayers[layer.Layer.nom] = unLayer; // Stocker la couche dans l'objet}
        unLayer.addTo(map);
    }
    else
    {
        overlayLayers[layer.Layer.nom] = unLayer; // Stocker la couche dans l'objet
    }
});
let PositionMarker = L.marker([<?php echo $_REQUEST["LATITUDE"]?>, <?php echo $_REQUEST["LONGITUDE"]?>], {
    title: "La position"
}).addTo(map);

let reversedLayersSwitcher = {};
let keys = Object.keys(theLayersSwitcher).reverse();
index = 0;

for (let i = 0; i < keys.length; i++) {
    index += 1;
    reversedLayersSwitcher[index] = theLayersSwitcher[keys[i]];
}

let layerSwitcher = L.geoportalControl.LayerSwitcher({ layers: reversedLayersSwitcher });
map.addControl(layerSwitcher);

Products Not Filtering Correctly with AJAX in Django

I’m working on an e-commerce website using Django and jQuery to filter products based on selected criteria (price range, categories, and vendors). While the AJAX request seems to be sent correctly and I receive a response, all products are still displayed on the page, regardless of the selected filters.
What I’ve Implemented:
JavaScript (AJAX) Code:

$(document).ready(function() {
    function filterProducts() {
        let filter_object = {};

        // Get price range values
        let min_price = $("#price-min").val() || 0;
        let max_price = $("#price-max").val() || 9999999;

        filter_object.min_price = min_price;
        filter_object.max_price = max_price;

        // Get selected categories and vendors
        $(".filter-checkbox").each(function() {
            let filter_key = $(this).data("filter");
            filter_object[filter_key] = Array.from(
                document.querySelectorAll('input[data-filter=' + filter_key + ']:checked')
            ).map(function(element) {
                return element.value;
            });
        });

        // Send AJAX request to filter products
        $.ajax({
            url: '/filter-product',
            data: filter_object,
            dataType: 'json',
            beforeSend: function() {
                console.log("Filtering products...");
            },
            success: function(response) {
                console.log("Products filtered successfully.");
                $(".showcase").html(response.data);
            },
            error: function(xhr, status, error) {
                console.error("Error filtering products:", error);
            }
        });
    }

    // Event listener for checkbox and filter button
    $(".filter-checkbox, #filter-btn").on("click", filterProducts);
});

HTML Structure:

<div class="u-s-m-b-30">
    <div class="shop-w">
        <div class="shop-w__intro-wrap">
            <h1 class="shop-w__h">PRICE</h1>
            <span class="fas fa-minus shop-w__toggle" data-target="#s-price" data-toggle="collapse"></span>
        </div>
        <div class="shop-w__wrap collapse show" id="s-price">
            <form class="shop-w__form-p">
                <div class="shop-w__form-p-wrap">
                    <div>
                        <label for="price-min"></label>
                        <input class="input-text input-text--primary-style" type="text" id="price-min" placeholder="Min">
                    </div>
                    <div>
                        <label for="price-max"></label>
                        <input class="input-text input-text--primary-style" type="text" id="price-max" placeholder="Max">
                    </div>
                    <div>
                        <button class="btn btn--icon fas fa-angle-right btn--e-transparent-platinum-b-2" id="filter-btn" type="button"></button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="u-s-m-b-30">
    <div class="shop-w">
        <div class="shop-w__intro-wrap">
            <h1 class="shop-w__h">MANUFACTURER</h1>
            <span class="fas fa-minus shop-w__toggle" data-target="#s-manufacturer" data-toggle="collapse"></span>
        </div>
        <div class="shop-w__wrap collapse show" id="s-manufacturer">
            <ul class="shop-w__list-2">
                {% for v in vendors %}
                <li>
                    <div class="list__content">
                        <input type="checkbox" name="vendor" data-filter="vendor" class="filter-checkbox" value="{{v.id}}">
                        <span>{{v.title}}</span>
                    </div>
                </li>
                {% endfor %}
            </ul>
        </div>
    </div>
</div>

Django Product Model:

class Product(models.Model):
    # Product fields...
    price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99)
    # Other fields...

Django View to Handle Filtering:

def filter_product(request):
    categories = request.GET.getlist("category[]")
    vendors = request.GET.getlist("vendor[]")

    min_price = request.GET.get('min_price', 0)
    max_price = request.GET.get('max_price', 9999999)

    products = Product.objects.filter(product_status="published").order_by("-id").distinct()

    products = products.filter(price__gte=min_price)
    products = products.filter(price__lte=max_price)

    if categories:
        products = products.filter(category__id__in=categories).distinct()

    if vendors:
        products = products.filter(vendor__id__in=vendors).distinct()

    context = {
        "products": products
    }
    data = render_to_string("core/async/product-list.html", context)

    return JsonResponse({"data": data})

Current Issue:

  1. Despite receiving the AJAX response with Products filtered successfully., all products are still displayed on the page regardless of the applied filters.

What I’ve Tried:

  1. Verified that the AJAX request is sending the correct filter parameters.
  2. Ensured that the Django view logic correctly applies the filters.
  3. Confirmed that the filtered product HTML is rendered correctly in the response.

Questions:

  1. What could be the reason for all products being displayed despite the filters?
  2. Are there any debugging tips or common pitfalls I should look out for in my implementation?

Thank you for your help!