How to prevent query strings from being attached to the URL when blocking navigation?

I created this hook to stop warn the user that they have unsaved form changes (React Hook Form). This also works when the user is, say, switching tabs: the code checks for query strings like these: ?tab=vcard. Everything works well…except ?tab=vcard is attached to the URL, so you will see the, say, other tab briefly.

import { useEffect, useState } from 'react';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';

export const useUnsaved = (isDirty: boolean) => {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [prevQueryString, setPrevQueryString] = useState(() =>
    searchParams.toString(),
  );

  useEffect(() => {
    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      if (isDirty) {
        event.preventDefault();
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [isDirty]);

  useEffect(() => {
    const currentQueryString = searchParams.toString();
    if (isDirty && currentQueryString !== prevQueryString) {
      const confirmLeave = window.confirm(
        'You have unsaved changes. Are you sure you want to leave this page?',
      );
      if (!confirmLeave) {
        // Prevent navigation by restoring the previous state
        router.push(`${pathname}?${prevQueryString}`);
        return; // Stop execution without throwing an error
      } else {
        setPrevQueryString(currentQueryString); // Update to the new query string
      }
    }
  }, [isDirty, pathname, searchParams, prevQueryString, router]);

  useEffect(() => {
    const originalPush = router.push;
    router.push = async (url: string, ...args: any[]) => {
      const currentQueryString = searchParams.toString();
      const fullCurrentPath = `${pathname}?${currentQueryString}`;
      if (isDirty && url !== fullCurrentPath) {
        const confirmLeave = window.confirm(
          'You have unsaved changes. Are you sure you want to leave this page?',
        );
        if (!confirmLeave) {
          // Prevent navigation by staying on the current path
          router.push(fullCurrentPath);
          return; // Just return here, no error thrown
        }
      }
      return originalPush(url, ...args);
    };

    return () => {
      router.push = originalPush;
    };
  }, [isDirty, pathname, searchParams, router]);
};

So I think I need to stop Next.js from attaching the query string to the URL, and only proceed if the user clicks “Ok.” How can I accomplish this?

PreBuffer only 1 sec of Video in HLS

I am using two different Video on Demand (VOD) Streaming Services GCore & Mux, both of which output *.m3u8 HLS playlists for different resolutions and segments.

To play these videos, I am using the hls.js player. However, even after configuring the player, it downloads the full segment of the video as specified in the .m3u8 playlist. This behavior aligns with how HLS streaming typically works, but I want to change the buffering strategy to optimize for my use case.

My Requirement I want to pre-buffer only 1 second of video instead of the entire segment (usually 5 seconds in length) and continue downloading/buffering further only if the user is watching the video.

Here’s a simplified snippet of how I’m currently setting up hls.js:

const video = document.getElementById('video');
const hls = new Hls({
    maxBufferLength: 1, // Tried this to limit buffer length but it doesn't limit initial segment download
    maxBufferSize: 1,   // Tried this to control memory usage, no effect on segment fetch behavior
});

if(Hls.isSupported()){
    hls.loadSource('my-m3u8-playlist-url.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, () => {
        video.play();
    });
}

My Question

  1. Is there a way to achieve this behavior using hls.js or other existing tools/configurations?
  2. Are there any alternatives to reduce the initial buffering without modifying the original HLS playlist?

I also played along with Shaka Player but this too wasn’t helpful either.

Trigger animation when another starts in motion

I am using motion to animate a background color whenever the variable colorHex changes, which works nicely. I would also like to scale up and back down each time the color changes. For this I’ve used scale: [1, 2, 1] however because the value never changes, it only runs on the initial animation. How can I ensure it retriggers whenever colorHex changes?

<motion.div
  transition={{ duration: 0.3, delay: offset * 0.1, ease: "easeOut" }}
  animate={{
    backgroundColor: colorHex,
    scale: [1, 2, 1],
  }}
  ...

How to make a HTTP call from a Vue.js app that includes a list of files to upload

I need to call a Spring controller that has a @RequestPart parameter of type List<MultipartFile> and expects a list of files. The front end application is written in Vue.js and so far I have tried to use the FormData: append() method. The JS code for the call is:

const bodyFormData = new FormData();
bodyFormData.append('body', etc.);
bodyFormData.append('attached_files', file_1, 'file_1.pdf');
bodyFormData.append('attached_files', file_2, 'file_2.pdf');
return axios.post(
  `url`,
  bodyFormData,
  { headers: { 'Content-Type': 'multipart/form-data' } }
);

The controller is:

@PostMapping(
   path = "/upload-files",
   consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
   produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody ResponseEntity<String> uploadFiles(
     @RequestPart(value = "body") @Valid Request request,
     @RequestPart(value = "attached_files", required = false) List<MultipartFile> files) { ...

If I call the controller using Postman or Swagger using the label ‘attached_files’ for both files:

enter image description here

the Controller parameter files is correctly filled with a list of the two sent files. But if I make the call above through Axios, the parameter files is null.

Maybe append() is the wrong method here? Maybe I can’t use Axios for what I need? Thanks in advance for any help I can get 🙂 .

“Load failed” on fetch request, but only in the Instagram app

I use a form on my WordPress site. The data is sent asyncronously to wp-ajax.php. This works fine in all browsers, but in the Instagram app browser in iOS I get the error “Load failed”. The interesting thing is that the request still arrived at the server and was processed correctly. What could be the reason for this?

<script>
    document.querySelector('.gm_courseform').addEventListener('submit', function(event) {
        event.preventDefault();

        const form = this;
        form.classList.add('sending');

        const submitButton = document.getElementById('submit_button');
        const originalButtonText = submitButton.textContent;
        submitButton.disabled = true;
        submitButton.textContent = "Wird geladen...";
        document.querySelectorAll(".form-message").forEach(el => el.remove());
        const formData = new FormData(this);
        formData.append('action', 'create_booking');

        fetch("<?php echo admin_url('admin-ajax.php'); ?>", {
                method: "POST",
                headers: {
                    "Cache-Control": "no-cache, no-store, must-revalidate",
                    "Pragma": "no-cache",
                    "Expires": "0"
                },
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
              // [...]
            })
            .catch(error => {
             // [...]
    });
</script>

React: Function instered within onClick vs function in component’s body

Let’s say I have two sample components written in React with logging functions. Where is better performance?

Component 1:

const Component = () => { 
 function test() { console.log('test'); } 
 return (<div onClick={test}>Test</div>) 
}

Component 2:

const Component = () => {
 return (<div onClick={() => console.log('test')}>Test</div>)
}

My questions:

  • Which component performs better and why?
  • Is the test function reference somewhere stored and optimized by React or it’s just destroyed so there is no better performing Component in this case?

Tried to ask Microsoft Copilot and I have checked multiple forums about that, couldn’t find the solution.

Not able to do bulk Import in FHIR server

I am uploading data which is generated by synthea in FHIR server but I am not able to do bulk import. My question is how to do it?
Also if my file contains data id of practitioners and patients, then first I have to upload these two resources. Only then I will able to upload other data which is related to those practitioner and patients. Is there any other method to do this? Here’s my sample data.
NOTE: I have done salting in the below data.
{
“resourceType”: “Bundle”,
“type”: “transaction”,
“entry”: [ {
“fullUrl”: “urn:uuid:2b74dd4b-ea3f-f6f3-1d309c2eef”,
“resource”: {
“resourceType”: “Patient”,
“id”: “2b74dd4b-ea3f-14c-a83d309c2eef”,
“meta”: {
“profile”: [ “http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient” ]
},
“text”: {
“status”: “generated”,
“div”: “<div xmlns=”http://www.w3.org/1999/xhtml”>Generated by <a href=”https://github.com/synthetichealth/synthea”>Synthea.Version identifier: synthea-java . Person seed: 267872469990842 Population seed: 1723723738047″
},
“extension”: [ {
“url”: “http://hl7.org/fhir/us/core/StructureDefinition/us-core-race”,
“extension”: [ {
“url”: “ombCategory”,
“valueCoding”: {
“system”: “urn:oid:2.16.0.1.113883.6.238”,
“code”: “2106-3”,
“display”: “White”
}
}, {
“url”: “text”,
“valueString”: “White”
} ]
}, {
“url”: “http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity”,
“extension”: [ {
“url”: “ombCategory”,
“valueCoding”: {
“system”: “urn:oid:2.16.0.1.113883.6.238”,
“code”: “2186-5”,
“display”: “Not Hispanic or Latino”
}
}, {……..

I want to do bulk import in FHIR server.

How to handle a button which is in new window using cypress

Using Cypress, I need to click on a button in an iframe and also the button which appears in a new window and verify the status.

I am executing below steps:

  1. Click on a button which is in an iframe which then opens a new browser window.
  2. There are two buttons in new window, ‘Success’ and ‘Failure’. I need to click on either of them and browser window will be closed and accordingly status will be updated.

I am able to click on a button in the iframe, but I am not able to click on the buttons in new window. I am aware about the fact that cypress does not officially supports operations in multi window or tab. Hence we need to set target as blank and I am aware about other workarounds.

The TML looks something like this (without a or href)

<div role="button" tabindex="-1">
  <div class="abc" data-value="abc" data-index="-1">
    <img data-testid="" src="abc.gif" alt="abc" class="abc">  
    <div class="abc"> 
      <span class="abc">
        <span class="abc">BOB</span> 
      </span>  
      <div slot="abc">
        <div class="abc"></div>
      </div> 
    </div> 
  </div>
</div>

Azure App Services built in auth programatic log out

I am working on an azure app services application using built in auth. I am trying to implement an auto logout due to inactivity feature, so when the user steps away from their browser the app should log out.

Following the documentation of how to sign out of a session I would expect when I redirect to /.auth/logout it should

  • Clears authentication cookies from the current session.
  • Deletes the current user’s tokens from the token store.
  • For Microsoft Entra and Google, performs a server-side sign-out on the identity provider.

… however, instead of doing the above, the user is presented with an account chooser screen to ask which account to sign out of. The problem is that there is no user there to make the choice, so the browser hangs on that screen, and when visiting the application the user is still authenticated.

Does anyone know how to programatically log out of azure app services apps without requiring user interaction?

Making an Output based on Selected Filters

I’m trying to make a proof-of-concept random name generator. I’ve exhausted just about everything I could think of, but everything I’ve tried has not functioned. I’m very new to this, so there’s bound to be rookie mistakes I’m sure.

It’s designed to be 2 dropdown menus to determine what array to choose. It then should randomly choose a name from that array and return it in an output.

var gendervar, countryvar, finalnameset;
gendervar = 3
countryvar = 3

document.getElementById("male").onclick(gendervar = 1)
document.getElementById("female").onclick(gendervar = 2)
document.getElementById("either-g").onclick(gendervar = 3)
document.getElementById("greek").onclick(countryvar = 1)
document.getElementById("norse").onclick(countryvar = 2)
document.getElementById("either-c").onclick(countryvar = 3)

let greek_m = [exampleoption1];
let greek_f = [exampleoption2];
let norse_m = [exampleoption3];
let norse_f = [exampleoption4];
let graeco = [greek_m, greek_f];
let nordic = [norse_m, norse_f];
let masculine = [greek_m, norse_m];
let feminine = [greek_f, norse_f];
let all_of_it = [graeco, nordic];

function filternames() {
  if ((gendervar == 1)(and)(countryvar == 1))
    finalnameset = greek_m;
  else if ((gendervar == 2)(and)(countryvar == 1))
    finalnameset = greek_f;
  else
    finalnameset = null;
}

function randomnames(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
}

function getfinalname() {
  randomnames(finalnameset);
  let finalname = finalnameset[0];
  document.getElementById("output_name").setAttribute.value = finalname;
}
<div class="dropdown">
  <button class="dropbtn">Gender</button>
  <div class="dropdown-content">
    <a id="male">Male</a>
    <a id="female">Female</a>
    <a id="either-g">IDC</a>
  </div>
</div>
<div class="dropdown">
  <button class="dropbtn">Origin</button>
  <div class="dropdown-content">
    <a id="greek">Greek</a>
    <a id="norse">Norse</a>
    <a id="either-c">IDC</a>
  </div>
</div>
<button onclick="getfinalname()">SUBMIT</button>
<output id="output_name">Press submit to generate a name!</output>

buttons in dialog flow cx

How can we align 2 buttons side by side dialog flow cx horizontally?

{
  "richContent": [
    [
      {
        "type": "button",
        "text": "button1"
      },
      {
        "type": "button",
        "text": "button2"
      }
    ]
  ]
}

this configuration shows 2 buttons one below the another . Is their any way to give custom styling in dialog flow cx or any other way of achieving this behaviour

enter image description here

Ensure that the axis covers the entire canvas – Chartjs 3.7.1

I cannot seem to find a way to control these spaces on the side of my chartjs chart. According to the time range, it seems to generate different spaces on the sides. Are there any way to ensure that the axis always cover the entire canvas?

Here are some screenshots of the “spaces” that I want to remove:

enter image description here

enter image description here

Here’s my code configuration so far:

const config = {
type: 'bar',
data: ganttData,
options: {
    responsive: true,
    maintainAspectRatio: false,
    animation: true,
    indexAxis: 'y',
    scales: {
        x: {
            min: startTime,
            max: endTime,
            type: 'time',
            time: {
                unit: false,
                displayFormats: {
                    second: 'HH:mm:ss',
                    minute: 'HH:mm',
                    hour: 'HH:mm',
                    day: 'MMM D',
                    week: 'MMM D',
                    month: 'MMM YYYY',
                    year: 'YYYY'
                },
            },
            ticks: {
                major: {
                    enabled: true
                },
                color: 'white',
                maxRotation: 0,
                minRotation: 0,
                includeBounds: false
            },
            border: {
                color: 'rgb(199,199,199)'
            },
            grid: {
                tickLength: 5, 
                color: 'rgb(199,199,199, 0.1)',
            }
        },
        y: {
            beginAtZero: true,
            stacked: true,
            display: false
        }
    }
}

};

ESM and CJS Conflict Leading to Different Module Formats Being Loaded per Workspace

On the server, jotai is being loaded in different formats:

In workspaces/, jotai is resolved as CJS
In workspaces/shared, jotai is resolved as ESM
This inconsistency causes separate store instances to be created on the server, so when the app hydrates, changes are not reflected in shared

Environment
Next.js: v12
Node.js: v18
Project Module Format: CommonJS (CJS)
Turborepo: Yes

Attempts to Resolve
Using next-transpile-modules:

I added jotai to next-transpile-modules for transpilation, but it resulted in the following error:
ReferenceError: exports is not defined
2. Adding Webpack Alias:
I attempted to force a single resolution path for jotai by adding the following alias to my Webpack configuration:
config.resolve.alias[‘jotai’] = path.resolve( __dirname, ‘node_modules/jotai’ );
However, this did not resolve the issue.

How can I ensure that libraries like jotai are loaded consistently as either ESM or CJS in the server environment to maintain a single store instance…??!

carousel next page and last page snap and show white page

i want to create carousel but when i click next or previous page it replace data of the current index in a second and go next page and show white and nothing i dont know js a lot and i cant figure it out if you can help me with this 😉

<div class="container">
    <div class="custom-carousel">
        <div class="carousel-inner">
            <?php foreach ($topic as $index => $model): ?>
                <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>">
                    <div class="community-box col-md-2">
                        <article class="community-item blog-item">
                            <div class="item">
                                <div class="image-wrapper">
                                    <div class="image-frame">
                                        <figure>
                                            <?php if ($model->hasFile('image')) : ?>
                                                <?= Html::a(
                                                    Html::img(
                                                        $model->getFile('image')->getUrl('gridview-thumb'),
                                                        [
                                                            "alt" => he($model->title),
                                                            "preset" => "gridview-thumb",
                                                            "class" => "card-image"
                                                        ]
                                                    ),
                                                    [
                                                        '/community/front/view',
                                                        'id' => $model->id,
                                                        'title' => he($model->title)
                                                    ],
                                                    [
                                                        'class' => ''
                                                    ]
                                                );?>
                                            <?php endif; ?>
                                        </figure>
                                    </div>
                                </div>
                                <div class="item-content">
                                    <h3 class="card-title">
                                        <?= Html::a(
                                            he($model->title),
                                            [
                                                '/community/front/view',
                                                'id' => $model->id,
                                                'title' => he($model->title)
                                            ]
                                        ); ?>
                                    </h3>
                                </div>
                            </div>
                        </article>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <button class="carousel-control-prev" onclick="prevSlide()">&#10094;</button>
        <button class="carousel-control-next" onclick="nextSlide()">&#10095;</button>
    </div>
</div>

my js :

let currentIndex = 0;

function showSlide(index) {
    const slides = document.querySelectorAll('.carousel-item');
    const totalSlides = slides.length;

    currentIndex = (index + totalSlides) % totalSlides;

    slides.forEach((slide, i) => {
        if (i === currentIndex) {
            slide.classList.add('active');
        } else {
            slide.classList.remove('active');
        }
    });

    const offset = -currentIndex * 100;
    document.querySelector('.carousel-inner').style.transform = `translateX(${offset}%)`;
}

function nextSlide() {
    currentIndex++;
    showSlide(currentIndex);
}

function prevSlide() {
    currentIndex--;
    showSlide(currentIndex);
}


showSlide(currentIndex);

please fix it funcionally that when i click next page or previous it go there and show 4 new index

Client-side path rewriting using JavaScript [closed]

Due to corporate IT restrictions, I’m looking at rewriting every href/XMLHttpRequest URL path on the client-side to add a prefix. This is intended to be backend agnostic hence client-side rewriting. I can hook into XMLHttpRequest and fetch, but I’m struggling to rewrite href and other redirects with the History API. Is this possible to do? Happy to use iframes as needed.