How to add a div element inside the parent of a carousel element, without visually shifting the sibling items/divs inside?

I have a horizontal carrousel that im trying to make infinitely scrolling on both directions using the intersection observer api (There are several elements that are visible at once).

However when I add slides, the carrousel expands to the right visually shifting all the elements as well. (With the intersection observer it creates this loop as well, so I hope there is a way to expand the div to the left instead.)

  • I need it to stop shifting all the elements already in the div, is there a way to only shift the new elements?/expand the carrousel to the left direction instead of right?

This is currently how the slides are added to the left:

hmtl
<div class="parentCaros"> <!-- Its so nested, because there will be more than one carrousel-->
    <div class="parentCont">
        <div class="parent">
            <li class="child"></li>
            <li class="child"></li>
            <li class="child"></li>
            <li class="child"></li>
            <li class="child"></li>
            <li class="child"></li>
         </div>
    </div>
</div>`

CSS
.parentCaro{
    width: 100vw;
    height: 30rem;
    display: flex;
    flex-direction: column; /* for the other carousels*/
    justify-content: center;
}

.parent{
    width: fit-content;
    justify-content: center; /* Incase there are less items than the */
    gap: 5rem;
    height: 10rem;
}

li{
    list-style: none;
    border: solid 1px green;
    width:10rem;
    height: 5rem;
}


JS

//________________The observer I made if its relevant_______________
const observaa = new IntersectionObserver(entries => {
      entries.forEach(entry=>{
          entry.target.classList.toggle("up", entry.isIntersecting);
      })
  },
  { 
    rootMargin: "20% -10% 20% -10%",
  });


// _______________________________THIS IS WHERE THE ISSUE ACTUALLY STARTS____________________
let caroBack = document.querySelector("parent");
function loadSlidesA(){
      let u = caroBack.children.length-1
      for (let i = 0; i < 5; i++) {
        const cardBefore = caroBack.children[u].cloneNode(true);
        u--;
        cardBefore.classList.add("up")
        observaa.observe(cardBefore);
        caroBack.insertBefore(cardBefore, caroBack.children[0]) //!!! HI THIS IS WHERE I APPEND
      }
    }

So when I use .insertBefore(), it automatically shifts my items to the right. I hoped there would be a way to append items to an array, without visually shifting items to the right, which subsequently expands the div rightwards.

What is the bug in my collision detection algorithm?

I am creating an Air Hockey game using JavaScript, in which, I am having problems in implementing the collision detection algorithm perfectly. My algorithm takes ‘disc’ which is held by the user’s mouse, and ‘puck’ which is being hit. Note that both can be in motion. Also note that both disc and puck are 2d circles.

I am providing the HTML, CSS and JS files. The collision detection function is written in main.js

(PC only) Run using live-server on VS Code. Click on the bottom disc to interact.

index.html

<!DOCTYPE html>
<html lang = "en">
    <head>
        <meta charset = "UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Air Hockey</title>
        <link href = "stylesheet.css", rel = "stylesheet">
        <link rel = 'icon' type = 'image/x-icon' href = ''>
    </head>
    <body scroll = "no" style = "overflow: hidden;">
        <canvas id = "ca"></canvas>
        <script type = "module" src = "main.js"></script>
    </body>
</html>

main.js

/** @type {HTMLCanvasElement} */

let canvas1 = document.getElementById('ca');
canvas1.height = canvas1.clientHeight;
canvas1.width = canvas1.clientWidth;
let height = canvas1.height, width = canvas1.width;
let ctx = canvas1.getContext('2d');
ctx.strokeStyle = 'black';
ctx.lineWidth = 5;

// Parameters

const timeStep = 1000/100;
let last = 0; // last time step
const rect = canvas1.getBoundingClientRect();
let inGame = {'val' : false} // is canvas active
let cursor = {'X' : 0, 'Y' : 0}; // cursor positions
let prevCursor = {'X' : 0, 'Y' : 0}; // previous cursor positions
let forceFactor = 1.5;

// event listeners

canvas1.addEventListener('click', (e) => {  // click on disc to move, click again to quit
    if(!inGame['val']) {
        inGame['val'] = true;
        cursor['X'] = prevCursor['X'] = e.clientX;
        cursor['Y'] = prevCursor['Y'] = e.clientY;
    }
    else
        inGame['val'] = false;
})

document.addEventListener('mousemove', (e) => {
    if(inGame['val']) {
        prevCursor['X'] = cursor['X'];
        prevCursor['Y'] = cursor['Y'];
        cursor['X'] = e.clientX;
        cursor['Y'] = e.clientY;
    }
})

// Main

class Disc {
    constructor(width, height) {  //  width and height are same as diameter
        this.x = 0;
        this.y = 0;
        this.prevX = 0;
        this.prevY = 0;
        this.height = height;
        this.width = width;
    }
    reset(x, y) {
        this.x = x;
        this.y = y;
        this.prevX = x;
        this.prevY = y;
    }
    upperBoundary() {
        return this.y < this.height*0.5;
    }
    lowerBoundary() {
        return this.y + this.height*0.5 > height;
    }
    leftBoundary() {
        return this.x < this.width*0.5;
    }
    rightBoundary() {
        return this.x + this.width*0.5 > width;
    }
    boundaryCheck() {
        if(this.rightBoundary())
            this.x = width - this.width*0.5;
        else if(this.leftBoundary())
            this.x = this.width*0.5;
        if(this.lowerBoundary())
            this.y = height - this.height*0.5;
        else if(this.upperBoundary())
            this.y = this.height*0.5;
    }
    draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.width*0.5, 0, 2*Math.PI);
        ctx.stroke();
    }
}

class User extends Disc {
    constructor(width, height) {
        super(width, height);
    }
    update() {
        let xDiff = cursor['X'] - prevCursor['X'], yDiff = cursor['Y'] - prevCursor['Y'];
        this.prevX = this.x;
        this.prevY = this.y;
        this.x += xDiff;
        this.y += yDiff;
        prevCursor['X'] = cursor['X'];
        prevCursor['Y'] = cursor['Y'];
    }
}
let user = new User(70, 70);

class Puck extends Disc {
    constructor(width, height) {
        super(width, height);
        this.maxSpeed = 30;
        this.speedX = 0;
        this.speedY = 0;
    }
    reset(x, y) {
        super.reset(x, y);
        this.speedX = 0;
        this.speedY = 0;
    }
    update() {
        this.x += this.speedX;
        this.y += this.speedY;
        let speed = Math.sqrt(this.speedX*this.speedX + this.speedY*this.speedY);
        let cos = Math.abs(this.speedX/speed), sin = Math.abs(this.speedY/speed);
        if(speed > this.maxSpeed) {
            this.speedX = Math.sign(this.speedX)*this.maxSpeed*cos;
            this.speedY = Math.sign(this.speedY)*this.maxSpeed*sin;
        }
    }
    boundaryCheck() {
        if(this.leftBoundary() || this.rightBoundary())
            this.speedX *= -1;
        if(this.upperBoundary() || this.lowerBoundary())
            this.speedY *= -1;
        super.boundaryCheck();
    }
}
let puck = new Puck(50, 50);

user.reset(width*0.5, 0.75*height);
puck.reset(width*0.5, 0.5*height);

function dist(x1, y1, x2, y2) {  // calculates the square of the distance between two points
    return (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);
}

//  comparing distance between centers of disc and puck with sum of their radii to
//  detect collision. Note that instead of dividing RHS with 4, I am multiplying LHS
//  with 4, to avoid floating point errors

function collision(disc, puck) {
    if(dist(disc.x, disc.y, puck.x, puck.y)*4 >= (disc.width + puck.width)*(disc.width + puck.width)) // no collision, return immediately
        return false;
    let dxDisc = disc.x - disc.prevX, dyDisc = disc.y - disc.prevY, dxPuck = puck.x - puck.prevX, dyPuck = puck.y - puck.prevY;  // change in positions in this frame

    // total is the value over which binary search will be performed, greater value of total
    //  will give greater precision
    let total = 1000;
    // ans is the latest time when they have not collided, which we want to find
    // Initial value of ans is 0 which means just start of the frame
    let low = 0, high = total, ans = 0;
    while(high - low >= 1e-3) {  // binary search over this time frame
        let mid = (low + high)*0.5, ratio = mid/total;  //  a point of time in this frame

        //  predicted positions at this point of time
        let discX = disc.prevX + dxDisc*ratio, discY = disc.prevY + dyDisc*ratio;
        let puckX = puck.prevX + dxPuck*ratio, puckY = puck.prevY + dyPuck*ratio;

        if(dist(discX, discY, puckX, puckY)*4 >= (disc.width + puck.width)*(disc.width + puck.width)) {  // no collision till this point of time
            ans = mid;  // record this point of time
            low = mid;  // now search after this point of time
        }
        else  // collision
            high = mid;  // search before this point of time
    }
    // finally changing the positions according to best found value of ans
    let ratio = ans/total;
    disc.x = disc.prevX + dxDisc*ratio;
    disc.y = disc.prevY + dyDisc*ratio;
    puck.x = puck.prevX + dxPuck*ratio;
    puck.y = puck.prevY + dyPuck*ratio;

    // changing velocity according to oblique collision of two spheres

    let relX = puck.speedX - dxDisc, relY = puck.speedY - dyDisc; //  relative velocity
    let normal = Math.sqrt(dist(disc.x, disc.y, puck.x, puck.y)); // line of impact
    let nx = (puck.x - disc.x)/normal, ny = (puck.y - disc.y)/normal; // unit vector
    let rel = relX*nx + relY*ny; // dot product
    puck.speedX -= rel*forceFactor*nx;
    puck.speedY -= rel*forceFactor*ny;
    return true;
}

window.addEventListener('load', function() {
    function animate(timeStamp) {
        const deltaTime = timeStamp - last;
        if(deltaTime >= timeStep) {
            ctx.clearRect(0, 0, width, height);
            ctx.strokeRect(0, 0, width, height);
            
            user.update();
            user.boundaryCheck();
            puck.update();
            puck.boundaryCheck();
            
            collision(user, puck);
            
            user.draw();
            puck.draw();
            last = timeStamp - (deltaTime % timeStep);
        }
        requestAnimationFrame(animate);
    }
    animate(0);
})

stylesheet.css

body {
    background-size: cover;
}
#ca {
    position: absolute;
    left : 37.5vw;
    top: 5.5vh;
    width: 22.8vw;
    height: 79.1vh;
    z-index: 1;
}

According to my algorithm, if a collision is detected, the puck and the disc are placed back to the position at which they are just about to collide. But sometimes the disc and puck get stuck to each other. And the other times, the puck kind of teleports to a the other side of my disc.

HIde the smallest array element on window resize in JavaScript

I am trying to hide the smallest element of my JavaScript array on the window resize event if all rendered elements do not fit within the container width. Unfortunately, the issue I encounter happens to be with the wrong width calculation for the total element width, which makes it hard for me to debug.

const MyBrokenComponent = (props) => {
  const [visibleItems, setVisibleItems] = useState<string[]>(props.preselectedAmounts);
  const containerRef = useRef<HTMLDivElement>(null);
  const containerWidthRef = useRef<number>(0);

  const updateVisibleItems = useCallback(() => {
    const container = containerRef.current;
    if (!container) return;
  
    const buffer = 10; // Buffer to ensure elements fit comfortably
    const containerWidth = Math.floor(container.getBoundingClientRect().width - buffer);
  
    if (containerWidth === containerWidthRef.current) return; // Prevent unnecessary recalculations
    containerWidthRef.current = containerWidth;
  
    const childrenWidths = preselectedAmounts.map((_, index) => {
      const child = container.children[index] as HTMLElement;
      return child ? Math.ceil(child.getBoundingClientRect().width) : 0;
    });
  
    const currentItems: string[] = [];
    let totalWidth = 0;
  
    for (const item of preselectedAmounts) {
      const index = preselectedAmounts.indexOf(item);
      const itemWidth = childrenWidths[index];
  
      if (totalWidth + itemWidth <= containerWidth) {
        currentItems.push(item);
        totalWidth += itemWidth;
      } else {
        break; // Stop adding items when the width limit is reached
      }
    }
  
    setVisibleItems((prevItems) => {
      // Update state only if the visible items actually changed
      if (JSON.stringify(prevItems) !== JSON.stringify(currentItems)) {
        return currentItems;
      }
      return prevItems;
    });
  }, [preselectedAmounts]);
  

  const debouncedUpdate = debounce(updateVisibleItems, 100);

  useEffect(() => {
    window.addEventListener('resize', debouncedUpdate);
    updateVisibleItems();

    return () => {
      window.removeEventListener('resize', debouncedUpdate);
      debouncedUpdate.cancel();
    };
  }, [debouncedUpdate, preselectedAmounts, updateVisibleItems]);
}

  return (
    <Fragment>
    {
        preselectedAmounts?.length > 0 ? 
          <div
           className={`d-fl jc-sb fl-d-r ai-c
           ref={containerRef}
          >
          {
            visibleItems.map((amount) => {
              return <div key={amount}>
                <SomeButton
                  label={amountToCurrency(amount, symbol)}
                />
              </div>;
            })
          }
        </div> : null
      }
    </Fragment>
  )

The updateVisibleItems function clearly contains some redundant variable declarations, or calculations but I can’t really figure out at what point the calculation goes wrong. The core issue is that once JavaScript understands that the items do not fit within the container, it starts adding and removing elements once I continue to scale the browser window down:

enter image description here

Link to div scrolls to a wrong position on a page

I have this page, which has an anchor link to a div, but when I click it the viewport lands far above the top of this div. Also, the reloading of the page doesn’t change viewport position. The page is build using Adobe AEM tool and has multiple third party libraries, so even though I have an access to parts of the code and the assets I am afraid that it might some library that is causing the issue.
I the solutions in other similar questions and they all are not applicable, I am stuck at this point and I don’t know where to start.

How to use seleniumbase get_page_source() to retrieve current html after clicking button?

I’m using python seleniumbase to verify a website. After arriving at a certain url, the html is verified using the self.get_page_source() method.

In the url there is a button to configure the form page. After clicking the button, the screen changes but the url on the browser navigation bar remains the same. Also the self.get_page_source() method is returning the previous html before the button was clicked.

From the browser, using View Page Source just returns the top level html. When inspecting the button element from the browser, the correct html is returned.

How can I use seleniumbase to return the current html after the button click?

Tests for Express middleware fail despite correct function execution

I’m writing tests for an Express middleware function addPagination, which sets a pagination object on the req object. The middleware works correctly during manual testing and in the application, but my Jest tests fail. I’ve added console.logs inside the middleware, and they show that all logic paths are executed as expected during testing.

//other imports...
import { standardResponse } from "@utils/responses";
import { normalizeError } from "@toolbox/common/errors";
import { paginationValidations } from "src/validators/pagination.validator";
import validationResultFormatter from "src/validators/validationResultFormatter";

export const addPagination = (req: Request, res: Response, next: NextFunction) => {
  Promise.all(paginationValidations.map((validation) => validation.run(req)))
    .then(() => {
      const errors = validationResultFormatter(req);
      if (!isObjectEmpty(errors)) {
        res.status(400).json(standardResponse({ isSuccess: false, res, message: "Validation error.", errors }));
        return;
      }

      const { page = 1, pageSize } = (req as unknown as RequestWithQuery<PaginationParamsType>).query;
      req.pagination = {
        skip: (page - 1) * pageSize,
        take: pageSize,
        page: page,
        pageSize: pageSize,
      };

      next();
    })
    .catch((error) => {
      log.error(error);
      res
        .status(500)
        .json(
          standardResponse({ isSuccess: false, res, message: "Failed to fetch company.", errors: normalizeError(error) })
        );
      return;
    });
};

All the tests below fail:

//other imports...
import { addPagination } from "src/middleware/pagination.middleware";
import { standardResponse } from "@utils/responses";
import validationResultFormatter from "src/validators/validationResultFormatter";

jest.mock("@utils/logger");
jest.mock("src/validators/pagination.validator", () => ({
  paginationValidations: [{ run: jest.fn().mockResolvedValue(undefined) }],
}));
jest.mock("src/validators/validationResultFormatter", () => jest.fn());
(validationResultFormatter as jest.Mock).mockImplementation(() => []);

const mockRequest = (query = {}): Partial<Request> => ({ query });
const mockResponse = (): Partial<Response> => {
  const res: Partial<Response> = {};
  res.status = jest.fn().mockReturnValue(res);
  res.json = jest.fn().mockReturnValue(res);
  return res;
};

describe("addPagination", () => {
  let req: Partial<Request>;
  let res: Partial<Response>;
  let next: NextFunction;

  beforeEach(() => {
    req = mockRequest();
    res = mockResponse();
    next = jest.fn();
    jest.clearAllMocks();
  });

  it("should call next when no validation errors are found", async () => {
    (validationResultFormatter as jest.Mock).mockReturnValue([]);
    req.query = { page: "2", pageSize: "10" };

    await addPagination(req as Request, res as Response, next);

    expect(validationResultFormatter).toHaveBeenCalledWith(req);
    expect(req.pagination).toEqual({
      skip: 10,
      take: 10,
      page: 2,
      pageSize: 10,
    });
    expect(next).toHaveBeenCalled();
  });

  it("should return 400 when validation errors are found", async () => {
    (validationResultFormatter as jest.Mock).mockReturnValue([{ field: "pageSize", message: "Page size is required." }]);

    await addPagination(req as Request, res as Response, next);

    expect(res.status).toHaveBeenCalledWith(400);
    expect(res.json).toHaveBeenCalledWith(
      standardResponse({
        isSuccess: false,
        res: res as Response,
        message: "Validation error.",
        errors: [
          {
            field: "pageSize",
            message: "Page size is required.",
          },
        ],
      })
    );
    expect(next).not.toHaveBeenCalled();
  });

  it("should return 500 on promise rejection", async () => {
    const error = new Error("Something went wrong");
    const mockRun = jest.fn().mockRejectedValueOnce(error);
    jest.mock("src/validators/pagination.validator", () => ({
      paginationValidations: [{ run: mockRun }],
    }));

    await addPagination(req as Request, res as Response, next);

    expect(log.error).toHaveBeenCalledWith(error);
    expect(res.status).toHaveBeenCalledWith(500);
    expect(res.json).toHaveBeenCalledWith(
      standardResponse({
        isSuccess: false,
        res: res as Response,
        message: "Failed to fetch company.",
        errors: expect.any(Object),
      })
    );
    expect(next).not.toHaveBeenCalled();
  });
});

It seems like none of the mocked function calls are being made:

expect(jest.fn()).toHaveBeenCalledWith(...expected)   
Expected: {"query": {"page": "2", "pageSize": "10"}}
Number of calls: 0
    
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: 400
Number of calls: 0
    
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: [Error: Something went wrong]
Number of calls: 0

Why are my Jest tests failing to detect the expected calls even though the middleware works correctly? Is there an issue with how I’m mocking dependencies or setting up the test environment?

Rotate Border Radius

A photo from the site I’m building.

Hi friends,
I want to style the button to look like the first image, but unfortunately, no matter what I try, I can’t round the corners of the image. Only the top-left corner becomes rounded. How can I fix this? I’d really appreciate your guidance. Thank you!

A site I made myself.

<div class="image-container">
<img src="Images/m7_banner_01.jpg" alt="Your Image" class="hover-image">
<div class="text-overlay">
<p class="mute">کت و شلوار زنانه</p>
<h3>زرق و برق بی انتهای مخصولات تاکسیدو</h3>
<p class="mute">لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با
                                            استفاده از طراحان گرافیک است.</p>
</div>
<div class="bg-banner-btn">
<button class="btn-bottom-right">مشاهده و خرید</button>
</div>
</div>
.image-container {
    position: relative;
    overflow: hidden;
    display: inline-block;
    margin: 10px 5px;

    border-radius: 20px;
}

.image-container img {
    display: block;
    width: 100%;
    height: auto;
}
.hover-image {
    width: 100%;
    transition: transform 0.7s ease;
}

.image-container:hover .hover-image {
    transform: scale(1.1);
}

.text-overlay {
    position: absolute;
    top: 20px;
    right: 30px;
    width: 50%;
}

.btn-bottom-right {

    padding: 10px 20px;
    background-color: black;
    color: white;
    border: none;
    border-radius: 20px 20px 20px 20px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    /* border: 20px solid white; */
}

.bg-banner-btn {
    background-color: white;
    border-radius: 30px 30px 0px 0px;
    padding: 10px 0 0 10px;
    position: absolute;
    bottom: 0px;
    right: 0px;
}

.btn-bottom-right:hover {
    background-color: #424649;
}

use webcomponent as replacement for iframe

Since I could not get iframes to work in browsers on ios, I am trying to replace the functionality of the iframe with a webcomponent:

class EmbeddedWebview extends HTMLElement {
  connectedCallback() {
    fetch(this.getAttribute('src'))
      .then(response => response.text())
      .then(html => {
        const shadow = this.attachShadow({ mode: 'closed' });
        shadow.innerHTML = html;
      });
  }
}
 
window.customElements.define(
  'embedded-webview',
  EmbeddedWebview
);

and then use it in html as follows:

<embedded-webview src="a/b/index.html"></embedded-webview>

This works, except when the site with the embedded-webview tag is loaded a different path, e.g. root (e.g. /index.html) the included content tries to load assets (e.g. css, etc) from the wrong url.

How can I solve this issue? Is there a way to set the origin of the innerHTML?

Code refuses to continue after injecting website with script -Selenium

So this is my code:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

script = """
(() => {
    let clickCount = 0;  // Track total clicks
    const interval = setInterval(() => {
        const buyButton = document.getElementById('TheBuyButton');
        const winningsElement = document.getElementById('numWinnings8');

        buyButton.click();
        clickCount++;

        // Check the winnings value
        const reward = winningsElement.innerText;
        console.log(`Click #${clickCount}: Winnings = ${reward}`);
        
        // Stop if it changes to "1" (indicating a win)
        if (reward === "1") {
            clearInterval(interval);
            document.body.setAttribute("data-status", "won");
            console.log(`Win detected after ${clickCount} clicks!`);
        }
    }, 0);  // 0ms delay for speed
})();
"""
clickslist = []
for i in range(2):
    options = webdriver.EdgeOptions()
    options.add_argument("--headless") 
    options.add_argument("--mute-audio")
    browser = webdriver.Edge(options=options)

    browser.get("https://www.skrabejulekalender-simulator.dk/game.php")

    for j in range(2):
        element = browser.find_element(By.ID, "menuButton")
        element.click()
    
    print("Im here")
    browser.execute_script(script)
    print("Im here now")

    while True:
        status = browser.execute_script("return document.body.getAttribute('data-status');")
        clicksCheck = browser.execute_script("return document.getElementById('numCalenders').innerText;")

        if status == "won":
            print("Win detected! Exiting loop.")
            clicks = browser.execute_script("return document.getElementById('numCalenders').innerText;")
            clickslist.append(clicks)
            break
        time.sleep(2)
        print(f"number of clicks: {clicksCheck}")
        

    browser.save_screenshot(f"Screenshot_{i}.png")
    print("Screenshot saved.")
    browser.quit()

k = " stk."

newList = [int(ele.replace(k,'')) for ele in clickslist]
print(newList)
print(f"average clicks till win: {sum(newList)/len(newList)}")

I’ve been trying for the past hour to make this work, but it just doesn’t seem to go past: “browser.execute_script(script)”. I’m running it on a Danish scratch card simulator. I want to see how many “scratch cards” it takes to get the 1 million reward. Thing is, the likelihood of getting a 1 million scratch card is so low that it takes a long time. Due to that Selenium ends up timing out, and I get a timeout error. How can I avoid this?

I tried polling, so Selenium shouldn’t be “connected” to the server browser and it should be running independently and then Selenium will do some calls here and there (every 2 seconds) to check if it got a 1 million scratch card. Thing is even when I get the error, the website still runs the script, so it is independent of Selenium. The script also makes it stop, which works too.

Problem is that I need to do it for a long time with the 1 million scratch card, and I need to get past “browser.execute_script(script)” so I can actually get the amount of clicks, and append it to the clickslist and eventually see what I get.

When I run the program for a more common reward, it does go past the “browser.execute_script(script)”. I’m doing something wrong, but I can’t see it or maybe Selenium isn’t the right module for me

Are there any alternatives to .env files that make it possible to modify configuration in production?

I’m creating a new app using Vite. The app needs a baseURL to communicate with an external API.

One could use .env files for local dev and environment variables for production ( https://vite.dev/guide/env-and-mode.html#env-variables-and-modes ), so I could pass in the baseURL in my CI/CD pipeline.

But since there are several app deployments on different systems I would have to create one build per system with the correct baseURL environment variable.

It would be better to be able to modify this baseURL configuration somewhere in production.

Are there any solutions to this?

I thought about passing in the baseURL as a URL parameter but my app got routing, things get tricky when I have to take care of passing the baseURL parameter to the next route..

How can I style XML to render the source in broswers?

I understand this is a niche question. I have need for a client side web app to show the user some XML. The default XML renderer (say as a data:text/xml,… based iframe) in most browsers is perfect for this except they place a message at the top of the document:

This XML file does not appear to have any style information associated with it. The document tree is shown below.

How can I instruct the browser to shoe the document tree but without the missing style information warning?

With a Next.js application, how can I prevent or detect failures due to incomplete file loading?

I’m currently working with a Next.js-based frontend system using fairly vanilla configuration options.

Recently I’ve run into some issues where the application is effectively broken to end users because one or more of the JS/CSS files hasn’t loaded properly. For example, a page isn’t usable because the key CSS file doesn’t load, and the page looks mangled. Or the user’s browser fails to load an incremental JS file, and so when they click into a different tab, the tab superficially loads, but (because the JS file was requested and didn’t pull correctly from the server) doesn’t actually work.

Is there a way to improve this robustness?

For example, is there a way to hint Next.js to have Webpack bundle everything into one file? (So that when it fails, the user is implicitly prompted to reload, and when that succeeds they’ll get everything.) Or is there a plug-in that more proactively checks for load failures and can retry in the case where a chunk of JS/CSS fails to pull from the server?

I saw a variety of standalone tools like RequireJS (http://requirejs.org), but my understanding is that those basically conflict with things that the Next.js framework is already doing to package and bundle files together.

Videos Not Loading in Telegram WebView: Triggering JavaScript Execution on Page Load

Good evening, everyone.

I came across the need to place around 10 video files on a website (to showcase app functionality), with a total size of about 10 MB. The website itself is quite fast.

However, there’s a problem: when accessing the website through a link in Telegram, only the first video loads, while the others do not (it opens in the WebView, of course). The remaining videos only start loading if I interact with the page (tapping multiple times on the screen or scrolling through a slider).

Has anyone encountered a way to trigger JavaScript execution immediately after the page loads?

I’ve tried various methods like listening for scroll events, touch interactions, etc., but none of them seem to work.

  1. IntersectionObserver: Attempted to preload and play videos as they approach the viewport, adjusting rootMargin and threshold.

  2. Event-Based Triggers: Implemented scroll, touchstart, and pointerdown events to manually trigger video loading or simulate interaction.

  3. Forced Interaction Simulation: Tried forcing synthetic user interactions using JavaScript to “wake up” the WebView’s JavaScript engine.

  4. Immediate JS Execution: Added basic scripts to force activity on page load, such as toggling classes or logging events.

  5. Different Video Attributes: Experimented with data-src, preload, autoplay, and other video attributes for lazy loading and manual play.

Unfortunately, none of these reliably resolved the issue in the Telegram WebView.

How to simply generate N colors?

I’m using D3 7.9 and can’t find a way to simply generate N colors, for example, from rainbow. How do you do that outside the D3 way of doing things?

For example;

const categories = ['a', 'b', 'c', ..., ]
const n = parseFloat(categories.length);
const colors = d3.sequentialScale(d3.rainbowInterpolation);
const palette = categories.reduce((acc, category, i) => {
    return Object.assign(acc, {[category]: colors(parseFloat(i) / n});
 }

Error about Context when running react native for web

I’m trying to run my react navite app on Web and I get this error:
It works fine on iOS but when I try to add Stack.Navigator it just starts compalaining about Context.

undefined is not an object (evaluating 'Context._context')
useContext@
SafeAreaProviderCompat@
renderWithHooks@
mountIndeterminateComponent@
callCallback@
dispatchEvent@[native code]
invokeGuardedCallbackDev@
invokeGuardedCallback@
beginWork$1@

Here’s my sample app
App.web.tsx:

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { SafeAreaProvider } from 'react-native-safe-area-context'; // You may need this for safe area handling
import { View, Text } from 'react-native';

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    // Wrapping with SafeAreaProvider for safe area support
    <SafeAreaProvider>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Details" component={DetailsScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </SafeAreaProvider>
  );
}

Here’s my Webpack
webpack.config.js:


const path = require('path');

module.exports = {
  entry: './index.web.js', // Point to the root-level index.js
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  resolve: {
    alias: {
      'react-native-linear-gradient': path.resolve(
        __dirname,
        './react-native-linear-gradient.mock.js'
      ),
      'react-native-safe-area-context': path.resolve(
        __dirname,
        './react-native-safe-area-context.mock.js'
      ),
      'react-native': 'react-native-web',
      'react-native-reanimated': 'react-native-reanimated/lib/reanimated2',
    },
    extensions: ['.js', '.jsx', '.tsx'],
  },
};

Anybody seen this issue before?