Updating a value in String.raw block via REGEXP or something else?

I’m printing some values inside my HTML page where a textarea carries values that are String.raw. For example:

<script>

var ENV = String.raw`
{
    "id": "15bbb91c-b9d9-4238-8eb5-01c991d613ba",
    "name": ""${ENV_NAME_VARIABLE}"
}
`;

document.write(`
   <textarea id="envid" >` + ENV + ` </textarea>
`
);
</script>

This textarea shows up properly. Now through some interactivity in the page, let’s say a button, I want to change the value of this ENV_NAME_VARIABLE, and I’d like to show that in the textarea in the page. How could I retrieve the current value inside this bit, and replace with a new value?

<script>

    let ENV_NAME_VARIABLE = 'TESTING NAME';

    var ENV = String.raw`
    {
        "id": "15bbb91c-b9d9-4238-8eb5-01c991d613ba",
        "name": "${ENV_NAME_VARIABLE}""
    }
    `;

    document.write(`
    <textarea id="ENV" style="width: 80%; height: 100">` + ENV + ` </textarea>
    `
    );


    function updateName() { 
        original_text = document.getElementById('ENV').value;
        //////------ HERE I WANT TO GET THE value of ENV_NAME_VARIABLE..... 
        /////--------- AND REPLACE THAT to ABC
    }

</script>

<p>
<button onclick="updateName(); ">Change value of name to ABC</button>

Invoking function in Julia from Javascript using Electron.jl

I am trying to build a simple Electron app using Julia as my back-end language and HTML/CSS/Javascript as front-end by means of the Electron.jl package. Essentially, I have written a CVM structure on the back-end to handle data from my SQLite database, which I want to communicate to the front-end in order to display (sufficient for now). I am aware that you can run Javascript functions in Julia, but cannot figure out how to request the data on the back-end from Javascript. As you may notice, I am not the most advanced user of these languages (I have only self-taught knowledge of front-end development and some shallow work experience), so please excuse me if I asked a preposterous question.

I have tried to add

win.webContents.executeJavaScript("const {ipcRenderer} = require('electron'); function callJulia(name, ...args) { ipcRenderer.send('ipc-message', name, ...args); }; global['callJulia'] = callJulia;undefined")

to the existing snippets in Electron.jl:

win.webContents.on("did-finish-load", function() {
        win.webContents.executeJavaScript("const {ipcRenderer} = require('electron'); function sendMessageToJulia(message) { ipcRenderer.send('msg-for-julia-process', message); }; global['sendMessageToJulia'] = sendMessageToJulia;undefined")
    })

However, the function was not recognized in Javascript when I tried to use it. I must say this was mainly the suggestion of ChatGPT, whose ‘expertise’ in this niche is rather unhelpful.

Thank you in advance!

Livewire wire:navigate directive and iframes

Im making an app with laravel using livewire to make an SPA. I’ve created several full page components and I navigate between them using the wire:navigate directive. I also have a div with an Iframe in the parent layout that is encapsuled in an @persist livewire directive that I dont want to refresh. My problem is that everytime I click in a wire:navigate link the iframe refreshes. I change the div’s background color programmatically on the run and when I navigate between pages the background color persists but the iframe inside this div keeps reloading. Why is this happening?
Please help, I can’t find any hint on Internet.

I’ve tried data-navigate-once for scripts and persist for the html elements and works for everything but the iframe.

How to pass values from URL to an ODOO form

I have this landing page in ODOO:

https://vonride.odoo.com/booking-form?origin=Thessaloniki+Airport+%28SKG%29&depart=Sydney&departureDate=2024-05-16&returnDate=2024-05-18&adults=1&children=0&infants=0&transferType=ride-share

and as you can see the URL contains some information that I want to prefill in the form.

The landing page’s html is the following:

<t name="Contact Us" t-name="website.contactus">
        <t t-call="website.layout">
            <t t-set="logged_partner" t-value="request.env['website.visitor']._get_visitor_from_request().partner_id"/>
            <t t-set="contactus_form_values" t-value="{                 'email_to': res_company.email,                 'name': request.params.get('name', ''),                 'phone': request.params.get('phone', ''),                 'email_from': request.params.get('email_from', ''),                 'company': request.params.get('company', ''),                 'subject': request.params.get('subject', ''),             }"/>
            <span class="hidden" data-for="contactus_form" t-att-data-values="contactus_form_values"/>
            <div id="wrap" class="oe_structure oe_empty">
                <section class="s_title parallax s_parallax_is_fixed bg-black-50 pt24 pb24 o_colored_level" data-vcss="001" data-snippet="s_title" data-scroll-background-ratio="1" data-name="Title">
                    <span class="s_parallax_bg oe_img_bg" style="background-image: url('/web/image/website.s_parallax_default_image'); background-position: 50% 0;"/>
                    <div class="o_we_bg_filter bg-black-50"/>
                    <div class="container">
                        <h1>Booking Form</h1>
                    </div>
                </section>
                <section class="s_text_block pt40 pb40 o_colored_level" data-snippet="s_text_block" data-name="Text">
                    <div class="s_allow_columns container">
                        <div class="row">
                            <div class="mt-4 mt-lg-0 o_colored_level col-lg-8">
                                <p>
                                    Contact us about anything related to our company or services.<br/>
                                    We'll do our best to get back to you as soon as possible.
                                </p>
                                <section class="s_website_form" data-vcss="001" data-snippet="s_website_form" data-name="Form">
                                    <div class="container">
                                        <form id="contactus_form" action="/website/form/" method="post" enctype="multipart/form-data" class="o_mark_required" data-mark="*" data-model_name="mail.mail" data-success-mode="redirect" data-success-page="/contactus-thank-you" data-pre-fill="true">
                                            <div class="s_website_form_rows row s_col_no_bgcolor">
                                                <div class="mb-0 py-2 col-12 s_website_form_field s_website_form_custom s_website_form_required" data-type="char" data-name="Field">
                                                    <div class="row s_col_no_resize s_col_no_bgcolor">
                                                        <label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="contact1">
                                                            <span class="s_website_form_label_content">Name</span>
                                                            
                                                        <span class="s_website_form_mark"> *</span></label>
                                                        <div class="col-sm">
                                                            <input id="contact1" type="text" class="form-control s_website_form_input" name="name" required="" data-fill-with="name"/>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom s_website_form_required" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="owrem1mtipto"><span class="s_website_form_label_content">Phone Number</span><span class="s_website_form_mark"> *</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Phone Number" required="1" placeholder="" id="owrem1mtipto" data-fill-with="phone"/></div></div></div>
                                                <div class="mb-0 py-2 col-12 s_website_form_field s_website_form_required s_website_form_model_required" data-type="email" data-name="Field">
                                                    <div class="row s_col_no_resize s_col_no_bgcolor">
                                                        <label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="contact3">
                                                            <span class="s_website_form_label_content">Email</span>
                                                            
                                                        <span class="s_website_form_mark"> *</span></label>
                                                        <div class="col-sm">
                                                            <input id="contact3" type="email" class="form-control s_website_form_input" name="email_from" required="" data-fill-with="email"/>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                
                                                
                                                
                                                <div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="okrnw4dmgwrr"><span class="s_website_form_label_content">Pickup Location</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Pickup Location" placeholder="" id="okrnw4dmgwrr" data-fill-with="undefined"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="ovidp6buq8u"><span class="s_website_form_label_content">Destination</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Destination" placeholder="" id="ovidp6buq8u" data-fill-with="undefined"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="o07yl9vfg3bmw"><span class="s_website_form_label_content">Pickup Date</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Pickup Date" placeholder="" id="o07yl9vfg3bmw" data-fill-with="undefined"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="o0kj7girt231"><span class="s_website_form_label_content">Return Date</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Return Date" placeholder="" id="o0kj7girt231" data-fill-with="undefined"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="ocasezgtzgos"><span class="s_website_form_label_content">Adults</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Adults" id="ocasezgtzgos"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="ofvlz4jmtkod"><span class="s_website_form_label_content">Children</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Children" placeholder="" id="ofvlz4jmtkod" data-fill-with="undefined"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="onw8u9um8dv"><span class="s_website_form_label_content">Infants</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Infants" id="onw8u9um8dv"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="char"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="oew9ot9i5kpj"><span class="s_website_form_label_content">Transfer Type</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="text" name="Transfer Type" id="oew9ot9i5kpj" data-fill-with="undefined"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="text"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="ouxyjeu82zy"><span class="s_website_form_label_content">Comments</span></label><div class="col-sm"><textarea class="form-control s_website_form_input" name="Comments" placeholder="" id="ouxyjeu82zy" rows="2"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_custom" data-type="url"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px" for="o063d24dsn5ws"><span class="s_website_form_label_content">Tracking values</span></label><div class="col-sm"><input class="form-control s_website_form_input" type="url" name="Tracking values" placeholder="null" id="o063d24dsn5ws" data-fill-with="undefined"/></div></div></div><div data-name="Field" class="s_website_form_field mb-3 col-12 s_website_form_dnone"><div class="row s_col_no_resize s_col_no_bgcolor"><label class="col-form-label col-sm-auto s_website_form_label" style="width: 200px"><span class="s_website_form_label_content"/></label><div class="col-sm"><input type="hidden" class="form-control s_website_form_input" name="email_to" value="[email protected]"/></div></div></div><div class="mb-0 py-2 col-12 s_website_form_submit" data-name="Submit Button">
                                                    <div style="width: 200px;" class="s_website_form_label"/>
                                                    <a href="#" role="button" class="btn btn-primary s_website_form_send">Submit</a>
                                                    <span id="s_website_form_result"/>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </section>
                            </div>
                            
                            <script>
                                                document.addEventListener('DOMContentLoaded', function() {
                                                    // Get the value of the 'pickup_location' URL parameter
                                                    const urlParams = new URLSearchParams(window.location.search);
                                                    const pickupLocation = urlParams.get('origin');

                                                    // Fill the 'Pickup Location' input field with the value from the URL parameter
                                                    const pickupLocationInput = document.querySelector('input[name="Pickup Location"]');
                                                    if (pickupLocationInput) {
                                                        pickupLocationInput.value = pickupLocation;
                                                    }
                                                }
                            </script>
                            
                            <div class="mt-4 mt-lg-0 col-lg-4 o_colored_level">
                                <ul class="list-unstyled mb-0 ps-2">
                                    <li>My Company</li>
                                    <li><i class="fa fa-map-marker fa-fw me-2"/><span class="o_force_ltr">3575 Fake Buena Vista Avenue</span></li>
                                    <li><i class="fa fa-phone fa-fw me-2"/><span class="o_force_ltr">+1 (650) 555-0111</span></li>
                                    <li><i class="fa fa-1x fa-fw fa-envelope me-2"/>[email protected]</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </section>
            </div>
        </t>
    </t>

What I tried so far:

I included the part:

 <script>
                                                document.addEventListener('DOMContentLoaded', function() {
                                                    // Get the value of the 'pickup_location' URL parameter
                                                    const urlParams = new URLSearchParams(window.location.search);
                                                    const pickupLocation = urlParams.get('origin');

                                                    // Fill the 'Pickup Location' input field with the value from the URL parameter
                                                    const pickupLocationInput = document.querySelector('input[name="Pickup Location"]');
                                                    if (pickupLocationInput) {
                                                        pickupLocationInput.value = pickupLocation;
                                                    }
                                                }
 </script>

to try to just prefill one value (Pickup Location) but apparently didn’t work.

Is there a solution or ODOO just does not allow this customatization?

Incorect data reading workflow from Amazon S3 in Node Express API

I have Node JS Express backend API method in controller like this

async getImageStream(req, res) {
     ...
     let data = await readFromS3(MyImageURL)
     console.log(`Data ready ${data}`)
     res.setHeader("Content-Type", "application/json");
     res.status(200).send(JSON.stringify( data));
 }

and function to read data from Amazon S3 like this

 async function readFromS3(ImageURL) {
      ...
      s3.getObject(params, async function (err, data) {
         if (err) {
            console.error(err, err.stack);
         } else {
            console.log("Reading succesfully")
            return data.Body;
         }
      ...
 }

I can see data in debugger, data is correct, but my problem is incorrect workflow: “Data ready undefined” I receive always before “Reading succesfully”. So, backend API finished with undefined data than after seconds break on “Reading succesfully” fires and I can see correct data. I need insert something additional await (and force frontend waiting) or alternatively I need to change communication workflow between backend and frontend at all (something like emitter/subscriber events and send data to frontend when data from Amazon S3 will be ready. First way, of course, is simple. But I can not insert additional await correctly.

In Safari, service worker doesn’t intercept the first page load

I have created a very simple service worker as you see below. It simply intercepts the fetch requests and adds X-Custom-Header to the headers.

self.addEventListener('install', () => {
    self.skipWaiting();
});

self.addEventListener('activate', event => {
    event.waitUntil(self.clients.claim());
});

self.addEventListener('fetch', event => {
    event.respondWith(fetchWithHeader(event.request));
});

function fetchWithHeader(request) {
    const newHeaders = new Headers();
    newHeaders.set('X-Custom-Header', `123`);

    return fetch(request, { headers: newHeaders });
}

I register the service worker for http://localhost:3000 like this:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js', {
    scope: '/',
  });
}

In chrome and firefox, when I navigate to http://localhost:3000 (service worker is already installed), only one request is recevied by the back-end. But when I do the same in Safari, two requests are received by the back-end.

I investigated a bit and realised that in Safari, when I type http://localhost:3000 in the browser address bar, a request is sent before the service worker starts, then after the service worker starts, another request is sent which gets intercepted by the service worker.

I don’t understand why Safari has this strange behaviour. Does anybody have an idea how to prevent this?

P.S: I tried with different versions of safari both on mac and iphone. Got the same results everytime.

Looping over array of objects with recursion causes ‘Cannot read properties of undefined’

I’m new in JavaScript and trying to build a Comments tree looping through Comment instances (API response from backend).
Rendering root comments (level 0) causes no issues while recursive call of child comments causes ‘Cannot read properties of undefined’ on child attributes.

ws.onmessage = function(e){
        const rawData = JSON.parse(e.data);
        const responseAction = rawData.action
        const data = rawData.data
            switch(responseAction) {

                case "list":
                    for (const rootComment of data) {
                        commentTreeBuilder(rootComment, allCommentsSection)       
                    }
                    break;

In a response I receive array of Comment objects (including nested comments as children).
In function above it takes 2 arguments : 1)Comment object itself; 2)Container where it has to be appended.

function commentTreeBuilder(comment, parentContainer) {

    var childrenArraySize = Object.keys(comment.children).length; 

    if (comment.parent == null) {

        let parentCommentBody = generateCommentContainer(comment)

        // creation of wrapper for comment tree
        let rootCommentWrapper = document.createElement("section")
        rootCommentWrapper.setAttribute("class", "root-comment-section") 
        rootCommentWrapper.appendChild(parentCommentBody)
        parentContainer.appendChild(rootCommentWrapper)
                              
        if (childrenArraySize !== null && childrenArraySize > 0) { 
            let children = comment.children
            for (const child of children) {
                let childBody = generateCommentContainer(child); // (child, where to append)
                childBody.classList.add("child");
                commentTreeBuilder(childBody, rootCommentWrapper) 
            };   
        }
    } 
}

Then it recursively calls generateCommentContainer(comment) which just create a new comment templates (header, text, footer).
Currently I have only 2 objects [in array] to test: Root comment and one child. However looping will continue to take objects from array causing undefined error: TypeError: Cannot read properties of undefined (reading 'avatar')

function generateCommentContainer(data) {
    // Body
    var commentBody = document.createElement("div")
    commentBody.setAttribute("class", "comment-body")
    // Header Root
    var commentHeader = document.createElement("div")
    commentHeader.setAttribute("class", "comment-header")
    // Header-SubSection
    var headerSubSection = document.createElement("div")
    headerSubSection.setAttribute("class", "comment-header-sub")
    commentHeader.appendChild(headerSubSection)
    // Header-Rating
    var headerRating = document.createElement("div")
    headerRating.setAttribute("class", "comment-rating-container")
    commentHeader.appendChild(headerRating)

    // Content
    var commentContent = document.createElement("div")
    commentContent.setAttribute("class", "comment-content")
    var commentContentText = document.createElement("span")
    commentContentText.setAttribute("class", "comment-text")

    // appending comment child sections to body
    commentContent.appendChild(commentContentText)
    commentBody.appendChild(commentHeader)
    commentBody.appendChild(commentContent)
    
    // header
        // avatar constructing
    if (data.user.avatar) {  //                   <== Error in this line
        var avatarPath = data.user.avatar
    } else {
        var avatarPath = defaultUserAvatar
    }

    var avatar = document.createElement("img")
    avatar.setAttribute("class", "user-avatar")
    avatar.setAttribute("src", avatarPath)
    avatar.setAttribute("alt", "UserAvatar")

    // content
    commentContentText.textContent = data.text

   return commentBody 
}

Looks like after objects in array no more exist loop takes undefined value and tries get avatar attribute which causes an exception. Or I might miss something in a syntax since originaly code on Python.

Can some please explain to me the difference between the function keyword and const in declaring a function

As demonstrated in the below examples, I used the function keyword to declare a function that will generate a random integer number within a range, and I also used a const keyword to declare another function that will convert a string and return an integer. Your brief explanation will be helpful and appreciated.

//Generating a random whole number within a range.
function isBeginner(a1, a2) {
  let randomRange = "";
  if (a2 >= a1) {
    randomRange = Math.floor(Math.random() * (a2 - a1 + 1) + a1);
  } else {
    randomRange = Math.floor(Math.random() * (a1 - 1 + a2) - a1);
  }
  return randomRange;
};

console.log(isBeginner(2, 4)); //positive integer expected
console.log(isBeginner(5, 3)); //negative integer expected

//Using ParseInt to generate an Integer

const isBeginner2 = function(lib) {
  let crib = "";

  // using Switch statement for better descriptions
  switch (lib) {
    case "Zero before a real number":
      crib = parseInt(lib)
      break;

    case "String":
      crib = parseInt(lib);
      break;

    case "Decimal number":
      crib = parseInt(lib);
      break;

    case "Letter before a number":
      crib = parseInt(lib);
      break;

    case "Number before a letter":
      crib = parseInt(lib);
      break;

    default:
      crib = parseInt(lib);
      break;

  }
  return crib;
};

console.log(isBeginner2(005)); // output **5** expected
console.log(isBeginner2("Stay Healthy")); // output **NaN** expected
console.log(isBeginner2(1.5)); // output **1** expected
console.log(isBeginner2("E7")); // output **NaN** expected 
console.log(isBeginner2("8S")); // output **8** expected

To combine timeline and line chart

I have two distinct datasets in Power BI:
Source 1: (top)
• Date (not aligned with Source2)
• Count1, Count2, Countn (Also legend for the counts)

Source 2: (bottom)
• Date (non-continuous)
• Symptom Text
• Technician Text
I want to visualize both datasets on the same chart, aligning them based on their respective dates. How can I achieve this effectively in Power BI without overlaying two different charts? I need to display both text data (Symptom Text, Technician Text) and count data (Count1, Count2) on the same time base (Date)/X axis without converting text into numerical values.

Can anyone suggest the best approach or visualization for achieving this?

Reference Picture

I tried to do 2 different chart but I want everything in single chart.

How to add Plain Javascript code in react component

I am learning React JS as I am new to React I am creating a website for learning purposes and previously I have created a website using HTML, CSS, and Javascript.
I am stuck While adding my custom Javascript code in the React JS Component.
I have pasted all the js files in the public folder and added the scripts to the index.html page.
Some of the Scripts are running fine and some are not. Please Guide me on how to do this cause I am stuck.
I have used useState and tested it but still no output.

React Component: Hero.js

import React from 'react'

export default function Hero(props) {

  return ( 
    
  <section id="hero" className="d-flex flex-column justify-content-center align-items-center">
    <div className="hero-container" data-aos="fade-in">
      <h1>Your Text here</h1>
      <p>demo <span className="typed" data-typed-items="Aaaa, acvcx, aajabjab, aavja">{props.show}</span></p>
       {/* <span className="typed-cursor typed-cursor--blink" aria-hidden="true">|</span> */}
       
    </div>
  </section>
  );
}

React App.js file code

import Content from "./components/Content";
import Footer from "./components/Footer";
import HeaderNav from "./components/HeaderNav";
import Hero from "./components/Hero";
import { useState } from 'react';

function App() {

  const [typed, Typed] = useState(0);

  const show = () => {  
    if (typed) {
    let typed_strings = typed.getAttribute('data-typed-items')
    typed_strings = typed_strings.split(',')
    new Typed('.typed', {
      strings: typed_strings,
      loop: true,
      typeSpeed: 100,
      backSpeed: 50,
      backDelay: 2000
    });
  }
}

  return (
    <>
    <HeaderNav/>
    <Hero show={show} />
    <Content/>    
    <Footer/>   
    <a href="#" className="back-to-top d-flex align-items-center justify-content-center"><i className="bi bi-arrow-up-short"></i></a>
    </>
  );
}

export default App;

Original JavaScript file code used in previous project(Working):

const typed = select('.typed')
  if (typed) {
    let typed_strings = typed.getAttribute('data-typed-items')
    typed_strings = typed_strings.split(',')
    new Typed('.typed', {
      strings: typed_strings,
      loop: true,
      typeSpeed: 100,
      backSpeed: 50,
      backDelay: 2000
    });
  }

enter image description here

I have tried multiple things like useState, useEffect and . Also tried snip codes from the previous same issues asked on Stackoverflow like:

componentDidMount () {
    const script = document.createElement("script");

    script.src = "https://use.typekit.net/foobar.js";
    script.async = true;

    document.body.appendChild(script);
}

but Still not working.

If it is possible and should work in the same way as working in the previous project that would be helpful for me.

How to calculate overlay scaling factors / aspect ratio when scaled to a different sized viewport?

I have 3 elements I’m working with:

  1. Video using <video> tag.
  2. Background container/viewport area of video (which contains videos of different sizes).
  3. Overlay on video.

How do I scale and position the overlay to properly overlay on the scaled video?

Here is my system basically:

enter image description here

Those are the 3 elements in the system.

  1. The video can be arbitrary aspect ratios (4/3, 1/1, 2/3, 1/3, 5/4, etc.). Width can be greater, less than, or equal to height.
  2. The video is large as data (let’s say it’s 4000px by 3000px width/height).
  3. The video is placed in a container, which has a fixed aspect ratio (2/1 in this case).
  4. The container is 600px x 300px dimensions.
  5. An overlay is placed over the video, and needs to be placed in a specific position and scale within the video, within the container.

Should look something like this:

enter image description here

I have tried doing this:

const videoAspectRatio =
  videoEl?.videoWidth && videoEl?.videoHeight
    ? videoEl.videoWidth / videoEl.videoHeight
    : 1;

const visibleVideoWidth =
  width > height
    ? videoAspectRatio < 1 // width is less than height
      ? height * videoAspectRatio
      : width
    : width;
const visibleVideoHeight =
  width > height
    ? videoAspectRatio < 1 // width is greater than height
      ? width * videoAspectRatio
      : height
    : height;

Here, width and height are the computed browser dimensions of the container.

The goal with visibleVideoWidth is to get the scaled down video dimensions, given the container w/h. That then lays as an absolutely positioned div over the video, and the overlay (which has a percentage width/height, as SVG), is placed in that div.

<div class="container" style={{ width, height }}>
  <video />
  <div
    style={{
      position: 'absolute',
      width: visibleVideoWidth,
      height: visibleVideoHeight,
      top: 0,
      bottom: 0,
      left: width / 2 - visibleVideoWidth / 2,
    }}
  >
    <Overlay width={visibleVideoWidth} height={visibleVideoHeight} />
  </div>
</div>

Something isn’t right with my equations, the overlay is spilling outside of the boundaries of my visible video. How do I calculate the position of the overlay properly?

The overlay internally has SVG polygons positioned in specific viewing box. So By scaling the overlay to the visible video w/h, and positioning the absolute div over the video the way I did, I would expect the overlay to fit within the video.

What am I doing wrong?

Value of input.step on illegal value for step attribute

Consider this code

const input = document.querySelector('input[type="number"]');
console.log(input.step); // Outputs: "foo" in Chrome/Safari/Firefox
console.log(input.getAttribute("step")); // Outputs: "foo" in all these three too
<input type="number" step="foo">

I can understand why getAttribute returns foo since that’s expected as there’s no validation performed but why does input.step yield foo. The spec reads so (emphasis mine)

if the rules for parsing floating-point number values, when they are
applied to the attribute’s value, return an error, zero, or a number
less than zero, then the allowed value step is the default step
multiplied by the step scale factor.

and the default step is 1. So why do all the major browsers deviate from the standard? Am I reading the spec wrong or is there some other reason to this behavior?

Timeout during backend unit testing with Vitest

Here the code of my method which is used in the repository which I cover with unit tests.

private async getOrderDataForId(
        orderData: any,
        splitOrders: any,
        responseOrders: any,
        tenant_id: number,
        trackingId?: string,

    ) {
        this.#logger.info({
            trackingId,
            message: "get order data for given orderID - start",
            data: { id: orderData.id, tenant_id: orderData.tenant_id },
        });
        const existingOrderData = await ManufactumCoreOrderService.getOrderById(
            orderData.id,
            orderData.tenant_id,
            trackingId,
        );
        if (!existingOrderData || existingOrderData.length < 1) {
            this.#logger.error({
                trackingId,
                message: "Order doesn't exist with id: ",
            });
            FbxError.throwBadRequest("WMS_Order_3", "Order doesn't exist with id: ");
        }
        const newOrderData = JSON.parse(JSON.stringify(existingOrderData));
        this.#logger.info({
            trackingId,
            message: "get order data for given orderID - end",
            data: newOrderData,
        });
        // optimize order_items
        for (const [key] of Object.entries(splitOrders)) {
            const position = parseInt(splitOrders[key][0].splitorder_position);
            const number = parseInt(splitOrders[key][0].orderId);
            if (key === "1") {
                console.log("=======got into if block");
                
                newOrderData.splitorder_position = position;
                newOrderData.parent_id = orderData.id;
                newOrderData.order_items = [];
                for (const [index] of newOrderData.order_addresses.entries()) {
                    delete newOrderData.order_addresses[index].id;
                }
                for (const [index] of newOrderData.order_partners.entries()) {
                    delete newOrderData.order_partners[index].id;
                    delete newOrderData.order_partners[index].order_id;
                }
                // prepare new order
                newOrderData.splitorder_number = number;
                let total_weight = 0;
                let total_volume = 0;
                for (const splitOrderItem of splitOrders[key]) {
                    const index = existingOrderData.order_items.findIndex(
                        (item: any) => item.article_barcode == splitOrderItem.barcode && item.item_number === splitOrderItem.ManufactumPositionNumber,
                    );
                    if (index < 0) continue;
                    const orderItemData = existingOrderData.order_items[index];

                    orderItemData.amount = parseInt(splitOrderItem.amount);
                    orderItemData.item_number = splitOrderItem.ManufactumPositionNumber;
                    const articleId = orderItemData.article_id;
                    let articleData = await DB.query(
                        "select weight, length, width,height from articles where id = ?",
                        [articleId],
                    );
                    articleData = articleData[0];
                    const weight = articleData.weight;
                    const _total_weight = await this.calculateAnyISOUnitToAnyIsoUnit(
                        "KG",
                        "GRM",
                        weight * orderItemData.amount,
                    );
                    const width = articleData.width;
                    const height = articleData.height;
                    const length = articleData.length;

                    const realVolume = width * height * length;
                    const maxVolume = (realVolume + realVolume * 0.05) * orderItemData.amount;
                    total_volume += maxVolume;

                    total_weight += parseFloat(_total_weight);
                    orderItemData.WMS_Positionsnummer = parseInt(splitOrderItem.WMS_Positionsnummer);
                    if (existingOrderData.order_items[index]) {
                        existingOrderData.order_items[index].WMS_Positionsnummer = orderItemData.WMS_Positionsnummer;
                    }
                    newOrderData.order_items.push(existingOrderData.order_items[index]);
                }
                newOrderData.total_weight = total_weight + 200;
                newOrderData.net_weight = total_weight;
                newOrderData.volume = total_volume;
                // create split order
                this.#logger.info({
                    trackingId,
                    message: `Create split order for order id:${orderData.id} - start`,
                    data: newOrderData,
                });
                const newOrder = await ManufactumCoreOrderService.createOrder(newOrderData, orderData.tenant_id, trackingId, false);
                if (!newOrder) {
                    this.#logger.error({ trackingId, message: "Failed to create order csv." });
                    FbxError.throwInternalError("WMS_Order_4", "Failed to create order csv.");
                }
                this.#logger.info({
                    trackingId,
                    message: `Create split order for order id:${orderData.id} - end`,
                    data: newOrder,
                });
                this.#logger.info({
                    trackingId,
                    message: `Update order id:${orderData.id} - start`,
                    data: newOrderData,
                });
                const updateQuery = "UPDATE orders SET erp_id = "" WHERE id = ?";
                await DB.query(updateQuery, [orderData.id]);
                this.#logger.info({
                    trackingId,
                    message: `Update order id:${orderData.id} - end`,
                    data: newOrder,
                });
            } else {
                console.log("=======got into else block");
                const newOrderManufactum: any = {
                    id: orderData.id,
                    new_order_number: formatNumbers(
                        parseInt(await this.getNewOrderNumber(orderData.tenant_id, "Split")),
                        10,
                    ),
                    erp_id: existingOrderData.erp_id,
                    splitorder_number: number,
                    splitorder_position: position,
                    order_items: [],
                };
                for (const splitOrderItem of splitOrders[key]) {
                    newOrderManufactum.order_items.push({
                        new_order_item_number: await this.checkIfPositionIsStandardInt(
                            splitOrderItem.ManufactumPositionNumber,
                            orderData.id,
                            splitOrderItem.barcode,
                            tenant_id,
                        ),
                        amount: parseInt(splitOrderItem.amount),
                        change_amount: false,
                        WMS_Positionsnummer: parseInt(splitOrderItem.WMS_Positionsnummer),
                    });
                }
                responseOrders.push(newOrderManufactum);
            }
        }
    }

And here the code of the test. As you can see I mocked all async method and DB calls and still facing timeout. specifying different timeouts doesn’t help

describe("getOrderDataForId", () => {
    let repo: any;
    let orderDataMock: any = {
        "id" : 303226,
        "date" : "2024-04-10T14:00:11.000Z",
        "erp_id" : "0089123048",
        "tenant_id" : 4,
        "shipping_service_id" : 2,
        "shipping_type" : "",
        "shipping_priority" : 5,
        "customer_number_erp" : "",
        "payment_method" : "",
        "currency" : "",
        "parent_id" : 4766580,
        "splitorder_position" : 2,
        "splitorder_number" : "98873524",
        "order_status_id" : 47,
        "bill_number" : "",
        "sales_channel" : "",
        "system_id" : 4,
        "created_at" : "2024-04-10T16:00:11.000Z",
        "updated_at" : "2024-04-11T16:11:07.000Z",
        "order_type" : null,
        "order_tracking_number" : null,
        "tracking_id" : null,
        "return_tracking_id" : null,
        "wmsx_status" : "unprocessed",
        "volume_measurement_unit_id" : 5,
        "weight_measurement_unit_id" : 4,
        "volume" : 25.65,
        "total_weight" : 2486.0,
        "incoterms1" : "FH",
        "incoterms2" : "Frei Haus",
        "net_weight" : "2140.000",
        "number_of_packages" : 0,
        "ship_condition" : "Z0",
        "shipping_point" : "V007",
        "sales_organisation" : "0200",
        "warehouse_number" : "HER",
        "desired_delivery_date" : "20240403220000",
        "timezone" : "CET",
        "description" : "{}",
        "custom_attributes_MF" : "{"VSART":"SP","ZTERM":"D201","PAPERTYPE":"AT","BUNDESLAND":"Niederösterreich"}",
        "is_valid" : 1,
        "delivery_type" : "LF",
        "document_status" : null,
        "document_timestamp" : null,
        "carrier_mapping_id" : 2,
        "label_response" : null,
        "Flyer" : null,
        "cod_amount" : null,
        "cod_purpose" : null,
        "ps_sync_id" : null,
        "processed_fine" : null,
        "WMS_Auftragsnummer" : null,
        "WMS_Teil_Auftragsnummer" : null,
        "drop_off_point" : null,
        "error_description" : "Failed to detect carrier. Country short name: AT, sales organisation: 200, VSART: SP, ship_condition: Z0",
        "packaging_id" : null,
        "fine_status" : null,
        "fine_processed" : null,
        "channel_id" : null,
        "channel_sign" : null,
        "channel_no" : null,
        "item_count" : null,
        "warehouse_id" : null,
        "priority" : null,
        "cancel_reason_code" : null,
        "cancel_reason" : null,
        "carrier" : null,
        "merchant_id" : null,
        "integrator" : null,
        "order_items" : [{"id": 2290664, "amount": 1, "article_id": 2939, "article_name": "Balkonkasten Stahl verzinkt gross", "article_barcode": "2050000804168", "article_description": "", "article_weight": 2.14, "erp_id": "000000000000018996", "hazardus_material_number": null, "short_text": "Balkonkasten Stahl verzinkt gross", "sales_unit_id": 1, "sales_unit_iso_measure": "CMT", "item_hierarchy": "000000", "loading_group": "0003", "partial_delivery": "C", "overdelivery_percentage": 0, "underdelivery_percentage": 0, "movement_type": "601", "reference_movement_type": null, "movement_indicator": "L", "cumulated_batch_quantity": "0.000", "distribution_channel": "10", "division": "01", "plant": "0100", "storage_location": "L007", "profit_centre": null, "number_profitability": "0000000000", "sales_item_number": "000000", "item_number": "000010", "sales_document": "0852011163", "sales_document_item": "000010", "sales_document_category": "C", "document_date": "20240402", "order_date_customer": null, "order_date_to_party": "00000000", "date_of_call_off": null, "weight": 2140, "material_type": "HAWA", "article_width": 19, "article_length": 91, "article_height": 15, "article_length_measurement_unit": "CM", "article_weight_measurement_unit": "KG", "WMS_Positionsnummer": "1", "change_amount": 0}],
        "order_addresses" : [{"id": 1060667, "salutation": "Firma", "name": null, "first_name": null, "last_name": null, "full_name": "Schlosserei Bock GmbH", "company_name": "", "street": "Ascherstraße", "street_number": "0180795", "house_number": "10", "postal_code": "2734", "city": "Puchberg am Schneeberg", "email": null, "country_short_name": "AT", "contact": "02636 2303", "floor": null, "room_number": null, "erp_id": "0026824582", "county": null, "address_notes": null, "fax": null, "time_zone": "CET", "address_info": {"AT":{"COUNTRYISO":"AT","LANGU_ISO":"DE"}}},{"id": 1060668, "salutation": "Firma", "name": null, "first_name": null, "last_name": null, "full_name": "Schlosserei Bock GmbH", "company_name": "", "street": "Ascherstraße", "street_number": "0180795", "house_number": "10", "postal_code": "2734", "city": "Puchberg am Schneeberg", "email": null, "country_short_name": "AT", "contact": "02636 2303", "floor": null, "room_number": null, "erp_id": "0026824582", "county": null, "address_notes": null, "fax": null, "time_zone": "CET", "address_info": {"AT":{"COUNTRYISO":"AT","LANGU_ISO":"DE"}}}],
        "order_partners" : null,
        "shipping_service_name" : "DHL",
        "order_status_name" : "Carrier and shipping type are not determined.",
        "order_status_code" : "error_2000",
        "shipped_out_date" : null,
        "invoice_number" : null,
        "weight_measurement_unit" : "G",
        "volume_measurement_unit" : "CDM"
    };
    let responseOrders: any = orderDataMock;
    let splitOrders: any = {
        1: [
            {
                splitorder_position: 1,
                orderId: 123,
            },
            {
                splitorder_position: 2,
                orderId: 124,
            },
            {
                splitorder_position: 3,
                orderId: 125,
            },
        ],
    };
    beforeEach(async () => {
        repo = new ManufactumWmsxOrderRepository();
        ManufactumCoreOrderService.getOrderById = vi.fn().mockResolvedValue(orderDataMock)
        DB.query = vi.fn().mockResolvedValue(orderDataMock);
        DB.query = vi.fn().mockResolvedValue(true);
        repo.calculateAnyISOUnitToAnyIsoUnit = vi.fn().mockResolvedValue(1);
        ManufactumCoreOrderService.createOrder = vi.fn().mockResolvedValue(orderDataMock);
        repo.getNewOrderNumber = vi.fn().mockResolvedValue("0088123456");
        repo.checkIfPositionIsStandardInt = vi.fn().mockResolvedValue("000390");
    })

    test("should update responseOrders array", async () => {
        await repo.getOrderDataForId(orderDataMock, splitOrders, responseOrders, 4);
    })
}, { timeout:10000 })

I’ve tried mocking all async methods and db calls with vi.fn(). Also, tried to change timeout.