Why, oh why, isn’t this String.match() matching?

I am totally unable to explain this, despite having used this script and others like it plenty before. Maybe someone can help?

I have a match() function in Apps Script set up like this:
else if (desc.match(/.*ENTERPRISE.*/i))

With this earlier in the code: let desc = row[3];

And I have a line in a spreadsheet like this (apparently the post should make sense without images too, so: cell D of the line contains the text Direct debit ENTERPRISE FUND):

enter image description here

It’s not matching anything earlier in the if chain, as I’d be able to see it performing the wrong action. I’ve reread the script and cell to ensure I’m not getting mixed up about the spelling.. I’ve tried swapping /.*ENTERPRISE.*/i for ".*ENTERPRISE.*" in case it’s something about the regex. I cannot fathom why it’s not picking it up. Any ideas?

Thanks!

How to make the last page fill the entire A4 paper when printed?

I’m working on a resume template using HTML and CSS, and I’m encountering an issue when printing the html page on A4 size paper. When the last page content is smaller than the a4 paper size my html page does not take the remaning height of a4 paper size. See the picture attached.

enter image description here

  • The content layout works fine on the screen, but when I print it, the
    last page doesn’t use all the available space on the A4 paper.

  • The last page should take up all the remaining space of A4 paper, but currently,
    only the content itself is shown, leaving some blank space below.

My Code:

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>

<style>

    @page {
        size: A4;
        margin: 20mm;
    }

    body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        height: 100%;
    }


    @media print {
        body {
            height: 100%;
        }
    }

    .resume-container {
        width: 21cm;
        display: flex;
        /*this will bring the whole cv in centre of screen*/
        margin: 0 auto;
        background-color: #fff;


    }


    .left-panel {
        width: 7.24cm;


        background-color: var(--left-panel-background-color);
        color: #fff;
    }


    .right-panel {
        width: 13.76cm;

        background-color: #fff;
    }
</style>

<body>


<div class="resume-container">

    <div class="left-panel">
        <!-- left side content goes here -->
    </div>

    <div class="right-panel">
        <!-- right side content goes here -->
    </div>
</div>

</body>
</html>

Setup multiple pages with vite in a JS project

I would like to render a page located in app/pages/language/index.html of my JS project (no React, no Typescript stuff).
When I go to the url http://localhost:3000/pages/language/, the main /index.html file is displayed (with some errors).

Here is my vite.config.ts file (without imports):

export default defineConfig({
    root: './app',
    base: './', // For local devs
    //base: '/Admin/', // For deployment
    resolve: {
      alias: {
        '~bootstrap': resolve(__dirname, 'node_modules/bootstrap'),
        '~bootstrap-icons': resolve(__dirname, 'node_modules/bootstrap-icons'),
      },
    },
    plugins: [
        image(),
        htmlPurge(),
        createHtmlPlugin({
            entry: './assets/index.js', // for live run
            template: 'index.html',
            inject: {
              data: {
                title: 'index',
                injectScript: `<script>window.APP_VERSION = '${app.version}'</script><script src="./inject.js"></script>`,
              },
            }
        }),
    ],
    define: {
        'process.env.NODE_ENV': JSON.stringify('developpment'),
    },
});

How can I configure vite to provide pages in subfolders of my project?

After reading this post https://stackoverflow.com/questions/77498366/how-do-i-setup-a-multi-page-app-using-vite, and updated my project, the provided solution does not work.

How do i Prevent Layout Shifting in react

The issue Im facing here is I have many components in a page and this code is a particular component so when I hover any card of this component the card is expanding but the below components of page are also moving down when i hover on any card so the whole layout is shifting down.

import React, { useState } from "react";
import card1 from "../assets/Logos/card1.gif";
import card2 from "../assets/Logos/card2.gif";
import card3 from "../assets/Logos/card3.gif";
import card4 from "../assets/Logos/card4.gif";

const Card = ({ image, title, description, color, index }) => {
  const [isHovered, setIsHovered] = useState(false);

  // Dynamically determine the translate-y value based on the card index
  const translateClass = index % 2 === 0 ? "-translate-y-8" : "translate-y-8";

  return (
    <div
      className={`bg-beeblack p-6 rounded-3xl flex flex-col hover:h-80 transition-all duration-800 ease-in transform ${translateClass} hover:translate-y-0`}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <img src={image} className="w-16 h-16 mb-4" />
      <h2 className={`font-Poppins-Medium text-xl mb-2 ${color}`}>{title}</h2>
      <div
        className={`transition-all duration-0 ease-in ${
          isHovered ? "max-h-20 opacity-100" : "h-0 opacity-0"
        }`}
      >
        <p className="text-beetxt text-base font-Poppins-Regular py-4 -my-4">
          {description}
        </p>
      </div>
    </div>
  );
};

export default function Demo() {
  const cards = [
    {
      title: (
        <>
          Creativity With <br /> Purpose:
        </>
      ),
      description:
        "We bring ideas to life, crafting innovative and meaningful narratives that resonate with your audience.",
      image: card1,
      color: "text-[#7670EA]",
    },
    {
      title: (
        <>
          Client-Service <br /> Focused:
        </>
      ),
      description:
        "Your vision is our mission. We partner with you to create strategies that elevate your brand.",
      image: card2,
      color: "text-[#F43C3C]",
    },
    {
      title: (
        <>
          Commitment <br />
          to Excellence:
        </>
      ),
      description:
        "Your vision is our mission. We partner with you to create strategies that elevate your brand.",
      image: card3,
      color: "text-[#58BC83]",
    },
    {
      title: (
        <>
          Integrity in <br />
          Action:
        </>
      ),
      description:
        "Your vision is our mission. We partner with you to create strategies that elevate your brand.",
      image: card4,
      color: "text-[#3BCDF6]",
    },
  ];

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-36 bg-beebg px-24 items-start py-24">
      {cards.map((card, index) => (
        <Card key={index} {...card} index={index} />
      ))}
    </div>
  );
}

I tried many other position properties and when I tried to use position:fixed everything disappears .

Extract HTML Page variable from script-tag in Javascript

How can I extract a variable from a script tag of the page from a returned HTML Page in Javasc./Typescript?

My API request to the Server:
const response = await fetch( ... )

The response contains a big HTML Page, here just an example:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Steam App Daten</title>
</head>
<body>

    <h1>Willkommen auf der Seite für Steam App Daten</h1>

    <script type="text/javascript">
        var g_rgAppContextData = {
            "730": {
                "appid": 730,
                "name": "Counter-Strike 2",
                "icon": "https://cdn.fastly.steamstatic.com/steamcommunity/public/images/apps/730/8dbc71957312bbd3baea65848b545be9eae2a355.jpg",
                "link": "https://steamcommunity.com/app/730"
            }
        };
        var g_rgCurrency = [];
    </script>

</body>
</html>

I only want to extract the Variable g_rgAppContextData without anything else. I know, that i can select the script tag with getElementsByTagName(“script”) but what if there are 2 script tags? And how to select only the Variable?

What is the difference between initial, specified, computed, resolved, used and actual values in CSS? [closed]

I’ve tried to find the answer on MDN but still find it quite confusing.
I’m trying to wrap my head around them and understand the object returned by window.getComputedStyle() as well as understand the computed value in the formal definition of CSS.

When does the difference between the values matter?

I was expecting it to be way simpler to understand.

Why is my agent not retaining past conversations?

I’m working on a project where I need to use Langchain with the Google Gemini model (ChatGoogleGenerativeAI), but I’m having trouble with memory retention across multiple invocations.

I want to maintain context between user messages, meaning that the agent should remember previous conversations when I invoke it with new prompts (i.e., having a chat history per thread).

Here is my current code setup:

import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import {
  MemorySaver,
} from "@langchain/langgraph";
import {
  createReactAgent,
} from "@langchain/langgraph/prebuilt";
import type { Tool } from "langchain/tools";



interface AgentInfo{
  id: string,
  name: string,
  job: string,
  sex: 'male' | 'female',
}

class Agent {
  private model: BaseChatModel;
  private tools: Tool[];
  private agent: any;
  private checkpointer: MemorySaver;
  public info: AgentInfo;

  constructor(model: BaseChatModel, tools: Tool[], info: AgentInfo) {
    const checkpointer = new MemorySaver();
    this.model = model;
    this.tools = tools;
    this.checkpointer = checkpointer 
    this.info = info;

    const agent = createReactAgent({
      llm: model,
      tools: tools,
      checkpointSaver: this.checkpointer,
    });

    this.agent = agent;
  }

  public getId(){
    return this.info.id
  }

  public async invoke(prompt: string, thread_id?: string) {

    const message = await this.agent.invoke(
      {
        messages: [{ role: "user", content: prompt }],
      },
      {
        configurable: {
          thread_id: thread_id,
        },
      }
    );
    return message.messages[message.messages.length - 1].content
  }
}

const geminiModel = new ChatGoogleGenerativeAI({
  model: "gemini-1.5-flash-8b",
});

const agent = new Agent(geminiModel, [], {id: '1', name:'josh', job: 'developer', sex: 'male'});

console.log(await agent.invoke('My name is test', 'test'));
console.log(await agent.invoke('What is my name', 'test'));

Problem:
I expect the agent to remember the context between the invocations (i.e., “My name is John” should be retained and used for answering “What is my name?”).
However, it seems that memory is not being retained across invocations, and the agent doesn’t respond with the expected context.
What I’ve tried:
Ensured that MemorySaver is saving and loading memory correctly using checkpointer.load() and checkpointer.save().
Passed the loaded memory to the agent invocation, hoping it would maintain the context.

How can I change an image source based on text content?

I’m making a weather app and wanted to have an image based on what the weather is. When I tried to do this, the image stayed blank.

Here is my code:
JS:

let button = document.querySelector('.button')
let inputLocation = document.querySelector('.location')
let temp = document.querySelector('.temp');
let desc = document.querySelector('.desc');
let image = document.getElementById("image");


button.addEventListener('click', function(){

    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${inputLocation.value}&units=metric&appid=9f5cf42409938f351c3a005bbc01773f`)
        .then(response => response.json())
        .then(
            displayData)
        .catch(err => alert('Not a city name.'));

},

function changeImg() {
    image.src = "images/" + desc.textContent + ".svg";
    console.log(image.src);

})

const displayData=(weather)=>{
    temp.innerText=`${weather.main.temp.toFixed(0)}°C`
    desc.innerText=`${weather.weather[0].main}`

}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Weather App</title>
    <link rel="stylesheet" href="styles.css">
    <script src="main.js" defer></script>
    <script src="https://kit.fontawesome.com/cdcbf8161c.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <div class="input" id="input">
        <input type="text" class="location" id="location" placeholder="Location">
        <button class="button" id="button"><i class="fas fa-search"></i></button>
    </div>
    <div class="image">
        <image id="image"></image>
    </div>
    <div class="output" id="output">
        <h1 class="temp" id="temp">˚C</h1>
        <p class="desc" id="desc"></p>
    </div>
</div>
</body>
</html>

I tried to change the weather to lowercase then make that my image source:
image.src = "images/" + desc.textContent.toLowerCase() + ".svg";
But that also didnt work. It also doesn’t give any errors.

How to edit the multiple files in jQuery

actually am facing an issue with edit functionality while hit on edit button am enabled the fields of respective row and in that i have lab-report column i am showing multiple file in that column so when hit on edit am enabled input field to upload the files and also holding existing file but when i hit on edit button it’s coming input field (file upload) and existing files multiple times for example if i have 3 files it’s coming like this

No file chosen
47.pdf
48.pdf
49.pdf

No file chosen
47.pdf
48.pdf
49.pdf

No file chosen
47.pdf
48.pdf
49.pdf

and if have 4 files it’s coming four times what is the issue actually I want to showcase once that input field and existing files

please help me anyone`

$('#addPackagingModuleList tbody').on('click', '.edit-btn', function () {
    const $row = $(this).closest('tr');
    const isEditing = $(this).text() === 'Update';
    const rowId = $(this).data('id');
    console.log('Entered inside the edit function');

    // For handling when the edit button is clicked
    if (isEditing) {
        $(this).text('Edit');
        $row.find('input, select').prop('disabled', true);

        // Prepare updated data (this remains unchanged)
        const variety = $row.find('.variety-select').val();
        const otherVariety = $row.find('.other-variety-input').val();
        const labReportLink = existingLabReports[rowId].concat(labReportUrls).join(','); // Combine existing and new URLs
        const updatedData = {
            id: rowId,
            labReport: labReportLink,
            farmSlide: "",  // Fill with your desired link if needed
            farmCertifications: "",
            farmPackagingVideo: "",
            growerName: $row.find('.grower-name').val(),
            crop: $row.find('.crop').val(),
            variety: variety === 'Other' ? otherVariety : variety,
            farmRegistrationNumber: $row.find('.farm-registration-number').val(),
            ggn: $row.find('.ggn').val(),
            lotTracebility: $row.find('.lot-traceability').val(),
            customerName: $row.find('.customerName').val(),
        };

        // Send updated data to the server
        $.ajax({
            url: '/admin/sys/sec/edit/qrcode/details',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(updatedData),
            success: function (response) {
                if (response.status) {
                    table.ajax.reload();
                    $('#alert-message').text(response.data);
                    $('#alert-container').show();
                    setTimeout(function () {
                        $('#alert-container').fadeOut();
                    }, 3000);
                    location.reload();
                } else {
                    alert('Error updating data.');
                }
            },
            error: function () {
                alert('Failed to update data.');
            }
        });
    } else {
        // When the "Edit" button text is "Update"
        $(this).text('Update');
        $row.find('input, select').prop('disabled', false);

        // Grab the lab report container
        const $labReportContainer = $row.find('.labReport');

        // Log the state of the lab report container before clearing it
        console.log('Before clearing, labReportContainer:', $labReportContainer.html());

        // Clear out any previous content in the labReport section
        $labReportContainer.empty();

        // Log again after clearing
        console.log('After clearing, labReportContainer:', $labReportContainer.html());

        // Add file input field (only once)
        $labReportContainer.append(`
            <input type="file" class="form-control labReportInput" accept="application/pdf">
        `);

        // Log the state of the lab report container after adding file input
        console.log('After adding file input, labReportContainer:', $labReportContainer.html());

        // Check if there are existing lab reports and append them
        if (existingLabReports[rowId] && existingLabReports[rowId].length > 0) {
            const existingReportsHtml = existingLabReports[rowId].map(link => `
                <div class="existing-lab-report" data-url="${link.trim()}">
                    <a href="${link.trim()}" target="_blank">${link.substring(link.lastIndexOf('/') + 1)}</a>
                    <i type="button" class="remove-lab-report-btn fa fa-times" style="font-size: 14px; color: #dc3545;"></i>
                </div>
            `).join('');
            $labReportContainer.append(existingReportsHtml);  // Append the existing reports only once
        }

        // Final log after appending all content
        console.log('Final state of labReportContainer:', $labReportContainer.html());
    }
});








     // Handle file input change for lab report
        $('#addPackagingModuleList tbody').on('change', '.labReportInput', function () {
            const labReportFiles = this.files;

            // Loop through each file to validate and upload
            Array.from(labReportFiles).forEach(file => {
                if (file.size > MAX_FILE_SIZE) {
                    alert('File size exceeds the 1MB limit.');
                    return;
                }

                const formData = new FormData();
                formData.append('file', file);

                $.ajax({
                    url: '/admin/sys/sec/qr/uploadFile',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    dataType: 'json',
                    success: function (response) {
                        if (response.status) {
                            // Store the uploaded file URL in the array
                            labReportUrls.push(response.data); // Store the new file URL

                            // Update the UI to display the new lab report next to the existing ones
                            const rowId = $(this).closest('tr').find('.edit-btn').data('id');
                            const existingReports = existingLabReports[rowId] || [];

                            // Combine existing and newly uploaded URLs
                            const allReports = [...existingReports, response.data];

                         // Create the new HTML for the lab report links
                            const labReportLinks = allReports.map(link => `
                                <div class="existing-lab-report" data-url="${link.trim()}">
                                    <a href="${link.trim()}" target="_blank">${link.substring(link.lastIndexOf('/') + 1)}</a>
                                    <button type="button" class="remove-lab-report-btn btn-sm btn-danger ms-1">
                                        <i class="fa fa-times"></i>
                                    </button>
                                </div>
                            `).join('');


                            // Update the lab report section with both existing and new links
                            $(this).closest('tr').find('.labReport').html(`
                                <input type="file" class="form-control labReportInput" accept="application/pdf">
                                ${labReportLinks}
                            `);

                            // Optionally, display a success message
                            $('#alert-message').text(response.message);
                            $('#alert-container').removeClass('alert-danger').addClass('alert-success').show();

                            setTimeout(function () {
                                $('#alert-container').fadeOut();
                            }, 3000);
                        } else {
                            alert('Error uploading file.');
                        }
                    },
                    error: function () {
                        alert('Error uploading file. Please try again.');
                    }
                });
            });
        });

`

Next.js + TypeScript: SyntaxError in Production Mode with Custom Server

I am working on a full-stack application using Next.js with TypeScript, and I need to use Socket.IO for real-time features. To achieve this, I have created a custom server (src/server.ts) to set up Socket.IO on startup.

Everything works perfectly in development mode when I run the app using:

npm run dev

However, when I try to run the application in production mode, I encounter issues. Here’s how I run it:

  1. Build the app:
next build
  1. Start server:
npm run start

The server starts without errors, but when I access any page in the browser, I get the following error:

SyntaxError: Invalid left-hand side in for-in loop: Must have a single binding.
    at <unknown> (.next/server/chunks/675.js:3414)

Here is my src/server.ts file:

import next from "next";
import { Server } from "socket.io";
import logger from "./logger";

const dev = process.env.NODE_ENV !== "production";
const hostname = process.env.APP_HOSTNAME;
const port = Number(process.env.APP_PORT) || 3000;

const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    const server = createServer(handler);

    const io = new Server(server, {
      cors: {
        origin: "*",
        methods: ["GET", "POST"],
      },
    });

    io.on("connection", (socket) => {
      logger.info("A client connected");

      socket.on("disconnect", () => {
        logger.info("Client disconnected");
      });
    });

    server
      .once("error", (err) => {
        console.error(err);
        process.exit(1);
      })
      .listen(port, () => {
        logger.info(`Server started on http://${hostname}:${port}`);
      });
  })
  .catch((error: unknown) => {
    logger.error("Error starting the server: ", error);
    process.exit(1);
  });

I suspect the issue is related to how Next.js handles the build output in production mode. I’m fairly new to Next.js and TypeScript, so I might be missing something critical. I’ve also tried adding output: "standalone", but the issue still occurs.

package.json

{
  "name": "nextjsapp",
  "version": "1.0.0",
  "description": "Template for web apps",
  "main": "dist/index.js",
  "scripts": {
    "dev": "ts-node src/server.ts",
    "build": "next build",
    "start": "NODE_ENV=production ts-node src/server.ts",
    "lint": "next lint",
    "prettier:format": "prettier --write .",
    "prettier:check": "prettier --check .",
    "component-tests": "cypress run --component",
    "e2e:chrome": "cypress run --e2e --browser chrome",
    "e2e:edge": "cypress run --e2e --browser edge",
    "commitlint": "commitlint --from develop --to HEAD",
    "check-updates": "npx npm-check-updates -u",
    "test": "jest",
    "storybook": "storybook dev -p 6006",
    "build-storybook": "storybook build",
    "prepare": "if [ "$SKIP_HUSKY" = "true" ]; then echo 'Skipping husky'; else husky; fi"
  },
  "private": true,
  "dependencies": {
    "@braintree/sanitize-url": "7.1.0",
    "@mdi/js": "7.4.47",
    "@mdi/react": "1.6.1",
    "@newrelic/next": "0.10.0",
    "@serwist/next": "9.0.11",
    "classnames": "^2.5.1",
    "dayjs": "1.11.13",
    "kafkajs": "2.2.4",
    "mssql": "11.0.1",
    "newrelic": "12.9.0",
    "next": "15.1.2",
    "next-auth": "4.24.11",
    "react": "19.0.0",
    "react-dom": "19.0.0",
    "react-toastify": "11.0.2",
    "sass": "^1.83.0",
    "sharp": "0.33.5",
    "socket.io": "^4.8.1",
    "socket.io-client": "^4.8.1"
  },
  "devDependencies": {
    "@chromatic-com/storybook": "^3.2.3",
    "@commitlint/cli": "19.6.1",
    "@commitlint/config-conventional": "19.6.0",
    "@eslint/js": "9.17.0",
    "@storybook/addon-essentials": "^8.4.7",
    "@storybook/addon-interactions": "^8.4.7",
    "@storybook/addon-onboarding": "^8.4.7",
    "@storybook/blocks": "^8.4.7",
    "@storybook/nextjs": "^8.4.7",
    "@storybook/react": "^8.4.7",
    "@storybook/test": "^8.4.7",
    "@testing-library/dom": "^10.4.0",
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^16.1.0",
    "@types/jest": "^29.5.14",
    "@types/jira-client": "7.1.9",
    "@types/mssql": "9.1.5",
    "@types/newrelic": "9.14.6",
    "@types/node": "22.10.2",
    "@types/react": "19.0.2",
    "@types/react-dom": "19.0.2",
    "@types/sharp": "0.31.1",
    "cypress": "13.17.0",
    "dotenv": "16.4.7",
    "eslint": "9.17.0",
    "eslint-config-next": "15.1.2",
    "eslint-config-prettier": "9.1.0",
    "eslint-plugin-cypress": "4.1.0",
    "eslint-plugin-storybook": "^0.11.1",
    "husky": "^9.1.7",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "jira-client": "8.2.2",
    "npm-check-updates": "^17.1.11",
    "prettier": "3.4.2",
    "serwist": "9.0.11",
    "start-server-and-test": "2.0.9",
    "storybook": "^8.4.7",
    "ts-node": "^10.9.2",
    "typescript": "5.7.2",
    "typescript-eslint": "8.18.1"
  },
  "browserslist": [
    ">0.3%",
    "last 2 versions",
    "not dead"
  ],
  "eslintConfig": {
    "extends": [
      "plugin:storybook/recommended"
    ]
  }
}

Checked the documentation for custom servers but couldn’t find anything specific to this issue. Searched online for similar issues but didn’t find an exact match. Has anyone faced this issue or something similar? What could be causing this SyntaxError?

Thank you in advance!

How do I show button to open the app as a PWA?

If the app is not installed, I can show a button to prompt to install the app as a PWA.

After installed, if I goto the app URL again via the address bar, the install button is not there (great, because I’ve hidden it)…but the user is now in the browser, whereas I want them to be in the standalone app.

Is there a way I can show a button for them to open the app as a standalone PWA or have it automatically open the PWA when they navigate to the app via the URL in the address bar?

Following this, I should just be able to add a link, but this doesn’t work: How to open PWA from a button within the web-app?.

Attempt 1: <a href="Http://localhost:8081/">Open PWA</a>

Attempt 2: window.open("Http://localhost:8081/")

Both just open in a new Chrome tab.

My app is at: Http://localhost:8081/

My manifest has the following in it: "start_url": ".", "scope": "."

When do custom elements invoke lifecycle hook formStateRestoreCallback with reason argument equal to “autocomplete”?

I tried to find examples where the formStateRestoreCallback lifecycle hook could return autocomplete as the second reason argument, but I didn’t find anything.

Here is a quote from the specification:

When user agent updates a form-associated custom element’s value on behalf of a user or as part of navigation, its formStateRestoreCallback is called, given the new state and a string indicating a reason, “autocomplete” or “restore”, as arguments.

To get the reason with restore you just need to refresh the page with a certain custom element on the page (don’t forget to use setFormValue)

customElements.define(
  "my-input",
  class extends HTMLElement {
    constructor() {
      super();
      this.internals_ = this.attachInternals();
      this.internals_.setFormValue("sendData", "localData");
    }
    static get formAssociated() {
      return true;
    }
    connectedCallback() {
      console.log("connectedCallback has been invoked");
    }
    formResetCallback() {
      console.log("formResetCallback has been invoked");
    }
    formStateRestoreCallback(state, mode){
      console.log("formStateRestoreCallback:", state, mode);
    }
  }
);

but what do you need to do to get autocomplete?

Does anyone know if this thing works?

How to change the height and width of video js player in react js

I’m using video-js to play mpeg-dash streams in react. I have made this component for my use:

"use client";
import { VideoPlayerProps } from "@/lib/types/video-player-interface";
import React, { useEffect } from "react";
import videojs from "video.js";
import Player from "video.js/dist/types/player";
import "video.js/dist/video-js.css";
export function VideoPlayer(videoPlayerProps: VideoPlayerProps) {
  const videoRef = React.useRef<HTMLDivElement>(null);
  const playerRef = React.useRef<Player | null>(null);
  // extract filename without extension
  const extractedFilename = videoPlayerProps.filename.replace(/.[^.]+$/, "");
  const playerOptions = {
    autoplay: videoPlayerProps.autoPlay,
    preload: "auto",
    enableSmoothSeeking: true,
    experimentalSvgIcons: true,
    nativeControlsForTouch: true,
    noUITitleAttributes: true,
    loop: true,
    controls: true,
    fluid: true,
    responsive: true,
    sources: [
      {
        src: `${process.env.NEXT_PUBLIC_MEDIA_SERVER_URL}/${extractedFilename}/${extractedFilename}.mpd`,
        type: "application/dash+xml",
      },
    ],
    userActions: {
      click: true,
    },
  };
  useEffect(() => {
    if (!playerRef.current && videoRef.current) {
      const videoElement = document.createElement("video-js");
      videoElement.classList.add("vjs-9-16");
      videoRef.current.appendChild(videoElement);
      playerRef.current = videojs(videoElement, playerOptions);
    }
  }, []);

  useEffect(() => {
    const player = playerRef.current;
    return () => {
      if (player && !player.isDisposed()) {
        player.dispose();
        playerRef.current = null;
      }
    };
  }, [playerRef]);
  return (
    <div data-vjs-player>
      <div ref={videoRef} />
    </div>
  );
}

I’m trying to change the height of the video player but I’m unable to do so. I tried using the tailwind classes like h-4/5 etc but they are not taking any effect. But then I found this document in video-js site. Stating:

In some cases, particularly with web applications using frameworks that may manage the element (e.g. React, Ember, Angular, etc), these elements are not desirable. They can be suppressed by setting window.VIDEOJS_NO_DYNAMIC_STYLE = true before including Video.js.
This disables all CSS-based player sizing. Players will have no height or width by default! Even dimensional attributes, such as width=”600″ height=”300″ will be ignored. When using this global, you will need to set their own dimensions in a way that makes sense for their website or web app.

I’m not sure how to set this property properly and change the height. Please help me with this.

Is any issue if we use Window.writebto add html on blank page

On button click, I am opening a blank window and after few delay loading word document.

However I want to show loading text at initial load till that new window/tab get replaced with documents.

I am prefering
Window.write(“loading”);

Is there any better approach?
Is it safe to use write method?

As it’s new/blank window,I cant use create elements ( head , body is not exist in new window)

Used window write() which work fine