auto-hyperlinking a url in text

I have a situation like

<td><a href="http://www.bar.com/">http://www.bar.com</a>http://www.other.com/</td>

And I have a regular expression set up to capture urls

But is there any reliable way to link link up the other URL? I was thinking I could use .innerHTML, but that is going to catch links that are already linked up. And if I just use textContent, find the url and replace it, how can I set this back to the td without wiping out the bar link? I am not looking for a solution to this specific problem, but a general solution for where an element may have a url but also have other element children (that might also contain url text or in their html/hrefs).

I could go node by node, but this is not reliable – the text could be broken up into multiple nodes, or?

I’d like to auto-link up discovered URLs that aren’t already linked, but I can’t think of a reliable way to do this. Does anyone have a solution to this problem?

Illegal return statement when importing class from Node.js

I’m running Node.js from VS Code. I copied the Color class from this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_classes

Here is the color.mjs:

export class Color {
  #values;
  // …
  toString() {
    return this.#values.join(", ");
  }
}

And then, I import this class from app.js:

import { Color } from "./color.mjs";

Here is the error:

Uncaught SyntaxError SyntaxError: Illegal return statement
    at compileSourceTextModule (<node_internals>/internal/modules/esm/utils:338:16)
    at moduleStrategy (<node_internals>/internal/modules/esm/translators:102:18)
    at #translate (<node_internals>/internal/modules/esm/loader:468:12)
    at loadAndTranslate (<node_internals>/internal/modules/esm/loader:515:27)
    --- await ---
    at runEntryPointWithESMLoader (<node_internals>/internal/modules/run_main:138:19)
    at loadESMFromCJS (<node_internals>/internal/modules/cjs/loader:1329:42)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1536:5)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1706:10)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1289:32)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1108:12)
    at traceSync (<node_internals>/diagnostics_channel:322:14)
    at wrapModuleLoad (<node_internals>/internal/modules/cjs/loader:220:24)
    at executeUserEntryPoint (<node_internals>/internal/modules/run_main:170:5)
    at <anonymous> (<node_internals>/internal/main/run_main_module:36:49)
utils:338
No debugger available, can not send 'variables'

Why can’t I import class in app.js? What’s missing in my code? And how to fix?

React Native Dropdown Picker Category

I am a complete beginner and I am building an inventory app in react native. I came across this external library called Dropdown Picker. I managed to make it work but I just want to ask how can I include categories?

For example:

I want to have two dropdowns; one for category selection and one for specific item selection

I can’t seem to comprehend what is said on the docs because it only says to include a parent property to use categories. I want something like when the first drop down (for category) is given a selection the second dropdown (for specific item) will display the category’s children./

Thank you! Have a great day!

    export const items = [
  { label: "Cement", value: "cement", parent: "form_works" },
  { label: "Steel Rebar", value: "steel_rebar", parent: "steel_works"  },
  { label: "Coco Lumber", value: "coco_lumber", parent: "form_works"  },
  { label: "Sand", value: "sand", parent: "masonry_works"  },
  { label: "Gravel", value: "gravel", parent: "masonry_works"  },
  { label: "Plywood", value: "plywood", parent: "form_works"  },
  { label: "Concrete Mix", value: "concrete_mix", parent: "masonry_works"  },
  { label: "Paint", value: "paint", parent: "architectural_works"  },
  { label: "Nails", value: "nails", parent: "form_works"  },
  { label: "Bricks", value: "bricks", parent: "masonry_works"  },
];

[JavaScript]I want to add watermark to photo like this in Vue, is there any code sample or module I could use?

Problem:

  1. I am building an h5 based app.

  2. There is an Application called Zebra that offers good-looking watermark like this.

  3. What is the sample code that I could use to achieve effects like this.

I would like watermark like this one.

Currently there is a problem uploading picture to overflow.

enter image description here

The image link is as below: https://imgur.com/a/Ok9o6hg

I tried to upload the picture here, but failed.

How to use pdfjs FindController to navigate between matches programmatically?

I am using PDF.js to display PDFs in my React project. I have implemented a search bar that allows users to search for text within the PDF. However, I want to add Next and Previous buttons to navigate between search results and bring the matched text into view.

Here’s what I have so far:

  1. I am using PDFFindController for text search.
  2. I have a search function that highlights all matches.
  3. I added navigation buttons but don’t know how to trigger movement
    between results.

Here’s the relevant code:

eventBus.dispatch('find', {
  query: searchTerm,
  caseSensitive: false,
  highlightAll: true,
  findPrevious: false,
});

And for navigating between matches, I tried:

eventBus.dispatch('again', {
  query: searchTerm,
  caseSensitive: false,
  highlightAll: true,
  findPrevious: false, // or false for next match
});

But this doesn’t work as expected. How can I properly navigate through search results and ensure that the matched text is scrolled into view in PDF.js?

Any guidance or examples would be really helpful! Into View. is there a way to do it.

How to make Material UI sidebar slide and push?

I created a React app that uses a sidebar that is supposed to ease-in-out, but it doesn’t. It just pops in while successfully pushing the content to the right, and pops out when clicked again.

The code uses

  transition: transform 0.3s ease-in-out; 
  transform: translateX(-250px);

to move the sidebar on and off canvas. But it doesn’t seem to be working in the sandbox example. It does work in my real app, but not animated.

Here’s a pic that shows expanded

enter image description here

This one shows it collapsed:

enter image description here

Notice that the sidebar is all white. I can’t get it to be a different color.

I’ve looked at many other examples but they all have issues that I don’t like. I want the button to remain in place when the tray below it slides in and out. Most examples push the header over too, which requires you to move the mouse over to a different spot to close it.

I’d also like the user to have the option of having the sidebar close after selection, or remain open.

I’ve created a small sandbox example. I ported a snipped from the main app, but now the content goes under the menu instead of to the right of it. I hope one of you experts can show me what I’m missing!

Why does this react-bootstrap DropdownButton menu not properly load only on the first click?

I’m working on the Snow Today code repository over at https://nsidc.org/snow-today/snow-viewer and have run into a very confusing and frustrating bug.

When you load the map by clicking “Western United States” and click the “Select A Region” button, the dropdown menu does not initially load unless the button is clicked two more times, or you scroll on the page a little.

On the backend, the button is a react-bootstrap DropdownButton, but the weird part is that the rest of the buttons are also DropdownButtons, but do not experience this issue.

Does anyone have any insight to go about fixing this problem?

can not make a multi form post request via JS run without error

  1. First Question

I have a route tested in insomnia which is working
The route is sent aswith multiform option
also, I have to setchange the preferences in insomnia not to validate SSL

However, I can not make it work on JS

import FormData from 'form-data';
import fetch    from 'node-fetch';
import  https   from 'https';

// process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

const form = new FormData();
form.append("...", "...");
form.append("...", "...");
form.append("...", "...");
form.append("...", "...");

// Following block is to bypass wht authorization
const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001',
    // 'User-Agent': 'insomnia/2023.5.8',
    'agent': httpsAgent,  // This Line is to bypass wht authorization
  }
};

options.body = form;

fetch('https:XXXXX', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

If I dont add form-data, I can not make a multiform option
If I dont add httpAgent, I can not avoid SSL from been verified.
Still, the request sends an error in token.

What am I doing wrong?
How to bypass ALL this requirements

  1. Second Question
    As I said before, I have this route running properly under insomnia
    How can I make to invoke a specific request (from outside INSOMNIA) and make it execute every XXX seconds? Can this be done automatically?

TIA

Smooth OverlayScrollbars scroll from fixed header wheel event in React

I’m building a React application using TypeScript and overlayscrollbars-react to handle scrolling for the main content area. Above this scrollable content, I have a fixed header component (HeaderApp).

Goal:

I want the user to be able to scroll the OverlayScrollbars container even when their mouse cursor is hovering over the fixed HeaderApp. The desired scrolling behavior should be smooth, ideally matching the native feel of scrolling directly within the OverlayScrollbars viewport.

Problem:

Naturally, wheel events over the fixed header don’t scroll the underlying content. Following recommendations (like in OverlayScrollbars GitHub Issue #150), I’m capturing the wheel event on the HeaderApp, preventing its default action, and then programmatically scrolling the OverlayScrollbars container.

However, achieving smooth scrolling comparable to the native OverlayScrollbars behavior has proven difficult.

What I’ve Tried:

  1. Manual Animation with requestAnimationFrame: This approach feels the
    closest, but it’s still not perfect – the scrolling can feel
    slightly jerky or disconnected from the native scroll feel,
    especially with small, single wheel movements.

Here’s the relevant code from my HeaderApp.tsx component:

// Simplified HeaderApp component structure
import React, { useRef, useEffect, useCallback } from 'react';
import type { OverlayScrollbars } from 'overlayscrollbars';
// osGlobalInstance is obtained from the ScrollableContainer component
import { osGlobalInstance } from "../ScrollableContainer/ScrollableContainer";

const HeaderApp: React.FC<HeaderAppProps> = (/*...props*/) => {
const headerRef = useRef<HTMLDivElement>(null);

// Function for smooth scroll animation
const scrollContent = useCallback((deltaY: number) => {
    if (osGlobalInstance) {
        const { scrollOffsetElement } = osGlobalInstance.elements();
        if (!scrollOffsetElement) return;

        // Cancel any previous animation frame for this specific scroll action
        // (Requires managing animation frame IDs - simplified here)
        // cancelAnimationFrame(animationFrameIdRef.current);

        const targetScrollTop = scrollOffsetElement.scrollTop + deltaY;
        const duration = 300; // Animation duration
        const start = scrollOffsetElement.scrollTop;
        const startTime = performance.now();

        const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);

        const smoothScrollStep = (currentTime: number) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const easing = easeOutCubic(progress);

            scrollOffsetElement.scrollTop = start + (targetScrollTop - start) * easing;

            if (progress < 1) {
               requestAnimationFrame(smoothScrollStep);
               // Store animationFrameIdRef.current = requestAnimationFrame(...)
            }
        };

        requestAnimationFrame(smoothScrollStep);
         // Store animationFrameIdRef.current = requestAnimationFrame(...)
    }
 }, []); // Dependency on osGlobalInstance if it changes

 // Wheel event handler on the header
 const handleWheel = useCallback((event: WheelEvent) => {
    if (osGlobalInstance) {
        // Prevent default page scroll and stop propagation
        if (event.cancelable) {
            event.preventDefault();
        }
        event.stopPropagation(); // Prevent event from bubbling further if needed

        // Adjust sensitivity if necessary
        const scrollAmount = event.deltaY * 1.5; // Example multiplier

        scrollContent(scrollAmount);
    }
 }, [scrollContent]); // Dependency on scrollContent

 // Attach wheel listener
 useEffect(() => {
    const headerElement = headerRef.current;
    if (headerElement && osGlobalInstance) {
        headerElement.addEventListener('wheel', handleWheel, { passive: false });
    }
    return () => {
        if (headerElement) {
            headerElement.removeEventListener('wheel', handleWheel);
        }
    };
 }, [osGlobalInstance, handleWheel]); // Dependencies

 return (
    <motion.header ref={headerRef} /* ...other props */ >
        {/* Header content */}
    </motion.header>
 );
};

export default HeaderApp;

// In ScrollableContainer.tsx (simplified):
// export let osGlobalInstance: OverlayScrollbars | null = null;
// ...
// const handleInitialized = (instance: OverlayScrollbars) => {
//     osGlobalInstance = instance;
//     // ...
// };
// ...
// <OverlayScrollbarsComponent events={{ initialized: handleInitialized }} ... >
  1. Using scrollOffsetElement.scrollBy({ behavior: ‘smooth’ }): This
    seemed promising, but calling it rapidly from the stream of wheel
    events caused the browser’s smooth scroll animation to stutter and
    interrupt itself, resulting in very jerky movement. Throttling the
    calls helped slightly but didn’t fully resolve the jerkiness.

  2. Using scrollOffsetElement.scrollBy({ behavior: ‘auto’ }) (with
    Throttling): This avoids the animation interruption issue, but the
    resulting scroll is instantaneous for each step, lacking the desired
    smoothness.

Question:

How can I achieve a truly smooth, native-feeling programmatic scroll of an OverlayScrollbars container triggered by wheel events on a separate fixed element (like a header) in React?

Is there a better way to implement the requestAnimationFrame loop to handle the stream of deltaY values more gracefully? (e.g., adjusting target dynamically, better cancellation).

Is there an OverlayScrollbars API feature or specific technique I’m missing for this scenario?

What is the best practice for translating high-frequency wheel events into a smooth scroll animation within a custom scroll container like OverlayScrollbars?

Any help or pointers would be greatly appreciated!

How do I stream non-critical data?

I have a CSR app with the following route definitions:

const router = createBrowserRouter([
  {
    path: '/app/',
    element: <NavBar />,
    loader: navBarLoader,
    children: [
      {
        path: 'placement-selection',
        Component: PlacementSelection,
        loader: placementSelectionLoader,
        children: [
          {
            path: 'options',
            Component: PlacementSelectionOptions,
            loader: placementSelectionOptionsLoader,
            children: [
              {
                path: 'summary',
                Component: PlacementSelectionOptionsSummary,
                loader: placementSelectionOptionsSummaryLoader,
              },
            ],
          },
        ],
      },
    ],
  },
]);

And the following loaders:

export async function navBarLoader() {
  console.log('called navBarLoader')
  return await new Promise((res, rej) => {
    setTimeout(() => res('response'), 2000)
  })
}

export async function placementSelectionLoader() {
  console.log('called placementSelectionLoader')
  return await new Promise((res, rej) => {
    setTimeout(() => res('response'), 2000)
   })
}

export async function placementSelectionOptionsLoader() {
  console.log('called placementSelectionOptionsLoader')
  return await new Promise((res, rej) => {
    setTimeout(() => res('response'), 2000)
  })
}

export async function placementSelectionOptionsSummaryLoader() {
  console.log('called placementSelectionOptionsSummaryLoader')
  return new Promise((res, rej) => {
    setTimeout(() => res('response'), 10000)
  })
}

This is how PlacementSelectionOptionsSummary is using the loader data:

import { Suspense } from 'react';
import './styles.css';
import { Await } from 'react-router';

export default function PlacementSelectionOptionsSummary({ loaderData }) {
  return (
    <>
      <Suspense fallback={<div>Loading...</div>}>
        <Await resolve={loaderData}>
          {value => <h3>Non critical value: {value}</h3>}
        </Await>
      </Suspense>
      <div className="main-container" style={{ width: '30%' }}>
        <div className="container" style={{ height: '500px' }}>
          <div className="card" style={{ backgroundColor: 'blue' }}>
            <span className="description">
              {' '}
              'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean
              tempor ante ligula, id aliquet ligula laoreet id. In aliquam
              hendrerit mauris, at sagittis tortor efficitur non. Proin egestas
              facilisis augue. Sed aliquet maximus tempus. Nullam ornare
              efficitur blandit. Sed eu mattis tortor. Lorem ipsum dolor sit
              amet, consectetur adipiscing elit. Aenean tempor ante ligula, id
              aliquet ligula laoreet id. In aliquam hendrerit mauris, at
              sagittis tortor efficitur non. Proin egestas facilisis augue. Sed
              aliquet maximus tempus. Nullam ornare efficitur blandit. Sed eu
              mattis tortor',
            </span>
          </div>
        </div>
      </div>
    </>
  );
}

As you can see, placementSelectionOptionsSummaryLoader takes 10 seconds, where all others take 2 seconds.

Based on what’s mentioned here: https://reactrouter.com/how-to/suspense, I figured that all I need to do was to just return the Promise directly, which I am doing for this loader.

Still, the UI for the route /app/placement-selection/options/summary waits for all of these loaders to “finish” before the UI renders.

How can I get most of the UI to render, and then only have PlacementSelectionOptionsSummary render a fallback until it’s slow-10-seconds-loader finishes?

Javascript radio button price change giving garbage answer

I’ve been busy working on a Shopify website page alongside a co-worker, who has tried to add radio buttons to change the output price on a purchasing page, however instead of adding to the base price, it just gives a garbage value as an output (the garbage value being & pound;0.00, when it should be adding £2 to the base price), I’ve looked at the script and I’m a bit stumped, the only indicated from Shopify being that newPrice in t: price: newPrice on line 17 is an unknown object.

Any pointers to a fix or better solution would be greatly appreciated.

<script>     
    var radioButtons = document.querySelectorAll('input[type="radio"]');
    var priceDisplay = document.querySelector('.product-price'); // Replace with your price element selector
    var basePrice = {{ product.price | money_without_currency }}; // Get the base price from Liquid

    radioButtons.forEach(function(button) {
      button.addEventListener('change', function() {
        var selectedValue = this.value;
        var newPrice = basePrice;

         if (selectedValue === 'without core drops') {
          newproductprice = +0;  //Increase price by £0 for without core drops
        } else if (selectedValue === 'with core drops') {
          newproductprice = +2;  //Increase price by £2 for with core drops
        } 

        priceDisplay.textContent = "{{ 'products.general.from' | t: price: newPrice | money }}";
      });
    });
</script>

Cross-origin resource sharing error wildcard origin not allowed when i use auth request to my server ngrok

I am writing and testing a full-stack application. My frontend is uploaded to hosting and has the address for example – planner. And my server is on a local computer with a database. For the test, I run the server through the ngrok tunnel, I registered, and received a free static domain for example – grateful.
In requests, I use axios, I have public requests – $public, and authorized with a token – $auth. Public requests work without problems, but for requests with authorization I get a CORS error. This error is in both desktop Google Chrome and mobile Google Chrome, in Microsoft Edge, and also in Safari on the iPhone.
My CORS ERROR is: cross-origin resource sharing error wildcard origin not allowed


I am sending next code

  1. axios request settings
  2. CORS settings on the server
  3. as well as responses in the Google Chrome browser to an authorized request, as well as the response from the Microsoft Edge browser.

  1. const $auth = axios.create({
    baseURL: “grateful”,
    withCredentials: true,
    });
    const $public = axios.create({
    baseURL: “grateful”,
    withCredentials: true,
    });
    $auth.interceptors.request.use((config) => {
    config.headers.Authorization = Bearer ${localStorage.getItem( "accessTokenPlanner" )};
    return config;
    });

  2. const allowedOrigins = [
    “planner”,
    “grateful”,
    ];

    app.use(
    cors({
    origin: function (origin, callback) {
    if (!origin || allowedOrigins.includes(origin)) {
    callback(null, true);
    } else {
    callback(new Error(“CORS not allowed”));
    }
    },
    credentials: true,
    methods: [“GET”, “POST”, “PUT”, “DELETE”, “OPTIONS”],
    allowedHeaders: [“Content-Type”, “Authorization”],
    })
    );

  3. Google chrome
    access-control-allow-origin: *
    content-length: 2906
    content-security-policy: default-src ‘self’ https://cdn.ngrok.com ‘unsafe-eval’ ‘unsafe-inline’; img-src data: w3.org/svg/2000
    content-type: text/html
    date: Thu, 27 Mar 2025 14:43:11 GMT
    referrer-policy:no-referrer
    x-content-type-options:nosniff

    MS Edge
    access-control-allow-origin:*
    content-length:2906
    content-security-policy:default-src ‘self’ https://cdn.ngrok.com ‘unsafe-eval’ ‘unsafe-inline’; img-src data: w3.org/svg/2000
    content-type:text/html
    date:Thu, 27 Mar 2025 15:31:51 GMT
    referrer-policy:no-referrer
    x-content-type-options:nosniff

I checked all the link addresses and rewrote the settings several times.
The most interesting thing is that with these settings that I wrote above, everything works periodically in the desktop version of Google Chrome. But now it doesn’t work anymore, although I didn’t change anything.

Recursively apply a projection to a nested object in Mongo DB

I have a data structure like this in MongoDB. It can have many levels:

{
    _id: ObjectId("123"),
    name: "Top level",
    someData: "hello world",
    parent: null,
    children: {
        "456": {
            _id: ObjectId("456"),
            name: "Nested Obj",
            parent: "123",
            someData: "lorem ipsum",
            children: {
                "963": {
                    _id: ObjectId("963"),
                    name: "2nd level nesting",
                    parent: "456",
                    someData: "some data",
                    children: {}
                }
        },
        "798": {
            _id: ObjectId("798"),
            parent: "123",
            name: "Another entry",
            someData: "more data here",
            children: {},
        }
    }
}

Is there a way to make a query that would allow me to:

  1. Recursively apply a projection to all nested objects.
  2. Create a calculated field that contains the path to get to each object.

For example, say that I am only interested in the _id and name fields, I would expect to see this as a result of the query:

{
    _id: ObjectId("123"),
    name: "Top level",
    path: []
    children: {
        "456": {
            _id: ObjectId("456"),
            name: "Nested Obj",
            path: ["123"]
            children: {
                "963": {
                    _id: ObjectId("963"),
                    name: "2nd level nesting",
                    path: ["123", "456"]
                    children: {}
                }
        },
        "798": {
            _id: ObjectId("798"),
            name: "Another entry",
            path: ["123"]
            children: {},
        }
    }
}