Getting React type is Invalid

I’ve restarted using React 18 and react-bootstrap, but I’m not understanding the error it is giving out to me. The error is:

React.jsx: type is invalid — expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

This doesn’t make any sense to me since I imported the react-bootstrap modules properly like below.

Navigation.tsx


import React from 'react'
import { 
    Navbar,
    Nav,
    NavDropdown,
    NavbarBrand,
    NavbarToggle,
    NavLink,
    NavbarCollapse,
    Container
} from 'react-bootstrap';
// Tried the imports as below but still giving me the type is invalid error
// import NavDropdown from 'react-bootstrap/NavDropdown';
// import Container from 'react-bootstrap/Container';
// import Nav from 'react-bootstrap/Nav';

console.log(Navbar)
const Navigation = () => {
    return (
        <React.Fragment>
            <Navbar expand="lg" className="bg-body-tertiary">
                <Container>
                    <NavbarBrand>React-Bootstrap</NavbarBrand>
                    <NavbarToggle aria-controls="basic-navbar-nav" />
                    <NavbarCollapse id="basic-navbar-nav">
                        <Nav className="me-auto">
                            <NavLink >Home</NavLink>
                            <NavLink >Link</NavLink>
                            <NavDropdown title="Dropdown" id="basic-nav-dropdown">
                            // Complains on NavDropdowon.Item
                            <NavDropdown.Item >Action</NavDropdown.Item>
                            <NavDropdown.Item >
                                Another action
                            </NavDropdown.Item>
                            <NavDropdown.Item >Something</NavDropdown.Item>
                            <NavDropdown.Divider />
                            <NavDropdown.Item >
                                Separated link
                            </NavDropdown.Item>
                            </NavDropdown>
                        </Nav>
                    </NavbarCollapse>
                </Container>
            </Navbar>
        </React.Fragment>
    )
}

export default Navigation;

I conclude that it doesn’t like the . that comes after (EX: NavDropdown.Item). I see in the documentation that there should be no issue using that syntax. How do I fix this or what am I missing on the imports?

Why am i getting 500 internal server error Next js dynamic page route Firebase Production environment

Using Next js 15 with firebase

My dynamic page routes cant get data from firebase without giving 500 server errors in production only. I DONT see this in development and emulator environment.

I can get the slug id but when I use the db for firebase I get 500 errors in Production only

// app/meettheteam/[id]/page.tsx (Server Component)

import type { Coach } from '@/types';
import { getCoachById } from '@/lib/coaches-data';
import CoachComp from './CoachComp';
import { Suspense } from 'react';
import { notFound } from 'next/navigation';

async function CoachPage({ params }: { params: Promise<{ id: string }> }) {
  const id = (await params).id;

  try {
    const coach: Coach | null = await getCoachById(id);

    if (!coach) {
      notFound();
      return;
    }

    return (
      <>
        <Suspense fallback={<p>Loading coach details...</p>}>
          <CoachComp coach={coach} />
        </Suspense>
      </>
    );
  } catch (error) {
    console.error('Error fetching coach:', error);
    return <div>Error loading coach. Please try again later.</div>;
  }
}

export default CoachPage;

'use server';

// lib/coaches-data.ts

import { DocumentData } from 'firebase/firestore';

import { db } from '@/config/firebaseServer';

const getCoaches = async () => {
  try {
    const snapshot = await db.collection('coaches').get();

    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }

    const coachesDocs: DocumentData[] = snapshot.docs;

    const coaches = coachesDocs.map((doc) => ({
      id: doc.id,
      ...doc.data(),
    }));

    return coaches;
  } catch (error) {
    console.error('Error fetching coachs:', error);
    throw error;
  }
};

const getCoachById = async (id: string) => {
  try {
    const coachDoc: DocumentData = await db.collection('coaches').doc(id).get();

    if (coachDoc.exists) {
      const coach = coachDoc.data();

      coach.id = coachDoc.id;

      return coach;
    } else {
      console.log('Coach not found with ID:', id);
      return null;
    }
  } catch (error) {
    console.error('Error in getCoachById:', error);
    throw error;
  }
};

export { getCoaches, getCoachById };


// config/firebaseServer.tsx
import { initializeApp, getApps } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';
import { getFirestore } from 'firebase-admin/firestore';
import { getStorage } from 'firebase-admin/storage';
import { credential } from 'firebase-admin';

function initializeFirebaseAdmin() {
  const projectId = process.env.FIREBASE_PROJECT_ID;
  const storageBucket = process.env.FIREBASE_STORAGE_BUCKET;

  if (!projectId || !storageBucket) {
    // Check for these
    console.error(
      'Missing required Firebase environment variables (projectId or storageBucket).',
    );
    throw new Error(
      'Missing required Firebase environment variables (projectId or storageBucket).',
    );
  }

  try {
    const serviceAccount = require('../firebase.json'); // Directly require the JSON

    if (getApps().length === 0) {
      initializeApp({
        credential: credential.cert(serviceAccount),
        projectId,
        storageBucket,
      });

      console.log('Firebase Admin initialized successfully.');
    } else {
      console.log('Using existing Firebase Admin app.');
    }
  } catch (error) {
    console.error('Error initializing Firebase Admin:', error);
    throw error;
  }
}


initializeFirebaseAdmin();

const admin = getAuth();
const db = getFirestore();
const storage = getStorage();

export { admin, db, storage };

I was expecting the code to get the data

Using a server function in a server component

Pass data as a prop to client comp on page.

How to properly handle eventListener cross platform for separate left or right button events

I had a script that returned the element clicked or right clicked upon, origionally I did this by using the following:

document.addEventListener('click', function(e) {
  const targetEl = e.target;
  console.log('lc', targetEl);  
  clickCell(targetEl);
}, false);


document.addEventListener('contextmenu', function(e) {
  e.preventDefault();
  const targetEl = e.target;
  console.log('rc', targetEl); 
  rightClickCell(targetEl);
}, false);

this seemed to work, however I noticed some odd behaviour with left click, i.e. when the mouse was moved during click sometimes I would get the parent element (even though the parent el is completely covered) and realised that this was happening when the mouse pointer moved from one child cell to another during the click event.

I didn’t want to simply have the parent element ignored at this stage as then some appropriate clicks would be ignored… and changing the click event listener to mouseup would fix the left click issue, but fire both events on right click, so, after some testing and reading I moved to:

document.addEventListener('contextmenu', e => e.preventDefault());

document.addEventListener('mouseup', function(e) {
  const targetEl = e.target;
  if (e.button === 0) {
    console.log('lc', targetEl);
    clickCell(targetEl);
  } else if (e.button === 2) {
    console.log('rc', targetEl);
    rightClickCell(targetEl);
  }
}, false);

This now seems to work how I want it to; handling left-click or trackpad 1-finger-click for function A and rightclick or trackpad 2-finger-click for function B…

Given the issues I already encountered I am worried that this may not work reliably in other environments, e.g. Mac’s having a different implementation of right click. I have tried for a while to research this but have found confusing / contradictory explinations, so I would like to know how I should implement these event listeners to reliably work in any environment.

Angular error using new input signal transform to update other property in component

I have an angular 18 app and I have a form in a component that needs to get its value updated when an input property for the component changes.

The “old” way I would do this by defining setters and getters for the input property like this:

  private _shiftUpdate: ShiftUpsert | null = null;

  @Input()
  set shiftUpdate(value: ShiftUpsert | null) {
    this._shiftUpdate = value;
    if (value) {
      this.shiftForm.patchValue({ shiftId: value.shiftId, shiftGuid: value.shiftGuid });
    }
  }

  get shiftUpdate(): ShiftUpsert | null {
    return this._shiftUpdate;
  }

You can see that the form value is patched when this property is changed from the parent component.

My question is how to do this with the “new” signal input type.
When I try the following:

updatedShift = input<ShiftUpsert, ShiftUpsert>({ shiftId: 0 }, {
    transform(value: ShiftUpsert) {
      if (value) {
        this.shiftForm.patchValue(value);
      }
      return value;
    }
  });

I get an error on the this.shiftForm saying:

Property ‘shiftForm’ does not exist on type
‘Required<Pick<InputOptions<ShiftUpsert, ShiftUpsert>, “transform”>> &
InputOptions<ShiftUpsert, ShiftUpsert>’.

So I can see that the context of the inner input transform does not have access to the component properties.

Is there a way to do this with the new signal inputs or is the fact that I can’t do it telling me its an anti pattern?

Thanks

What is the the most efficient way of endering an MJPEG-Stream in browser

My application displays groups of MP4 (.H264) camera streams (displayed side by side) very efficiently. This is utilising feeding fragmented MP4 segments to a video element.

I am currently adding MJPEG support for legacy ip cameras, that can not provide .H264. This is however, as expected, quite expensive in the browser. I am looking for the absolutely most efficient way to implement this functionality.

My current test method:

Backend (Node.js, in a spawned child process) I am pulling an MJPEG-RTSP stream with FFMPEG, muting all channels(data/subtitels, audio) but the MJPEG stream itself.

The output is piped to sockets io thus:

    const IOptions = {
        path: '/streams/' + cameraID
    }

And

        Spawned.stdio[x].on('data', function (data) {

            let frame = Buffer.from(data).toString('base64')

            socket.emit('canvas', frame)
        })

Frontend I am currently creating new image Objects to be drawn to canvas:

let socket = io('/', { path: '/streams/camtitle' })
socket.on('canvas', function (data) {
    try {
        const canvas = document.getElementById('mjpegCanvas')
        const context = canvas.getContext('2d')
        const imageObj = new Image()
        imageObj.src = "data:image/jpeg;base64," + data
        imageObj.onload = function () {
            context.height = imageObj.height
            context.width = imageObj.width
            context.drawImage(imageObj, 0, 0, context.width, context.height)
        }
    } catch (e) { console.log('Canvas Drawing Error:' + e) }
})

This is leads to varying processer core loads between 8% and 29% client side on VGA (640 x 480, low framerates) and users would expect to be able to feed in much higher resolutions and framerates.

I have delved into related topics over the last 5 days and found senior sources stating that the generation of Objects is generally a very costly process in Javascript, possibly also related to garbage collection.

Is there a better way of handling or even reusing my image Objects? As far as my understanding goes, I am reusing my const imageObj. Is there more happening in the background?

I have seen other cases on stackoverflow, who implement MJPEG via image tags, with the source pointing to a MJPEG stream like this:

<img src="http://[some ip]:[port]/mjpg"> 

Others simply point the image source to a route ending with .jpg.

Either seems to however not work with the MJPEG-Sream I am providing. It also surpasses my understanding how this should actually work, without passing JPGs or at least splitting data by the respective frame delimiter. What am I missing here? I would like to benchmark that method for comparison.

I am additionally implementing a test diffing function server side, that reduces the work by only sending frames with a certain measure of pixel changes. It will be interesting to see how costly that will turn out to be.

Any optimisation suggestions or highly applicable resources pointing me into the right direction would be highly appreciated. Vanilla Javascript without libraries and moduls are preferred, but other options will be considered as well.

The solution can also suggest changes on the server. This is all just experimental at this point.

Next.js `router.refresh()` not updating data after POST request

I’m working on a Next.js application where I’m creating a new payment record in the database. After the record is created, I want to refresh the page to display the updated list of payments. I’m using router.refresh(), but the new data isn’t showing up unless I manually refresh the entire browser.

I have a page app/(user)/user/[userId]/page.tsx which is set to be dynamically rendered.

import { Suspense } from "react";
import { UserIdPageWrapper } from "./_components/userId-page-wrapper";

interface UserIdPageProps {
  params: Promise<{ userId: string }>;
}
export const dynamic = "force-dynamic";

export default async function UserIdPage({ params }: UserIdPageProps) {
  const { userId } = await params;

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <UserIdPageWrapper userId={userId} />
    </Suspense>
  );
}

The page uses a component called UserIdPageWrapper to fetch the user and payment data:

import { db } from "@/lib/db";
import { UserInfo } from "./userInfo";
import { redirect } from "next/navigation";

interface UserIdPageWrapperProps {
  userId: string;
}
export const UserIdPageWrapper = async ({ userId }: UserIdPageWrapperProps) => {
  const [userData, paymentsData] = await Promise.all([
    db.user.findUnique({
      where: {
        id: userId,
      },
    }),

    db.payment.findMany({
      where: {
        userId: userId,
      },
      include: {
        items: true,
      },
    }),
  ]);

  if (!userData || !paymentsData) {
    redirect("/");
  }

  return (
    <UserInfo
      user={userData}
      payments={paymentsData}
    />
  );
};

Inside the UserInfo component (a client component), I have a function handleAddPayment that sends a POST request to create a new payment:

"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import toast from "react-hot-toast";

interface userInfoProps {
  user: User;
  payments: (Payment & { items: PaymentItem[] })[];
}

export const UserInfo = ({ user, payments }: userInfoProps) => {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);

  const handleAddPayment = async () => {
    setIsLoading(true);
    try {
      const res = await fetch("/api/payments", {
        method: "POST",
        body: JSON.stringify({
          userId: user.id,
          totalAmount: 0,
          supervisionRatio: 0,
        }),
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (!res.ok) {
        throw new Error("Failed to add payment");
      }
      const jsonData = await res.json();

      console.log(jsonData);

      toast.success("New payment added");
      router.refresh();
    } catch (error) {
      toast.error("Failed to add payment");
    } finally {
      setIsLoading(false);
    }
  };

  // ... rest of the component
};

The /api/payments route handler looks like this:

import { NextResponse } from "next/server";
import { db } from "@/lib/db";

export async function POST(req: Request) {
  try {
    const { userId, totalAmount, supervisionRatio } = await req.json();
    const res = await db.payment.create({
      data: {
        userId,
        totalAmount,
        supervisionRatio,
        supervisionFee: (totalAmount * supervisionRatio) / 100,
        paymentDate: new Date(),
        remainingAmount: totalAmount - (totalAmount * supervisionRatio) / 100,
      },
    });

    return NextResponse.json(res);
  } catch (error) {
    console.error("[ORDERS_POST]", error);
    return new NextResponse("Internal error", { status: 500 });
  }
}

I’ve tried setting export const dynamic = "force-dynamic"; in my page.tsx file, but it’s still not working.

What I’ve tried:

  • Using router.refresh() after the POST request.
  • Setting dynamic = "force-dynamic" in the page.tsx file.

What I expect:

After creating a new payment, I expect the PaymentList component to re-render with the updated list of payments without a full browser refresh.

Question:

What am I missing? Is there a caching issue, or is router.refresh() not the correct approach for this scenario? How can I ensure that the page updates with the new data after the POST request?

chrome extension unable to filter out contents

I want to build a chrome extension named Personalized content feed, which suggest personalized content feed to the users after giving a input

Ex – machine learning, javascript

chrome extension needs to suggest contents as per the input, but it is failing to suggest the content. what could the problem?

content.js –

function getStoredKeywords(callback) {
    chrome.storage.sync.get(["youtubeKeywords"], (data) => {
        callback(data.youtubeKeywords || []);
    });
}

function rearrangeYouTubeContent() {
    getStoredKeywords((keywords) => {
        if (!keywords.length) return;

        let videoContainers = document.querySelectorAll("ytd-rich-item-renderer, ytd-video-renderer, ytd-grid-video-renderer");
        let matchingVideos = [];
        let nonMatchingVideos = [];

        videoContainers.forEach((video) => {
            let titleElement = video.querySelector("#video-title");
            if (!titleElement) return;

            let title = titleElement.innerText.toLowerCase();
            if (keywords.some(keyword => title.includes(keyword.toLowerCase()))) {
                matchingVideos.push(video);
            } else {
                nonMatchingVideos.push(video);
                video.style.display = 'none'; // Hide irrelevant videos
            }
        });

        let parentContainer = document.querySelector("ytd-section-list-renderer");
        if (parentContainer) {
            matchingVideos.forEach(video => parentContainer.prepend(video));
            console.log("✅ Moved relevant videos to the top");
        }
    });
}

// Observe for changes and reapply filtering
let observer = new MutationObserver(() => {
    setTimeout(rearrangeYouTubeContent, 500);
});

function startObserving() {
    let feedContainer = document.querySelector("ytd-page-manager");
    if (feedContainer) {
        observer.observe(feedContainer, { childList: true, subtree: true });
        console.log("✅ MutationObserver started.");
    } else {
        console.warn("⚠️ YouTube feed not found. Retrying...");
        setTimeout(startObserving, 500);
    }
}

// Run when the page loads
window.addEventListener('load', function () {
    console.log("✅ content.js is running on YouTube!");
    rearrangeYouTubeContent();
    startObserving();
    
    // Auto-scroll to ensure all videos load
    let scrollInterval = setInterval(() => {
        window.scrollBy(0, 1000);
        if (document.documentElement.scrollHeight - window.scrollY <= window.innerHeight) {
            clearInterval(scrollInterval);
        }
    }, 1000);
});


fetch("http://localhost:5000/recommend?query=" + encodeURIComponent(userInput))
    .then(response => response.json())
    .then(data => {
        let videos = document.querySelectorAll("ytd-video-renderer");
        videos.forEach(video => {
            let title = video.querySelector("#video-title").innerText.toLowerCase();
            if (!data.recommended_titles.includes(title)) {
                video.style.display = 'none';
            }
        });
    })
    .catch(error => console.error("❌ Error fetching recommended videos:", error));

Is it possible to use App.vue’s event in each views?

I’m trying to make a single page app with vue, which act with swipe (in mobile).

I’m very new in javascript and vue. it seems obvious that i don’t need to put event code in every single pages. Can I make some sort of function in App.vue file and use it in each view pages?

I want it be like, detect the swipe in app.vue and just simple if->move to somewhere (push) script in view pages.

<script>
var start = null;
window.addEventListener("touchstart",function(event){
  if(event.touches.length === 1){
    start = event.touches.item(0).clientX;
  }else{
    start = null;
  }
});
window.addEventListener("touchend",function(event){
  var offset = 100;
  if(start){
    var end = event.changedTouches.item(0).clientX;
    if(end > start + offset){
      console.log('prev');
      //Something in here?
    }
    else if(end < start - offset ){
      console.log('next');
      //Something in here?
    }
  }
});
</script>

This is my script part of the App.vue. (I copied from stackoverflow, and i can not recall the post) What should I add in //Something in here? part and in view files?

I had read throw documents about js event, but in this case, this is not parent-child relationship, so I couldn’t find right wording to describe my question. I’m sorry if i’m asking obvious question, and it’ll be welcome to let me know what method i should know.

Thank you.

How to calculate matrix transform for Canvas from polar coordinates

I have an image in 3d space of which I know some coordinates.
I’d like to use the HTML canvas to re-draw the image into a picture of set width and height.

For example when using this image:
enter image description here

I know the coordinates of the orange dots and I know the width and height of the blue rectangle.
I think using HTMLCanvasContext2D.transform should be enough to get the black rectangle drawn in the blue rectangle.
However, I can’t figure out how to calculate the values for the transform.

I don’t even know what to google for.
I don’t have an advance math background and I don’t want to use opencv.

Where would I start? What terms do I search for?
Searching “matrix transform” only results in math websites.

I’ve read the Canvas docs https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform,
I’ve read some wikipedia articles on matrix tranforms,
and, I’ve googled for a number of terms involving canvas, matrix tranform, inverse matrix transform etc.
I found this 9year old question, but it was never really answered and most of the links don’t work anymore: How to fix image perspective distortion and rotation with JavaScript?

Javascript show/hide multiple buttons with relational condition

can somebody help me code this relational condition problem…

basicly there are 7 dropdown button list and inside are checkboxes and every each of those checkboxes have their own related data in every dropdown button..

here is the log of structured array for reference:

[
    {
        "ic_manufacturer": "China",
        "ic_family": [
            "fruits"
        ],
        "field_cry_part_num": {
            "fruits": [
                "CT2016DB19200C0FLHA7",
                "KV5032G622A644L2GF00"
            ]
        },
        "field_cry_dimensions": {
            "fruits": {
                "CT2016DB19200C0FLHA7": [
                    "2.0×1.6mm"
                ],
                "KV5032G622A644L2GF00": [
                    "5.0×3.2mm"
                ]
            }
        },
        "field_cry_freq_khz": {
            "fruits": {
                "CT2016DB19200C0FLHA7": [
                    "2"
                ],
                "KV5032G622A644L2GF00": [
                    ""
                ]
            }
        },
        "field_cry_load_capacitance": {
            "fruits": {
                "CT2016DB19200C0FLHA7": [
                    "7pF"
                ],
                "KV5032G622A644L2GF00": [
                    ""
                ]
            }
        },
        "field_cry_aec": {
            "fruits": {
                "CT2016DB19200C0FLHA7": [
                    "45"
                ],
                "KV5032G622A644L2GF00": [
                    ""
                ]
            }
        }
    },
    {
        "ic_manufacturer": "Russia",
        "ic_family": [
            "animals",
            "human"
        ],
        "field_cry_part_num": {
            "animals": [
                "CX1210DB27120D0FFFCC",
                "CX1210DB27120H0FFFCC"
            ],
            "human": [
                "CX1210DB27120H0FLHCC",
                "CX1210DB27120D0GLHCC"
            ]
        },
        "field_cry_dimensions": {
            "animals": {
                "CX1210DB27120D0FFFCC": [
                    "1.2×1.0mm"
                ],
                "CX1210DB27120H0FFFCC": [
                    "1.2×1.0mm"
                ]
            },
            "human": {
                "CX1210DB27120H0FLHCC": [
                    "1.2×1.0mm"
                ],
                "CX1210DB27120D0GLHCC": [
                    "1.2×1.0mm"
                ]
            }
        },
        "field_cry_freq_khz": {
            "animals": {
                "CX1210DB27120D0FFFCC": [
                    "1"
                ],
                "CX1210DB27120H0FFFCC": [
                    "1"
                ]
            },
            "human": {
                "CX1210DB27120H0FLHCC": [
                    "1"
                ],
                "CX1210DB27120D0GLHCC": [
                    "1"
                ]
            }
        },
        "field_cry_load_capacitance": {
            "animals": {
                "CX1210DB27120D0FFFCC": [
                    "8pF"
                ],
                "CX1210DB27120H0FFFCC": [
                    "1pF"
                ]
            },
            "human": {
                "CX1210DB27120H0FLHCC": [
                    "12pF"
                ],
                "CX1210DB27120D0GLHCC": [
                    "8pF"
                ]
            }
        },
        "field_cry_aec": {
            "animals": {
                "CX1210DB27120D0FFFCC": [
                    "1"
                ],
                "CX1210DB27120H0FFFCC": [
                    "1"
                ]
            },
            "human": {
                "CX1210DB27120H0FLHCC": [
                    "1"
                ],
                "CX1210DB27120D0GLHCC": [
                    "1"
                ]
            }
        }
    },
    {
        "ic_manufacturer": "America",
        "ic_family": [
            "place"
        ],
        "field_cry_part_num": {
            "place": [
                "KV5032G*******P3GF00",
                "KV5032G*******P2GF00"
            ]
        },
        "field_cry_dimensions": {
            "place": {
                "KV5032G*******P3GF00": [
                    "5.0×3.2mm"
                ],
                "KV5032G*******P2GF00": [
                    "5.0×3.2mm"
                ]
            }
        },
        "field_cry_freq_khz": {
            "place": {
                "KV5032G*******P3GF00": [
                    "1"
                ],
                "KV5032G*******P2GF00": [
                    "1"
                ]
            }
        },
        "field_cry_load_capacitance": {
            "place": {
                "KV5032G*******P3GF00": [
                    "1"
                ],
                "KV5032G*******P2GF00": [
                    "1"
                ]
            }
        },
        "field_cry_aec": {
            "place": {
                "KV5032G*******P3GF00": [
                    "1"
                ],
                "KV5032G*******P2GF00": [
                    "1"
                ]
            }
        }
    }
]

also my existing code:

    let groupedData = []; 

    // Fetch IC manufacturer and IC family array from PHP
    fetch('/ic-family-array')
    .then(response => response.json())
    .then(data => {
        console.log('Raw data:', data);  // Check the data returned by the AJAX call
        groupedData = groupByManufacturer(data);
        console.log('Grouped IC Family Array:', groupedData);
    })
    .catch(error => {
        console.error('Error fetching IC family array:', error);
    });

    // Function to group related array
    function groupByManufacturer(data) {
        const { ic_manufacturer_arr, ic_family_arr, cry_part_num_arr, cry_dimensions_arr, cry_freq_khz_arr, cry_load_capacitance_arr, cry_aec_arr } = data;
        const result = [];
    
        ic_manufacturer_arr.forEach(manufacturer => {
            let families = ic_family_arr.filter(family => family.ic_manufacturer === manufacturer);
            let manufacturerEntry = {
                ic_manufacturer: manufacturer,
                ic_family: [],
                field_cry_part_num: {}, 
                field_cry_dimensions: {},
                field_cry_freq_khz: {}, 
                field_cry_load_capacitance: {},
                field_cry_aec: {}
            };

            families.forEach(family => {
                // Find all part numbers for this manufacturer and family
                let partNumbers = cry_part_num_arr
                    .filter(part => part.ic_manufacturer === manufacturer && part.ic_family === family.ic_family)
                    .map(part => part.field_cry_part_num);
    
                let dimensionsByFamily = {}; 
                let freqByFamily = {}; 
                let loadCapByFamily = {}; 
                let aecByFamily = {}; 
    
                partNumbers.forEach(partNumber => {
                    // Find dimensions for the part number
                    let dimensions = cry_dimensions_arr
                        .filter(dim => dim.ic_manufacturer === manufacturer && dim.ic_family === family.ic_family && dim.field_cry_part_num === partNumber)
                        .map(dim => dim.field_cry_dimensions);
                    if (dimensions.length > 0) {
                        dimensionsByFamily[partNumber] = dimensions;
                    }
    
                    // Find frequencies for the part number
                    let frequencies = cry_freq_khz_arr
                        .filter(freq => freq.ic_manufacturer === manufacturer && freq.ic_family === family.ic_family && freq.field_cry_part_num === partNumber)
                        .map(freq => freq.field_cry_freq_khz);
                    if (frequencies.length > 0) {
                        freqByFamily[partNumber] = frequencies;
                    }
    
                    // Find load capacitance for the part number
                    let loadCapacitance = cry_load_capacitance_arr
                        .filter(load => load.ic_manufacturer === manufacturer && load.ic_family === family.ic_family && load.field_cry_part_num === partNumber)
                        .map(load => load.field_cry_load_capacitance);
                    if (loadCapacitance.length > 0) {
                        loadCapByFamily[partNumber] = loadCapacitance;
                    }
    
                    // Find AEC for the part number
                    let aec = cry_aec_arr
                        .filter(a => a.ic_manufacturer === manufacturer && a.ic_family === family.ic_family && a.field_cry_part_num === partNumber)
                        .map(a => a.field_cry_aec);
                    if (aec.length > 0) {
                        aecByFamily[partNumber] = aec;
                    }
                });
    
                // Add the family to the manufacturer entry
                manufacturerEntry.ic_family.push(family.ic_family);
    
                // Organize 
                manufacturerEntry.field_cry_part_num[family.ic_family] = partNumbers;
                manufacturerEntry.field_cry_dimensions[family.ic_family] = dimensionsByFamily;
                manufacturerEntry.field_cry_freq_khz[family.ic_family] = freqByFamily;
                manufacturerEntry.field_cry_load_capacitance[family.ic_family] = loadCapByFamily;
                manufacturerEntry.field_cry_aec[family.ic_family] = aecByFamily;
            });
    
            result.push(manufacturerEntry);
        });
    
        const finalResult = result.map(manufacturer => {
            return {
                ic_manufacturer: manufacturer.ic_manufacturer,
                ic_family: manufacturer.ic_family,
                field_cry_part_num: manufacturer.field_cry_part_num,
                field_cry_dimensions: manufacturer.field_cry_dimensions,
                field_cry_freq_khz: manufacturer.field_cry_freq_khz,
                field_cry_load_capacitance: manufacturer.field_cry_load_capacitance,
                field_cry_aec: manufacturer.field_cry_aec
            };
        });
    
        return finalResult;
    }

    const manufacturerCheckboxes = document.querySelectorAll('#manufacturerDropdown input[type="checkbox"]');
    manufacturerCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function () {
            const selectedManufacturer = this.value;
            const familyCheckboxes = document.querySelectorAll('#familyDropdown input[type="checkbox"]');
            const crypartnumCheckboxes = document.querySelectorAll('#crypartnumDropdown input[type="checkbox"]');
            const dimensionsCheckboxes = document.querySelectorAll('#dimensionsDropdown input[type="checkbox"]');
            const frequencyCheckboxes = document.querySelectorAll('#frequencyDropdown input[type="checkbox"]');
            const load_capacitanceCheckboxes = document.querySelectorAll('#load_capacitanceDropdown input[type="checkbox"]');
            const aecCheckboxes = document.querySelectorAll('#aecDropdown input[type="checkbox"]');
 <div class="row d-flex justify-content-center align-items-start">
        <div class="col-sm-7">
            <div class="cr_filter" id="filter1">
                <div class="card text-s cr-card-filter" data-id="large">
                    <div class="card-header p-0" id="large_category_h01">
                        <button class="btn text-s d-flex arrow-down arrow-bl justify-content-between align-items-center w-100 collapsed" type="button" 
                            data-toggle="collapse" data-target="#large_category" 
                            aria-expanded="false" aria-controls="large_category" id="btn-large">
                            <span>IC Manufacturer</span>
                        </button>
                    </div>
                    <div class="collapse" id="large_category" aria-labelledby="large_category_h01">
                        <div class="card-body d-flex flex-column">
                            <ul id="manufacturerDropdown" class="list-unstyled">
                                {% for ic_manufacturer in ic_manufacturer_arr %}
                                    <li>
                                        <label>
                                            <input 
                                                class="kc_checkbox" 
                                                type="checkbox"
                                                id="manufacturer_{{ loop.index }}" 
                                                value="{{ ic_manufacturer }}" 
                                                data-column="manufacturer">
                                            <span class="kc_checkbox_parts d-flex align-items-center">
                                                {{ ic_manufacturer }}
                                            </span>
                                        </label>
                                    </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row d-flex justify-content-center align-items-start">
        <div class="col-sm-7">
            <div class="cr_filter" id="filter2">
                <div class="card text-s cr-card-filter" data-id="large">
                    <div class="card-header p-0" id="large_category_h02">
                        <button class="btn text-s d-flex arrow-down arrow-bl justify-content-between align-items-center w-100 collapsed" type="button" 
                            data-toggle="collapse" data-target="#family_category" 
                            aria-expanded="false" aria-controls="family_category" id="btn-family">
                            <span>IC Family</span>
                        </button>
                    </div>
                    <div class="collapse" id="family_category" aria-labelledby="large_category_h02">
                        <div class="card-body d-flex flex-column">
                            <ul id="familyDropdown" class="list-unstyled">
                                {% for ic_family in ic_family_arr %}
                                    <li>
                                        <label>
                                            <input 
                                                class="kc_checkbox" 
                                                type="checkbox" 
                                                id="family_{{ loop.index }}" 
                                                value="{{ ic_family['ic_family'] }}" 
                                                data-column="family" 
                                                data-manufacturer="{{ ic_family['ic_manufacturer'] }}">
                                            <span class="kc_checkbox_parts d-flex align-items-center">
                                                {{ ic_family['ic_family'] }}
                                            </span>
                                        </label>
                                    </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row d-flex justify-content-center align-items-start">
        <div class="col-sm-5">
            <div class="cr_filter">
                <div class="before_search_icon position-relative">
                    <input class="cr_filter_txt" type="text" id="searchInput" autocomplete="off" placeholder="Enter IC part number">
                    {# <div class="suggestionsList" id="suggestionsList"></div> #}
                </div>
            </div>
        </div>
        <div class="col-sm-2 h-100">
            <div class="submit_container">
                <input type="submit" name="submit_search" id="submit-search" value="Search" class="input-submit w-100">
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-sm-4">
          <div class="cr_filter" id="filter3">
                <div class="card text-s cr-card-filter" data-id="large">
                    <div class="card-header p-0" id="large_category_h03">
                        <button class="btn text-s d-flex arrow-down arrow-bl justify-content-between align-items-center w-100 collapsed" type="button"
                                data-toggle="collapse" data-target="#crystal_part_num_category"
                                aria-expanded="false" aria-controls="crystal_part_num_category" id="btn-crystal-part-num">
                            <span>Crystal Device Part Number</span>
                        </button>
                    </div>
                    <div class="collapse" id="crystal_part_num_category" aria-labelledby="large_category_h03">
                        <div class="card-body d-flex flex-column">
                            <ul id="crypartnumDropdown" class="list-unstyled">
                                {% for cry_part_num in cry_part_num_arr_no_duplicate %}
                                <li>
                                    <label>
                                        <input 
                                            class="kc_checkbox" 
                                            type="checkbox" 
                                            id="crystal_part_num_{{ loop.index }}" 
                                            value="{{ cry_part_num.field_cry_part_num }}" 
                                            data-column="crystal_part_num" 
                                            data-family="{{ cry_part_num.ic_family }}" 
                                            data-manufacturer="{{ cry_part_num.ic_manufacturer }}">
                                        <span class="kc_checkbox_parts d-flex align-items-center">
                                            {{ cry_part_num.field_cry_part_num }}
                                        </span>
                                    </label>
                                </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-4">
          <div class="cr_filter" id="filter4">
                <div class="card text-s cr-card-filter" data-id="large">
                    <div class="card-header p-0" id="large_category_h04">
                        <button class="btn text-s d-flex arrow-down arrow-bl justify-content-between align-items-center w-100 collapsed" type="button"
                                data-toggle="collapse" data-target="#dimentions_category"
                                aria-expanded="false" aria-controls="dimentions_category" id="btn-dimentions">
                            <span>Dimensions (L×W)</span>
                        </button>
                    </div>
                    <div class="collapse" id="dimentions_category" aria-labelledby="large_category_h04">
                        <div class="card-body d-flex flex-column">
                            <ul id="dimensionsDropdown" class="list-unstyled">
                                {% for cry_dimensions in cry_dimensions_arr_no_duplicate %}
                                <li>
                                    <label>
                                        <input 
                                            class="kc_checkbox" 
                                            type="checkbox" 
                                            id="cry_dimensions_{{ loop.index }}" 
                                            value="{{ cry_dimensions.field_cry_dimensions }}" 
                                            data-column="dimensions" 
                                            data-family="{{ cry_dimensions.ic_family }}" 
                                            data-manufacturer="{{ cry_dimensions.ic_manufacturer }}">
                                        <span class="kc_checkbox_parts d-flex align-items-center">
                                            {{ cry_dimensions.field_cry_dimensions }}
                                        </span>
                                    </label>
                                </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-4">
          <div class="cr_filter" id="filter4">
                <div class="card text-s cr-card-filter" data-id="large">
                    <div class="card-header p-0" id="large_category_h05">
                        <button class="btn text-s d-flex arrow-down arrow-bl justify-content-between align-items-center w-100 collapsed" type="button"
                                data-toggle="collapse" data-target="#frequency_category"
                                aria-expanded="false" aria-controls="frequency_category" id="btn-frequency">
                            <span>Frequency (kHz)</span>
                        </button>
                    </div>
                    <div class="collapse" id="frequency_category" aria-labelledby="large_category_h05">
                        <div class="card-body d-flex flex-column">
                            <ul id="frequencyDropdown" class="list-unstyled">
                                {% for cry_freq_khz in cry_freq_khz_arr_no_duplicate %}
                                <li>
                                    <label>
                                        <input 
                                            class="kc_checkbox" 
                                            type="checkbox" 
                                            id="cry_freq_khz_{{ loop.index }}" 
                                            value="{{ cry_freq_khz.field_cry_freq_khz }}" 
                                            data-column="frequency" 
                                            data-family="{{ cry_freq_khz.ic_family }}" 
                                            data-manufacturer="{{ cry_freq_khz.ic_manufacturer }}">
                                        <span class="kc_checkbox_parts d-flex align-items-center">
                                            {{ cry_freq_khz.field_cry_freq_khz }}
                                        </span>
                                    </label>
                                </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-4">
          <div class="cr_filter" id="filter4">
                <div class="card text-s cr-card-filter" data-id="large">
                    <div class="card-header p-0" id="large_category_h06">
                        <button class="btn text-s d-flex arrow-down arrow-bl justify-content-between align-items-center w-100 collapsed" type="button"
                                data-toggle="collapse" data-target="#load_capacitance_category"
                                aria-expanded="false" aria-controls="load_capacitance_category" id="btn-load_capacitance">
                            <span>Load Capacitance</span>
                        </button>
                    </div>
                    <div class="collapse" id="load_capacitance_category" aria-labelledby="large_category_h06">
                        <div class="card-body d-flex flex-column">
                            <ul id="load_capacitanceDropdown" class="list-unstyled">
                                {% for cry_load_capacitance in cry_load_capacitance_arr_no_duplicate %}
                                <li>
                                    <label>
                                        <input 
                                            class="kc_checkbox" 
                                            type="checkbox" 
                                            id="cry_load_capacitance_{{ loop.index }}" 
                                            value="{{ cry_load_capacitance.field_cry_load_capacitance }}" 
                                            data-column="load_capacitance" 
                                            data-family="{{ cry_load_capacitance.ic_family }}" 
                                            data-manufacturer="{{ cry_load_capacitance.ic_manufacturer }}">
                                        <span class="kc_checkbox_parts d-flex align-items-center">
                                            {{ cry_load_capacitance.field_cry_load_capacitance }}
                                        </span>
                                    </label>
                                </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-4">
          <div class="cr_filter" id="filter4">
                <div class="card text-s cr-card-filter" data-id="large">
                    <div class="card-header p-0" id="large_category_h07">
                        <button class="btn text-s d-flex arrow-down arrow-bl justify-content-between align-items-center w-100 collapsed" type="button"
                                data-toggle="collapse" data-target="#AEC_Q_category"
                                aria-expanded="false" aria-controls="AEC_Q_category" id="btn-AEC_Q">
                            <span>AEC-Q</span>
                        </button>
                    </div>
                    <div class="collapse" id="AEC_Q_category" aria-labelledby="large_category_h07">
                        <div class="card-body d-flex flex-column">
                            <ul id="aecDropdown" class="list-unstyled">
                                {% for cry_aec in cry_aec_arr_no_duplicate %}
                                <li>
                                    <label>
                                        <input 
                                            class="kc_checkbox" 
                                            type="checkbox" 
                                            id="cry_aec_{{ loop.index }}" 
                                            value="{{ cry_aec.field_cry_aec }}" 
                                            data-column="aec" 
                                            data-family="{{ cry_aec.ic_family }}" 
                                            data-manufacturer="{{ cry_aec.ic_manufacturer }}">
                                        <span class="kc_checkbox_parts d-flex align-items-center">
                                            {{ cry_aec.field_cry_aec }}
                                        </span>
                                    </label>
                                </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div> 
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <div class="table-container"></div>
        </div>
    </div>
</div>

what im trying to get is

every checkboxes i click it will show the related checkboxes and hide those checkbox that are not related..

i will give example scenario..

if i check/click russia from manufacturer, it show russia with checkmark and hide USA and china also it will show “animals and human” because they are related to russia and hide “fruits and place” in family dropdown… same goes to other dropdown buttons.

if i check/click animals from family it show animals with checkmark and hide other families
also it will show russia since russia is related to animals hide the others manufacturer.. same goes to other checkboxes.

aslong as there are checkmark in any of the dropdown button it will only show the related checkboxes.. also if there are no checkmarked in any of dropdown button it will show all checkboxes..

My website is very slow and waiting for server response (fast with translatepress)

I have a wordpress website that users can send message to each other.

When a user clicks “Send Message” button, waits too much and takes very long to send message.

But there is very interesting thing, I use TranslatePress plugin to translate website, in default language this function is very slow, but if a user clicks this button in translated languages, it is fast. I don’t know why.

Please check the server response times with default language and translated language with translatepress.

In default language without translatepress:

enter image description here

In translated language:

enter image description here

How can I solve this situation and make this function in default language too?

I am tying to learn front and in this code, I am trying to call data from basehub cms and show it on a carousel

Here is the code i am trying. I think the problem is I am calling a both server component and a client component on the same file. But i don’t know how solve for that.

I have tried to break the slide items as a separate component but then the carousel doesn’t work. it only renders the first item only.

Any advice is appreciated.

    const Projects = async () => {
    return (
        <Pump
            queries={[
                {
                    __typename: true,
                    projects: {
                        items: {
                            _title: true,
                            descriptions: {
                                plainText: true,
                            },
                            projectImage: { url: true, width: true, height: true, alt: true },
                        },
                    },
                },
            ]}
        >
            {async ([data]) => {
                'use server';

                if (!data.projects.items.length) {
                    return <div>No projects found</div>;
                }

                const projectPosts = data.projects.items;

                // <>{JSON.stringify(data, null, 2)}</>

                return (
                    <section className='flex flex-col h-screen min-h-[400px]'>
                        <InnerNav />
                        <Swiper className='grow relative flex flex-row  swiper'>
                            <div className='flex flex-row h-full'>
                                {projectPosts.map((projects, index) => (
                                    <div
                                        className='h-full flex-grow flex flex-row swiper-slide '
                                        key={index}
                                    >
                                        <div className='flex-grow w-full bg-slate-100 p-4 flex items-center justify-center'>
                                            {/* <Image src={proimage} alt='' width={100} height={100} /> */}
                                            <img
                                                src={projects.projectImage?.url as string}
                                                alt={projects.projectImage?.alt as string}
                                                width='auto'
                                                height='100%'
                                            />
                                        </div>
                                        <div className='p-6 w-[500px] relative flex flex-col justify-start pb-8 gap-4'>
                                            <h2 className='text-2xl font-bold'>{projects._title}</h2>
                                            <p>{projects.descriptions?.plainText}</p>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </Swiper>
                    </section>
                );
            }}
        </Pump>
    );
};

I am trying to show a list of projects in a carousel and for carousel i am using the swiper (swiperjs.com). Again my guess is basehub and swiper are not playing well with each other.

How to format phone number in Japanese format with Vue2 and v-mask

I have a text box in Vue 2 application and I am using the v-mask library to format phone numbers as the user types them.

The problem

I want them to be formatted as per Japanese phone number format which is like this: (+81) ### #### ####

After the country code (+81), the first part of the phone is the area code. This code can be from 1 to 3 digits long. So, when the user types in the number, the program should assume that the area code is 1-digit long as per the available information. When the user exhausts the allowed number of digits in a single-digit area code phone number, the program should take additional digit and rearrange the spaces in such a way that it will become a phone number of 2 digits long area code. Similarly, on addition of another digit by the user, it should rearrange again as per 3-digit area code phone number.

What I have tried yet

  1. I have tried giving it the optional value ? character like (+81) #?#?# #### #### but it adds unwanted spaces after the first digit and does not consider it as we want it. Sample here: https://codesandbox.io/p/sandbox/v-mask-demo-forked-7r6rd4 (this sandbox can be run to test and forked to edit and debug).
  2. I have tried giving the v-mask as a method which changes the mask string as per the length of the user input, but there is a known-issue in the v-mask library which keeps emitting values when a function (or computed property) is given to it. The issue is logged here: https://github.com/probil/v-mask/issues/511

References

I have referred the official documentation of v-mask at https://www.npmjs.com/package/v-mask to build my masking logic.

NodeJS – Connecting auth backend to frontend

I’m trying to connect my backend for logging in and signing up to the frontend and this is my implenetation of the auth backend:

const jwt = require("jsonwebtoken");
const User = require("../models/userModel");
const catchAsync = require("../utils/catchAsync");
const { promisify } = require("util");

const signToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });
};

const createSendToken = (user, statusCode, res, req) => {
  const token = signToken(user._id);

  res.cookie("jwt", token, {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    secure: true,
    httpOnly: true,
  });

  //Remove password from output
  user.password = undefined;

  res.status(statusCode).json({
    status: "success",
    token,
    data: {
      user,
    },
  });
};

exports.register = catchAsync(async (req, res) => {
  const { name, email, password, passwordConfirm, role } = req.body;

  const newUser = await User.create({
    name,
    email,
    password,
    passwordConfirm,
    role,
  });

  createSendToken(newUser, 201, res, req);
});

exports.logIn = catchAsync(async (req, res, next) => {
  const { email, password } = req.body;

  // 1) Check if email and password exist
  if (!email || !password) {
    return res
      .status(400)
      .json({ status: "fail", message: "Please provide email and password!" });
  }
  // 2) Check if the user exists and if the password is correct
  const user = await User.findOne({ email }).select("+password");

  if (!user || !(await user.checkPassword(password, user.password))) {
    return res
      .status(401)
      .json({ status: "fail", message: "Incorrect email or password!" });
  }

  // 3) If everythin is ok, send token to the client
  createSendToken(user, 200, res, req);
});

exports.protect = catchAsync(async (req, res, next) => {
  // 1) Get the token and check if it exists
  let token;
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    token = req.headers.authorization.split(" ")[1];
  }

  if (!token) {
    return res.status(401).json({
      status: "fail",
      message: "You are not logged in! Please log in to get access.",
    });
  }
  // 2) Validate token
  let decoded;
  try {
    decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
  } catch (err) {
    if (err.name === "JsonWebTokenError")
      return res.status(401).json({
        status: "fail",
        message: "Invalid token. Please log in again!",
      });
    if (err.name === "TokenExpiredError")
      return res.status(401).json({
        status: "fail",
        message: "Your token has expired. Please log in again!",
      });
  }

  // 3) Check if user still exists
  const currentUser = await User.findById(decoded.id);
  if (!currentUser) {
    return res.status(401).json({
      status: "fail",
      message: "The user belonging to this token no longer exists.",
    });
  }

  // 4) Check if user changed password after the token was issued
  if (currentUser.changedPasswordAfter(decoded.iat)) {
    return res.status(401).json({
      status: "fail",
      message: "User recently changed password! Please log in again.",
    });
  }

  // Everything is passed, go to the protected route.
  req.user = currentUser;
  next();
});

exports.restrictTo = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        status: "fail",
        message: "You do not have permission to perform this action",
      });
    }

    next();
  };
};

Which just sends JSON data when i post to that in the frontend

Now when i added req.session.user = { id: user.id, name: user.name, email: user.email };
To createSendToken the req.session.user was always undefined what fixed it was just removing createSendToken and just doing res.redirect while storing to req.session.user but I Feel like thats not how i should be implementing it because thats logging me in without even saving a cookie can anyone tell me how to implement it or send me a tutorial/guide? im using EJS for the front