How to synchronize SpeechSynthesis and Text Color Changes in Web Project

I’m currently working on a web project using the SpeechSynthesis API to read paragraphs of text on a webpage. I’ve been trying to synchronize the spoken words with the color changes in the text, but I’m facing some challenges.

Here’s a brief overview of the issue:

  • I have a function that reads out the content of

    tags on a page using the SpeechSynthesis API.

  • The goal is to synchronize the spoken words with color changes in real-time.
  • Specifically, I’d like each word to change to red while it’s being spoken and revert to the original color when the word is completed.
  • every attempt led to the whole paragraph being red.

My working code without the sync is below.

function speakAllParagraphs(page) {
  // Get all <p> elements within the current page
  var paragraphs = document
    .getElementById("page" + page)
    .getElementsByTagName("p");

  // Iterate through each <p> tag
  Array.from(paragraphs).forEach(function (paragraph, index) {
    // Speak the text of the paragraph
    var text = paragraph.innerText;

    // Create a new SpeechSynthesisUtterance
    var utterance = new SpeechSynthesisUtterance();
    utterance.text = text;

    // Find the voice by name
    const voices = speechSynthesis.getVoices();
    const targetVoice = voices.find(
      (voice) =>
        voice.name === "Microsoft Emily Online (Natural) - English (Ireland)"
    );

    if (targetVoice) {
      utterance.voice = targetVoice;
    } else {
      // Fallback: if the target voice is not available, use default voice
      utterance.voice = voices[0];
    }

    // Play the synthesized speech
    speechSynthesis.speak(utterance);
  });
}
  • I attempted to use the onboundary event to change the color of individual words, but it didn’t work as expected.
  • I’ve tried a few approaches, including using timers and events, but I haven’t been able to achieve the desired synchronization.
  • every attempt led to the whole paragraph being red.
  • The goal is to have each word change to red while it’s being spoken, and revert to the original color when the word is completed.

Hovered modal not getting positioned properly

So basically this is calander and there are 30 boxes(calendarBox) representing each date of a month. So when I hover over any box then the eventDetails modal should up
I applied the CSS to achieve that but for some reason the position absolute is featured with respect to a global div and is placed at a fixed place, instead with relative to calendarbox. I don’t understand why.
Want I want to achieve is that when I hover over any box then the modal should show up right below the box.
Please help me understand whats happening here?

Note: Both are sibling divs

function getHoveredEventDetails() {
    const formattedDay = day.format("DD-MM-YYYY");
    let matchingDates = [];
  
    eventsCountandDate.forEach((event) => {
      if (event.date === formattedDay) {
        matchingDates.push(event);
      }
    });
    if (matchingDates.length > 0) {
      return matchingDates.map((event, index) => {
        const coursesDetails = event.courses;
        return coursesDetails.map((course, courseIndex) => {
          return (
            <div className="profile" key={`${index}-${courseIndex}`}>
              {console.log(course.courseName)}
              <h1 className="profile_title">{course.courseName}</h1>
              <p className="profile_para">On {course.startProgramDates} till {course.endProgramDates}, From {course.startTime} to {course.endTime}</p>
            </div>      
          )
        });
      });
    }
  }

return (
    <>
      <div className={`border border-gray-200 flex flex-col calendarbox ${getCurrentDayClass()} ${hasEventsOnDay}`}>
        {rowIdx === 0 && (
            <p className="text-sm text-slate-950 day text-center bg-personal">
              {day.format("ddd").toUpperCase()}
            </p>
        )}
        <div className="flex flex-col">
          <p className={`text-base p-1 my-1 text-center`}>{day.format("DD")}</p>
        </div>
        <div className="flex-1 cursor-pointer" 
             onClick={()=> {
              setDaySelected(day);
              handleShowEventModal(day.format("DD-MM-YYYY")
              )}}
        >
          {getDetails()}
        </div>
      </div>
      <div className="eventDetails"> 
        {getHoveredEventDetails()}
      </div>
    </>
  );
.calendarbox {
  display: inline-block;
  position:relative;
  background-color: #fff4e4;
  border: 1px solid #BBB;
  min-width: 120px;
  min-height: 100px;
  max-height: 120px;
  transition: 3000ms; 
  cursor: pointer;
  height: 20rem;
  z-index: 0;
}

.eventDetails{
  display: none;
  position: absolute;  
  top: 20%;
  left: 40%; 
  width: 50%;
  opacity: 1;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
  background-color: #313131e8;
  visibility: hidden;
  /* transition: opacity 0.3s ease-in-out; */
  transition-delay: 3s;
  z-index: 2000;

}

.calendarbox:hover + .eventDetails{
  display: block;
  opacity: 1;
  display: absolute;
  visibility: visible;
  transform: translateY(0);
  /* z-index: 20000; */
}

Is this an unavoidable use of instanceof?

In my JavaScript program. There are be nodes. These nodes are kind of like post-it notes on a webpage and could be a text, video, image, website, or a collection node. They all inherit from the Node class. All of the nodes are simple, except the collection node, which can have the other nodes inside of it, using an Array to keep track of what nodes are inside of it.
I need to list all of the nodes that are on the entire page, but since there can be a collection node inside of a collection node, I needed to cycle through the main collection of Nodes, and use instanceof to find a collectionNode and then call .getNodes() on it.

I eventually need to list all of the nodes that are on the entire page, but since there can be a collection node inside of a collection node, I needed to cycle through the main collection, and use instanceof to call .getNodes(). I’ve heard that instanceof should be avoided at all cost and is a sign of poor design but I can’t come up with anything else.
My code looks something like this.

for (const node of this.props.mainNodeArray) {
    if (node instanceof CollectionNode) {
        const nestedResult = findInNestedCollections(node);
        if (nestedResult) return nestedResult;
    }
}

findInNestedCollections is now able to call .getNodes() on node since it will know it is a CollectionNode.

Is there an alternative? Thank you.

.env file to use process.env in JS, Node.js and MySQL sn’t working – seems to be the .env file as when putting info direct in JS it works fine

I’m new to Mysql and I am trying to write a program that will let me use js to manipulate the data in it. I am following a tutorial and have done exactly what iot says but for some reason when I make the env file, it stops working. I have written out eveything as the tutorial states, but when I come to run it I get this error:

Error: getaddrinfo ENOTFOUND '127.0.0.1',
    at PromisePool.query (C:UsersAdminDesktopDatabase practisedatabase mySQL-node.js practisenode_modulesmysql2promise.js:356:22)
    at getAllnotes (file:///C:/Users/Admin/Desktop/Database%20practise/database%20mySQL-node.js%20practise/database.js:16:31)
    at file:///C:/Users/Admin/Desktop/Database%20practise/database%20mySQL-node.js%20practise/database.js:20:23
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12) {
  code: 'ENOTFOUND',
  errno: -3008,
  sql: undefined,
  sqlState: undefined,
  sqlMessage: undefined

I was hoping that it would show the data that I had but is just coming up with the error above.

It definitely looks like the .env file as when I put all the info direct into js (host, user etc) it works fine, but for some reason it doesn’t work when I transfer all the info to the env file.

This is the JS file

import mysql from "mysql2"
import dotenv from 'dotenv'
dotenv.config()



const pool = mysql.createPool({
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE
}).promise()


async function getAllnotes() {
    const [rows] = await pool.query("SELECT * from notes")
    return rows
  }
  
  const notes = await getAllnotes()
  console.log(notes)

this is the .env file

MYSQL_HOST = '127.0.0.1',
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'password',
MYSQL_DATABASE ='notes_app'

and the package.json file

{
  "dependencies": {
    "dotenv": "^16.3.1",
    "mysql": "^2.18.1",
    "mysql2": "^3.7.0"
  },
  "name": "admin",
  "type": "module",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

the tutorial if you want to see it is https://www.youtube.com/watch?v=Hej48pi_lOc and the part I’m stuck on is at 9.50.

Ive installed dotenv & mysql2, but still isn’t working

MUI Datagrid preProcessEditCellProps Error Message

How can I add error message to mui preProcessEditCell?
I will like to display “Supplier Name cannot be empty” for the error text

{
field: “supplierName”,
headerName: “Name”,
width: 300,
editable: true,
preProcessEditCellProps: (params: GridPreProcessEditCellProps) => {
const hasError = params.props.value === ”;
return { …params.props, error: hasError};
},
},

I tried including helperText to the object being returned but it seems it(helperText) is not a valid property.

How can I generate a timetable in a React frontend based on user input?

I’m working on a project where I need to allow users to input various events (e.g., lectures, meetings) with details such as name, location, date, and time. Once the user has added these events, I want to generate a timetable that visually displays these events in a structured format.

I’m using React for the front end, and I’m wondering if there are any libraries, packages, or approaches that can help me achieve this. I want to display the timetable as a table or grid, with each event occupying the appropriate time slot.

This is my backend code that connects to the ChatGPT4 API to generate the output:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List
import openai

app = FastAPI()

# Configure CORS to allow requests from your React frontend's origin (e.g., http://localhost:3000).
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],  # Replace with the actual origin of your React app.
    allow_credentials=True,
    allow_methods=["*"],  # Allow all HTTP methods (GET, POST, etc.).
    allow_headers=["*"],  # Allow all headers in the request.
)

# Set your OpenAI API key
api_key = 'YOUR KEY'

class Event(BaseModel):
    name: str
    location: str
    from_date: str
    finish_date: str
    time: str
    event_type: str
    event_time: str
    eventColor: str  # Add this field back
    eventNotes: str

def generate_event_timetable(event_data):
    # Define the prompt for ChatGPT (same as before)
    prompt = f"Organise my time in 3 timetables as a table with these inputs:nName: {event_data.name}nLocation: {event_data.location}nFrom Date: {event_data.from_date}nFinish Date: {event_data.finish_date}nTime: {event_data.time}nEvent Type: {event_data.event_type}nEvent Time: {event_data.event_time}nEvent Color: {event_data.eventColor}nEvent Notes: {event_data.eventNotes}n"

    # Send the prompt to ChatGPT (same as before)
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant that generates event timetables."},
            {"role": "user", "content": prompt},
        ],
        max_tokens=200,
        api_key=api_key
    )

    # Get the table HTML generated by ChatGPT
    event_table_html = format_event_table([event_data])

    # Append the HTML table to the response content
    response.choices[0].message["content"] += event_table_html

    return response.choices[0].message["content"]

def format_event_table(events):
    table_html = '<table>'
    table_html += '<tr><th>Name</th><th>Location</th><th>From Date</th><th>Finish Date</th><th>Time</th><th>Event Type</th><th>Event Time</th><th>Event Notes</th></tr>'
    
    for event in events:
        table_html += f'<tr><td>{event.name}</td><td>{event.location}</td><td>{event.from_date}</td><td>{event.finish_date}</td><td>{event.time}</td><td>{event.event_type}</td><td>{event.event_time}</td><td>{event.eventNotes}</td></tr>'
    
    table_html += '</table>'
    return table_html

@app.post("/create_events/")
def create_events(events: List[Event]):
    # Initialize an empty list to store responses for each event
    responses_from_gpt = []

    # Iterate through each event and generate a response from ChatGPT
    for event in events:
        response_from_gpt = generate_event_timetable(event)
        responses_from_gpt.append(response_from_gpt)

    # Return the events data along with the responses from ChatGPT
    return {"events_data": [event.dict() for event in events], "gpt_responses": responses_from_gpt}

@app.post("/generate_timetable/")
def generate_timetable(events: List[Event]):
    # Create a list to store event descriptions
    event_descriptions = []

    # Iterate through events and create descriptions
    for event in events:
        description = f"Event: {event.name}nLocation: {event.location}nFrom Date: {event.from_date}nFinish Date: {event.finish_date}nTime: {event.time}nEvent Type: {event.event_type}nEvent Time: {event.event_time}nEvent Notes: {event.eventNotes}n"
        event_descriptions.append(description)

    # Join event descriptions to create the combined timetable
    combined_timetable = "n".join(event_descriptions)

    return {"generated_timetable": combined_timetable}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

And this below is my front-end written in React:

import React, { useState, ChangeEvent } from 'react';
import axios from 'axios';
import '../styles/GenerateCalendar.css';

interface EventData {
  name: string;
  location: string;
  from_date: string;
  finish_date: string;
  time: string;
  event_type: string;
  event_time: string;
  // eventColor: string;
  eventNotes: string;
}

function GenerateCalendar() {
  const [events, setEvents] = useState<EventData[]>([]);
  const [eventName, setEventName] = useState('');
  const [eventLocation, setEventLocation] = useState('');
  const [eventFromDate, setEventFromDate] = useState('');
  const [eventFinishDate, setEventFinishDate] = useState('');
  const [eventTime, setEventTime] = useState('');
  const [selectedOptionRow2, setSelectedOptionRow2] = useState('');
  const [selectedOptionRow3, setSelectedOptionRow3] = useState('');
  const [eventColor, setEventColor] = useState('');
  const [eventNotes, setEventNotes] = useState('');
  const [gptResponses, setGptResponses] = useState<string[]>([]);
  const [timetable, setTimetable] = useState<string>('');

  const handleOptionChangeRow2 = (option: string) => {
    setSelectedOptionRow2(option);
  };

  const handleOptionChangeRow3 = (option: string) => {
    setSelectedOptionRow3(option);
  };

  const handleEventNameChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEventName(e.target.value);
  };

  const handleEventLocationChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEventLocation(e.target.value);
  };

  const handleEventFromDateChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEventFromDate(e.target.value);
  };

  const handleEventFinishDateChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEventFinishDate(e.target.value);
  };

  const handleEventTimeChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEventTime(e.target.value);
  };

  const handleEventColorChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEventColor(e.target.value);
  };

  const handleEventNotesChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEventNotes(e.target.value);
  };

  const handleAddEvent = (e: React.FormEvent) => {
    e.preventDefault();
    const eventData = {
      name: eventName,
      location: eventLocation,
      from_date: eventFromDate,
      finish_date: eventFinishDate,
      time: eventTime,
      event_type: selectedOptionRow2,
      event_time: selectedOptionRow3,
      eventColor: eventColor,
      eventNotes: eventNotes,
    };

    // Push the new event to the events array
    setEvents([...events, eventData]);
  };

  const handleGenerateTimetable = async () => {
    try {
      const response = await axios.post('http://localhost:8000/generate_timetable/', events);
      if (response.status === 200) {
        console.log('Timetable generated successfully');
        console.log('Timetable Data:', response.data);

        // Update the 'timetable' state to store the generated timetable
        const generatedTimetable = response.data.generated_timetable;
        setTimetable(generatedTimetable);
      }
    } catch (error) {
      console.error('Error generating timetable', error);
    }
  };

  return (
    <div className="Calendar">
      <header>
        <h1 style={{ textAlign: 'center' }}>Enter Your Calendar</h1>
      </header>
      <form onSubmit={handleAddEvent}>
        <div className="name-table-wrapper" style={{ borderRadius: '100%' }}>
          <table className="name-table" style={{ borderRadius: 'inherit' }}>
            <tbody>
              <tr style={{ borderRadius: '100%' }}>
                <td style={{ width: '150px' }}>Name:</td>
                <td style={{ width: '666.5px' }}>
                  <input
                    type="text"
                    value={eventName}
                    onChange={handleEventNameChange}
                    style={{ borderColor: 'transparent', width: '100%' }}
                  />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <table className="options-table">
          <tbody>
            <tr>
              <td style={{ width: '150px' }}>Event:</td>
              <td
                style={{ width: '120px' }}
                onClick={() => handleOptionChangeRow2('Lecture')}
                className={selectedOptionRow2 === 'Lecture' ? 'selected' : ''}
              >
                Lecture
              </td>
              <td
                style={{ width: '120px' }}
                onClick={() => handleOptionChangeRow2('Laboratory')}
                className={selectedOptionRow2 === 'Laboratory' ? 'selected' : ''}
              >
                Laboratory
              </td>
              <td
                style={{ width: '120px' }}
                onClick={() => handleOptionChangeRow2('Extracurricular')}
                className={selectedOptionRow2 === 'Extracurricular' ? 'selected' : ''}
              >
                Extracurricular
              </td>
              <td
                style={{ width: '120px' }}
                onClick={() => handleOptionChangeRow2('Commute time')}
                className={selectedOptionRow2 === 'Commute time' ? 'selected' : ''}
              >
                Commute time
              </td>
              <td
                style={{ width: '120px' }}
                onClick={() => handleOptionChangeRow2('Study')}
                className={selectedOptionRow2 === 'Study' ? 'selected' : ''}
              >
                Study
              </td>
            </tr>
          </tbody>
        </table>
        <table className="options-table">
          <tbody>
            <tr>
              <td style={{ width: '150px' }}>Event time:</td>
              <td
                onClick={() => handleOptionChangeRow3('Strict')}
                className={selectedOptionRow3 === 'Strict' ? 'selected' : ''}
              >
                Strict
              </td>
              <td
                onClick={() => handleOptionChangeRow3('Flexible but preferred')}
                className={selectedOptionRow3 === 'Flexible but preferred' ? 'selected' : ''}
              >
                Flexible but preferred
              </td>
              <td
                onClick={() => handleOptionChangeRow3('Flexible')}
                className={selectedOptionRow3 === 'Flexible' ? 'selected' : ''}
              >
                Flexible
              </td>
            </tr>
          </tbody>
        </table>
        <table className="options-table">
          <tbody>
            <tr>
              <td style={{ width: '150px' }}>Location:</td>
              <td>
                <input
                  type="text"
                  value={eventLocation}
                  onChange={handleEventLocationChange}
                  style={{ width: '666.5px' }}
                />
              </td>
            </tr>
          </tbody>
        </table>
        <table className="options-table">
          <tbody>
            <tr>
              <td style={{ width: '150px' }}>Date and Time:</td>
              <td style={{ width: '135px' }}>From</td>
              <td>
                <input
                  type="text"
                  value={eventFromDate}
                  onChange={handleEventFromDateChange}
                />
              </td>
              <td style={{ width: '150px' }}>Finish</td>
              <td>
                <input
                  type="text"
                  value={eventFinishDate}
                  onChange={handleEventFinishDateChange}
                />
              </td>
            </tr>
          </tbody>
        </table>
        {/* <table className="options-table">
          <tbody>
            <tr>
              <td style={{ width: '150px' }}>Colour of event:</td>
              <td>
                <input
                  type="text"
                  value={eventColor}
                  onChange={handleEventColorChange}
                />
              </td>
            </tr>
          </tbody>
        </table> */}
        <table className="options-table">
          <tbody>
            <tr>
              <td style={{ width: '150px' }}>Notes:</td>
              <td>
                <input
                  type="text"
                  value={eventNotes}
                  onChange={handleEventNotesChange}
                  style={{ width: '666.5px' }}
                />
              </td>
            </tr>
          </tbody>
        </table>
        <button type="submit">Add Event</button>
      </form>
      <button onClick={handleGenerateTimetable}>Generate Timetable</button>
      {events.map((event, index) => (
        <div key={index}>
          <h2>Event {index + 1}:</h2>
          <p>Name: {event.name}</p>
          <p>Location: {event.location}</p>
          <p>From Date: {event.from_date}</p>
          <p>Finish Date: {event.finish_date}</p>
          <p>Time: {event.time}</p>
          <p>Event Type: {event.event_type}</p>
          <p>Event Time: {event.event_time}</p>
          {/* <p>Color: {event.eventColor}</p> */}
          <p>Notes: {event.eventNotes}</p>
        </div>
      ))}
      {/* {timetable && (
        <div>
          <h2>Generated Timetable:</h2>
          <p>{timetable}</p>
        </div>
      )} */}
      {timetable && (
        <div>
          <h2>Generated Timetable:</h2>
          <div dangerouslySetInnerHTML={{ __html: timetable }} />
        </div>
      )}
    </div>
  );
}

export default GenerateCalendar;


This is how the front-end looks like:

This is how the front-end looks like

It just gets the user input and sends it to the backend, and the backend connects to the GPT4 API to generate the timetable. The problem is that, right now, it doesn’t generate timetable, it just generates text like this:

enter image description here

But the generated timetable should be like this:

enter image description here

Specifically, I’d like to know:

Is it possible this to be done? And if yes, how it is possible?

unauthorized request problem of an endpoint in javascript

Hello to all of my I am in question in the influence of JavaScript development, but I have a problem when questioning the API in the intention of deleting data from its ID. I created a token during authentication in the location and when deleting the data I refer to the token in the at the top of the request.

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Sophie Bluel - Architecte d'intérieur</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=Work+Sans&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
    crossorigin="anonymous" referrerpolicy="no-referrer">   
    <meta name="description" content="">
    <link rel="stylesheet" href="./assets/css/style.css">
</head>
<body>
    <header>
        <h1>Sophie Bluel <span>Architecte d'intérieur</span></h1>
        <nav>
            <ul>
                <li class="nav_menu projects"><a href="#portfolio">projets</a></li>
                <li class="nav_menu contact"><a href="#contact">contact</a></li>
                <li class="nav_menu login"><a href="pages/login.html">login</a></li>
                <li class="nav_menu logout_hidden"><a href="index.html">logout</a></li>
                <li><a href="#"><img src="./assets/icons/instagram.png" alt="Instagram"></a></li>
            </ul>
        </nav>
    </header>
    <main>
        <section id="introduction">
            <figure>
                <img src="./assets/images/sophie-bluel.png" alt="">
            </figure>
            <article>
                <h2>Designer d'espace</h2>
                <p>Je raconte votre histoire, je valorise vos idées. Je vous accompagne de la conception à la livraison finale du chantier.</p>
                <p>Chaque projet sera étudié en commun, de façon à mettre en valeur les volumes, les matières et les couleurs dans le respect de l’esprit des lieux et le choix adapté des matériaux. Le suivi du chantier sera assuré dans le souci du détail, le respect du planning et du budget.</p>
                <p>En cas de besoin, une équipe pluridisciplinaire peut-être constituée : architecte DPLG, décorateur(trice)</p>
            </article>
        </section>
        <section id="portfolio">
            <div class="edit_project">
                <h2>Mes Projets</h2>
                <div class="popup_edit">
                    <a href="#modal1" class="js-modal modify_action modify_hidden"><i class="fa-xs fa-solid fa-edit"></i> modifier</a>
                </div>
            </div>
            <div class="navigation">
                <a href="#" class="active nav_link tous">Tous</a>
                <a href="#" class="nav_link objets">Objets</a>
                <a href="#" class="nav_link appartements">Appartements</a>
                <a href="#" class="nav_link hotels_restaurants">Hôtels&restaurants</a>
            </div>
            <div class="gallery">
                
            </div>
        </section>
        <section id="contact">
            <h2>Contact</h2>
            <p>Vous avez un projet ? Discutons-en !</p>
            <form action="#" method="post">
                <label for="name">Nom</label>
                <input type="text" name="name" id="name">
                <label for="email">Email</label>
                <input type="email" name="email" id="email">
                <label for="message">Message</label>
                <textarea name="message" id="message" cols="30" rows="10"></textarea>
                <input type="submit" value="Envoyer">
            </form>
        </section>
    </main>

    <footer>
        <nav>
            <ul>
                <li>Mentions Légales</li>
            </ul>
        </nav>
    </footer>

    <aside id="modal1" class="modal" aria-hidden="true" role="dialog" aria-labelledby="titlemodal" style="display:none;">
        <div class="modal-wrapper js-modal-stop">
            <div class="wrapper-nav">
                <a href="#" class="js-modal-close closed"><i class="fa-solid fa-xmark"></i></a>
            </div>
            <div class="wrapper-content">
                <div class="content-title modal1-title">
                    <h2>Galerie photo</h2>
                </div>
                <div class="modal_gallery">
                    
                </div>
            </div>
            <hr><br>
            <div class="wrapper-link">
                <a href="pages/modal/modal2.html#modal2" class="js-modal modal_submit">Ajouter une photo</a>
            </div>
        </div>
    </aside>
    <script src="assets/js/script.js"></script>
    <script src="assets/js/modal.js"></script>
</body>
</html>

This js code:

document.addEventListener("DOMContentLoaded", function() {
    const listOfWorks = document.querySelector(".modal_gallery");
    const _works = fetch('http://localhost:5678/api/works')
        .then(response => response.json())
        .then(data => {
            console.log('data', data);
            modalData(data);
        });

    async function modalData(data) {
        data.forEach((item, i) => {
            const sectionWorks = document.querySelector(".modal_gallery");
            const workElement = document.createElement("figure");
            workElement.classList.add('work-element');

            const imageElement = document.createElement("img");
            imageElement.src = item.imageUrl;
            imageElement.style.width = "76.86px";
            imageElement.style.height = "102.57px";

            const trashIcon = document.createElement("i");
            trashIcon.classList.add('fa-regular', 'fa-trash-can', 'trash-icon');

            const linkIcon = document.createElement("a");
            linkIcon.classList.add('link-icon');
            linkIcon.appendChild(trashIcon);

            linkIcon.addEventListener('click', function(e) {
                e.preventDefault();
                deleteImage(item);
            });

            const figcaptionElement = document.createElement("figcaption");
            figcaptionElement.style.fontSize = "14px";

            sectionWorks.appendChild(workElement);
            workElement.appendChild(imageElement);
            workElement.appendChild(linkIcon);
            workElement.appendChild(figcaptionElement);
        });
        return sectionWorks
    }        
});

function deleteImage(item) {
    console.log('item: ', item);
    token = window.localStorage.getItem("token")
    console.log(token)
    fetch(`http://localhost:5678/api/works/${item.id}`, {
        method: 'DELETE',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
    })
    .catch((error) => {
        console.error('Error:', error);
    });
}

This is the representation of the api

This is the error inside the log

enter image description here

Failed to load module script of type (.mjs)

I’m trying to integrate remark42 in my next js app but was unable to do so.

enter image description here

here is my configuration

`<script
dangerouslySetInnerHTML={{
__html:  var remark_config = { host: 'http://localhost:8080', site_id: 'remark', components:['embed'] }
}}
></script>
<script
   dangerouslySetInnerHTML={{
   __html:  !function (e, n) { for (var o = 0; o < e.length; o++) { var r =        n.createElement("script"), c = ".js",  // Update the file extension to ".mjs" d = n.head || n.body;   "noModule" in r ? (r.type = "module") : (r.async = !0), (r.defer = !0), (r.src = remark_config.host + "/web/" + e[o] + c), d.appendChild(r); } }(remark_config.components || ["embed"], document);,
  }}
></script>

I’m trying embed comment engine in my next js app I m runing the binary remark42 in my localhost,

all the configartions are ok but browser keeps giving MIME type error, any suggestion how should I resolve this issue.

Manual sorting breaks sorting directions in Mantine React Table

I am trying to do manual filtering for my data in mantine react table but I have met the problem – for some reason reseting the sorting direction stoped working for some columns. It is possible to sort asc and desc, but I cannot reset it.

There’s nothing different with column definition, it has only header and accessor key. When I press sort descending, and then ascending, the next option should reset the filter, but for some reason it is not working anymore for 2 of 8 columns.
example

Mongoose queries chain

I have a model and can do chaining queries like find(), limit(), skip().
The question is how can I apply limit or skip function to Model.find() output, if output (returning value) does not contain limit function?

For example this code works:

const mongoose = require("mongoose");
const password = encodeURIComponent("*****");
const username = encodeURIComponent("*****");

async function main() {

    await mongoose.connect(`mongodb+srv://${username}:${password}@cluster0.e5rojbd.mongodb.net/test?ssl=true&retryWrites=true&w=majority`);
    const userSchema = new mongoose.Schema({
        name: String
    });
    const Name = mongoose.model('names', userSchema);
    const limitedNames = Name.find().limit(2).skip(1);
    console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(limitedNames)))
    // output is [ 'constructor', '_queryMiddleware' ]
}
main().catch(err => console.log(err));


But how is it possible?

How to get ID’s of HTML element in a circular way?

This is my html element:

<div class="child-elements-container">
    <div id="116" is-open="true">
        <div class="element">
        </div>
        <div class="child-elements-container"></div>
    </div>
    <div id="105" is-open="true" draggable="false">
        <div class="element">
        </div>
        <div class="child-elements-container">
            <div id="4" is-open="true">
                <div class="element">
                </div>
                <div class="child-elements-container"></div>
            </div>
        </div>
    </div>
</div>

which is this:

var movedElement = document.getElementById(movedElementId);
console.log(movedElement.parentElement)

I have an id number 4 which is movedElementId and with this, I want to reach ID 105.

So I would like to push ‘s ID’d to an array as an object that includes id and children. Something like this:

[
   { id: 116, children: {} },
   { id: 105, children: { id: 4, children: {} } }
]

Can you help me with this?

NextJS static files 404 Not Found when behind NginX reverse proxy

When using NginX as a reverse proxy to a NextJS app, static files (.js, .css, etc) come up as 404 not found. The NextJS app works in dev mode. It works in production mode on my machine. It works as a docker container on my machine. But when I deploy it as a docker container in production behind NginX reverse proxy, it 404’s every static file.

I’ve connected to the running docker image and every file is there, right where it should be. I have no idea what is happening, but it’s super frustrating!

I created a Demo Repo on GitHub that you can clone and reproduce the issue yourself.

Here’s how I set up this demo project:

  • NextJS App created using npx create-next-app@latest.
  • NextJS App is dockerized following NextJS’s docs here: https://github.com/vercel/next.js/tree/canary/examples/with-docker
    • Edit next.config.js to include output: "standalone"
    • Create Dockerfile according to NextJS Documentation
  • The nginx folder at the root of this project has all the nginx config.
  • A docker-compose.yaml file was created to launch both apps.
    • NginX listens on port 80 for incoming traffic, and reverse-proxies traffic to the NextJS app.

Thanks in advance for any help!

How to use svgr with webpack and TypeScript in NextJS

I have svg files stored in separate files. I want to load them in React and use as react components as below:

import SampleIcon from '@/components/editor/icons/add-column-after.svg';
<SampleIcon className="my-icon" />

I installed svgr and used in next.config.js as below:

  webpack: (config) => {
    // SVG
    // Grab the existing rule that handles SVG imports
    const fileLoaderRule = config.module.rules.find((rule) =>
      rule.test?.test?.('.svg')
    );

    config.module.rules.push(
      // Reapply the existing rule, but only for svg imports ending in ?url
      {
        ...fileLoaderRule,
        test: /.svg$/i,
        resourceQuery: /url/, // *.svg?url
      },
      // Convert all other *.svg imports to React components
      {
        test: /.svg$/i,
        issuer: fileLoaderRule.issuer,
        resourceQuery: { not: [...fileLoaderRule.resourceQuery.not, /url/] }, // exclude if *.svg?url
        use: [
          {
            loader: '@svgr/webpack',
            options: {
              typescript: true,
              ext: 'tsx',
            },
          },
        ],
      }
    );

    // Modify the file loader rule to ignore *.svg, since we have it handled now.
    fileLoaderRule.exclude = /.svg$/i;

    return config;
  },

It works but intellisense does not work i.e. SampleIcon has any type. I tried to create declarations.d.ts file in root directory and add it in tsconfig.json in include list but does not work as well. Here is my declaration:

declare module '*.svg' {
  import React from 'react';
  const SVG: React.VFC<React.SVGProps<SVGSVGElement>>;
  export default SVG;
}

Any ideas?

Integrating Tauri for a Text Analysis Application on Windows

I’m working on a Windows desktop application using Tauri, aiming to build a simple text analysis tool. While I don’t need advanced NLP capabilities like Grammarly, I would like to send user input to a server and receive a JSON response with various data.

Here are the key points I’m trying to address:

  • Sending User Input to a Server:

I want to send user input (text) from my Tauri application to a server for analysis. What would be the best way to implement this client-server communication in a Tauri application?

  • Receiving JSON Response:

Once the server processes the input, I expect to receive a JSON response with analysis results. How can I handle and parse this JSON response within my Tauri application?

  • Gadget Icon Integration:

I’d like to implement a gadget icon for my application, similar to how Grammarly appears in the system tray. Are there specific Tauri APIs or best practices for integrating a gadget icon into a Tauri application on Windows?

  • Reading User Input Seamlessly:

To provide a smooth user experience, I’d like to read user input seamlessly. What Tauri features or considerations should I be aware of to capture and process user input efficiently?

  • Underlining and Highlighting Text in Other Windows Applications:

As an additional feature, I want to implement the ability to underline and highlight text in any window application, similar to Grammarly. Are there Tauri APIs or external libraries that can assist with this task?


If anyone has experience with similar tasks using Tauri or has insights into these specific challenges, including underlining and highlighting text, I would greatly appreciate your guidance.

Thank you for your time and assistance!

Using Cypress taking screenshot results in different size in local environment and when running in Jenkins pipline

I’m using Cypress and cypress-image-diff-js for visual regression tests.
Running Cypress headless generates screenshots in different sizes than the configured viewport in my cypress.config.ts file.
When running the test in my Jenkins pipeline, again, it generates screenshots in different sizes, failing the tests.

cypress.config.ts

{
  e2e: {
    baseUrl: "URL",
    chromeWebSecurity: false,
    supportFile: "./cypress/support/e2e-mock.ts",
    video: true,
    setupNodeEvents(on, config) {
      return getCompareSnapshotsPlugin(on, config);
    },
  },
  viewportWidth: 1300,
  viewportHeight: 800,
}

cypress-image-diff.config

const config = {
  FAILURE_THRESHOLD: 0.02,
  RETRY_OPTIONS: {
    log: true,
    limit: 3, // max number of iterations
    timeout: 20000, // time limit in ms
    delay: 500, // delay before next iteration, ms
  },
  CYPRESS_SCREENSHOT_OPTIONS: {
    capture: "viewport",
  },
};

Any idea how to solve this?
Thanks!