Replace DDSC component code with Javascript code

I am working on an ASP.NET Web Application that uses DDSC components with Javascript in an ASPX Page.
We need to remove/ retire DDSC components code

Following are the DDSC lines of Code that Need to be replaced with javascript code.

DDSC.WebPart(WPQ).Properties.GetValue("applicationCode", "someGUID");
DDSC.Properties.PutValueSession('applicationCode', 'someID', 0);

DDSC.Events.Raise("applicationCode", "onWindowOpenRequest", WPQ, Data, true);

DDSC.WebPart(WPQ).Close();

Any help or advice to replace the above DDSC codes with Javascript code.

Thanks in advance for helping.

Why don’t my platform and packageType states update correctly?

I have Index, LandingButtons, SelectPackages components. Index has platform and packageType states, which set initial states of SelectPackages component. I pass a function to LandingButtons component to update these states. They update, but for some reason they aren’t set in SelectPackages component.

Index.jsx

import SelectPackages from "../components/structure/landing_page/SelectPackages.jsx";
import LandingHeader from "../components/structure/landing_page/header/LandingHeader.jsx";
import HowItWorks from "../components/structure/landing_page/HowItWorks.jsx";
import FAQ from "../components/structure/landing_page/FAQ.jsx";
import LandingReviews from "../components/structure/landing_page/LandingReviews.jsx";
import LandingButtons from "../components/structure/landing_page/LandingButtons.jsx";
import Features from "../components/structure/landing_page/Features.jsx";
import {useState} from "react";

export default function Index() {
    const [platform, setPlatform] = useState("instagram")
    const [packageType, setPackageType] = useState("discussions")
    return (
        <>
            <LandingHeader/>
            <LandingButtons onPackageSelected={(newPlatform, newPackageType) => {
                console.log("Selected platform:", newPlatform, "Selected package type:", newPackageType);
                setPlatform(newPlatform);
                setPackageType(newPackageType);
            }}/>
            <HowItWorks/>
            <Features/>
            <SelectPackages initialPlatform={platform} initialPackageType={packageType}/>
            <FAQ/>
            <LandingReviews/>
        </>

    );
}

LandingButtons.jsx

import twocheckout1 from "../../../assets/img/landing/twocheckout1.png";

const buttons = [
    { text: "Instagram discussions", platform: "instagram", packageType: "discussions" },
    { text: "Instagram comments", platform: "instagram", packageType: "comments" },
    { text: "Instagram discussions + comments", platform: "instagram", packageType: "discussions+comments" },
    { text: "TikTok discussions", platform: "tiktok", packageType: "discussions" },
    { text: "TikTok comments", platform: "tiktok", packageType: "comments" },
    { text: "TikTok discussions + comments", platform: "tiktok", packageType: "discussions+comments" },
];

export default function LandingButtons({onPackageSelected}) {
    return (
        <div id="landing-buttons" className="text-center space-y-12 mb-16">
          

            <div className="grid grid-cols-3 gap-4 w-3/5 mx-auto">
                {buttons.map((button, index) => (
                    <button
                        key={index}
                        className="text-white font-semibold py-4 px-5 rounded-2xl text-center no-underline
                                    bg-gradient-to-tr from-yellow-500 to-pink-500 via-pink-500"
                        onClick={() => onPackageSelected(button.platform, button.packageType)}
                    >
                        {button.text}
                    </button>
                ))}
            </div>
            <img src={twocheckout1} className="mx-auto"/>
        </div>

    );
}

SelectPackages.jsx

import {useEffect, useState} from "react";
import DiscussionsPackages from "../../packages/DiscussionsPackages.jsx";
import CommentsPackages from "../../packages/CommentsPackages.jsx";
import DiscussionsCommentsPackages from "../../packages/DiscussionsCommentsPackages.jsx";
import {useNavigate} from "react-router";
import {getPrices} from "../../../services/infoRequests.js";

export default function SelectPackages({initialPlatform, initialPackageType}) {
    const navigate = useNavigate();
    const [platform, setPlatform] = useState(initialPlatform);
    const [packageType, setPackageType] = useState(initialPackageType);
    const [selectedPackage, setSelectedPackage] = useState(null);
    const [commentsPackages, setCommentsPackages] = useState({});
    const [discussionsPrices, setDiscussionsPrices] = useState({});
    const [slidersLimits, setSlidersLimits] = useState({}); 
    console.log("1 platform:", platform); //shows initial "instagram" value
    console.log("1 package type:", packageType);
    console.log("2 platform:", initialPlatform); //shows updated "tiktok" value
    console.log("2 package type:", initialPackageType);
    useEffect(() => {
        getPrices().then((res) => {
            setCommentsPackages(res.data.commentsPackages);
            setDiscussionsPrices(res.data.discussionsPrices);
            setSlidersLimits(res.data.discussionsSlidersLimits);
        });
    }, [platform, packageType]);


    function handlePackageSelected(_selectedPackage) {
        setSelectedPackage(_selectedPackage);
    }


    return (
        <div id="packages" className="mx-32 my-20 text-center">
            <h1>Packages</h1>
            <div id="platformButtons" className="space-x-10 my-5">
                <button
                    className={platform === "instagram" ? "bg-blue-500" : ""}
                    onClick={() => setPlatform("instagram")}>
                    Instagram
                </button>
                <button
                    className={platform === "tiktok" ? "bg-blue-500" : ""}
                    onClick={() => setPlatform("tiktok")}>
                    TikTok
                </button>
            </div>
            <div id="typeButtons" className="space-x-10 my-10">
                <button
                    className={packageType === "discussions" ? "bg-blue-500" : ""}
                    onClick={() => setPackageType("discussions")}>
                    Discussions
                </button>
                <button
                    className={packageType === "comments" ? "bg-blue-500" : ""}
                    onClick={() => setPackageType("comments")}>
                    Comments
                </button>
                <button
                    className={packageType === "discussions+comments" ? "bg-blue-500" : ""}
                    onClick={() => setPackageType("discussions+comments")}>
                    Discussions + comments
                </button>
            </div>
            <div id="packages-options" className="text-left mb-10">
                {
                    packageType === "discussions" ?
                        <DiscussionsPackages
                            prices={discussionsPrices}
                            slidersLimits={slidersLimits}
                            onPackageSelected={handlePackageSelected}
                        /> :
                        packageType === "comments" ?
                            <CommentsPackages
                                packages={commentsPackages}
                                onPackageSelected={handlePackageSelected}
                            /> :
                            <DiscussionsCommentsPackages
                                discussionsPrices={discussionsPrices}
                                slidersLimits={slidersLimits}
                                commentsPackages={commentsPackages}
                                onPackageSelected={handlePackageSelected}
                            />
                }
            </div>
        
        </div>
    )
}

Is there a way to declare an object property without initializing it?

A.S.: Object property order in JS is a very complicated topic. For my intents and purposes, only insertion order matters.

TL;DR: Is there a way to declare an object property without giving it a value?

const user = { name: unset, age: 42 }


I have a set of asynchronous functions, each returning a value associated with a unique key. They are then invoked in parallel to construct an object with key-value pairs used as entries (properties). Something like this:

const props = {}
const propsSet = getters.map(async ([key, getValue]) => {
  props[key] = async getValue()
})

await Promise.all(propsSet)

return props

Try it.

Sine all of this is asynchronous, the order of properties in props is all over the place: I get sometimes { foo: …, bar: … }, sometimes { bar: …, foo: … }. I could fix that by associating each getter with a sequence number. But a much easier solution is to just initiate the properties as soon as possible; due to how event loop works, this is basically a guarantee that properties of props will be ordered the same as in getters:

const propsSet = getters.map(async ([key, getValue]) => {
    props[key] = null // or any other initialization token
    props[key] = await getValue()
})

In pure JS this a perfectly normal thing to do, but in TS this is usually a compiler error (since arbitrary “initialization token” isn’t assignable to strictly typed properties of props); so, I have to do shush the compiler, which I don’t like to do:

// @ts-expect-error
values[key] = null

Try it.

I’ve realized that what I basically need is very similar to declaring variables separately from initializing them, – like in old-school JS style:

var value1, value2

value1 = 42
value2 = 17

Is there any existing or upcoming (proposal) way of declaring object properties without initializing them?

Note that I’m not asking about ways of ordering properties. There are many strategies to do that, including usage of the aforementioned sequence numbers (e.g., array indexes).

How to stop duplicating form submissions on a master database google sheet/ APPSCRIPT and data appendage

I have several google forms on my website that customers fill in. All of the responses to these different forms have been linked to go to one spreadsheet. I then used APPSCRIPT to merge all responses on one tab called “MasterSheet”.

My issue is this. I am using timestamps as my unique identifier so the script knows when there is a new submission and ONLY appends the new submission from each individual tab into my mastersheet. BUT if 2 submissions came at the same time, the script only picked up one. So I adjusted it in an attempt to pick up all new submissions, but now the script duplicates the data when there is a new submission.

I think the problem in in my
const data

HERE IS FULL SCRIPT:

const data = activeSheet.getRange(2, 1, lastRow - 1, activeSheet.getLastColumn()).getValues();
const newData = data.filter(row => !masterTimestampsAndEmails.has(row[0] + row[1])); // Check Timestamp + Email combo

if (newData.length > 0) {
  // Add the tab name to the "GUIDE REQUESTED" column
  const headers = masterSheet.getRange(1, 1, 1, masterSheet.getLastColumn()).getValues()[0];
  const guideRequestedIndex = headers.indexOf('GUIDE REQUESTED (DO NOT CHANGE)');
  if (guideRequestedIndex === -1) {
    throw new Error('GUIDE REQUESTED column not found in the MasterSheet.');
  }

  newData.forEach(row => {
    row[guideRequestedIndex] = activeSheetName; // Set the GUIDE REQUESTED column to the sheet name
  });

  // Append only new rows to the MasterSheet
  masterSheet.getRange(masterSheet.getLastRow() + 1, 1, newData.length, newData[0].length).setValues(newData);
  Logger.log(`Appended ${newData.length} rows from sheet "${activeSheetName}" to MasterSheet.`);
} else {
  Logger.log(`No new data to append from sheet "${activeSheetName}".`);
}

This was my original scrip which worked BEAUTIFULLY, but unfortunately if 2 form submissions

const data = activeSheet.getRange(lastRow, 1, 1, activeSheet.getLastColumn()).getValues();
const newData = data.filter(row => !masterTimestamps.has(row[0].toString().trim()));

if (newData.length > 0) {
  newData.forEach(row => {
    // Update state/province based on country
    const country = row[5]; // Country column
    const stateIndex = 6; // "U.S. State / Canada Province" column
    if (country !== 'US - United States of America (the)' && country !== 'CA - Canada') {
      row[stateIndex] = 'Not applicable (located outside of the United States and Canada)';
    }

    // Set the GUIDE REQUESTED column to the active sheet name
    const guideRequestedIndex = 14; // Adjust if the column position changes
    row[guideRequestedIndex] = activeSheetName;
  });

  masterSheet.getRange(masterSheet.getLastRow() + 1, 1, newData.length, newData[0].length).setValues(newData);
  Logger.log(`Appended 1 row from sheet "${activeSheetName}" to MasterSheet.`);
} else {
  Logger.log(`No new data to append from sheet "${activeSheetName}".`);
}

Script to import GIF ran fine but has suddenly stopped working with seemingly no changes

So I have created this script to import a night or day version of an animation for my static website.

I am hosting using Github Pages but I can’t find out for the life of me why it seems to have suddenly stopped importing the code to include the GIFs.

The script I’m having issues with is the ‘getimg’ one, the other one is for the night and day stylesheet.

I haven’t made any more commits to the github version since last night, when it was working flawlessly

the live website is: https://scrapbook.arronware.com/index.html

I’d really appreciate the help, I’m at a complete wits end with this

All I’ve really done on my local version is make some CSS adjustments for another page (each page has it’s own stylesheet alongside one with the core content) and added another GIF to another page

Thanks 🙂

(this page also has HTML includes from W3 school however I’ve removed the script from the top of the page to make troubleshooting easier for you.

THE ISSUE PERSISTS WITH THE STYLESHEET DAY/NIGHT SCRIPT

<script>
    function includeHTML() {
      var z, i, elmnt, file, xhttp;
      /* Loop through a collection of all HTML elements: */
      z = document.getElementsByTagName("*");
      for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        /*search for elements with a certain atrribute:*/
        file = elmnt.getAttribute("w3-include-html");
        if (file) {
          /* Make an HTTP request using the attribute value as the file name: */
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
              if (this.status == 200) {elmnt.innerHTML = this.responseText;}
              if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
              /* Remove the attribute, and call this function once more: */
              elmnt.removeAttribute("w3-include-html");
              includeHTML();
            }
          }
          xhttp.open("GET", file, true);
          xhttp.send();
          /* Exit the function: */
          return;
        }
      }
    }
    </script>


<html>
    <head>


      <script>
        function getimg() {
          var currentTime = new Date().getHours();
          if (0 <= currentTime&&currentTime < 8) {
            document.write("<img src='assets/scottownnight.gif' id='headergif' >");
          }
          if (8 <= currentTime&&currentTime < 17) {
            document.write("<img src='assets/scottownday.gif' id='headergif' >");
          }
          if (17 <= currentTime&&currentTime < 0) {
            document.write("<img src='assets/scottownnight.gif' id='headergif' >");
          }
          
        }
        
        
        
      </script>


      <script>
        function getstyle() {
          var currentTime = new Date().getHours();
          if (0 <= currentTime&&currentTime < 8) {
            document.write("<link href='nightstyle.css' rel='stylesheet'>");
          }
          if (8 <= currentTime&&currentTime < 17) {
            document.write("<link href='style.css' rel='stylesheet'>");
          }
          if (17 <= currentTime&&currentTime < 0) {
            document.write("<link href='nightstyle.css' rel='stylesheet'>");
          }
          
        }
        
        
        
      </script>
      <link href='style.css' rel='stylesheet'>
      <link href='core.css' rel='stylesheet'>
      <script>getstyle();</script>
        
    



      <title>arron ware's scrapbook</title>
      <link rel="icon" href="jessop.ico">


      
      <meta name="description" content="projects and recipes">
      <meta name="keywords" content="arron, ware, photography, sound design, manchester, lincolnshire, cleethorpes, video, art">
      <meta name="robots" content="index, follow">
      <meta http-equiv="Content-Type" content="text/html" charset="utf-8">
      <meta charset="UTF-8">
      <meta name="language" content="English">
      <meta name="author" content="Arron Ware">
      <meta name="viewport" content="width=device-width, initial-scale=1" />

    </head>

    <body>
      <div id="logolinks">
        <h3>
            <a href=index.html style="text-decoration: inherit; color: inherit; font-family: inherit; font-size: inherit;">arron</a> ware's scrapbook
        </h3>
        <div w3-include-html="include/links.html"></div>
      </div>
        
        <script>getimg();</script>
        
        <div class="content">
            Hi!
            This is my scrapbook website.
            I keep all my my little projects and bits that I would like to have online somewhere here. <br><br>
            The website has no sole objective other than to be one large mashup of odd and ends, I hope you enjoy exploring!
            

          

        </div>

        
    </body>




</html>

<script>
    includeHTML();
</script>

The splash is screen a icon image, not the splash screen image in React Native

Here is my app.json code { "expo": { "name": "MyApp", "slug": "MyApp", "version": "1.0.0", "orientation": "portrait", "icon": "./assets/images/icon.png", "scheme": "myapp", "userInterfaceStyle": "automatic", "newArchEnabled": true, "ios": { "supportsTablet": true }, "android": { "adaptiveIcon": { "foregroundImage": "./assets/images/coffee-splash.png", "backgroundColor": "#000000" } }, "web": { "bundler": "metro", "output": "static", "favicon": "./assets/images/favicon.png" }, "plugins": [ "expo-router", [ "expo-splash-screen", { "image": "./assets/images/coffee-splash.png", "resizeMode": "contain", "backgroundColor": "#000000" } ] ], "experiments": { "typedRoutes": true } } }

The image used in {“icon”: “./assets/images/icon.png”} only shown in splash or loading screen. I want to show the flash screen image – that is – {“image”: “./assets/images/coffee-splash.png”}

Paths are correct, But the icon images is only shown.

React Webcam Doesn’t Work When Using Firebase Hosting

I have a React App that uses the webcam to detect specific poses. As the title suggests, when I deploy the app locally, it works as expected.

However, when deploying the app to firebase hosting, the camera feed is black. I have provided the necessary permissions in Chrome and the website is being served securely over https. Curiously the camera light on my Macbook lights up green for a while but nothing shows up.

This is the relevant code in the camera component:

const PoseCamera = forwardRef(({ onCapture, poseType }, ref) => {
const videoRef = useRef(null);
const canvasRef = useRef(null);
const containerRef = useRef(null);
const [detector, setDetector] = useState(null);
const [isStreaming, setIsStreaming] = useState(false);
const [isInitializing, setIsInitializing] = useState(true);
const requestAnimationRef = useRef(null);
const localStreamRef = useRef(null);
const FRAMES_TO_HOLD = 30;
const poseBufferRef = useRef([]);
const currentPoseType = POSE_TYPES[poseType];
const SMOOTHING_WINDOW = 10; // Number of frames to average
const poseHistoryRef = useRef([]); // Store recent poses

const isReadyForDetection = useCallback(() => {
    if (!detector) {
        console.error("Pose detector is not initialized.");
        return false;
    }

    if (!videoRef.current) {
        console.error("Video element is not available.");
        return false;
    }

    if (!canvasRef.current) {
        console.error("Canvas element is not available.");
        return false;
    }

    if (!isStreaming) {
        console.error("Camera is not streaming.");
        return false;
    }

    return true;
}, [detector, isStreaming]);

… Which Throws: Video element is not available.


     const startCamera = useCallback(async () => {
    setIsInitializing(true);
    try {
        if (!window.isSecureContext) {
            console.error('Application not running in secure context - camera may not work');
        }

        const stream = await navigator.mediaDevices.getUserMedia({
            video: true,
            audio: false
        });

        console.log('Camera stream obtained:', stream);

        if (videoRef.current) {
            videoRef.current.srcObject = stream;
            console.log('Video element assigned stream:', videoRef.current.srcObject);

            localStreamRef.current = stream;

            videoRef.current.onplay = () => {
                console.log('Video is playing');
            };

            videoRef.current.onloadedmetadata = () => {
                const { videoWidth, videoHeight } = videoRef.current;
                if (canvasRef.current) {
                    canvasRef.current.width = videoWidth;
                    canvasRef.current.height = videoHeight;
                    if (containerRef.current) {
                        containerRef.current.style.aspectRatio = `${videoWidth}/${videoHeight}`;
                        console.log('Canvas dimensions set:', videoWidth, videoHeight);
                        const ctx = canvasRef.current.getContext('2d');
                        ctx.drawImage(videoRef.current, 0, 0, canvasRef.current.width, canvasRef.current.height);
                    }
                    setIsStreaming(true);
                }
            };

            // Add canplay event listener to ensure video is ready
            videoRef.current.oncanplay = () => {
                console.log('Video is ready to play');
                videoRef.current.play();
            };

        } else {
            console.error('Video element is not available.');
        }
    } catch (error) {
        console.error('Error accessing camera:', error);
    } finally {
        setIsInitializing(false);
    }
}, []);

Screenshot of React App in Local
Local Screenshot

Screenshot in Hosted App
Hosted Screenshot

Are there additional permissions that I need to include for the firebase application?

How to pass additional arguments to Next.js Server Actions

I am building a file upload page in NextJs.
I Utilised the useActionState alongside initialState.

The issue

If a validation error happend in the backend after submitting, the data retrurned to the frontend except the files. so the user have to re-select them all.
To avoid this behaviour i saved the files in a state (not anymore in the input itslef), this was the best approach since i can’t re-assign the data to the input field of type file.

However i don’t know how to attach them to the request going to the serverAction.

What did I try

I have tried to do it like this:

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    files.forEach((file) => formData.append("proof", file));
    formAction(formData);
  };

But i get this error after submitting, even tho everything works as expected:

An async function was passed to useActionState, but it was dispatched outside of an action context. This is likely not what you intended. Either pass the dispatch function to an `action` prop, or dispatch manually inside `startTransition`

I have tried to understand this error, but wasn’t able to.

Goal / Expectation

  1. As mentioned above, i want to keep the files until they are successfully uploaded to the cloud.

  2. On success i want to reset the states and remove the files from the state.

My Component

"use client";
import { useActionState, useCallback, useEffect } from "react";
import submit from "./action";
import { twJoin } from "tailwind-merge";
import Main from "@/components/Main";
import { useLocale, useTranslations } from "next-intl";
import Dropzone from "./Dropzone";
import PageHeader from "@/components/PageHeader";
import HugeRoundedButton from "@/components/RoundedButton";
import { useState } from "react";
import { FileRejection } from "react-dropzone";

const initialState = {
  zodErrors: null,
  message: null,
  success: false,
  data: {
    summary: "",
    proof: [],
    note: "",
  },
};
interface PreviewFile extends File {
  preview: string;
}
const CostTracker = () => {
  // States
  const [formState, formAction, pending] = useActionState(submit, initialState);
  const [files, setFiles] = useState<PreviewFile[]>([]);
  const [rejectedFiles, setRejectedFiles] = useState<FileRejection[]>([]);

  const onDrop = useCallback(
    (acceptedFiles: File[], rejectedFiles: FileRejection[]) => {
      if (acceptedFiles.length > 0) {
        setFiles((previousFiles) => [
          ...previousFiles,
          ...acceptedFiles.map((file) =>
            Object.assign(file, {
              preview: URL.createObjectURL(file),
            })
          ),
        ]);
      }

      if (rejectedFiles.length > 0) {
        setRejectedFiles((previousFiles) => [
          ...previousFiles,
          ...rejectedFiles,
        ]);
      }
    },
    []
  );

  const removeFile = (name: string) => {
    // Revoke the data uris to avoid memory leaks
    URL.revokeObjectURL(
      files.find((file) => file.name === name)?.preview as string
    );
    setFiles((files) => files.filter((file) => file.name !== name));
  };
  const removeRejectedFile = (name: string) => {
    setRejectedFiles((rejectedFiles) =>
      rejectedFiles.filter(({ file }) => file.name !== name)
    );
  };

  // Runs when the component unmounts
  useEffect(() => {
    // Make sure to revoke the data uris to avoid memory leaks, will run on unmount
    return () => files.forEach((file) => URL.revokeObjectURL(file.preview));
  }, [files]);

  // Locale
  const locale = useLocale();
  const translations = useTranslations("cost_tracking_page");
  const dir = locale === "ar" ? "rtl" : "ltr";

  // Form State
  const { data, zodErrors, message, success } = formState;

  // Handle form submission
  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    files.forEach((file) => formData.append("proof", file));
    formAction(formData);
  };

  return (
    <Main dir={dir} className="flex-grow gap-6">
      <PageHeader
        title={translations("title")}
        subTitle={translations("subTitle")}
      />
      <form
        onSubmit={handleFormSubmit}
        // action={formAction}
        className="flex flex-col gap-8 bg-primary rounded-3xl px-4 py-8"
        dir={dir}
      >
        <div className="flex gap-2 flex-col">
          <input
            step=".01"
            name="summary"
            type="number"
            defaultValue={data?.summary}
            placeholder={translations("summary_placeholder")}
            className="outline-none p-3 border border-secondary bg-background text-foreground w-full rounded-xl"
          />
          {zodErrors?.summary && (
            <p aria-live="polite" className="text-red-500">
              {zodErrors.summary}
            </p>
          )}
        </div>
        <div className="flex gap-2 flex-col">
          <Dropzone
            files={files}
            onDrop={onDrop}
            onRemoveFile={removeFile}
            rejectedFiles={rejectedFiles}
            onRemoveRejectedFile={removeRejectedFile}
          />
        </div>
        <div className="flex gap-2 flex-col">
          <textarea
            name="note"
            defaultValue={data?.note}
            placeholder={translations("note_placeholder")}
            className="outline-none p-3 border border-secondary bg-background text-foreground w-full rounded-xl min-h-24"
          />
          {zodErrors?.note && (
            <p aria-live="polite" className="text-red-500">
              {zodErrors.note}
            </p>
          )}
        </div>
        <p
          aria-live="assertive"
          className={twJoin(success ? "text-green-500" : "text-red-500")}
        >
          {message}
        </p>
        <HugeRoundedButton
          disabled={pending}
          text={
            pending ? translations("loading") : translations("submit_btn_text")
          }
          className="bg-blue-500 text-white"
        />
      </form>
    </Main>
  );
};

export default CostTracker;

Any Idea on how to achive this?
Thank all.

TAbulator addRow() causes uncontrolled scrolling with grouped rows

I have created a table with Tabulator that has several hundreds of rows grouped by a certain column.
I changed the height property from 100% to pixels to enable virtual DOM that affected the performance by making the grid very responsive.
The thing is that when I add a row to a group, the contents scroll uncontrollably.

the only solution that I came up with that somehow “works” is this that just brings the newly added row to the center of the table.

Tabulator version 6.3.0 on the latest Chrome

Any ideas?

{
// Calculate and set precise scroll position
const tableHolder = table.element.querySelector(“.tabulator-tableholder”); // Get the scroll container
const addedRowElement = addedRow.getElement(); // Get the DOM element of the added row

                if (tableHolder && addedRowElement) {
                    const rowPosition = addedRowElement.offsetTop; // Distance of the row from the top of the table
                    const holderHeight = tableHolder.offsetHeight; // Visible height of the table holder

                    // Center the row in the viewport
                    tableHolder.scrollTop = rowPosition - holderHeight / 2 + addedRowElement.offsetHeight / 2;

                    console.log("Scroll position adjusted for new row:", tableHolder.scrollTop);
                } else {
                    console.error("Failed to adjust scroll position. Table holder or row element not found.");
                }

}

Pull down menus for State -> County -> City from MySQL database [closed]

I’m trying to make an interactive drop down for State / County / City / SIC (choice of 5 SICS) using MySQL and PHP…

I can’t find any examples that work from this data.

PULL DOWN 1

select distinct state from data20251;

PULL DOWN 2

select distinct county from data20251 where state = 'xx';

PULL DOWN 3

select distinct city from data20251 where state = 'xx' and county = 'xxxxxxxxxxx';

PULL DOWN 4

select name,street from data20251  where state = 'xx' and county = 'xxxxxxxxxxx' and city = 'xxxxxxxxxxx' and SIC = '123451';
select name,street from data20251  where state = 'xx' and county = 'xxxxxxxxxxx' and city = 'xxxxxxxxxxx' and SIC = '123452';
select name,street from data20251  where state = 'xx' and county = 'xxxxxxxxxxx' and city = 'xxxxxxxxxxx' and SIC = '123453';
select name,street from data20251  where state = 'xx' and county = 'xxxxxxxxxxx' and city = 'xxxxxxxxxxx' and SIC = '123454';
select name,street from data20251  where state = 'xx' and county = 'xxxxxxxxxxx' and city = 'xxxxxxxxxxx' and SIC = '123455';

If anyone can help me I would really appreciate it.

Thanks!

Pass component and add style to it with solidjs and TypeScript

I have several icons in my web application which look like this:

type IconProps = ComponentProps<"svg">

const Icon = (props: IconProps) => {
  const [, rest] = splitProps(props, ["class"])
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      class={cn("", props.class)}
      {...rest}
    />
  )
}

export function IconUser(props: IconProps) {
  return (
    <Icon {...props}>
      <path .... />
    </Icon>
  )
}

Next I want to write the following component to receive one of the various icons and render it. However I need the ability to add the style prop to the given icon.

export const SettingButton = (props: {
    title: string;
    icon: ?; // JSX.Element maybe? 
    onPress: () => void;
}) => {


const { hovering, hoveringProps } = useHovering();
    const responsive = useResponsiveV2();
    const color = () => {
        if (hovering()) {
            return c.colors.text.secondary;
        }
        return c.colors.text.tertiary;
    };
    return (
    ? // {props.icon} works but I want to add the style prop to it here
// Ideally {props.icon style={{color: color()}}}
)

// Usage: <SettingButton title={"Test"} icon={<IconUser />} onPress={() => {}} />

Please note that I am using solidjs so to my knowledge cloneElement is not available.

Also I know I could wrap this in a div and apply the style there but I am wondering how to do it right.

Make Bootsrrap accordion wait for work complition before expand

Pressing on the accordion button, I’d likt to wait until accordion body will be computed, and just after this expand its content.
Otherwise expanding happens in several stages as appending new elements to accordion body. Non-smooth.

const ab = document.querySelector('.accordion-button');
ab.addEventListener('click', abListener);

function abListener(ev) {
    // Heavy DOM work to build accordion body;
}

I thought I could make it by using preventDefault method. but accordion still axpands.

ab.addEventListener('click', abListener);
// mouseup, mousedown and so on...

function abListener(ev) {
    ev.preventDefault();
    // Heavy DOM work to build accordion body;
    setTimeout(() => { /* Manually expand the accordion; */ }, 0);
}

Thank you.

How Can I Use Webpack to Concatenate JavaScript Files Without Breaking Global Scope? [duplicate]

I’m using Webpack for my JavaScript files, and my goal is simply to concatenate them. However, I’m unsure if Webpack can achieve this.

Here’s an example:

file1.js

var app = getApp();

file2.js

app.work();

In the browser, I use:

<script src="file1.js"></script>
<script src="file2.js"></script>

This works because app is stored on the global object (var/window).

However, when I use Webpack, it generates something like:

(() => {
  eval(`var app = ...`);
})();
(() => {
  eval(`app.work()...`);
})();

Since the scripts execute inside an IIFE (Immediately Invoked Function Expression), app is no longer stored on the window object but in the local scope.

I’m working with older JavaScript and can’t modify the files to use import/export. Is there a way to configure Webpack to handle this?