Does a browser cache responses to CORS fetch requests?

When running a fetch request on one domain (i.e. example.com), which requests a resource on another domain (i.e. example.net) through fetch, i.e.

// Code that gets executeed by i.e. example.com/index.js
const resp = await fetch("https://example.net/my-resource?id=42", { cache: "default" });

Given that the other domain is correctly configured to:

  • allow CORS (i.e. responds to OPTIONS and all sends all needed “allow cross-origin” headers)
  • provide cache headers (the response includes i.e. Cache-Control: max-age=10000)

Does the browser cache that response, so that subsequent fetch requests to the same resource URL will use the local cache?

Additional question: If this is the case, how is it possible to debug that with the browser’s dev tools? Seems like CORS fetch requests don’t display Headers/Request/Response details on the Network tab at least in Firefox, and no cache updates for the other domain appear in the “storage” tab (I assume they might just be filtered to only display the current origin’s cache).

“Invalid Date” Error when Loading Data from Google Sheets to BigQuery (Incorrect Date Format)

I am trying to load data from Google Sheets to BigQuery, but I am encountering an error related to the date format. Columns O and P in my Google Sheets contain dates that, although they are correctly displayed in the yyyy-mm-dd format (e.g., “2025-02-22”), when I try to upload them to BigQuery, I get the following error:

Invalid date: ‘Sat Feb 22 00:00:00 GMT+01:00 2025’

Problem Details:

The dates are displayed correctly in Google Sheets, but when they are transferred to BigQuery, the system interprets them as strings in an unrecognized date format.

I am using Google Apps Script to integrate Google Sheets with BigQuery.

I tried to format columns O and P correctly using Google Apps Script However, when I load the data into BigQuery, I continue to receive the “Invalid date” error.

I’ve attempted to format the cells in Google Sheets in yyyy-mm-dd date format manually and via Google Apps Script code, but the issue persists.
I tried casting the dates from Google Sheets using Utilities.formatDate() in Google Apps Script, but this hasn’t resolved the problem.
Question:
What is the solution to ensure that columns O and P are correctly recognized as dates in BigQuery and don’t trigger the “Invalid date” error? How can I ensure that the date format is correctly transferred from Google Sheets to BigQuery?

THIS IS MY CODE:

function exportToBigQuery() {
  var spreadsheet = SpreadsheetApp.openById("CHANGE id");
  var sheet = spreadsheet.getSheetByName("Ready Export");
  var range = sheet.getRange("A:AM"); // Seleziona l'intervallo specifico della tabella
  var values = range.getValues();

  if (values.length < 2) { // Controlla che ci siano dati oltre agli header
    Logger.log("Nessun dato da esportare.");
    return;
  }

  var headers = values[0]; // Intestazioni
  var data = values.slice(1); // Dati senza intestazione

  var projectId = "tCAHNGE id"; // Inserisci il tuo Project ID
  var datasetId = "Vivaio_Dataset"; // Inserisci il tuo Dataset ID
  var tableId = "Meta_conversion_official"; // Inserisci il nome della tabella


  var rows = data.map(row => {
    var obj = {};
    headers.forEach((header, index) => {
      obj[header] = row[index];
    });
    return { json: obj };
  });

  if (rows.length === 0) {
    Logger.log("Nessun dato da caricare.");
    return;
  }

  var insertJob = BigQuery.Tabledata.insertAll({
    rows: rows
  }, projectId, datasetId, tableId);

  if (insertJob.insertErrors) {
    Logger.log("Errore durante il caricamento: " + JSON.stringify(insertJob.insertErrors));
  } else {
    Logger.log("Caricamento riuscito! Ora pulisco il foglio...");

    // Mantieni solo gli headers
    sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn()).clearContent();
  }
}

Next.js Server Actions Causing Full Page Re-renders in Client Components

I’ve been experimenting with Next.js Server Actions and noticed something unexpected while analyzing re-renders using React Scan.

When I add an onClick handler to a button that updates a useState value, only the button component re-renders (indicated by a blue outline in React Scan). However, when I call a Server Action within the same onClick handler, it causes a re-render of the entire page—including all components, as seen by blue outlines around both the button and the entire body.

Interestingly, this behavior does not occur when using fetch to call an API route instead of a Server Action.

Is this expected behavior when using Server Actions in client components?

code:

// page.tsx

import SimpleButton from "./simple-button";

export default function Home() {
  return (
    <div className="flex h-svh w-full flex-col items-center justify-center gap-2">
      <SimpleButton />
    </div>
  );
}

// simple-button.tsx

"use client";
import { test } from "@/actions";
import { Button } from "@/components/ui/button";
import { useState } from "react";

export default function SimpleButton() {
  const [counter, setCounter] = useState(0);
  return (
    <Button
      onClick={() => {
        test();

        fetch("https://jsonplaceholder.typicode.com/todos/1");

        setCounter((prev) => prev + 1);
      }}
    >
      Start {counter}
    </Button>
  );
}

// actions.ts

"use server";

export async function test() {
  return "test";
}

video: https://streamable.com/w40zls

Ajax Post a variable without sending the result to anything specific [closed]

What is shown when the user first loads the page is an unfilled form, and the only option the user has is to select an item from a dropdown box.

Based on that selection, most of the rest of the form fields are automatically filled out, with some fields left over for the user to fill.

For example, the dropdown holds a list of parts. When the user clicks on a part, then some of the other fields such as Description and Part Number are auto-filled, then the user puts in the serial number, and the Submit button adds this to the database.

Here is my form + PHP:

    <form class = "form-body" method = "POST" action = "../includes/tech_parts_contr.inc.php">
                    <?php get_Master_parts_dropdown($pdo_User); ?>
                    <input type = "text" id = "partNumber" name = "partNumber" placeholder = "Part/Model Number"><br>
                    <textarea id = "partDescription" name = "partDescription" 
                        placeholder = "Description of the part..." rows = "5"></textarea><br>
                    <input type = "text" id = "serialNumber" name = "serialNumber" placeholder = "Serial Number"><br>

There are other fields after, but you get the picture.

The function get_Master_parts_dropdown checks to see if there is any parts available to be listed in the dropdown, and then displays them:

    else 
    {
        echo '<form method = "post">';
        echo '<select id = "masterPartsList" name = "masterPartsList">';
        foreach ($results as $row)
        {
            $htmlpname = htmlspecialchars($row["partName"]);
            $htmlpartID = $row["id"];

            echo '<option value = ' . $htmlpname . ' id = ' . $htmlpartID . '>' . $htmlpname . '</option>';
        }

The issue I have is the JavaScript portion.

I should do an onChange on the Select, but all the books I have, all the on-line resources I can find, all seem to want to send the data to specific output.

I don’t want that. I would rather have the onChange call a JS function that sends the data via POST back to the same PHP file that has the form.

At the top of the page: if ($_SERVER["REQUEST_METHOD"] === "POST") {.... then get the rest of the data from the database for that selection.

I tried something like:

    <script>
            $(document).ready(function() {
                $('#masterPartsList').change(function() {
                    var inputValue = $(this).val();
                    $.post('partsCheck.php', {dropdownValue: inputValue });
                });
            });
        </script>

…but that didn’t seem to work.

I would like Ajax to post a variable without sending the result to anything specific

What is shown when the user first loads the page is an unfilled form, and the only option the user has is to select an item from a dropdown box. Based on that selection, most of the rest of the form fields are automatically filled out, with some fields left over for the user to fill.
For example, the dropdown holds a list of parts. When the user clicks on a part, then some of the other fields such as Description and Part Number are auto-filled, then the user puts in the serial number, and the Submit button adds this to the database.
Here is my form + PHP:

<form class = "form-body" method = "POST" action = "../includes/tech_parts_contr.inc.php">
                <?php get_Master_parts_dropdown($pdo_User); ?>
                <input type = "text" id = "partNumber" name = "partNumber" placeholder = "Part/Model Number"><br>
                <textarea id = "partDescription" name = "partDescription" 
                    placeholder = "Description of the part..." rows = "5"></textarea><br>
                <input type = "text" id = "serialNumber" name = "serialNumber" placeholder = "Serial Number"><br>

There are other fields after, but you get the picture.
The function get_Master_parts_dropdown checks to see if there is any parts available to be listed in the dropdown, and then displays them:

else 
{
    echo '<form method = "post">';
    echo '<select id = "masterPartsList" name = "masterPartsList">';
    foreach ($results as $row)
    {
        $htmlpname = htmlspecialchars($row["partName"]);
        $htmlpartID = $row["id"];

        echo '<option value = ' . $htmlpname . ' id = ' . $htmlpartID . '>' . $htmlpname . '</option>';
    }

The issue I have is the JavaScript portion. I should do an onChange on the Select, but all the books I have, all the on-line resources I can find, all seem to want to send the data to specific output. I don’t want that. I would rather have the onChange call a JS function that sends the data via POST back to the same PHP file that has the form. At the top of the page: if ($_SERVER[“REQUEST_METHOD”] === “POST”) {…. then get the rest of the data from the database for that selection.

I tried something like:

<script>
        $(document).ready(function() {
            $('#masterPartsList').change(function() {
                var inputValue = $(this).val();
                $.post('partsCheck.php', {dropdownValue: inputValue });
            });
        });
    </script>

…but that didn’t seem to work.

Can anybody help w/ my situation here?

Opening user’s mail client for reading OTP – Without mailto compose window

It seems this isn’t answered directly anywhere but I have a feeling it may not be possible…

Use case is simply that I am sending an OTP to a user for login either via web app or mobile app. I would like a helper button in UI that says “Open Mail App” which then redirects them to read their email.

To clarify, I do NOT want to use mailto: as that opens the compose window and is terrible UX. All I want is to redirect the user so they can READ their incoming OTP email from me.

Is this possible or no?

@types/webpack dependency suddenly started giving error

Recently I believe some changes were made to webpack dependency due to which I’m unable to deploy the service. This is the code snippet in types.d.ts file which was changed.
Old Version

type ArrayBufferView =
    | Uint8Array
    | Uint8ClampedArray
    | Uint16Array
    | Uint32Array
    | Int8Array
    | Int16Array
    | Int32Array
    | BigUint64Array
    | BigInt64Array
    | Float32Array
    | Float64Array
    | DataView;

New Version

type ArrayBufferView =
    | Uint8Array<ArrayBufferLike>
    | Uint8ClampedArray<ArrayBufferLike>
    | Uint16Array<ArrayBufferLike>
    | Uint32Array<ArrayBufferLike>
    | Int8Array<ArrayBufferLike>
    | Int16Array<ArrayBufferLike>
    | Int32Array<ArrayBufferLike>
    | BigUint64Array<ArrayBufferLike>
    | BigInt64Array<ArrayBufferLike>
    | Float32Array<ArrayBufferLike>
    | Float64Array<ArrayBufferLike>
    | DataView<ArrayBufferLike>;

I just want to know what specifically is causing this error and why it started appearing suddenly.

Downgrading @types/webpack from 5.28.0 to 4.41.26 solved the error.

But I do not want to downgrade. Please suggest any other solution.

Discord Bot: Registering slash commands doesnt show the console log

There is no console output when I run the

node src/register-commands.js

. Already set up the .env file correctly, and this is how my codes looks like:

require('dotenv').config();

console.log('TOKEN:', process.env.TOKEN);
console.log('CLIENT_ID:', process.env.CLIENT_ID);
console.log('GUILD_ID:', process.env.GUILD_ID);

const { REST, Routes } = require('discord.js');

const commands = [
    {
        name: 'greet', // must be lowercase
        description: 'Replies your greetings!',
    },
];

const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);

(async () => {
    try {
        console.log('Registering slash commands...');
        
        await rest.put(
            Routes.applicationGuildCommands(
                process.env.CLIENT_ID, 
                process.env.GUILD_ID
            ),
            { body: commands }
        );
        console.log('Slash commands were registered successfully!');
    } catch (error) {
        console.log(`An error has occured: ${error}`);
    }
})();

Expected terminal output:
“Registering slash commands…”
And if the discord commands registered successfully, should’ve be
“Slash commands were registered successfully!”

How can i make button show on all questions?

Everything works fine for the first question, but the next button with id ‘next’
won’t show up when answering the second question. I’ve been trying to fix this for hours can someone help thanks!

let firstQuestion = document.getElementById('question1')
let secondQuestion = document.getElementById('question2')
let thirdQuestion = document.getElementById('question3')
let fourthQuestion = document.getElementById('question4')
let fifthQuestion = document.getElementById('question5')
let sixthQuestion = document.getElementById('question6')
let seventhQuestion = document.getElementById('question7')
let eighthQuestion = document.getElementById('question8')
let ninthQuestion = document.getElementById('question9')
let tenthQuestion = document.getElementById('question10')
let nextButton = document.getElementById('next')

let answers = document.querySelectorAll('.answer')
let correctAnswers = 0

firstQuestion.hidden = false
secondQuestion.hidden = true
thirdQuestion.hidden = true
fourthQuestion.hidden = true
fifthQuestion.hidden = true
sixthQuestion.hidden = true
seventhQuestion.hidden = true
eighthQuestion.hidden = true
ninthQuestion.hidden = true
tenthQuestion.hidden = true

let questions = [

  {
    question: 'What is Harry's full name?',
    correctAnswer: 'Harry James Potter'
  },

  {
    question: 'Who are Harry Potter's parents?',
    correctAnswer: 'Lily and James Potter'
  },

  {
    question: 'What is the name of the scar on Harry's forehead?',
    correctAnswer: 'Lightning Bolt Scar'
  },

  {
    question: 'Who was Harry's first friend at Hogwarts?',
    correctAnswer: 'Ron Weasley'
  },

  {
    question: 'What magical creature does Harry first encounter in "The Sorcerer's Stone" ?',
    correctAnswer: 'Fluffy the Three-Headed Dog'
  },

  {
    question: 'What is the name of Harry's godfather?',
    correctAnswer: 'Sirius Black'
  },

  {
    question: 'What is Harry's Patronus?',
    correctAnswer: 'A stag'
  },

  {
    question: 'What Quidditch position does Harry play?',
    correctAnswer: 'Seeker'
  },

  {
    question: 'What is the name of Harry's wand?',
    correctAnswer: 'The Holly and Phoenix Feather Wand'
  },

  {
    question: 'How does Harry first learn he is a wizard?',
    correctAnswer: 'Hagrid visits him on his birthday'
  }

];

let currentQuestionIndex = 0;

answers.forEach(answer => {
  answer.onclick = () => {
    if (answer.textContent.trim() === questions[currentQuestionIndex].correctAnswer) {
      answer.style.boxShadow = '0 0 25px rgba(50, 205, 50, 1)'
      answer.style.backgroundColor = '#32cd32'
      correctAnswers++
    } else {
      answer.style.boxShadow = '0 0 25px rgba(255, 0 , 0, 1)'
      answer.style.backgroundColor = 'red'
      for (let i = 0; i < answers.length; i++) {
        if (answers[i].textContent.trim() === questions[currentQuestionIndex].correctAnswer) {
          answers[i].style.boxShadow = '0 0 25px rgba(50, 205, 50, 1)'
          answers[i].style.backgroundColor = '#32cd32'
        }
      }
    }

    nextButton.style.visibility = 'visible'
    nextButton.style.opacity = '1'
    nextButton.style.transition = 'opacity 0.5s ease'

    answers.forEach(answer => answer.style.pointerEvents = 'none')
  }

})

nextButton.onclick = () => {

  let currentQuestionElement = document.getElementById(`question${currentQuestionIndex + 1}`);
  currentQuestionElement.hidden = true;

  currentQuestionIndex++;

  if (currentQuestionIndex >= questions.length) {
    nextButton.style.visibility = 'hidden';
    nextButton.style.opacity = '0';
    return;
  }

  let nextQuestionElement = document.getElementById(`question${currentQuestionIndex + 1}`);
  nextQuestionElement.hidden = false;

  let answerElements = nextQuestionElement.querySelectorAll('.answer');
  answerElements.forEach(answer => {
    answer.style.boxShadow = '';
    answer.style.backgroundColor = '';
    answer.style.pointerEvents = 'auto';
  });

  nextButton.style.visibility = 'hidden';
  nextButton.style.opacity = '0';
};
<main>
  <div id="question1" class="question">

    <h1 class="quest-title">What is Harry's full name?</h1>
    <h2 id="first-answer" class="answer">Harry James Potter</h2>
    <h2 id="second-answer" class="answer">Harry Albus Potter</h2>
    <h2 id="third-answer" class="answer">Harry Sirius Potter</h2>
    <h2 id="fourth-answer" class="answer">Harry Tom Potter</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question2" class="question">

    <h1 class="quest-title">Who are Harry Potter's parents?</h1>
    <h2 id="first-answer" class="answer">Lily and James Potter</h2>
    <h2 id="second-answer" class="answer">Lily and Severus Potter</h2>
    <h2 id="third-answer" class="answer">Alice and Frank Longbottom</h2>
    <h2 id="fourth-answer" class="answer">Hermione and Ron Potter</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question3" class="question">

    <h1 class="quest-title">What is the name of the scar on Harry's forehead</h1>
    <h2 id="first-answer" class="answer">Dark Mark</h2>
    <h2 id="second-answer" class="answer">Lightning Bolt Scar</h2>
    <h2 id="third-answer" class="answer">The Curse Scar</h2>
    <h2 id="fourth-answer" class="answer">The Prophecy Scar</h2>
    <h2 id="next">Next</h2>

  </div>

  <div id="question4" class="question">

    <h1 class="quest-title">Who was Harry's first friend at Hogwarts?</h1>
    <h2 id="first-answer" class="answer">Ron Weasley</h2>
    <h2 id="second-answer" class="answer">Neville Longbottom</h2>
    <h2 id="third-answer" class="answer">Hermione Granger</h2>
    <h2 id="fourth-answer" class="answer">Draco Malfoy</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question5" class="question">

    <h1 class="quest-title">What magical creature does Harry first encounter in "The Sorcerer's Stone"?</h1>
    <h2 id="first-answer" class="answer">Hippogriff</h2>
    <h2 id="second-answer" class="answer">Troll</h2>
    <h2 id="third-answer" class="answer">Mountain Troll</h2>
    <h2 id="fourth-answer" class="answer">Fluffy the Three-Headed Dog</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question6" class="question">

    <h1 class="quest-title">What is the name of Harry's godfather?</h1>
    <h2 id="first-answer" class="answer">Sirius Black</h2>
    <h2 id="second-answer" class="answer">Remus Lupin</h2>
    <h2 id="third-answer" class="answer">Album Dumbledore</h2>
    <h2 id="fourth-answer" class="answer">Severus Snape</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question7" class="question">

    <h1 class="quest-title">What is Harry's Patronus</h1>
    <h2 id="first-answer" class="answer">A stag</h2>
    <h2 id="second-answer" class="answer">A doe</h2>
    <h2 id="third-answer" class="answer">A lion</h2>
    <h2 id="fourth-answer" class="answer">A wolf</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question8" class="question">

    <h1 class="quest-title">What Quidditch position does Harry play</h1>
    <h2 id="first-answer" class="answer">Beater</h2>
    <h2 id="second-answer" class="answer">Chaser</h2>
    <h2 id="third-answer" class="answer">Keeper</h2>
    <h2 id="fourth-answer" class="answer">Seeker</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question9" class="question">

    <h1 class="quest-title">What is the name of Harry's wand</h1>
    <h2 id="first-answer" class="answer">The Elder Wand</h2>
    <h2 id="second-answer" class="answer">The Phoenix Wand</h2>
    <h2 id="third-answer" class="answer">The Holly and Phoenix Feather Wand</h2>
    <h2 id="fourth-answer" class="answer">The Ash and Dragon Heartstring Wand</h2>
    <h2 id="next">Next</h2>
  </div>

  <div id="question10" class="question">

    <h1 class="quest-title">How does Harry first learn he is a wizard?</h1>
    <h2 id="first-answer" class="answer">He sees a letter in the mailbox</h2>
    <h2 id="second-answer" class="answer">He receives a letter on his birthday</h2>
    <h2 id="third-answer" class="answer">Hagrid visits him on his birthday</h2>
    <h2 id="fourth-answer" class="answer">A magical accident happens at school</h2>
    <h2 id="next">Next</h2>
  </div>
</main>

Get page count before printing a web page

I’m trying to automate PDF generation from web pages. My goal is to create single-page PDFs by adjusting print dimensions dynamically.

Currently, I have this working solution that requires manual verification of the page count:

heightMultiplier = 2.5;
document.head
    .appendChild(document.createElement("style"))
    .sheet.insertRule(`@page { size: 21cm ${heightMultiplier * 29.7}cm; }`, 0);
window.print();

This code adjusts the print height to create a single-page PDF by multiplying the standard A4 height (29.7cm) by a factor.
The width remains at A4 standard (21cm).
I execute it in the browser’s developer console.

What I need is a way to programmatically determine the initial page count that would be shown in the browser’s print dialog. This would allow me to:

  1. Calculate the number of pages before printing
  2. Set the heightMultiplier automatically
  3. Generate the PDF without manual intervention

Is there a way to get this information using JavaScript? I’ve tried looking into the window.print() API but couldn’t find relevant methods.

What I’ve considered

  • Using a print preview API (if it exists)
  • Calculating based on content height vs page height
  • Intercepting print dialog information

Any suggestions would be appreciated!

I had this issue when I try to connect mysql server in window 10 WAMP server

const mysql = require('mysql2');
const express = require('express');
const bodyparser = require('body-parser');

var app = express();

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

app.listen(8888, () => {
  console.log("Listening to : 8888");
})
 
var mysqlConnection = mysql.createConnection({
  user: "abebe",
  password: "abebe",
  host: "localhost",
  database: "abebe"
});

and get this error:

Listening to : 8888
Error: Unknown error 1044
    at Packet.asError (C:UserspcOneDriveDesktopReactapple-fullstackserverDatabase1node_modulesmysql2libpacketspacket.js:740:17)
    at ClientHandshake.execute (C:UserspcOneDriveDesktopReactapple-fullstackserverDatabase1node_modulesmysql2libcommandscommand.js:29:26)
    at Connection.handlePacket (C:UserspcOneDriveDesktopReactapple-fullstackserverDatabase1node_modulesmysql2libbaseconnection.js:475:34)
    at PacketParser.onPacket (C:UserspcOneDriveDesktopReactapple-fullstackserverDatabase1node_modulesmysql2libbaseconnection.js:93:12)
    at PacketParser.executeStart (C:UserspcOneDriveDesktopReactapple-fullstackserverDatabase1node_modulesmysql2libpacket_parser.js:75:16)
    at Socket.<anonymous> (C:UserspcOneDriveDesktopReactapple-fullstackserverDatabase1node_modulesmysql2libbaseconnection.js:100:25)
    at Socket.emit (node:events:524:28)
    at addChunk (node:internal/streams/readable:561:12)
    at readableAddChunkPushByteMode (node:internal/streams/readable:512:3)
    at Readable.push (node:internal/streams/readable:392:5) {
  code: 'ER_DBACCESS_DENIED_ERROR',
  errno: 1044,
  sqlState: '42000',
  sqlMessage: 'Unknown error 1044',
  sql: undefined
}

react drag calendar when stutters when I drag the event

I use a React calendar system to create new events for scheduling appointments. However, the user can also drag an existing event to a new position if desired. The problem is that when the event is larger than the calendar view, it starts to stutter back and forth. I have some code that shows what it does now.

import React, { useState, useEffect, useRef } from 'react';
import { Calendar, momentLocalizer, Views } from 'react-big-calendar';
import withDragAndDrop from 'react-big-calendar/lib/addons/dragAndDrop';
import 'react-big-calendar/lib/addons/dragAndDrop/styles.css';
import 'react-big-calendar/lib/css/react-big-calendar.css';

import moment from 'moment';
import PlanningStats from './PlanningStats';
import DebugCalendar from './DebugCalendar';
import EventOptionScreen from './EventOptionScreen';
import CustomDeleteEvent from './CustomDeleteEvent'; 
import { retrieveReservations } from './ReservationHttpHandler';
import { ReservationProvider } from './ReservationProvider';
import { useReservation } from './ReservationProvider';
import { consoleLog, debugMode } from './General';
import './SystemCalendar.css';

const localizer = momentLocalizer(moment);
const DragAndDropCalendar = withDragAndDrop(Calendar);

const SysCalendar = ({ user, system, systemName }) => {
  const {
    handleMouseDown,
    handleMouseMove,
    handleMouseUp,
    setVisibleRange,
    handleRangeChange,
    deleteEvent,
    eventStyleGetter,
    setEvents,
    events,
    tempEvent,
    debugDateRef,
    createHandleEventDrop,
  } = useReservation();

  const [view, setView] = useState(Views.WEEK);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isSelectionLocked, setIsSelectionLocked] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false); 




  const calendarRef = useRef(null);

  useEffect(() => {
    setLoading(true);
    const now = new Date();
    setVisibleRange({
      start: moment(now).startOf('week').toDate(),
      end: moment(now).endOf('week').toDate(),
    });
  
    retrieveReservations(system.id, user.userId, setEvents)
      .catch((err) => {
        console.error('Error fetching reservations:', err);
        setError('Could not fetch reservations. Please try again.');
      })
      .finally(() => setLoading(false));
  }, [system.id, user.userId]);

  //handel dubble click event for opening a new modal screen for the event options
  const handleDoubleClickEvent = (event) => {
    if( user.userId===event.userId)
    {
    console.log("Open new Overlay")
    setSelectedEvent(event); // Set the clicked event
    setIsModalOpen(true);    // Open the modal
    }
  };

  // when the mouse is pressed down
  // event:   event is for checking and passing on for the handelmouse down.
    const handleMouseDownWrapper = (event) => {
      if (!isSelectionLocked && !isModalOpen && !event.target.closest('button')) {
        event.currentTarget.style.cursor = 'crosshair';
        handleMouseDown(event);
  
        // Add the global listener
        document.addEventListener('mouseup', handleGlobalMouseUp);
      }
    };

    // handleGlobalMouseUp when the mouse is outside the boundery of the calendar
    // event:   pass on the event that has been selected.
    const handleGlobalMouseUp=(event)=>{
       handleMouseUp(event, calendarRef, user, system);
       document.removeEventListener('mouseup', handleGlobalMouseUp);
    }


  const handleEventDrop = createHandleEventDrop({ setEvents, user, system, setIsSelectionLocked });
  
  if (loading) return <div>Loading...</div>;
  if (error) return <div>{error}</div>;

  return (
    <div
      style={{
        height: '50vh',
        cursor: isSelectionLocked ? 'default' : 'pointer',
      }}
      ref={calendarRef}
      onMouseDown={handleMouseDownWrapper}
      onMouseMove={!isSelectionLocked && !isModalOpen ? (event) => handleMouseMove(event, calendarRef, user) : undefined}
      // mouse up is responsible that the delete event is not working.
      onMouseUp={(event) => {
        console.log("-------------MOUSE BUTTON UP----------------")
        if ((!isSelectionLocked && !isModalOpen) ) {
      
          event.currentTarget.style.cursor = 'pointer';
         handleMouseUp(event, calendarRef, user, system);
        }
      }}
    >
      {debugMode() && 
    
      <DebugCalendar
      isSelectionLocked={isSelectionLocked}
        view={view}
        tempEvent={tempEvent}
        debugDateRef={debugDateRef}
      />
      }
      
      <PlanningStats sysId={system.id} sysName={systemName} sysEvents={events} />
      <DragAndDropCalendar
        localizer={localizer}
        events={tempEvent ? [...events, tempEvent] : events}
        startAccessor="start"
        endAccessor="end"
        style={{ height: '100%' }}
        defaultView={view}
        views={{ month: true, week: true, day: true, agenda: true }}
        selectable
        onEventDrop={handleEventDrop}
        onDoubleClickEvent={handleDoubleClickEvent} // Use your double-click handler here
        onView={setView}
        
        step={30}
        timeslots={1}
        showMultiDayTimes
        onEventResize={handleEventDrop}
        resizable={true}
        onRangeChange={handleRangeChange}
        draggableAccessor={(event) => user.userRoll === 'Planner' || event.userId === user.userId}
        onEventResizeStart={(type, { start, end }) => {
          console.log(`Resize started: start=${start}, end=${end}`);
        }}
        onEventResizeStop={(type, { start, end }) => {
          console.log(`Resize stopped: start=${start}, end=${end}`);
        }}
        eventPropGetter={(event) => eventStyleGetter(event, user)}
        components={{
          event: (props) => <CustomDeleteEvent {...props} deleteEvent={deleteEvent} user={user} setIsSelectionLocked={setIsSelectionLocked}  />,
        }}
      />
      {isModalOpen && (
        <EventOptionScreen event={selectedEvent} onClose={() => setIsModalOpen(false)}  />
      )}
    </div>
  );
};

const SystemCalendar = ({ system, user, systemName }) => {
  return (
    <ReservationProvider>
      <h2 style={{ color: '#ff0000' }}>Availability</h2>
      <SysCalendar user={user} system={system} systemName={systemName} />
    </ReservationProvider>
  );
};

export default SystemCalendar;

Css

/* Change the background color of the event rows */
.rbc-agenda-content .rbc-agenda-event-cell {
  background-color: #e0f7fa; /* Light blue background */
  color: #105a7c; /* Dark teal text */
}

/* Change the color of the date headers */
.rbc-agenda-content .rbc-agenda-date-cell {
  background-color: #006179; /* Dark teal background */
  color: #ffffff; /* White text */
  font-weight: bold; /* Bold text */
}

/* Style the time columns */
.rbc-agenda-content .rbc-agenda-time-cell {
  color: #0871a1; /* Teal color for the time */
  font-style: italic; /* Italic text */
}

.rbc-event {
  background-color: rgba(248, 255, 147, 0.89); /* Light yellow background */
  color: rgb(0, 0, 0) !important; /* Black text color */
  border-width: 2px;
  max-height: 100px;
  overflow: hidden;
}

/* change the color to yellow for requested */
.user-event {
  background-color: rgba(248, 255, 147, 0.89) !important; /* Light yellow background */
  color: rgb(0, 0, 0) !important; /* Black text color */
  border: 2px solid black !important; /* Black border */
  cursor: pointer !important; /* Pointer cursor to indicate interaction allowed */
}

/* Non-user event styles */
.non-user-event {
  background-color: rgba(192, 192, 192, 0.5) !important; /* Light gray background */
  color: gray !important; /* Gray text color */
  border: 2px solid lightgray !important; /* Light gray border */
  cursor: not-allowed !important; /* 'Not-allowed' cursor to indicate restricted access */
}
/* change the color to green for accepted */
.user-event-approved{
  background-color: rgba(147, 255, 170, 0.89) !important; /* Light yellow background */
  color: rgb(0, 0, 0) !important; /* Black text color */
  border: 2px solid black !important; /* Black border */
  cursor: pointer !important; /* Pointer cursor to indicate interaction allowed */
}
/* change the color to red for rejected */
.user-event-reject{
  background-color: rgba(255, 36, 36, 0.89) !important; /* Light yellow background */
  color: rgb(255, 255, 255) !important; /* Black text color */
  border: 2px solid black !important; /* Black border */
  cursor: pointer !important; /* Pointer cursor to indicate interaction allowed */

}
/* change the color to orange for planned */
.user-event-planned{
  background-color: rgba(214, 162, 20, 0.89) !important; /* Light yellow background */
  color: rgb(255, 255, 255) !important; /* Black text color */
  border: 2px solid black !important; /* Black border */
  cursor: pointer !important; /* Pointer cursor to indicate interaction allowed */
}

/* Add custom styles for drag selection indication */
.rbc-selected-cell {
  background-color: rgba(0, 128, 255, 0.3); /* Light blue background */
  border: 1px solid #007bff; /* Blue border */
}

/* Hide the default selection box of react-big-calendar */
.rbc-slot-selection {
  display: none; /* Completely hides the selection box */
}

/* Optional: Hide the borders of the selected cells */
.rbc-selected-cell {
  background-color: transparent; /* Removes the background color */
  border: none; /* Removes the border */
}

/* Temporary event styling */
.temp-event {
  background-color: rgba(61, 61, 61, 0.7) !important;
  border: 1px solid rgba(133, 133, 133, 0.8) !important;
  color: white !important;
  border-radius: 5px;
  opacity: 0.8;
}

I ask different people at the office and google but no answer has been founded. I don’t know if it is a re-rendering problem or wrong way of logic thinking of myself.

I tried to see if it needed some autoscroll handling, but that didn’t work. I also tried making changes in the CSS, including overflow and handlers, but the same problem still occurs.

Latest edit Css file added.

Responsive innerText

I’m trying to change the Text inside a table based on the widthof the screen.

This works fine, when i reach the breakpoint.
The Problem is, that the text does not change back to the original when i resize to the bigger width.

Here is the code:

 <div class="schedule-container">
        <div class="header responsive-text" data-alt-text="1. HJ">1. Halbjahr</div>
        <div class="header responsive-text" data-alt-text="MO">Montag</div>
        <div class="header responsive-text" data-alt-text="DI">Dienstag</div>
        <div class="header responsive-text" data-alt-text="MI">Mittwoch</div>
        <div class="header responsive-text" data-alt-text="DO">Donnerstag</div>
        <div class="header responsive-text" data-alt-text="FR">Freitag</div>
</div>
<script>

        function updateText() {
            const elements = document.querySelectorAll('.responsive-text');
            const originaltext = document.querySelectorAll('.responsive-text').innerText;
            elements.forEach(element => {
                if (window.matchMedia('(min-width: 400px) and (max-width: 600px)').matches) {
                    element.textContent = element.getAttribute('data-alt-text');
                }
                else {
                    element.textContent = originaltext;
                }

            });
        }

        window.addEventListener('resize', updateText);
        window.addEventListener('load', updateText);


    </script>

Thanks for your help!

Blockly Error: “Failed to load example: Blockly.Xml.textToDom is not a function”

Issue
I’m developing a visual block-based compiler for C programming using Blockly. However, I’m facing an issue where the following error appears in the console:

Failed to load example: Blockly.Xml.textToDom is not a function
This happens when I try to load an example XML workspace into Blockly.

What I Have Tried:
Checked that Blockly is properly imported.
Verified that Blockly.Xml.textToDom() exists in the Blockly documentation, but it doesn’t seem to work.
Tried alternative methods like Blockly.utils.xml.textToDom(), but that didn’t resolve the issue.
Relevant Code
Here’s the part where I attempt to load the XML workspace:

js

const xmlText = `<xml xmlns="https://developers.google.com/blockly/xml">
  <block type="controls_if"></block>
</xml>`;

const xml = Blockly.Xml.textToDom(xmlText);  // Error occurs here
Blockly.Xml.appendDomToWorkspace(xml, workspace);