Populating Card With Data (Javascript & Firestore)

I am currently working on building a KDS which will display orders using javascript & firestore. The orders are being displayed with cards. However when i try to display the order items for each order in their respective card, all of the items are being placed in the first order card as you can see in the image attached.

Each order is a document in Firestore and in turn each order has a subcollection called ‘Order Items’ where the order items are stored as seen here.

I’m honestly lost as to what i am doing wrong. Can someone point me in the right direction? Thank you. Screenshot

const openOrdersQuery = query
                                (
                                    collection(db, "Orders"),
                                    where("orderStatus", "==", "New"),
                                    orderBy("timeStamp")
                                );
                        
        const querySnapshot = onSnapshot(openOrdersQuery, (querySnapshot) => 
        {
            container.innerHTML = "";
            ordersArray = [];
            querySnapshot.forEach((doc) => 
            {
                const orderObject = doc.data();
                ordersArray.push
                (
                    [
                        orderObject.orderNumber, 
                        orderObject.guestRmNum, 
                        orderObject.server, 
                        orderObject.orderStatus, 
                        orderObject.server, 
                        orderObject.table, 
                        orderObject.timeStamp,
                        orderObject.dateCreated.toDate().toLocaleTimeString()
                    ]
                );

                createOrderCard(orderObject);
            });

            async function createOrderCard(order) 
            {
                const card = document.createElement('div');
                card.classList = 'card-body';
                
                const orderContent = `
                                    <div class="card">
                                        <h1 id="orderNumberH1">Order: ${order.orderNumber}</h1>
                                        <h2 id="orderInfoH2">Room: ${order.guestRmNum}</h1>
                                        <h2 id="orderInfoH2">Table: ${order.table}</h2>
                                        <h2 id="orderInfoH2">Server: ${order.server}</h2>
                                        <h2 id="orderInfoH2">Time: ${order.dateCreated.toDate().toLocaleTimeString()}</h2>
                                        <hr></hr>
                                        <ul id="orderItemsList"></ul>
                                        <hr></hr>
                                        <button id="completeBtn" onclick="markCompleted('${order.orderNumber}')">Mark As Completed</button>
                                    </div>
                                `
                ;
                container.innerHTML += orderContent;
                
                var orderItemsArray = new Array();
                const orderItemsDocSnap = await getDocs(collection(db, "Orders/" + order.orderNumber + "/Order Items"));
                orderItemsDocSnap.forEach((doc) => 
                {
                    const orderItemsObject = doc.data();
                    orderItemsArray.push
                    (
                        [
                            orderItemsObject.item, 
                            orderItemsObject.quantity, 
                            orderItemsObject.modifiers, 
                            orderItemsObject.guestRequests
                        ]
                    );

                    let orderItemsList = document.getElementById("orderItemsList");
                        
                    let li = document.createElement('li');
                    li.innerText = orderItemsObject.quantity + "x " + orderItemsObject.item;
                    orderItemsList.appendChild(li);
                });
            }
        });

Issue with Filtering Data by Date Input Parameter in Prisma Query

I’m working on a procedure that filters data based on the creation date within the last 24 hours. The code works perfectly when the date is explicitly specified within the procedure:

appReqscreated24H: protectedProcedure
  .query(async ({ ctx }) => {
    return await ctx.prisma.appRequest.count({
      where: {
        created_at: {
          gte: new Date(Date.now() - 24 * 60 * 60 * 1000)
        },
        NOT: {
          status: {
            in: [RequestStatus.COMPLETE]
          }
        }
      }
    })
  })

However, when I try to pass the date as an input parameter, the code doesn’t work as expected:

appReqscreated24H: protectedProcedure
  .input(
    z.object({
      startDate: z.date()
    }) 
  )
  .query(async ({ ctx, input }) => {
    return await ctx.prisma.appRequest.count({
      where: {
        created_at: {
          gte: input.startDate
        },
        NOT: {
          status: {
            in: [RequestStatus.COMPLETE]
          }
        }
      }
    })
  }),

I’ve compared the types and they appear to be identical, yet I’m encountering issues with it not functioning as expected. As someone new to this, I would greatly appreciate any assistance.
Thank you in advance!

how to optimize the pdf.js microtask to make the pdf render smoothly

I have tried to add partial pdf loading and virtual list for the pdf rendering, now I found the pdf still flashing when I zoom the pdf page. I have already tried the official idea to show the legacy pdf page before the pdf render success, this is the code look like:

import React, { useRef, useState } from "react";
import { Page } from "react-pdf";
import styles from "./TeXPDFPage.module.css";
import { PageCallback } from "react-pdf/dist/cjs/shared/types";
import { readConfig } from "@/config/app/config-reader";
import { PageViewport } from "pdfjs-dist";
import { ProjAttribute } from "@/model/proj/config/ProjAttribute";
import { useSelector } from "react-redux";
import { AppState } from "@/redux/types/AppState";

interface PDFPageProps {
  index: number;
  style: React.CSSProperties;
  projId: string;
  width: number;
}

const TeXPDFPage: React.FC<PDFPageProps> = ({
  index,
  style,
  projId,
  width,
}) => {
  let pdfScaleKey = "pdf:scale:" + projId;
  let cachedScale = Number(localStorage.getItem(pdfScaleKey));
  const { projAttr } = useSelector((state: AppState) => state.proj);
  const canvasArray = useRef<
    Array<React.MutableRefObject<HTMLCanvasElement | null>>
  >([]);
  const [projAttribute, setProjAttribute] = useState<ProjAttribute>({
    pdfScale: cachedScale,
    legacyPdfScale: cachedScale,
  });
  const updateRefArray = (index: number, element: HTMLCanvasElement | null) => {
    if (element) {
      canvasArray.current[index] = { current: element };
    }
  };
  const [renderedPageNumber, setRenderedPageNumber] = useState<number>(-1);

  React.useEffect(() => {
    if (projAttr.pdfScale === 1 && cachedScale) {
      return;
    }
    setProjAttribute(projAttr);
  }, [projAttr, cachedScale]);

  const handlePageRenderSuccess = (page: PageCallback) => {
    
    setRenderedPageNumber(page.pageNumber);
  };

  const handlePageChange = (page: any) => {};

  /**
   * to avoid the pdf page flashing & flicking when zoom the pdf
   * keep the legacy page before the new pdf page rendered success
   * https://github.com/wojtekmaj/react-pdf/issues/875
   * https://github.com/wojtekmaj/react-pdf/issues/418
   *
   * @param page
   */
  const renderLegacyPage = (pageNumber: number, width: number) => {
    if (isLoading) {
      console.log("page" + pageNumber + " not rendered. using the legacy page");
      // debugger;
      return (
        <Page
          /**
           * IMPORTANT: Keys are necessary so that React will know which Page component
           * instances to use.
           * Without keys, on page number update, React would replace the page number
           * in 1st and 2nd page components. This may cause previously rendered page
           * to render again, thus causing a flash.
           * With keys, React, will add prevPage className to previously rendered page,
           * and mount new Page component instance for the new page.
           */
          key={pageNumber + "@" + projAttribute.legacyPdfScale}
          className="prevPage"
          scale={projAttribute.legacyPdfScale}
          pageNumber={pageNumber}
          // onLoad={handlePageChange}
          onChange={handlePageChange}
          //canvasRef={(element) => updateRefArray(index, element)}
          // onRenderSuccess={handlePageRenderSuccess}
          width={width}
        />
      );
    } else {
      console.log("page" + pageNumber + " has rendered");
      return null;
    }
  };

  const isLoading = renderedPageNumber !== index;

  return (
    <div style={style}>
      {renderLegacyPage(index, width)}
      <Page
        key={index + "@" + projAttribute.pdfScale}
        className={styles.pdfPage}
        scale={projAttribute.pdfScale}
        onLoad={handlePageChange}
        canvasRef={(element) => updateRefArray(index, element)}
        onChange={handlePageChange}
        onRenderSuccess={handlePageRenderSuccess}
        pageNumber={index}
        width={width}
      ></Page>
    </div>
  );
};

export default TeXPDFPage;

but the page still flashing when zoom(the page will disappear for a short time and show the new scale page). I have tried to use the chrome performance to found out the issue and found that the pdf.js have some microtask takes a long time:

enter image description here

is the pdf.js microtask make the render slow? what should I do to optimize it? this is the outer level code that foreach to render the pdf page:

const renderPdfList = () => {
      if (pdf && pageViewports) {
        return (
          <AutoSizer onResize={onResize}>
            {({ width, height }: { width: number; height: number }) => (
              <VariableSizeList
                ref={virtualListRef}
                width={width}
                height={height}
                estimatedItemSize={50}
                initialScrollOffset={getInitialScrollOffset()}
                itemCount={pdf.numPages}
                onScroll={(e: ListOnScrollProps) => handleWindowPdfScroll(e)}
                itemSize={(pageIndex) => getPageHeight(pageIndex, width)}
              >
                {({ index, style }: { index: number; style: any }) => (
                  <TeXPDFPage
                    index={index + 1}
                    width={width}
                    style={style}
                    projId={projId}
                  />
                )}
              </VariableSizeList>
            )}
          </AutoSizer>
        );
      } else {
        return <div>loading...</div>;
      }
    };

I am using the virtual list to just render the viewport pdf(maybe 3-5 pages) and not render the whole pdf pages(>500 pages).

Is Null Checking Necessary in TypeScript for Runtime Safety?

TypeScript types are only enforced at compile time and do not exist at runtime. Given this, if I define a TypeScript function that accepts a string parameter, is it necessary to perform null checks? This question arises because if the API returns null, it could lead to runtime errors.

Consider the following code snippet:

const capitalise = (val: string) => {
   // Question: Is this check redundant due to TypeScript's type checking?
   if (!val) {
      return '';
   }

   return val.toUpperCase();
};

// Assume 'name' is fetched from an API or another source that could return null
const name: string = /* fetch from API or another source */;

capitalise(name);

What are the best practices in such scenarios to ensure runtime safety in TypeScript applications?

Generate a pkcs8 key suitable for ECDSA private key import using subtlecrypto

I need to generate a deterministic set ECDSA keys using zero dependencies javascript, for which I produce a pkcs8 key out of raw bytes and then importe it as ECDSA private key. Is this logically possible and if so what’s wrong with the code below, as it gives me DataError error during the import call.

// Example function to convert derived bits to a PKCS#8 formatted key and import it
function convertRawKeyToPKCS8(rawKey, curveOid) {
    // PKCS#8 header for ECDSA with the chosen curve OID
    const pkcs8Header = [
        0x30, 0x81, 0x87,       // SEQUENCE (header, total length)
        0x02, 0x01, 0x00,       // INTEGER (version 0)
        0x30, 0x13,             // SEQUENCE (AlgorithmIdentifier header)
        0x06, 0x07,             // OBJECT IDENTIFIER (1.2.840.10045.2.1 - ecPublicKey OID)
        0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
        0x06, 0x08,             // OBJECT IDENTIFIER for curve (this is curve specific, provided as parameter)
        ...curveOid,
        0x04, 0x6d,             // OCTET STRING (privateKey length follows)
        0x30, 0x6b,             // SEQUENCE
        0x02, 0x01, 0x01,       // INTEGER (version 1)
        0x04, 0x20              // OCTET STRING (private key length, 32 bytes for P-256)
    ];

    // Append the raw private key bytes
    const pkcs8Key = new Uint8Array(pkcs8Header.length + rawKey.length);
    pkcs8Key.set(pkcs8Header);
    pkcs8Key.set(rawKey, pkcs8Header.length);

    return pkcs8Key;
}

// Example OIDs for different elliptic curves:
const OID_P256 = [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]; // P-256 curve OID

// Example raw ECDSA private key for P-256 (32 bytes):
const rawPrivateKey = new Uint8Array([
    0x93, 0x6a, 0x62, 0x91, 0x62, 0xa9, 0xba, 0x46,
    0x0c, 0x12, 0xfa, 0xb7, 0xdb, 0xe0, 0x2f, 0x91,
    0x52, 0xfa, 0xd2, 0xda, 0x47, 0x9a, 0x7d, 0xf2,
    0xbe, 0xab, 0xaa, 0x04, 0x48, 0x67, 0x6b, 0xa1
]);

// Generate the PKCS#8 key
const pkcs8Key = convertRawKeyToPKCS8(rawPrivateKey, OID_P256);

// Log the resulting PKCS#8 key as a hexadecimal string for display (optional)
console.log(Array.from(pkcs8Key).map(b => b.toString(16).padStart(2, '0')).join(''));

// Use the SubtleCrypto API to import the PKCS#8 key
async function importECDSAPrivateKey(pkcs8Key) {
    const privateKey = await crypto.subtle.importKey(
        "pkcs8",
        pkcs8Key.buffer,
        {
            name: "ECDSA",
            namedCurve: "P-256",
        },
        true,    // Extractable
        ["sign"] // Key usage
    );
    return privateKey;
}

// Example usage
importECDSAPrivateKey(pkcs8Key).then(privateKey => {
    console.log('Private key imported:', privateKey);
}).catch(console.error);

How to use Sharp in AWS Lambda function? I keep getting errors. (node.js, for image resizing)

I added this Lambda layer to my function, which is described as follows: “This serverless application provides a Lambda Layer that includes the sharp image processing library for Node.js”

I’m now trying to run a Lambda function that uses Sharp, but I keep getting errors.

When I try to run it including an import statement, like so…

import sharp from 'sharp';
...
await sharp(inputImagePath)
    .resize(desiredWidth, desiredHeight)
    .toFile(outputImagePath);

…I get this error message:

{
  "errorType": "Error",
  "errorMessage": "Could not load the "sharp" module using the linux-x64 runtimenPossible solutions:n- Ensure optional dependencies can be installed:n    npm install --include=optional sharpn    yarn add sharp --ignore-enginesn- Ensure your package manager supports multi-platform installation:n    See https://sharp.pixelplumbing.com/install#cross-platformn- Add platform-specific dependencies:n    npm install --os=linux --cpu=x64 sharpn- Consult the installation documentation:n    See https://sharp.pixelplumbing.com/install",
  "trace": [
    "Error: Could not load the "sharp" module using the linux-x64 runtime",
    "Possible solutions:",
    "- Ensure optional dependencies can be installed:",
    "    npm install --include=optional sharp",
    "    yarn add sharp --ignore-engines",
    "- Ensure your package manager supports multi-platform installation:",
    "    See https://sharp.pixelplumbing.com/install#cross-platform",
    "- Add platform-specific dependencies:",
    "    npm install --os=linux --cpu=x64 sharp",
    "- Consult the installation documentation:",
    "    See https://sharp.pixelplumbing.com/install",
    "    at Object.<anonymous> (/opt/nodejs/node_modules/sharp/lib/sharp.js:114:9)",
    "    at Module._compile (node:internal/modules/cjs/loader:1469:14)",
    "    at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)",
    "    at Module.load (node:internal/modules/cjs/loader:1288:32)",
    "    at Module._load (node:internal/modules/cjs/loader:1104:12)",
    "    at Module.require (node:internal/modules/cjs/loader:1311:19)",
    "    at require (node:internal/modules/helpers:179:18)",
    "    at Object.<anonymous> (/opt/nodejs/node_modules/sharp/lib/constructor.js:10:1)",
    "    at Module._compile (node:internal/modules/cjs/loader:1469:14)",
    "    at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)"
  ]
}

Then when I try to run Sharp commands without any overt import statement, it gives me “sharp is undefined” errors.

I’m just very confused because my understanding is, the Lambda layer makes it so I can use Sharp in my Lambda function? What am I missing or doing wrong here? Thanks.

NextJS app caching gives error when deployed to app engine

Description : I have created a NextJS App and deployed it to Google App Engine.
Problem : When NextJS tries to cache the images and store it, app engine throws this error.

DEFAULT 2024-09-15T11:48:52.646123Z path: '/workspace/.next/cache/images'
DEFAULT 2024-09-15T11:48:52.646109Z syscall: 'mkdir',
DEFAULT 2024-09-15T11:48:52.646097Z code: 'ENOENT',
DEFAULT 2024-09-15T11:48:52.646093Z errno: -2,
DEFAULT 2024-09-15T11:48:52.646090Z at async /workspace/node_modules/next/dist/lib/batcher.js:45:32 {
DEFAULT 2024-09-15T11:48:52.646086Z at async /workspace/node_modules/next/dist/server/response-cache/index.js:121:25
DEFAULT 2024-09-15T11:48:52.646083Z at async ImageOptimizerCache.set (/workspace/node_modules/next/dist/server/image-optimizer.js:436:13)
DEFAULT 2024-09-15T11:48:52.646078Z at async writeToCacheDir (/workspace/node_modules/next/dist/server/image-optimizer.js:177:5)
DEFAULT 2024-09-15T11:48:52.646074Z at async Object.mkdir (node:internal/fs/promises:858:10)
DEFAULT 2024-09-15T11:48:52.646063Z ⨯ Failed to write image to cache Cyx4zJYF-A+sCaU4OaW1aqTtDqQ+UHD0kNi0DjBpqPk= Error: ENOENT: no such file or directory, mkdir '/workspace/.next/cache/images'
DEFAULT 2024-09-15T11:48:51.333178Z }

While I understand error is because App Engine is read-only, but I really don’t know how to solve it.

What I tried : I have changed my next.js.config to this

const nextConfig = {
...
  distDir: path.join('/tmp', '.next'),
  async headers () {
    return [
      {
        source: '/images/(.*)',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable'
          }
        ]
      }
    ]
  }
...
}

Axios request response 401 in React Native app, but working in Postman and browser?

Request failed with status code 401
this is the error that i am getting in my react native application in response to this api call

     const fetchData = async () => {
            try {
                const response = await axios.get(`${API_URL}/general-setting`, {
                    headers: {
                        'Accept': 'application/json',
                    }
                });
                const generalSetting = response.data.data.general_setting;
                const newTheme = {
                    baseColor: `#${generalSetting.base_color}`,
                    secondColor: `#${generalSetting.secondary_color}`,
                };
                setTheme(newTheme);
            } catch (error) {
                Alert.alert('Error Fetching Theme', 'Please check your internet connection and try again.');
            }
        };

but in Postman or in the browser I am getting the response correctly. Here it is
Api response in postman

I tried the same api in browser, its working there also but not in my react native application

The grant was issued to another client. Please make sure the ‘client_id’ matches the one used at the authorize request

I am new to okta. and I have a problem as follows:
I have configured Okta application for both frontend (SPA application) and backend (web application) in Okta Console.

  1. Create Frontend Application (SPA)
    Log in to Okta Developer Console.
    Go to: Applications > Applications.
    Select Create App Integration.
    Select OIDC – OpenID Connect > Single-Page App (SPA)

  2. Create Backend Application (Web Application)
    Log in to Okta Developer Console.
    Go to: Applications > Applications.
    Select Create App Integration.
    Select OIDC – OpenID Connect > Web

Here is an example of how I setup the Frontend side

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Okta SPA App</title>
</head>
<body>
    <h1>Okta SPA OAuth2 Example</h1>
    <button id="login">Login with Okta</button>
    <button id="logout" style="display:none;">Logout</button>
    <p id="status"></p>
    <script src="https://cdn.jsdelivr.net/npm/@okta/[email protected]/dist/okta-auth-js.min.js"></script>

    <script>
        const oktaAuth = new OktaAuth({
            issuer: 'https://{myOktaDomain}}/oauth2/default',
            clientId: 'my_client_id',
            redirectUri: 'http://localhost:8080/callback',
            responseType: ['code'],
            scopes: ['openid', 'profile', 'email']
        });
        document.addEventListener('DOMContentLoaded', () => {
            const loginButton = document.getElementById('login');
            const logoutButton = document.getElementById('logout');
            const statusElement = document.getElementById('status');

            loginButton.addEventListener('click', () => {
                console.log('Login button clicked');
                statusElement.innerText = 'Redirecting to Okta...';
                oktaAuth.token.getWithRedirect({
                    responseType: 'code',
                    scopes: ['openid', 'profile', 'email']
                }).catch(err => {
                    console.error('Error during redirect:', err);
                    statusElement.innerText = 'Error during login.';
                });
            });

            logoutButton.addEventListener('click', () => {
                console.log('Logout button clicked');
                statusElement.innerText = 'Logging out...';
                oktaAuth.signOut().catch(err => {
                    console.error('Error during logout:', err);
                    statusElement.innerText = 'Error during logout.';
                });
            });

            handleCallback();
        });

        async function handleCallback() {
            if (window.location.pathname === '/callback') {
                console.log('Handling callback...');
                try {
                    const tokenResponse = await oktaAuth.token.parseFromUrl();
                    const authorizationCode = new URL(window.location.href).searchParams.get('code');
                    
                    console.log('Authorization Code:', authorizationCode);
                    document.getElementById('status').innerText = `Authorization Code: ${authorizationCode}`;
                    document.getElementById('login').style.display = 'none';
                    document.getElementById('logout').style.display = 'block';
                } catch (err) {
                    console.error('Error during callback handling:', err);
                    document.getElementById('status').innerText = 'Error during login process.';
                }
            }
        }
    </script>
</body>
</html>

This is my backend side:

const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const app = express();

const CLIENT_ID = 'my_clientId'; 
const CLIENT_SECRET = 'my_clientsecret'; 
const REDIRECT_URI = 'http://localhost:8080/callback'; 

// Middleware
app.use(bodyParser.json());

app.get('/callback', async (req, res) => {
    const authorizationCode = req.query.code;

    if (!authorizationCode) {
        return res.status(400).send('Authorization code is missing.');
    }

    try {
        const tokenResponse = await axios.post('https://{myOktaDomain}/oauth2/default/v1/token', new URLSearchParams({
            'grant_type': 'authorization_code',
            'code': authorizationCode,
            'redirect_uri': REDIRECT_URI,
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET
        }), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });

        const accessToken = tokenResponse.data.access_token;
        console.log('Access Token:', accessToken);
        res.json({ message: 'Login successful', accessToken });

    } catch (error) {
        console.error('Error exchanging authorization code for token:', error.response ? error.response.data : error.message);
        res.status(500).json({ 
            error: 'Error exchanging authorization code for token', 
            details: error.response ? error.response.data : error.message 
        });
    }
});

app.get('/health', (req, res) => {
    res.send('Server is running.');
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
    console.log(`Backend server is running on http://localhost:${PORT}`);
});

my problem is that even though i have configured client_id correctly for both frontend (spa application) and backend (web application) in okta console but when i run the program i keep getting error

Error exchanging authorization code for token: {
  error: 'invalid_grant',
  error_description: "The grant was issued to another client. Please make sure the 'client_id' matches the one used at the authorize request."
}

can anyone please help me find the cause

I want the Frontend to provide the user interface for logging in via Okta, including navigating the user to the Okta page for authorization and handling the callback response. The Backend receives the authorization code from the frontend, then exchanges that code with Okta to get the access token and responds to the frontend

JS function for Darkmode / Lightmode with value checking via Local Storage gives me a quick color change when going on subpages

I would like to add a button for switching to darkmode and lightmode on my website.

I use var()’s in my css to control the color of my elements.
This is my code:

function loadMode() {
    const mode = localStorage.getItem('mode');
    if (mode === 'dark') {
        setDarkMode();
    }
}

// set darkmode
function setDarkMode() {
    document.documentElement.style.setProperty('--textColor', '#eaeaea');
    document.documentElement.style.setProperty('--backgroundColor', '#333333');
    document.getElementById('toggleMode').textContent = 'Wechsel zu Lightmode';
    localStorage.setItem('mode', 'dark');
}

// set lightmode
function setLightMode() {
    document.documentElement.style.setProperty('--textColor', '#313131');
    document.documentElement.style.setProperty('--backgroundColor', '#e0e0e0');
    document.getElementById('toggleMode').textContent = 'Wechsel zu Darkmode';
    localStorage.setItem('mode', 'light');
}

// toggle the color mode
function toggleMode() {
    const isDarkMode = localStorage.getItem('mode') === 'dark';
    if (isDarkMode) {
        setLightMode();
    } else {
        setDarkMode();
    }
}

// event listener for button
document.getElementById('toggleMode').addEventListener('click', toggleMode);

// load mode on site load
loadMode();

This script is loaded on the end of the webpage (this is the problem, I know, but how can I fix it?)
Now I have the problem that every time I go to a subpage the website is being loaded with the Light Colors and then switched to the dark colors which results in a quick, but very annoying color flicker effect.

How can I prevent this form happening? My website is build with php so sessions could work? Or cookies?

Thank you for helping!

I tried to put the function in the header but then the body element cant receive the color change because I think its not loaded yes(?)

WhatsApp Flows Health Check requires base64 encoded string

My WhatsApp Flow returns this Health Check Error:

Response body is not Base64 encoded
Expected result
Base64 encoded string
Actual result
{“data”:{“status”:”active”}}

My endpoint has a file that handles the health check and data exchanges which looks like this:

console.log(decryptedBody)

 // handle health check request
  if (action === 'ping') {
    
    return {
      data: {
        status: "active", 
      }
    };
  }

   // handle initial request when opening the flow (INIT action)
   if (action === "INIT") {
    return {
      screen: "WELCOME",
      data: {
  "coverimage": "/9j...."

My log is returning action: ‘ping’

I don’t understand why it requires a base64 encoded string when the action is ping as it should be expecting {“data”:{“status”:”active”}} or am I wrong?

There’s a base64 image that gets loaded when action === ‘INIT’, but when I replace the result from the ‘ping’ function with the ‘INIT’ result then it returns another error that says:

Response body is not Base64 encoded
Expected result
Base64 encoded string
Actual result
{“screen”:”WELCOME”,”data”:{“coverimage”:”/9j/4AAQ…

simple keyboard delete button not working correctly -vuejs2

I am using a simplekeyboard for my project, I wrote the function of the delete button myself. I have an input and when I press the 1 key on the keyboard and then delete it and press the 2 key, it appears as 12 in the input. The old input value comes with it. How can I solve this?

My code is as follows;

SimpleKeyboard.vue

case "{delete}":
            this.screenStore.handleKeyboardChange(this.screenStore.inputs[this.screenStore.inputName].slice(0, -1));
            this.firstCharacter = true;
          break;

and screen.js;

handleKeyboardChange(value) {
      //console.info("handleKeyboardChange:", value, this.inputName, this.inputs);
      if (this.inputName) {
        //this.inputs[this.inputName] = value;
        Vue.set(this.inputs, this.inputName, value);

        eventBus.$emit('keyboard-event-triggered', this.inputName);

        var _this = this;
        this.checkinFields.forEach(function(field){
          console.info(field.id, _this.inputName);
          if(field.id == _this.inputName){
            var property = field.target;
            if(property === 'firstname'){
              property = 'firstName';
            }
            if(property === 'lastname'){
              property = 'lastName';
            }
            _this.appointment.visitor[property] = _this.inputs[_this.inputName];
            console.info(_this.appointment);
          }
        });
      }

    },

please can someone help me? I’ve been trying to solve this for days

Express Multer file upload issue

I can’t figure out why I can’t use express and multer in my code above. When I upload my file, all I get in the log is an empty array. I’ve spent several hours modifying it, I just don’t get it!

I’ve seen that several people have reported errors or bugs between Express and multer, but I still can’t solve my problem. If you have any ideas, I’d be grateful!

If you have any ideas, here’s my code, thank you!

const functions = require('firebase-functions');
const express = require('express');
const multer = require('multer');
const Replicate = require('replicate');
const cors = require('cors');

const app = express();

// Configuration de Multer avec gestion d'erreurs
const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 10 * 1024 * 1024 }, // Limite à 10MB
}).single('image');

app.use(cors({ origin: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const replicate = new Replicate({
  auth: functions.config().replicate.api_token,
});

const styleDescriptions = {
  'Gamer': `Upgrade this setup to create a gaming setup, with aesthetic rgb lights...`,
  'Aesthetic': `Transform this setup into a minimalist and visually pleasing design...`,
  'RGB Free': `Enhance this setup to create a professional and sophisticated environment...`
};

app.post('/generate', (req, res) => {
  console.log('Received generate request');
  
  upload(req, res, async function(err) {
    console.log('On arrive ici');
    if (err) {
      console.error('Upload error:', err);
      return res.status(400).json({ error: 'File upload error', details: err.message });
    }

    try {
      const { file } = req;
      const { style } = req.body;

      console.log('File uploaded successfully');
      console.log('File details:', file ? { originalname: file.originalname, size: file.size } : 'No file');
      console.log('Selected style:', style);

      console.log('File details:', file ? { originalname: file.originalname, size: file.size } : 'No file');
      console.log('Selected style:', style);

      if (!file) {  
        return res.status(400).json({ error: 'No image file provided' });
      }

      const styleDescription = styleDescriptions[style] || '';

      console.log('Preparing input for Replicate API');
      const input = {
        image: `data:${file.mimetype};base64,${file.buffer.toString('base64')}`,
        prompt: styleDescription,
        guidance: 3.5,
        num_outputs: 1,
        aspect_ratio: "1:1",
        output_format: "webp",
        output_quality: 80,
        prompt_strength: 0.80,
        num_inference_steps: 28
      };

      console.log('Sending request to Replicate API...');
      const output = await replicate.run(
        "black-forest-labs/flux-dev",
        { input }
      );

      console.log('Replicate API response received');
      res.json({ output: output[0] });
    } catch (error) {
      console.error('Error in generate function:', error);
      res.status(500).json({ error: 'An error occurred while generating the image', details: error.message });
    }
  });
});
// Export the Express app as a Firebase Cloud Function
exports.api = functions.https.onRequest(app);

FileEntry.file() method not working properly when opening an HTML file directly

I am working on a drag-and-drop upload feature. Through the drop event, I use e.dataTransfer.items to retrieve the handles for all files and folders, then call the items[n].webkitGetAsEntry() method to get the FileEntry object. Finally, I attempt to use the FileEntry.file((file) => {}) method to retrieve the file object from the callback:

function traverseFileTree(item, path = "") {
  // The item here is the return value of webkitGetAsEntry().
  const isRecursive = document.getElementById("recursiveOption").checked;
  if (item.isFile) {
    item.file(
      (file) => {
        console.log("file", file);
        if (file.name.toLowerCase().endsWith(".md")) {
          file.fullPath = path + file.name;
          files.push(file);
          updateFileList();
        }
      },
      (error) => {
        console.error(error);
        showPopup(`Failed to read file ${item.name}: ${error.message}`);
      }
    );
  } else if (item.isDirectory) {
    if (isRecursive || path === "") {
      let dirReader = item.createReader();
      dirReader.readEntries(
        (entries) => {
          for (let i = 0; i < entries.length; i++) {
            traverseFileTree(entries[i], path + item.name + "/");
          }
        },
        (error) => {
          console.error("Failed to read directory:", error);
          showPopup(`Failed to read directory ${item.name}: ${error.message}`);
        }
      );
    }
  }
}

However, something strange happens: when I open the HTML file directly in the browser (using the file protocol), the .file() method throws an EncodingError:
file:

EncodingError: A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs.

But, when I serve the same HTML file through a local server (e.g., using Live Server over HTTP), the .file() method works as expected and I can successfully retrieve the file object.
http:

I’ve searched various resources and consulted GPT but couldn’t find a definitive answer. I suspect the issue may be related to browser security policies or relative path restrictions. Has anyone encountered this problem or knows what might be causing it?

I wish:
Understand the specific cause of this issue.
How should I solve similar problems on my own in the future?

Thank you!

How to get the date difference between two jalali date (persianDatepicker) on clicking the second input date picker?

I use this https://github.com/behzadi/persianDatepicker script to show jalali date

I select date1 and date2 to from datepicker to my input

Code

<script>
$(document).ready(function() {
    $('.example').persianDatepicker({
    format: 'YYYY/MM/DD',
    observer: true,
    altField: '.observer-example-alt',
        autoClose: true,
});
  });
</script>

<input id="start-date" class="example" name="start-date"/>  
<input id="end-date" class="example" name="end-date"/>     
<input id="diff" class="example" name="diff"/>    

I want when I select date1 (id=”start-date”) and date 2 (id=”end-date”) it will immediately display in (id=”diff”) the difference between the two jalali dates

for example 1

date1= 1403/06/06 
date2= 1403/06/06  

result:

1 day

example 2

date1= 1403/06/06 
date2= 1403/06/07   

result:

2 days

i dont add what add in my javascript to earn my result

<script>
??????
??????
</script>