FFMPEG Command to convert images to svg

Users are trying to convert images to SVG image on my website, Below I’ve given a link to the site, more detail on error and code that handles the conversion of media files.

You can check out the live site Here.

Steps to reproduce the error.

  1. Upload the png file,
  2. Select SVG as output file
  3. Click convert.

It is throwing error.

Below is the code for that converts users input and gives input based on user preference.

// imports

import { createCanvas, loadImage } from "canvas";

import { Action } from "@/types";
import { FFmpeg } from "@ffmpeg/ffmpeg";
import { fetchFile } from "@ffmpeg/util";

function getFileExtension(file_name: string) {
  const regex = /(?:.([^.]+))?$/; // Matches the last dot and everything after it
  const match = regex.exec(file_name);
  if (match && match[1]) {
    return match[1];
  }
  return ""; // No file extension found
}

function removeFileExtension(file_name: string) {
  const lastDotIndex = file_name.lastIndexOf(".");
  if (lastDotIndex !== -1) {
    return file_name.slice(0, lastDotIndex);
  }
  return file_name; // No file extension found
}

export default async function convert(
  ffmpeg: FFmpeg,
  action: Action
): Promise<any> {
  const { file, to, file_name, file_type } = action;
  const input = getFileExtension(file_name);
  const output = removeFileExtension(file_name) + "." + to;
  ffmpeg.writeFile(input, await fetchFile(file));

  // FFMPEG COMMANDS
  let ffmpeg_cmd: any = [];

  if (to === "svg") {
    ffmpeg_cmd = [
      "-i",
      input,
      "-vf",
      "scale=trunc(iw/2)*2:trunc(ih/2)*2",
      "-c:v",
      "libvpx-vp9",
      "-crf",
      "30",
      "-b:v",
      "1M",
      "-c:a",
      "libopus",
      "-b:a",
      "128k",
      output,
    ];
  } else if (to === "3gp") {
    ffmpeg_cmd = [
      "-i",
      input,
      "-r",
      "20",
      "-s",
      "352x288",
      "-vb",
      "400k",
      "-acodec",
      "aac",
      "-strict",
      "experimental",
      "-ac",
      "1",
      "-ar",
      "8000",
      "-ab",
      "24k",
      output,
    ];
  } else {
    ffmpeg_cmd = ["-i", input, output];
  }

  // execute cmd
  await ffmpeg.exec(ffmpeg_cmd);

  const data = (await ffmpeg.readFile(output)) as any;
  const blob = new Blob([data], { type: file_type.split("/")[0] });
  const url = URL.createObjectURL(blob);
  return { url, output };
}

Help appreciated, Thank You

Error: Objects are not valid as a React child (found: [object Promise]). in MDX remote

I’m trying to use next.js to get all of the blogs on a mongodb backend, and converting all of the blog strings stored in blog.mdx into an array of objects wrapped in

  • wrappers. However, the code below gives me the error that:
    Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    I’m not really sure what’s the fix to this. I’ve followed this stackoverflow question for help but it hasn’t fixed my issue

    import Head from "next/head";
    import clientPromise from "../lib/mongodb";
    import type { InferGetServerSidePropsType, GetServerSideProps } from "next";
    import {useEffect, useState} from "react";
    import {MDXRemote} from "next-mdx-remote/rsc";
    import { serialize } from 'next-mdx-remote/serialize'
    import React from "react";
    
    type ConnectionStatus = {
        isConnected: boolean;
    };
    
    export const getServerSideProps: GetServerSideProps<
        ConnectionStatus
    > = async () => {
        try {
            await clientPromise;
            // `await clientPromise` will use the default database passed in the MONGODB_URI
            // However you can use another database (e.g. myDatabase) by replacing the `await clientPromise` with the following code:
            //
            // `const client = await clientPromise`
            // `const db = client.db("myDatabase")`
            //
            // Then you can execute queries against your database like so:
            // db.find({}) or any of the MongoDB Node Driver commands
    
            return {
                props: { isConnected: true },
            };
        } catch (e) {
            console.error(e);
            return {
                props: { isConnected: false },
            };
        }
    };
    
    const Home = ({ isConnected }: InferGetServerSidePropsType<typeof getServerSideProps>) => {
        const [blogs, setBlogs] = useState([]);
        useEffect(() => {
            async function fetchAllBlogs() {
                const response = await fetch("http://localhost:3000/api/getAllBlogs");
                const blogs = await response.json();
                const blogMDX = await Promise.all(blogs.map(async (blog) => (
                    <li key={blog._id}>
                        <MDXRemote {...(await serialize(blog.mdx))} />
                    </li>
                )))
                console.log("blogs ", blogs);
                console.log("blogsMDX ", blogMDX);
                setBlogs(blogMDX);
            }
            fetchAllBlogs();
        }, []);
    
    
        return (
            <div className="container">
                <Head>
                    <title>Create Next App</title>
                    <link rel="icon" href="/favicon.ico"/>
                </Head>
    
                <main>
                    <div>
                        {isConnected ? (
                            <h2 className="subtitle">You are connected to MongoDB</h2>
                        ) : (
                            <h2 className="subtitle">
                                You are NOT connected to MongoDB. Check the <code>README.md</code>{" "}
                                for instructions.
                            </h2>
                        )}
                    </div>
                    <div>
                        {
                            blogs == null ? (
                                <div></div>
                            ) :(
                                blogs.length > 0 ? (
                                    <ul>
                                        {blogs}
                                    </ul>
                                ) : (
                                    <p>Loading...</p>
                                )
                            )
                        }
                    </div>
                    <div>
    
                    </div>
                </main>
    
    
            </div>
        );
    }
    
    export default Home;
    

    I’ve tried converting my

    
    <ul>
        {blogs}
    </ul>
    

    to

    blogs.map( (blog:any, index) => (
                                        <React.Fragment key={index}>
                                            {blog}
                                        </React.Fragment>
                                    ))
    ```,
    but while this gets rid of the error, the MDXRemote no longer shows up.
    
    The console.logs print out this:
    
    

    blogs
    Array [ {…} ]

    0: Object { _id: “66358b465fb668714ea217b3”, mdx: “—ntitle: Example Postnpublished: 2021-02-13ndescription: This is some descriptionn—nnnnHere’s a neat demon:” }

    length: 1

    : Array []
    index.tsx:50:20
    blogsMDX
    Array [ {…} ]

    0: Object { “$$typeof”: Symbol(“react.element”), type: “li”, key: “66358b465fb668714ea217b3”, … }

    length: 1

    : Array []

  • Get “prompt()” input from a web worker and return it from function?

    I’m working with the pyodide library and i’ve ran into an issue, I need to add a handler for stdin, however I’m running pyodide in a web worker and I don’t have access to the window or any sort of prompt.

    pyodide.setStdin({ stdin: () => { 
        // code here
    }})
    

    I have tried using the postMessage() function to ask the page for input and send it back, but since I am returning this from a function I am unable to receive the input before I have to return. I have also tried using SharedArrayBuffer and Atomics to freeze the web worker until the page responds, but I was unable to figure out a solution with those, however I think it’s a good starting point. Most solutions I’ve seen so far have just been to restructure code, but since pyodide is an external library I am forced to return from the function I set in pyodide.setStdin

    How do I create a ticket with multiple attachment using freshservice api?

    exports.app = onRequest({cors: true}, (req, res) => {
      const form = formidable({ multiples: true, maxFileSize: 15 * 1024 * 1024 });
      form.parse(req, (err, fields, files) => {
        if (err) {
          logger.error(err);
          res.status(500).send({ error: 'Failed to parse form' });
        } else {      
          const dataSourceString = fields['dataSource[]'];
          var dataSourceList = JSON.parse(dataSourceString);
          
          const fileList = files['attachment[]'];
          
          fileList.forEach((file, index) => {
            // Modify filename as needed
            const parts = file.name.split('.');
            const name = parts[0]; // Filename without extension
            const extension = parts.slice(1).join('.'); // File extension
    
            var fileName = dataSourceList[index].docType;
            fileName = fileName.replace(///g, " ");
            file.name = `${fileName}.${extension}`;
         });
    
          const ticketData = {
                subject: 'Test',
                description: fields.description,
                priority: 1,
                status: 2,
                email: fields.email,
            };
          
            function formatDate(date) {
              return new Date(date).toISOString();
          }
    
          const formData = new FormData();
    
          formData.append('subject', ticketData.subject);
          formData.append('description', ticketData.description);
          formData.append('priority', ticketData.priority);
          formData.append('status', ticketData.status);
          formData.append('email', ticketData.email);
    
    
          fileList.forEach((file) => {
            const stream = fs.createReadStream(file.path);
            const blob = new Blob([stream], { type: file.type });
        
            formData.append('attachments[]', blob, {
                filename: file.name,
                contentType: file.type,
            });
        });
    
          const configData = {
            method: 'post',
            url: config.fsURL + '/api/v2/tickets',
            headers: {
              'Authorization': 'Basic ' + Buffer.from(config.fsAPIKey + ':x').toString('base64'),
              'Content-Type': 'multipart/form-data'
            },
            data : formData
          };
    
          axios(configData)
            .then(function (response) {
                console.log(response.data);
                res.status(200).json(response.data);
            })
            .catch(function (error) {
                console.log('Error:', error.toJSON());
            });
        }
      });
    });
    

    I have code as above and it seems to work fine for all fields. However there seems to be some problem when I try to upload multiple attachments. It doesn’t seem to be inserting files correctly as I am getting attachments as [[Object], [Object]] when return after create ticket.

    Details can be shown as below. Anyone have any idea how this can be done?

    enter image description here

    Javascript emulate CSS snap scroll with pointer-events

    I have the following code which can swipe child element left and right. This works well.

    Is there a way I could implement snap effect with this somehow with pointermove? So it behaves like CSS snap scroll (you drag slightly and you can see next / previous item entering, before swipe actually happens).

    I dont want to use CSS snap scroll because I cannot detect scrollend event (on Safari for start) so I cannot detect on which child I am currenty (I need this so I can show / hide previous / next buttons, numbering etc)

    var wrap = document.querySelector('.wrap'),
      touchstartX,
      touchendX
    
    
    wrap.addEventListener('pointerdown', startHorizSwipeDirection);
    document.addEventListener('pointerup', endHorizSwipeDirection);
    
    function startHorizSwipeDirection(e) {
      touchstartX = e.clientX;
    }
    
    function endHorizSwipeDirection(e) {
      touchendX = e.clientX;
      checkHorizSwipeDirection()
    }
    
    function checkHorizSwipeDirection() {
    
      if (touchendX < touchstartX - 100) {
        //left
        nextHorizMedia();
      }
      if (touchendX > touchstartX + 100) {
        //right
        previousHorizMedia();
      }
    }
    
    function nextHorizMedia() {
    
      var active_id = parseInt(wrap.getAttribute('data-active-id'), 10),
        len = wrap.querySelectorAll('.child').length
    
      if (active_id >= len - 1) {
        console.log('end')
        return false;
      }
    
      var width = wrap.querySelector('.child').offsetWidth
    
      var transform = wrap.style.transform.replace(/[^-?d.]/g, '')
      var value
      if (transform) value = parseInt(transform, 10)
      else value = 0;
    
      value -= width;
      active_id++;
    
      wrap.setAttribute('data-active-id', active_id)
    
      wrap.style.transform = "translateX(" + value + "px)";
    
    
    
    }
    
    function previousHorizMedia() {
    
      var active_id = parseInt(wrap.getAttribute('data-active-id'), 10),
        len = wrap.querySelectorAll('.child').length
     
      if (active_id <= 0) {
        return false;
      }
    
      var width = wrap.querySelector('.child').offsetWidth
    
      var transform = wrap.style.transform.replace(/[^-?d.]/g, '')
      var value
      if (transform) value = parseInt(transform, 10)
      else value = 0;
    
      value += width;
      active_id--;
    
      wrap.setAttribute('data-active-id', active_id)
    
      wrap.style.transform = "translateX(" + value + "px)";
    
    
    }
    .parent {
      width: 300px;
      height: 100px;
      overflow: hidden;
    }
    
    .wrap {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      transition: transform 0.3s;
    }
    
    .child {
      width: 300px;
      height: 100px;
      font-size: 30px;
      color: #fff;
      background: #ccc;
      flex-shrink: 0;
      text-align: center;
      user-select: none;
    }
    
    .child[data-id="0"] {
      background: red;
    }
    
    .child[data-id="1"] {
      background: blue;
    }
    
    .child[data-id="2"] {
      background: green;
    }
    
    .child[data-id="3"] {
      background: #ccc;
    }
    <div class="parent">
      <div class="wrap" data-active-id="0">
        <div class="child" data-id="0">0</div>
        <div class="child" data-id="1">1</div>
        <div class="child" data-id="2">2</div>
        <div class="child" data-id="3">3</div>
      </div>
    </div>

    How to edit and update on React JS?

    So i have UserList.jsx component which displays the all user data in a table. enter image description here When i click on edit button it goes to http://localhost:3000/user/id. I have created a form in there to update the user details. The problem is the form is not displaying the specific user data from id. How do i do that? And how to update as well? My UserList.jsx goes like this

    import "./userList.css";
    import { DataGrid } from '@mui/x-data-grid';
    import {DeleteOutline, Block} from '@mui/icons-material';
    // import { userRows, trainerRows } from "../../../dummyData";
    import { Link } from 'react-router-dom';
    import { useState, useEffect } from "react";
    
    
    export default function UserList() {
        const [data, setData] = useState([]);
        const [selectedRole, setSelectedRole] = useState('');
        const [filteredData, setFilteredData] = useState([]);
        // const [sessionID, setSessionID] = useState('');
    
        useEffect(() => {
          // Login as admin to get session ID
          fetch('http://localhost:3001/login', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                  email: '[email protected]',
                  password: 'password123',
              }),
          })
          .then(response => response.json())
          .then(data => {
              // Store the session ID in localStorage
              localStorage.setItem('sessionID', data.session);
              // Filter the data based on user_type
              
              
              // Fetch initial user data
              // const url = selectedRole === 'All_User'
              //     ? 'http://localhost:3001/register_detail/recieve'
              //     : 'http://localhost:3001/register_detail/recieve';
              // Function to get the stored session ID
              const sessionId = localStorage.getItem('sessionID');
              
              console.log(sessionId);
              
              fetch('http://localhost:3001/profile/allusers', {
                  method: 'GET',
                  headers: {
                    'session': `${sessionId}`,
                  },
              })
              .then(response => response.json())
              .then(data => {
                
                  // Ensure data is an array of objects
                  if (Array.isArray(data)) {
                      setData(data);
                      setFilteredData(data);
                  } else {
                      console.error('Received data is not an array:', data);
                  }
              })
              .catch(error => console.error('Error fetching users:', error));
                
          })
          .catch(error => console.error('Error logging in:', error));
      }, []);
      
    
     
    
        const handleDelete = (id) => {
            setData(data.filter(item=>item.id!==id))
        }
        const handleRoleChange = (event) => {
          console.log(event.target.value);
          setSelectedRole(event.target.value);
          filterData(event.target.value);
        };
    
        const filterData = (role) => {
          let filtered = [];
          if (role === 'All_User') {
              filtered = data;
              
          } else {
            // data.filter(item => item.user_type === 'trainer'
              filtered = data.filter(item => item.user_type.toLowerCase() === role.toLowerCase());
              console.log(filtered); //gives data according to filterd event
          }
          setFilteredData(filtered);
      };
      
        
        
        const columns = [
          
            { field: 'user_id', headerName: 'User_ID', width: 70 },
            { field: 'first_name', headerName: 'First Name', width: 150,
                // renderCell: (params) => {
                //     return (
                //         <div className="userListUser">
                //             <img className="userListImage" src={params.row.profile_image} alt="Profile" srcset="" />
                //             {params.row.username}
                //         </div>
                //     )
                // }
            },
            { field: 'last_name', headerName: 'Last Name', width: 150 },
            // {
            //   field: 'email',
            //   headerName: 'Email',
            //   width: 200,
            // },
            // {
            //   field: 'user_type',
            //   headerName: 'User Type',
            //   width: 150,
    
            // },
            { field: 'contact', headerName: 'Contact', width: 150 },
            { field: 'address', headerName: 'Address', width: 150 },
            {
                field:'action',
                headerName:'Action',
                width:150,
                renderCell: (params) => {
                    return (
                        <div className="userListAction">
                            <Link to = {"/user/" + params.row.user_id}>
                              
                                <button className="userListEdit">Edit</button>
                            </Link>
                            
                            <DeleteOutline className="userListDelete" onClick={() => handleDelete(params.row.id)}/>
                            <Block className="userListBlock"/>
                        </div>
                        
                    )
                }
            },
          ];
         
        return (
       
        <div className="userList">
           <div className="userDropdown">
            <select className= "userDropdownicon" value={selectedRole} onChange={handleRoleChange}>
              <option value="All_User">All User</option>
              <option value="Trainer">Trainer</option>
              <option value="Customer">Customer</option>
            </select>
          </div>
            <DataGrid
            rows={filteredData} // Use filteredData instead of data
            columns={columns}
            getRowId={(row) => row.user_id}
            initialState={{
              pagination: {
                paginationModel: { page: 0, pageSize: 8 },
              },
            }}
            pageSizeOptions={[5, 10]}
            checkboxSelection
            disableRowSelectionOnClick
          />
        </div>
      )
    }
    
    

    and my User.jsx goes like this

    import "./user.css";
    // import axios from 'axios';
    import { Link, useParams } from 'react-router-dom';
    import { useEffect, useState } from 'react';
    import {CalendarToday, LocationSearching, MailLockOutlined, PermIdentity, PhoneAndroid, Publish} from '@mui/icons-material';
    export default function User() {
        const {userId} = useParams();
        console.log(userId);
      useEffect(() => {
        fetch('http://localhost:3001/profile/allusers/' +userId)
        .then(res => res.json()) // Convert the response to JSON
        .then(data=> console.log(data)) //Log the data
        .catch(err=>console.log(err));
      }, [userId]);  
      return (
        <div className="user">
            <div className="userTitleContainer">
                <h1 className="userTitle">Edit User</h1>
                <Link to="/newUser">
                    <button className="userAddButton">Create</button>
                </Link>
                
            </div>
            <div className="userContainer">
                <div className="userShow">
                    <div className="userShowTop">
                        <img src={process.env.PUBLIC_URL + "/images/admin.jpeg"} alt="" className="userShowImg" />
                        <div className="userShowTopTitle">
                            <span className="userShowUsername">Robert Kiyosaki</span>
                            <span className="userShowUserTitle">Investor</span>
                        </div>
                    </div>
                    <div className="userShowBottom">
                        <span className="userShowTitle">Account Details</span>
                        <div className="userShowInfo">
                            <PermIdentity className="userShowIcon"/>
                            <span className="userShowInfoTitle">robert99</span>
                        </div>
                        <div className="userShowInfo">
                            <CalendarToday className="userShowIcon"/>
                            <span className="userShowInfoTitle">02.01.1998</span>
                        </div>
                        <span className="userShowTitle">Contact Details</span>
                        <div className="userShowInfo">
                            <PhoneAndroid className="userShowIcon"/>
                            <span className="userShowInfoTitle">0406687956</span>
                        </div>
                        <div className="userShowInfo">
                            <MailLockOutlined className="userShowIcon"/>
                            <span className="userShowInfoTitle">[email protected]</span>
                        </div>
                        <div className="userShowInfo">
                            <LocationSearching className="userShowIcon"/>
                            <span className="userShowInfoTitle">Keswick, Adelaide</span>
                        </div>
                        
                    </div>
                </div>
                <div className="userUpdate">
                    <span className="userUpdateTitle">Edit</span>
                    <form action="" className="userUpdateForm">
                        <div className="userUpdateLeft">
                            <div className="userUpdateItem">
                                <label>First Name</label>
                                <input type="text" placeholder="robert99" className="userUpdateInput" />
                            </div>
                            <div className="userUpdateItem">
                                <label>Last Name</label>
                                <input type="text" placeholder="Robert Kiyosaki" className="userUpdateInput" />
                            </div>
                            <div className="userUpdateItem">
                                <label>Email</label>
                                <input type="text" placeholder="[email protected]" className="userUpdateInput" />
                            </div>
                            <div className="userUpdateItem">
                                <label>Phone</label>
                                <input type="text" placeholder="0406687956" className="userUpdateInput" />
                            </div>
                            <div className="userUpdateItem">
                                <label>Address</label>
                                <input type="text" placeholder="Keswick, Adelaide" className="userUpdateInput" />
                            </div>
                        </div>
                        <div className="userUpdateRight">
                            <div className="userUpdateUpload">
                                <img src={process.env.PUBLIC_URL + "/images/admin.jpeg"} alt="userimg" className="userUpdateImg" />
                                {/* htmlFor Associates this label with an input element using the 'htmlFor' attribute */}
                                <label htmlFor="file"><Publish className="userUpdateIcon"/></label>
                                <input type="file" name="" id="file" style={{display:"none"}} />
                            </div>
                            <button className="userUpdateButton">Update</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
      )
    }
    
    

    The logic i was trying to use is to append the userId at the endpoint of an API /profile/allusers. But it didn’t gave me any data

    Navbar collapse using javascript

    I have created a navbar with HTML and selected all of the headers, saving them in a navEl object. After that, I created a function called showNav. This function takes one of the navEl properties as its parameter and shows the content of that navEl element to the user. It also hides it when the user removes their mouse from it.

    The problem I am facing is with the last event listener of the function. When I added a mouseleave to the item, it works perfectly when I hover over it the first time. However, the moment I change my navEl to another one, when one is already showing, it stays for 100ms and then disappears again.

    I have tried modifying the code slightly and put a clearTimeout function on the item when I am changing the navEl. But the problem, I think, was that my navEl properties and the content are not nested within each other or separated.

    Is there any way I could fix this?

    HTML code

    <header class="navbar navbar-expand-lg d-lg-block d-none ">
                <div class="container-fluid">
                    <ul class="navbar-nav me-auto mb-2 mb-lg-0 d-flex flex-wrap">
                        <li class="nav-item nav-item-1" id="photo-books">
                            <a class="nav-link active" href="#">Photo Books</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Cards-Stationery">
                            <a class="nav-link active" href="#">Cards & Stationery</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Gifts">
                            <a class="nav-link active" href="#">Gifts</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Wall-Art">
                            <a class="nav-link active" href="#">Wall Art</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Prints">
                            <a class="nav-link active" href="#">Prints</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Home-Decor">
                            <a class="nav-link active" href="#">Home Decor</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Graduation">
                            <a class="nav-link active" href="#">Graduation</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Wedding">
                            <a class="nav-link active d-xl-block d-none" href="#">Wedding</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Calendars">
                            <a class="nav-link active d-xxl-block d-none" href="#">Calendars</a>
                        </li>
                        <li class="nav-item nav-item-1" id="Deals">
                            <a class="nav-link active" href="#" style="color: #a81719;">Deals</a>
                        </li>
                        <li class="nav-item nav-item-1">
                            <a class="nav-link active d-xxl-block d-none" id="nav-tinyprints" href="#">Tinyprints</a>
                        </li>
                        <li class="nav-item nav-item-1 dropdown d-xxl-none d-xl-block">
                            <a class="nav-link " href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                More +
                            </a>
                            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                                <li>
                                    <a class="dropdown-item d-xl-none d-block" href="#" id="Wedding2">Wedding</a>
                                </li>
                                <li>
                                    <a class="dropdown-item" href="#" id="Calendars2">Calendars</a>
                                </li>
                                <li>
                                    <a class="dropdown-item" id="nav-tinyprints" href="#">Tinyprints</a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                    <div class="d-xl-none d-block"><i class="fas fa-search"></i></div>
                    <div class="search-container d-flex align-items-center d-xl-block d-none">
                        <input class="search-input p-1" type="search" placeholder="Search" aria-label="Search">
                        <button class="search-button" type="submit" title="search">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>              
                </div>
            </header>   
            <!-- Start of the Nav Content -->
            <div class="nav-content w-100 row">
                <div class="col-12 nav-content-header">Photo Books</div>
                <div class="col-md-15">
                    <ul class="navbar-nav me-auto d-flex flex-wrap column-1">
                        <!-- Column 1 will be added using javascript -->
                    </ul>
                </div>
                <div class="col-md-15">
                    <ul class="navbar-nav me-auto d-flex flex-wrap column-2">
                        <!-- Column 2 will be added using javascript -->
                    </ul>
                </div>
                <div class="col-md-15">
                    <ul class="navbar-nav me-auto d-flex flex-wrap column-3">
                        <!-- Column 3 will be added using javascript -->
                    </ul>
                </div>
                <div class="col-md-15">
                    <ul class="navbar-nav me-auto d-flex flex-wrap column-4">
                        <!-- Column 4 will be added using javascript -->
                    </ul>
                </div>
                <div class="col-md-15">
                    <ul class="navbar-nav me-auto d-flex flex-wrap column-5">
                        <!-- Column 5 will be added using javascript -->
                    </ul>
                </div>
                <div class="d-flex align-items-center justify-content-center gap-5" style="background-color: #fafafb;">
                    <a class="nav-link" id="nav-tinyprints" href="#">Tinyprints</a>
                    <a href="#"><img src="./Images/SpoonFlower-logo.png" alt="This is SpoonFlower-logo" width="100px" height="40px"></a>
                </div>
            </div>
            <!-- End of the Nav Content -->
    

    JavaScript code

    let navEl = {
        'Photo Books' : document.querySelector('#photo-books'),
        'Cards & Stationery' : document.querySelector('#Cards-Stationery'),
        'Gifts' : document.querySelector('#Gifts'),
        'Wall Art' : document.querySelector('#Wall-Art'),
        'Prints' : document.querySelector('#Prints'),
        'Home Decor' : document.querySelector('#Home-Decor'),
        'Graduation' : document.querySelector('#Graduation'),
        'Wedding' : document.querySelector('#Wedding'),
        'Wedding2' : document.querySelector('#Wedding2'),
        'Calendars' : document.querySelector('#Calendars'),
        'Calendars2' : document.querySelector('#Calendars2'),
        'Deals' : document.querySelector('#Deals'),
    }
    
    function showNav(item) {
        // Get the corresponding nav-content for each navigation item
        let navContent = document.querySelector(".nav-content");
        let timeoutId;
    
        item.addEventListener('mouseover', function() {
            // Clear any existing timeout
            clearTimeout(timeoutId);
            // Show the nav-content when mouseover the navigation item
            navContent.style.display = "block";
        });
    
        navContent.addEventListener('mouseover', function() {
            clearTimeout(timeoutId); // Clear the timeout if the mouse moves over the items
            const mediumScreenSize = 992;
            if (window.innerWidth <= mediumScreenSize) {
                navContent.style.display = "none";
            } else {
                navContent.style.display = "block"; // Keep the items visible
            }
        });
    
        navContent.addEventListener('mouseout', function() {
            // Start a timeout
            timeoutId = setTimeout(function() {
                // Hide the nav-content when mouseout of the nav-content
                navContent.style.display = "none";
            }, 100); // Add a small delay before hiding the nav-content
        });
    
    item.addEventListener('mouseleave', function(e) {
            // Start a timeout
            timeoutId = setTimeout(function() {
                // Get the mouse position
                let x = e.clientX, y = e.clientY;
                // Get the bounding rectangle of the current nav-content
                let rect = navContent.getBoundingClientRect();
                // Check if the mouse is outside the current nav-content
                if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
                    // If the mouse is outside the current nav-content, hide it
                    console.log('');
                }
            }, 100); // Same delay as the mouseover event
        });
    
    }
    
    Object.keys(navEl).forEach(function(key) {
        showNav(navEl[key]);
    });
    

    TypeError: “domElement” is read-only | THREE.WebGLRenderer

    I’m getting an error when trying to initialize WebGLRenderer:
    (I removed some unnecessary lines)

    import * as THREE from "https://cdn.skypack.dev/[email protected]/build/three.module.js";
    import { OrbitControls } from "https://cdn.skypack.dev/[email protected]/examples/jsm/controls/OrbitControls.js";
    import { GLTFLoader } from "https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js";
    
    
    async function load() {
        // THREE JS
        window.scene = new THREE.Scene();
        window.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    
        // Loader
        window.loader = new GLTFLoader();
        window.loader.load(
            "/assets/shotgun/scene.gltf",
            function (gltf) {
                const model = gltf.scene;
                scene.add(model);
                window.shotgun = model;
            },
            function (xhr) {
                console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
            },
            function (error) {
                console.error(error);
            }
        );
    
        // Renderer   Getting error here
        window.renderer = THREE.WebGLRenderer({
            canvas: document.getElementById("shotgun"),
            antialias: true,
            alpha: true
        });
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setPixelRatio(window.devicePixelRatio);
        camera.position.set( 10, 0, 0 );
    
        // Light
        var light = new THREE.PointLight(0xffffff);
        light.position.set(-5, 10, 10);
        scene.add(light);
    
        // Help
        window.ctrl = new OrbitControls(camera, renderer.domElement);
        scene.add(new THREE.PointLightHelper(light), new THREE.GridHelper(200, 50));
    
    }
    
    load().then(() => {
        document.getElementById("loading").animate({ opacity: 0 }, { fill: "forwards", duration: 1000 });
        render();
    });
    

    DevTools say that error occurs in this line:

    function WebGLRenderer(parameters) {
      parameters = parameters || {};
      const _canvas2 = parameters.canvas !== void 0 ? parameters.canvas : createCanvasElement() // ...
      let currentRenderList = null;
      let currentRenderState = null;
      const renderListStack = [];
      const renderStateStack = [];
      this.domElement = _canvas2; // <----
      this.debug = {
        checkShaderErrors: true
      };
      this.autoClear = true;
      this.autoClearColor = true;
      this.autoClearDepth = true;
      ...
    }
    

    error in console

    Also, how can I pause code execution while the model is loading? (Without putting it into loader’s function)

    It looks like your post is mostly code; please add some more details.
    Like what else can I add?

    Why useEffect fetch not work on mobile, but work on desktop?

    If I switch too fast in 5 seconds on mobile chrome, useEffect will not fetch data from openWeatherAPI.
    But wait it for 5 second and reswitch page, it is ok to fetch and display.

    My weather app by Next.js app route deploy on vercel has two pages “/”, “/week”.
    I use getPosition() get lat and lon, fetchApi() get weather data, and <Link> to switch pages.

    homePage(“/”)

    "use client";
    
    import { fetchApi } from "@/api/fetchApi";
    import InfoBox from "@/components/InfoBox";
    import RainChart from "@/components/RainChart";
    import TempChart from "@/components/TempChart";
    import { getPosition } from "@/utils/getPosition";
    import { unixToDate } from "@/utils/unixToDate";
    import { unixToTime } from "@/utils/unixToTime";
    import { useEffect, useState } from "react";
    
    export default function Home() {
      const [date, setDate] = useState<string>("");
      const [time, setTime] = useState<string>("");
      const [desc, setDesc] = useState<string>("");
      const [feel, setFeel] = useState<number>(0);
      const [hourFeel, setHourFeel] = useState<number[]>([]);
      const [hourRain, setHourRain] = useState<number[]>([]);
    
      useEffect(() => {
        getPosition()
          .then((position) => {
            fetchApi(position.coords.latitude, position.coords.longitude, "metric")
              .then((data: any) => {
                setTime(unixToTime(data.current.dt));
                setDate(unixToDate(data.current.dt));
                setDesc(data.current.weather[0].description);
                setFeel(Math.round(data.current.feels_like));
    
                const hourFeelData: number[] = [];
                const hourRainData: number[] = [];
    
                for (let i = 0; i < 24; i++) {
                  hourFeelData.push(Math.round(data.hourly[i].feels_like));
                  setHourFeel(hourFeelData);
    
                  hourRainData.push(Math.round(data.hourly[i].pop * 100));
                  setHourRain(hourRainData);
                }
              })
              .catch((err) => {
                console.error(err);
              });
          })
          .catch((err) => {
            console.log(err);
          });
      }, []);
    
      return (
        <main>
          <div className="mt-5 flex justify-evenly">
            <InfoBox date={date} time={time} content={desc} />
            <InfoBox label="現在體感" content={`${feel}℃`} />
          </div>
          <TempChart data={hourFeel} />
          <RainChart data={hourRain} />
        </main>
      );
    }
    

    weekPage(“/week”)

    "use client";
    
    import { fetchApi } from "@/api/fetchApi";
    import { getPosition } from "@/utils/getPosition";
    import { unixToDate } from "@/utils/unixToDate";
    import { useEffect, useState } from "react";
    import DaysDetails from "@/components/DaysDetails";
    
    const WeekPage = () => {
      const loop = [];
      for (let i = 0; i < 8; i++) {
        loop.push(i);
      }
    
      const [date, setDate] = useState<string[]>(["", "", "", "", "", "", "", ""]);
      const [desc, setDesc] = useState<string[]>(["", "", "", "", "", "", "", ""]);
      const [dayFeel, setDayFeel] = useState<number[]>([0, 0, 0, 0, 0, 0, 0, 0]);
      const [eveFeel, setEveFeel] = useState<number[]>([0, 0, 0, 0, 0, 0, 0, 0]);
      const [rain, setRain] = useState<number[]>([0, 0, 0, 0, 0, 0, 0, 0]);
    
      useEffect(() => {
        getPosition()
          .then((position) => {
            fetchApi(position.coords.latitude, position.coords.longitude, "metric")
              .then((data: any) => {
                const dateData: string[] = [];
                const descData: string[] = [];
                const rainData: number[] = [];
                const eveFeelData: number[] = [];
                const dayFeelData: number[] = [];
    
                for (let i = 0; i < 8; i++) {
                  dateData.push(unixToDate(data.daily[i].dt));
                  setDate(dateData);
    
                  descData.push(data.daily[i].weather[0].description);
                  setDesc(descData);
    
                  dayFeelData.push(Math.round(data.daily[i].feels_like.day));
                  setDayFeel(dayFeelData);
    
                  eveFeelData.push(Math.round(data.daily[i].feels_like.eve));
                  setEveFeel(eveFeelData);
    
                  rainData.push(Math.round(data.daily[i].pop * 100));
                  setRain(rainData);
                }
              })
              .catch((err) => {
                console.error(err);
              });
          })
          .catch((err) => {
            console.log(err);
          });
      }, []);
    
      return (
        <div className="flex h-[43.75rem] flex-col items-center justify-evenly">
          {loop.map((i) => (
            <DaysDetails
              key={i}
              date={date[i]}
              desc={desc[i]}
              rain={`${rain[i]}%`}
              dayFeel={`${dayFeel[i]}℃`}
              eveFeel={`${eveFeel[i]}℃`}
            />
          ))}
        </div>
      );
    };
    
    export default WeekPage;
    

    pageSwitch in Layout

    "use client";
    
    import Link from "next/link";
    import { useState } from "react";
    
    const PageSwitcher: React.FC = () => {
      const [page, setPage] = useState("now");
    
      return (
        <div className="flex justify-center">
          <Link
            href="/"
            onClick={() => setPage("now")}
            className={`flex h-14 w-[11.5rem] items-center justify-center ${page === "now" ? "bg-slate-300" : "bg-inherit"}`}
          >
            NOW
          </Link>
          <Link
            href="/week"
            onClick={() => setPage("7days")}
            className={`flex h-14 w-[11.5rem] items-center justify-center ${page === "7days" ? "bg-slate-300" : "bg-inherit"}`}
          >
            7 DAYS
          </Link>
        </div>
      );
    };
    
    export default PageSwitcher;
    

    I think the problem is useEffect dependencies([]), maybe <Link> to page not means the initial render?

    I try to link my phone to desktop with USB debug to see real mobile chrome devTool Network page.

    mobile devTool-Network page

    And compare with desktop devTool-Network page.

    desktop devTool-Network page

    I just hope it normally fetch data on android like desktop.
    Please give me some advice, thanks!

    set the font size of a child element relative to the height of its parent box when the parent box doesn’t have a specified font size

    I need to dynamically set the font size of the <span> element relative to the 10% height of the div.

    HTML:

    <div>
      <span>Example text</span>
    </div>
    

    CSS:

    div {
      height: 20vh;
      width: 100vh;
      background-color: #f0f0f0;
      position: relative;
    }
    

    I tried using vh, vmin, rem, em, % units with no luck.
    Is there a way to achieve this with pure CSS? Without relying on JavaScript?

    Ajax registration form strictly using bootstrap, HTML and javastript

    Please help me out. I am required to create a code using Ajax without PHP, JQeury or anything like that.
    I can only make use of HTML, Bootstrap and Javascript. It should be a registrion form(name, surname,email,username and password).

    I have looking at different videos and they all make use of IQuery or php or other servers.

    I read information on bootstrap, HTML and Ajax, that I understood.
    I watched different videos, they were helful. Problem is, they all make use of other servers such as PHP.
    I am knew to programming hence I first had to watch vides and research.
    I wanted explanations or a video that only uses Ajax, boostrap, HTML and Javastript. Thanks

    Converting from a slider to a chart graph

    I have a library https://splade.dev/docs/using-vue-libraries. I’m using the Splade table.
    I have app.js:

    import { Carousel, Slide, Pagination, Navigation } from 'vue3-carousel';
    
    const el = document.getElementById("app");
    
    const app = createApp({
        render: renderSpladeApp({ el }),
    })
    .use(SpladePlugin, {
        "max_keep_alive": 10,
        "transform_anchors": false,
        "progress_bar": true,
    })
    .component('Carousel', Carousel)
    .component('CarouselSlide', Slide)
    .component('CarouselCharts', Chart)
    .component('CarouselPagination', Pagination)
    .component('CarouselNavigation', Navigation)
    .mount(el);
    

    There are also test data in the controller:

    $products = [
        [
            'id' => 1,
            'name' => 'T-shirt',
            'price' => 20.99,
            'description' => 'Simple T-shirt',
        ],
        [
            'id' => 2,
            'name' => 'Jeans',
            'price' => 39.99,
            'description' => 'Classic jeans',
        ], 
    ];
    

    And I don’t know what to display in Blade.”

    I tried adding this, but it doesn’t work:

    <Carousel>
        @foreach($charts as $key => $chart)
            <CarouselSlide key="{{ $key }}">
                <CarouselCharts :chart-data="$chart" />
            </CarouselSlide>
        @endforeach
    
        <template #addons>
            <CarouselNavigation />
            <CarouselPagination />
        </template>
    </Carousel>
    

    Node-Canvas Library: Text not visible and coming below Image

    I’m trying to use node-canvas npm package to generate an image from canvas.
    But the texts(TITLE 1 and TITLE 2) are appearing below the image. I want the image to be a background spanning across the canvas size and then put the texts over the image.

    Here is my code:

    const { createCanvas, loadImage } = require("canvas");
    const fs = require("fs");
    
    // Dimensions for the image/canvas
    const width = 848;
    const height = 600;
    
    // Instantiate the canvas object
    const canvas = createCanvas(width, height);
    const context = canvas.getContext("2d");
    
    context.font = "bold 70pt 'PT Sans'";
    context.textAlign = "center";
    context.fillStyle = "#764abc";
    
    context.fillText("TITLE 1", 600, 170);
    
    context.font = "bold 100pt 'PT Sans'";
    context.textAlign = "center";
    context.fillStyle = "#764abc";
    
    context.fillText("TITLE 2", 600, 270);
    
    // Write the image to file
    loadImage("./assets/jimp-cert-template.jpg").then((image) => {
      const pattern = context.createPattern(image, "no-repeat");
      context.fillStyle = pattern;
      context.fillRect(0, 0, width, height);
      const buffer = canvas.toBuffer("image/jpeg");
      fs.writeFileSync("./image.jpeg", buffer);
    });
    
    

    I’ve tried putting the loadImage function before drawing the texts in the canvas, but that also didn’t work. I want the image to be a background spanning across the canvas size and then put the texts over the image.

    Seeking Smoothness Issue with HLS.js – Buffering Interruptions

    I’m currently experiencing buffering interruptions when seeking forward or backward in a video streamed using HLS.js with Cloudflare Stream. Despite configuring HLS.js with various optimizations, I’m still facing this issue, particularly during seek operations. My goal is to implement a smooth seeking feature without buffering interruptions.

    HLS Configuration:

    const hls = new Hls({
      startFragPrefetch: true,
      // abrMaxWithRealBitrate: true,
      // abrBandWidthUpFactor: 2,
      initialLiveManifestSize: 10,
      abrBandWidthFactor: 0.1,
      maxBufferLength: 120,
      maxFragLookUpTolerance: 0.05,
    });
    

    Description:

    I’m using HLS.js to stream videos from Cloudflare Stream, and while the playback itself is generally smooth, I encounter buffering interruptions when seeking forward or backward in the video. These interruptions occur every 2-4 seconds after seeking, leading to a suboptimal viewing experience for users.

    I’ve tried adjusting various HLS.js configurations, such as increasing the buffer length (maxBufferLength) and adjusting the Adaptive Bitrate (ABR) parameters (abrBandWidthFactor). However, these changes haven’t resolved the buffering issue during seek operations.

    Objective:

    My primary objective is to implement a smooth seeking feature that allows users to navigate through the video timeline without encountering buffering interruptions. I’m seeking advice or suggestions on how to achieve this using HLS.js and Cloudflare Stream, whether through configuration optimizations, code adjustments, or other techniques.

    Request for Assistance:

    • Are there any specific HLS.js configurations or optimizations that I should consider for implementing smooth seeking functionality?
    • Are there any best practices or techniques for reducing buffering interruptions during seek operations in HLS video streams?
    • Is there any additional information or context that I should provide to better diagnose and address this issue?