npm run build results in an error when I run it in a Dockerised environment

I am trying to host my website through a Docker container but i am facing an issue during the build process.

Following is my Dockerfile:

FROM node:18-alpine AS base

FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN sed -E -n 's/[^#]+/export &/ p' .env.production.local >> .envvars
RUN source .envvars && npm run build

FROM base AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public

RUN mkdir .next
RUN chown nextjs:nodejs .next

COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3001

ENV PORT 3001
ENV HOSTNAME "0.0.0.0"

CMD ["node", "server.js"]

When the build process reaches a line in my code that parses the Firebase Service Key, I get the following error: SyntaxError: Unexpected token t in JSON at position 1. This error does not however occur if I build the website outside the docker env (my local machine).

Following is the parsing code:

const serviceAccountKey = process.env.FIREBASE_SERVICE_ACCOUNT_KEY;

      if (!serviceAccountKey) {
        throw new Error('FIREBASE_SERVICE_ACCOUNT_KEY is missing');
      }

      let saK;

      if (typeof serviceAccountKey === 'string') {
        try {
          saK = JSON.parse(serviceAccountKey);
        } catch (error) {
          console.error('FIREBASE_SERVICE_ACCOUNT_KEY is not a valid JSON', error.stack);
        }
      } else if (typeof serviceAccountKey === 'object') {
        saK = serviceAccountKey;
      }

Why does it fail when my Docker image is building?

How do you reference a type in a statically imported (from html) file while using jsdoc+typechecking/linting?

Consider the following vanillaJS/HTML application:

- index.html
- main.js

Index.html looks like this:

<!doctype html>
<html>
  <head>
    <style>
        body{
            margin: 0px;
            overflow: hidden;
        }
    </style>
    <script src="https://pixijs.download/release/pixi.js"></script> 
    <script src="main.js" type="module" defer></script>
  </head>
  <body>
    
  </body>
  </html>

main.js is as follows:

//@ts-check
const app = new PIXI.Application({ 
    resizeTo:window,
    antialias: true,
    autoDensity: true,
    resolution: 2 });
  document.body.appendChild(app.view);

/**
 * 
 * @param {string} name 
 */
function sayHello(name){
    console.log(`hello ${name}`)
}
/**

the PIXI type def is not found because it is imported in the html. Since this is JS, this doesn’t affect execution, but is annoying in my IDE because it flags this as an error.
Using vanilla JS, I cannot import PIXI without using a bundler which I would really prefer not to do. How do I declare that a type def for PIXI exists somewhere, but not here?

calculate total amount from the sub total( New to JS ) [duplicate]

when ever i change value in Quantity the sub total is calculate. but i need to calculate the total amount also by sum all the sub total values. How to achieve this.

<td contenteditable="true">

                    <input type="text" class="form-control border-0" name="qty_{{ product_item.id }}"
                      value="{{ product_item.quantity }}" oninput="calculateTotal({{ product_item.id }})">
                  </td>
                  <td>
                    <input type="text" class="form-control border-0 total-input" name="total_{{ product_item.id }}"
                      id="total_{{ product_item.id }}" value="{{ product_item.total }}" readonly>
                  </td>

<div>
            <label for="total_amount">Total Amount</label>
            <input type="text" class="form-control border-0 " name="total_amount" id="total_amount_id" value="{{ total_amount }}"
              readonly>
          </div>



function calculateTotal(productId) {
var rate = parseFloat(document.getElementsByName('rate_' + productId)[0].value);
var quantity = parseFloat(document.getElementsByName('qty_' + productId)[0].value);
var total = rate * quantity;

document.getElementById('total_' + productId).value = total.toFixed(2);

}

Wrong length calculation google static image when screen size changes

The task is to calculate the line length between two points, created by the user clicking on the map. The only restriction is I have to use Google Static Map API. The problem is I receive significant delta, which differs from the original Google Maps measure distance functionality.

For example Google Maps:

enter image description here

Google Maps shows that the length between two points is 65.19m, while my program returns a distance of 61.99 m, pretty close but, delta grows if length is bigger. I need at least ~1-meter delta.

Interest thing is, when I change size of browser window length by my algorithm will change, and when there is particular size algorithm works correctly

So here are my steps to calculate line length:

  1. Get points
  2. Convert points X, Y coordinates to lat, lng
    function getLatLng(event)
    {
        var mapContainer = document.getElementById('mapImage');
        let mapWidth = mapContainer.clientWidth;
        let mapHeight = mapContainer.clientHeight;

        var x = event.clientX - (mapWidth / 2);
        var y = event.clientY - (mapHeight / 2);

        var s = Math.min(Math.max(Math.sin(mapCenterLat * (Math.PI / 180)), -.999999), .999999),
            tiles = 1 << mapZoom;

        var centerPoint = {
            'x': 128 + mapCenterLng * (256 / 360),
            'y': 128 + 0.5 * Math.log((1 + s) / (1 - s)) * -(256 / (2 * Math.PI))
        };

        var mousePoint= {
            'x': ((centerPoint.x * tiles) + x),
            'y': ((centerPoint.y * tiles) + y)
        };

        var mouseLatLng = {};
        mouseLatLng['lat'] =  ((2 * Math.atan(Math.exp(((mousePoint.y/tiles) - 128) / -(256/ (2 * Math.PI)))) - Math.PI / 2)/ (Math.PI / 180));
        mouseLatLng['lng'] =  (((mousePoint.x/tiles) - 128) / (256 / 360));

        return mouseLatLng;
    }
  1. Calculate length using lat, lng coordinates
    function calculateDistance(lat1, lng1, lat2, lng2) {
        const earthRadiusKm = 6371; 
      
        const dLat = degreesToRadians(lat2 - lat1);
        const dLng = degreesToRadians(lng2 - lng1);
      
        const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(degreesToRadians(lat1)) * Math.cos(degreesToRadians(lat2)) *
            Math.sin(dLng / 2) * Math.sin(dLng / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      
        const distanceKm = earthRadiusKm * c;
      
        return distanceKm;
      }
      
      function degreesToRadians(degrees) {
        return degrees * (Math.PI / 180);
      }

Here is sandbox with full code: https://codepen.io/losimen/pen/rNPpYMo

Sometimes hover not working as expected in Playwright JS

I am using Playwright’s JS library and am running into some issues with the hover functionality. I am getting a list of locators with the all call. Then I am looping over this list and calling hover on every locator in the list. On hover each element should change color and open a popover. I do this in two different tests that open different sites, but ultimately end up rendering the same html. Both tests are running with chromium. In one test hovering over every element works as expected (color changes and the popover becomes visible). In another test the first element in the list will change color on hover, but will not open the popover. If I manually hover on the second element in the list (which works as expected) and then I loop over all the elements then the hover works as expected on all elements.

Has anyone run into this with playwright before? I’m particularly stumped by the fact that hover works as expected in one test, but not another. Both tests are doing this hover action in an iframe in case that’s important.

My function for getting all the locators:

#getAll = async () =>
        await this.iframe.locator('.qa-hot-buttons-list.p0.m0').getByRole('button').all();

My function in my working test:

for (const button of buttons) {
    await button.hover();
    const buttonPopover = await myController.getActiveButtonPopover();
    await expect(buttonPopover).toBeVisible();
}

My function in my broken test:

await buttons[1].hover();
for (const button of buttons) {
    await button.hover();
    const buttonPopover = await myController.getActiveButtonPopover();
    await expect(buttonPopover).toBeVisible();
}

Accepted Array. What is code for finding 1 operator [closed]

An array is considered as accepted array if all the numbers between max and min element of array are present in the array. If the provided array is not an accepted array, you can do operations in array by replacing any element by any element. What is minimum number of operations required to make this array accepted?

For example, arr = [4, 2, 5, 3] is accepted, but arr = [1, 2, 3, 5, 6] is not accepted.

Example 1

Input [4, 2, 5, 3]

Output 0

Explanation: In the array above minimum element is 2 and maximum element is 5 and all the elements between 2 and 5 (inclusive) are present in array.

Example 2

Input [1, 2, 3, 5, 6]

Output 1

Explanation: In the array above minimum element is 1 and maximum is 6, but 4 is not present in array. We can replace 6 (last element) by 4, which makes array – [1,2,3,5,4], which is an accepted array. In this case we need 1 operation to make the array accepted.

function minOperations(arr) {
  
}

This is the initial code

Animating a collapsible side bar

I’m trying to create a simple page with a menu on one side of the main content. Now I want to make the menu collapsible.

As a proof of concept, consider the following example:

#container {
  display: flex;
  position: fixed;
  height: 100%;
}

#menu {
  background: yellow;
}

#toggle {
  cursor: pointer;
  user-select: none
}

#menu.collapsed .content {
  display: none;
}
<div id="container">
  <div id="menu">
    <div id="toggle" onclick="document.getElementById('menu').classList.toggle('collapsed')">X</div>
    <div class="content">Menu content</div>
  </div>
  <div class="content">Main content goes here</div>
</div>

You can click the X to toggle the menu, which works as intended, but the transition is instant which feels jarring. I would like to make it feel smoother by slowly closing the menu.

One way I found to make it work is by setting an explicit width on the menu and using a transition: width property. The stylesheet becomes:

This sort of works, as you can see here:

#container {
  display: flex;
  position: fixed;
  height: 100%;
}

#menu {
  background: yellow;
}

#toggle {
  cursor: pointer;
  user-select: none
}

#menu.collapsed .content {
  overflow: hidden;
}

#menu .content {
  transition: width 1s;
  width: 100px;
}

#menu.collapsed .content {
  width: 0px;
}
<div id="container">
  <div id="menu">
    <div id="toggle" onclick="document.getElementById('menu').classList.toggle('collapsed')">X</div>
    <div class="content">Menu content</div>
  </div>
  <div class="content">Main content goes here</div>
</div>

I don’t really like this solution for the following reasons (in decreasing importance):

  1. I have to guess the initial width (100px in this example). I would rather that the initial width is derived from the natural width of the content, as happened before. But I can’t just remove width: 100px because then the transition no longer works. And width: 100% doesn’t seem to work correctly either.

  2. While the menu is closing, the text reflows, which looks a little ugly. I’d like to prevent this if possible.

  3. Keeping the menu in the DOM tree with width: 0px might be less efficient than display: none because the browser still has to render it (maybe???)

Is there a better way to animate the closing/opening of the menu?

(I found a related question here: Collapsible flexible-width sidebar using only CSS. That one uses max-width instead of width, which sort of solves issue 1, but it introduces a new problem, namely that if max-width is high, it effectively adds a delay to the transition animation.)

How to use jquery selector to select Bootstrap Modal with {{ $item->id }}

I noticed that when the select2 is in a modal, the search input is not focusable, also the up and down keys are not working too.
jquery: 3.6.1
select2: 4.1.0

i want to use jquery selector to find/select select2 search input in a my bootstrap modal with {{ $item->id }} for example.

<div class="modal modal-end" tabindex="-1" id="edit{{ $item->id }}" aria-labelledby="modalRightLabel">
    <div class="modal-header">
        <h5 id="modalRightLabel">EDIT FRUIT</h5>
        <button type="button" class="btn-close text-reset" data-bs-dismiss="modal " aria-label="Close"></button>
    </div>
    
    <div class="modal-body">
        <form action="/fruit/{{ $item->id }}" method="POST">
           {{ method_field('put') }}
           {{ csrf_field('') }}
    
           <div class="form-group mb-3">
               <label class="form-label">Fruit name</label>
               <input type="text" class="form-control" name="fruit" value="{{ $item->fruit_name}}" placeholder="Fruit Name" required>
                </div>
    
    
            <div class="form-group mb-3">
                 <label class="form-label">Category</label>
                 <select name="category" class="js-example-placeholder-single" required>
                     <option value="{{ $item->id }}">{{ $item->category }}</option>
                     <option value="Berries">Berries</option>
                     <option value="Tropical Fruits">Tropical Fruits</option>
                     <option value="Citrus Fruits">Citrus Fruits</option>
                 </select>
            </div>
    
            <div class="text-center">
                <button type="button" class="btn btn-danger label-btn me-2" data-bs-dismiss="modal" aria-label="Close"><i class="ri-close-line me-2"></i>Cancel</button>
                <button type="submit" class="btn btn-primary"> <i class="ri-checkbox-circle-line me-2"></i> <span>Save Changes</span></button>
            </div>
        </form>
    </div>
</div>

i tried to this

$(function(){
  $('.js-example-placeholder-single').select2({
      dropdownParent: $('#edit{id}')
  });
});

How to trigger the iframe to load in a new tab?

I have a button that loads an iFrame. I would like to provide another button to open and load the iFrame in a new tab. Presently I hae the button to open essentially duplicate the page but not sure how to trigger the loading of the frame:

<button onclick="ViewFolder('f6f906a14')">Open cases below </button>    

<a href="#" target="_blank" rel="noopener"><button target="_blank">Open cases in a new tab</button></a>
    
<iframe id="postdicom-iframe" height="720" width="600"></iframe>

I tried to research some JS to load an iframe in a new tab. I found the tab would show the same page content on the new tab.

Any advice would be appreciated.

Many thanks,
Jack

trustpilot widget sveltekit does not load after changing the page SPA

The widget is rendered only on 1st page load, after clicking on any link and going to another page, it disappears, however onMount triggers on every page load and after any click

the code:

let scriptLoaded = false;

onMount(() => {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js';
  script.async = true;
  script.onload = () => {
    scriptLoaded = true; // Set flag when the script is loaded
  };
  document.body.appendChild(script);
});

{#if scriptLoaded}

Trustpilot

{/if}

I tried afterUpdate, beforeUpdate, with and without scriptLoaded trigger, the result is always the same:
after the 1st page load
after any link click

How to hide specific label and data related to it

In my dynamic chart, I have statistics of venues as separate bars.

Design

What would be the best way to hide labels (venues) and their data conditionally. In a grouped horizontal bar chart (or other).

I tried filtering out the state array of labels saved with a “visible” boolean property and not passing whichever is set to false to the “labels” property in my chart.

This caused the data to be misplaced and appear at wrong index.

Tools for generating pdf report? [closed]

This is a request for an appropriate tool. No code at this juncture.

I have a multi-page dashboard developed in JavaScript. The objects in the dashboard include D3 charts, plotly.js charts, and DataTable tables.

I want to find a library or set of tools that can generate a comprehensive PDF report from the dashboard.

In the dashboard, users can select up to 8 pages with unique items. The pages are rendered on demand. When the user clicks a button to download a PDF report, I want to have all of the objects written to the PDF, regardless of whether they have been rendered.

My thought is to write a serialized object to a “collection array” when a page is rendered (and then generate the PDF using the collection array as the source). But, how do I collect the objects for pages that are not rendered?

Does anyone have suggestions about a pdf library to use?

Any suggestions about how to produce objects that have not been rendered?

Many thanks.

The JavaScript dilemma – Regular expressions [duplicate]

i build regExp to fillter url from as a parameter

et data1="...."
let data2="...."
let data3="...."
let data4="...."
const linkRegex = /(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?/gi;
console.log("1:", linkRegex.test(data1)) // 1: true
console.log("2:", linkRegex.test(data2)) // 2: false
console.log("3:", linkRegex.test(data3)) // 3: true
console.log("4:", linkRegex.test(data4)) // 4: false

why this problem in javascirpt

supposed to four log equal to each other

Function executes twice after the first call – TODO list

I’ve got a problem with my JavaScript TODO program and was hoping someone could point me in the right direction.

I would like to give the user the ability to add ‘Projects‘ that store different todos/tasks.

The problem is after successfully adding the first project, subsequent additions always attempt to add an additional empty string “” project. The issue arises specifically on the second iteration of adding a project.

I have a render.js module with a renderProjects() function that dynamically creates project tabs and a button to add a new project. The event listener for adding a project modal is bound to this button.

I suspect the problem lies in the structure of my code, causing the event listener to be bound multiple times, leading to the unwanted addition of an empty string project.

How can I modify my code to ensure that the event listener is only bound once and that subsequent project additions function correctly?

Live Demo
(If you look at the console after the second proj is added, you should see a console.log which says “project title can’t be empty”)

**Here is my renderProjects function = **

const renderProjects = function() {
        while (tabContainer.firstChild) {
            tabContainer.removeChild(tabContainer.firstChild);
        }

        allProjectsArr.forEach((project, index) => {
            const newTab = document.createElement("button");
            newTab.textContent = `${changeCase(project)}`;
            newTab.classList.add("tab-btn");
            newTab.setAttribute("data-for-tab", `${index + 1}`);
            tabContainer.appendChild(newTab);
        })

        const addProjectBtn = document.createElement("button");
        addProjectBtn.classList.add("add-project-btn");
        tabContainer.appendChild(addProjectBtn);

        const addProjectIcon = document.createElement("img");
        addProjectIcon.src = addFolderImg;
        addProjectIcon.alt = "add folder image"
        addProjectIcon.classList.add("add-project-icon", "nes-pointer");
        addProjectBtn.appendChild(addProjectIcon);

        addProjectBtn.addEventListener("mouseenter", () => {
            addProjectIcon.src = addFolderImgActive;
        })
        addProjectBtn.addEventListener("mouseleave", () => {
            addProjectIcon.src = addFolderImg;
        })
        
        addProjectBtn.addEventListener("click", () => {
            modalController.addProjectModal();   // Is this causing the issue?
        })
    };

**Here is my addProjectModal function =
**

const addProjectModal = function () {
        const addProjectDialog = document.getElementById("add-project-dialog");
        const form = document.querySelector(".add-project-form");
        addProjectDialog.showModal();

        form.addEventListener("submit", (e) => {
            e.preventDefault();
            const warning = document.querySelector(".warning-result");

            // If Cancel - Close & Reset form, if cancel btn pressed
            if (e.submitter.id === "add-project-cancel"){
                addProjectDialog.close();
                form.reset();
                return;
            // If Confirm - Obtain title value & add project
            } else if (e.submitter.id === "add-project-confirm"){
                const title = document.getElementById("add-project_field").value;
                if (title === ""){
                    // Being called twice??
                    console.log("project title can't be empty");
                    return;
                }
                let addedProject = addProject(title);
                if (!addedProject){
                    form.reset();
                    warning.textContent = "Project Name Taken";
                } else if (addedProject) {
                    warning.textContent = "";
                    addProjectDialog.close();
                    form.reset();
                } else {
                    console.log("uh oh ")
                }
            }
        })