Fetch local file using JavaScript fetch() [closed]

So I tried this code to fetch a local file for my website: const response = await fetch("../../assets/folder/file.png");. What I mean is I created an assets folder that contains images uploaded by me. But I am having issues accessing those images because when I deployed the website, it cannot find the image/s that was stored on my own assets folder.

I tried adjusting the relative path to /assets/folder/file.png and it also doesn’t do anything. The server still responds with file.png:1: GET https://user.github.io/assets/folder/file.png 404 (Not Found).

The folder structure of my project is as follows:

index.html
assets/
     folder/
          file.png
scripts/
     data/
          fetch.js (which contains the fetch code)

How can I fix this? I would also like to note that this is a vanilla JS web app and I don’t use any frameworks nor libraries.

How do I still modify Objects in FabricJs on Rotation using PerspectiveJS

I am trying to integrate PerspectiveJs with FabricJs, as I need to provide functionality to transform the perspective of an image. It works fine when the image isn’t rotated, but when I rotate the image and then try to change its perspective, it becomes distorted. The PerspectiveJs functionality is accessible by double-clicking on the image. Any help would be appreciated. If you know of any other library that could achieve this, please let me know, as I need to implement this functionality as soon as possible.

https://shorturl.at/oAlNi

How do I make it work on rotation as well.

Does anycharts support stack labels in stacked charts?

Does anycharts support stack labels like highcahrts?
https://www.highcharts.com/demo/highcharts/column-stacked

Or is there any way to add these stack labels?

I have tried using the annotatios().label it works fine for stacked column charts but it does not work for stacked bar charts.

https://playground.anychart.com/KBKhP86c/2 //this works fine for column chart

https://playground.anychart.com/KBKhP86c/3 //this one does not work correctly.

I would prefer if there was a option to just enable the stackedLabels like in hightcharts but from the documentations anycharts does not support this.

React Audio Player Change current time of Audio

I’m working on a custom audio player in React with Bootstrap, and I want to make it possible to fast forward or rewind the playback by 5 seconds.
I also want to be able to change the time using a slider.
This somehow does not work.
CURRENTLY the code behaves in such a way that if I fast forward or rewind 5 seconds the MP-3 starts again.

App.js

import "bootstrap/dist/css/bootstrap.min.css";
import "./index.scss";
import { Button, Card, Container, ProgressBar } from "react-bootstrap";

import AudioPlayer from "./components/AudioPlayer";

export default function App() {
  return (
    <div className="App">
      <Container>
        <h1>Hello CodeSandbox</h1>
        <Card>
          <Card.Header> Audio </Card.Header>
          <Card.Body>
            <AudioPlayer
              audioSrc="/assets/Test_ogg_mp3_48kbps.wav.ogg"
              name="Lehrpfad Audio 1"
            />
          </Card.Body>
        </Card>
      </Container>
    </div>
  );
}

AudioPlayer

import React from "react";
import { Button, ProgressBar, InputGroup, FormControl } from "react-bootstrap";
import {
  PlayCircleFill,
  PauseCircleFill,
  VolumeMuteFill,
  VolumeDownFill,
  VolumeUpFill,
} from "react-bootstrap-icons";

class AudioPlayer extends React.Component {
  constructor(props) {
    super(props);
    this.audioRef = React.createRef();
    this.audioSrc = props.audioSrc;

    this.state = {
      isPlaying: false,
      currentTime: 0,
      volume: 1, // Range between 0 and 1
      progress: 0,
    };
  }

  togglePlayPause() {
    const { isPlaying } = this.state;
    const audio = this.audioRef.current;
    if (isPlaying) {
      audio.pause();
    } else {
      audio.play();
    }
    this.setState({ isPlaying: !isPlaying });
  }

  handleTimeUpdate() {
    const audio = this.audioRef.current;
    if (audio && !isNaN(audio.duration)) {
      const progressPercentage = (audio.currentTime / audio.duration) * 100;
      this.setState({ progress: progressPercentage });
      if (progressPercentage >= 100) {
        this.setState({ isPlaying: false, progress: 0 });
      }
    }
  }

  getVolumeIcon() {
    const { volume } = this.state;
    if (volume <= 0) {
      return <VolumeMuteFill />;
    } else if (volume > 0 && volume <= 0.5) {
      return <VolumeDownFill />;
    } else {
      return <VolumeUpFill />;
    }
  }

  handleVolumeChange(e) {
    const newVolume = e.target.value;
    this.setState({ volume: newVolume });
    if (this.audioRef.current) {
      this.audioRef.current.volume = newVolume;
    }
  }

  skipTime(seconds) {
    const player = document.getElementById("Player");
    if (player && !isNaN(player.currentTime)) {
      player.currentTime += seconds;
      this.setState();
    }
  }

  render() {
    const { isPlaying, progress, volume } = this.state;
    return (
      <div className="container mt-5 audio-player">
        <audio
          id="Player"
          ref={this.audioRef}
          src={this.audioSrc} // Ersetze dies durch den Pfad zu deiner Audiodatei
          onTimeUpdate={this.handleTimeUpdate.bind(this)}
          onEnded={() => this.setState({ isPlaying: false })}
        />
        <div className="d-flex align-items-center">
          <Button variant="primary" onClick={() => this.skipTime(-5)}>
            {" "}
            -5s{" "}
          </Button>
          <Button
            variant="primary"
            onClick={this.togglePlayPause.bind(this)}
            className="mx-2"
          >
            {isPlaying ? <PauseCircleFill /> : <PlayCircleFill />}
          </Button>
          <Button variant="primary" onClick={() => this.skipTime(5)}>
            {" "}
            +5s{" "}
          </Button>
        </div>
        <ProgressBar
          striped
          variant="success"
          now={progress}
          label={`${Math.round(progress)}%`}
        />
        <InputGroup className="mt-3">
          <InputGroup.Text>{this.getVolumeIcon()}</InputGroup.Text>
          <FormControl
            type="range"
            min="0"
            max="1"
            step="0.1"
            value={volume}
            onChange={this.handleVolumeChange.bind(this)}
          />
        </InputGroup>
      </div>
    );
  }
}

export default AudioPlayer;


I tried everything that came into my mind but i was not sucessfull.
I did accept that a method would change the time.

event does not return correct coordinates of element when moved using CSS position-try

I have a simplified reproduction of my issue here.

When the browser does its calculation to see if the anchored element will fit in the given space and then moves it, my JS still returns the original coordinates of the element before it was moved.

I’ve tried using requestAnimationFrame() that was suggested to me but this also does not work as expected.

Am I using it correctly or is there some other method I can use to run my script after the browser has rendered?

You will notice the red triangles one point on the first few divs all follow the mouse pointer until it moves to a different div. When you reach a div where the browser determines that there is not enough space for the popup to fit and then moves it to a different location, you will notice the triangle point will still use coordinates from the popup when it was in its original position.

@position-try --custom-bottom {
  top: unset;
  bottom: anchor(bottom);
}

:root {
  --size: 60px;
}

body {
  padding: 0;
  margin: 0;
  background: #333;
}

#sidebar {
  width: var(--size);
  height: 100dvh;
  background: white;
  display: grid;
  grid-template-rows: repeat(6, 1fr);
  gap: 2px;
}

.menu {
  --x: 0;
  --y: 24px;
  --w: 100%;
  width: var(--size);
  background: #666;
  position: relative;

  &:hover > .sub {
    visibility: visible;
  }
}

.sub {
  position: fixed;
  width: calc(var(--size) * 2);
  height: calc(var(--size) * 4);
  background: #999;
  visibility: hidden;
  left: calc(anchor(right) + 16px);
  top: anchor(top);
  position-try: most-height --custom-bottom;

  &:before {
    content: "";
    height: 100%;
    position: absolute;
    right: 100%;
    top: 0;
    width: var(--w);
    clip-path: polygon(var(--x) var(--y), 100% 0px, 100% 100%);
    background: red;
  }
}
    const hoverTrigger = document.querySelectorAll(".menu");
    let currentHoverElement;

    function handleMousemove(event) {
      const mouseX = event.clientX;
      const mouseY = event.clientY;

      hoverTrigger.forEach((element) => {
        if (element.matches(":hover")) {
          requestAnimationFrame(() => {
            const boundingRect = element.getBoundingClientRect();
            const elementY = Math.round(boundingRect.y);
            const offsetY = mouseY - elementY;

            if (mouseX === 0 || mouseX <= boundingRect.width) {
              element.style.setProperty("--x", mouseX + "px");
              element.style.setProperty(
                "--w",
                boundingRect.width / 2 + mouseX + 16 + "px"
             );
            }
            if (mouseY === elementY || mouseY <= elementY + boundingRect.height) {
              element.style.setProperty("--y", offsetY + "px");
            }
            currentHoverElement = element;
          });
        }
      });
    }
    
    function handleMouseleave(event) {
      if (currentHoverElement) {
        currentHoverElement.style.setProperty("--x", "0");
        currentHoverElement.style.setProperty("--y", "-24px");
        currentHoverElement.style.setProperty("--w", "100%");
      }
    }

    document.addEventListener("mousemove", handleMousemove);
    document.addEventListener("mouseleave", handleMouseleave);

Safari automatically reloads web app and breaks it

I’ve developed an app with Angular 17 and embedded it into a site via an iframe.

Now if I load the page on any Safari mobile device, it takes a few seconds until the page starts reloading. This happens twice until Safari shows a message that says A problem repeatedly occured on domain.com.

It works fine on all other devices and browsers.

Currently I can only test Safari on a IPad or IPhone so I can’t open any dev tools.

Any idea what can cause this?

React.js Custom Snippet Shortcuts

Hey i created a repository for custom snippet shortcuts you can use in your React application.Its containing a lot of little usefull snippets and a really nice Create ContextProvider File snippet wich creates an instant template for a Context Provider File. You can find the whole file in my github repository. Have fun.
https://github.com/tasipeter3000/React-SnippetsShortcuts/tree/main

If you have any improvments or new snippets you want to provide feel free to comment or message me.

How I get hamburger menu button top of the appbar using MUI?

enter image description here

why this box get cut when it push to the outside the appbar? i need to show that button half of the appbar.first i thought it was z-index issue. but even i add the box to Drawer, box still hidden when go outside the drawer. I need to show box between the drawer and appbar.but button need to be float.

import * as React from "react";



interface AppBarProps extends MuiAppBarProps {
  open?: boolean;
}

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== "open",
})<AppBarProps>(({ theme, open }) => ({
  zIndex: theme.zIndex.drawer + 1,
  transition: theme.transitions.create(["width", "margin"], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  width: `calc(100% - ${theme.spacing(8)} - 1px)`,
  ...(open && {
    marginLeft: DRAWER_WIDTH,
    width: `calc(100% - ${DRAWER_WIDTH}px)`,
    transition: theme.transitions.create(["width", "margin"], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
  }),
}));

const AppHeader: React.FC = () => {
  const { navigatorDrawerOpen, onCloseNavigatorDrawer, onOpenNavigatorDrawer } =
    useNavigatorDrawer();
  const { onOpenThemeDrawer } = useThemeDrawer();

  const handleDrawerOpenClose = () => {
    navigatorDrawerOpen ? onCloseNavigatorDrawer() : onOpenNavigatorDrawer();
  };

  return (
    <AppBar
      position="fixed"
      open={navigatorDrawerOpen}
      elevation={0}
      color="inherit"
      variant="outlined"
      sx={{ borderTop: 0 ,overflow:'visible'}}
    >
      <Toolbar>
        
        <IconButton
          edge="start"
          sx={{
            position: "absolute",
              left: 0,
              width: 35,
              height: 35,
              backgroundColor:'skyblue',
              color:'darkblue',
              borderRadius:1,
              zIndex: 5000,
              display: "flex",
              justifyContent: "center",
              alignItems: "center" }}
        >
         <Box color="primary" >{// this box is the showing half cut box}
            </Box>
        </IconButton>
            
        
         
        <Box sx={{ ml: 0, flexGrow: 1 }} />
        <IconButton>
          <Settings />
        </IconButton>
      </Toolbar>
    </AppBar>
  );
};

export default AppHeader;

Is this a redirect or not?

I see the following page behavior:

After clicking on a ahref link /product-1, a page with url product-1 loads, and, after few seconds, the url changes to product-1?param=1.

This is definitely not a meta equiv redirects. It happens with a javascript, and there is no status code change – the status code remains 200, and my DevTools Network tab doesn’t display the url switch from non-param to param version.

Should I consider this behavior as a redirect or not?

How do I do Secure Remote Password (SRP) based sign in with Amazon Cognito in JavaScript?

I need to authenticate users against Amazon Cognito, and get JWTs. My Amazon Cognito User Pool Client uses the default Secure Remote Password (SRP) flow.

I have the username and password ready, how do I now actually use these to do the SRP calculations and sign in?

I know there are some libraries out there that can do this for me, notably AmplifyJS, but I’m curious for alternatives that may be more lean and mean, and would work on the backend too–e.g. in integration tests we run in Node.js or Bun.

Http request from safari goes to infinite pending state on iOS 18 after collapsing the browser

On my web page, there is an HTTP request that triggers a push notification in the authorization application and the request gets the response after getting confirmation from the app. It works fine when another device receives push notifications and handles confirmation. But if I use the same device, the request will remain pending after switching to the auth application.

I tried to use visibilitychange event to cancel the pending request and restart it. But the second one also gets stuck. Only if I add 1-2 seconds timeout after cancelation new request works fine. I assume it’s related to Background Network Suspension when Safari goes to the background. But is there any way to track the network state to handle this scenario properly?

Handeling multiple dependent states effectively server site and client site

I have been looking everywhere for a solution but cannot find help or a solution anywhere. I hope someone will be able to help me with my problem.

I have the following setup:

| App
|-- Layout
|  |-- Navbar.tsx (Server Side) - Needs `user` and `userData`
|  |  |-- DesktopMenu.tsx (Server Side) - Needs `user` and `userData`
|  |-- {children} -> page.tsx (Server Side) - Needs `user` to redirect if not logged
|  |  |  | <Component>.tsx in page.tsx (Client Side) - Needs `profile`

Navbar.tsx

  • has a dependent query userData so I need to fetch user before it. It’s using that to hide or show menu items.

page.tsx

  • has also a dependent query profile which also needs user to be fetched before it. This component will also use the user to redirect server side if the user is not logged in. But also prefetches the profile state to provide it to a client side component which needs it to show the data.

<Componoent>.tsx

  • needs the profile state to show the data. So I prefetch it on the server side page.tsx component.

So I see two problems:

  1. Two server components need the same state to load another state. But const user = await queryClient.fetchQuery({ would not provide it to the other server component, it will also not provide it to the client side component. Passing it down as a prop would also not work as I have children in the layout.
  2. I use a state to validate something on the server as well as the client so they need to be in sync. I’m confused as the docs say you should not do that. But isn’t it better to redirect a user on the server side if he is not authenticated? So I want to use await queryClient.prefetchQuery({ to make it available on the client but as I need the state on the server I can’t use it. Therefore I would need to go with const user = await queryClient.fetchQuery({ but this would not make it available on the client side.

My goal is to fetch things only once. And keep states in sync between the server and the client.

Nuxt 3 with Nuxt content queryContent doesn’t work after nuxt build during the production but works fine in dev environment

I am developing the Nuxt 3-based Nuxt content website and everything works fine but for the pages/tags/[tags].vue the queryContent() does not work for the 1st time during the production deployment when I reload again it works. However, in the dev (npm run dev) environment, everything works fine. I have created a reproduction of the issue in CodeSandBox

Environment
“@nuxt/content”: “^2.13.2”,

“turbo”: “^2.0.9”,

“nuxt”: “^3.13.2”,

“vue”: “^3.5.10”

Following is my nuxt.config.js:

export default {
  compatibilityDate: "2024-08-31",

  modules: [
    "@nuxtjs/tailwindcss",
    "unplugin-fonts/nuxt",
    "@nuxtjs/i18n",
    "@nuxtjs/color-mode",
    "@nuxt/image",
    "@nuxt/content",
    "@nuxtjs/sitemap",
  ],

  ssr: true,
  target: 'static',

  site: {
    url: process.env.NUXT_PUBLIC_SITE_URL || "http://localhost:3000/",
    name: "Test Application",
    trailingSlash: true,
  },

  sitemap: {
    hostname: process.env.BASE_URL || "http://localhost:3000/",
  },

  //To support and display the .md files from /content using @nuxt/content
  content: {
    // To highlight the code sections using the theme
    highlight: {
      theme: {
        default: "aurora-x",
        dark: "everforest-dark",
        sepia: "monokai",
      },
      langs: ["json", "xml", "java", "shell"],
    },

    markdown: {
      remarkPlugins: ["remark-reading-time"], //To get the reading time for each .md file in /content
      anchorLinks: false, // Do not underline and highlight the h2, h3, h4 etc
    },
  },

  //To support the dark/light mode theme using @nuxtjs/color-mode
  colorMode: {
    classSuffix: "",
    preference: "system",
    fallback: "dark",
  },

  app: {
    head: {
      link: [
        {
          rel: "icon",
          type: "image/x-icon",
          href: `/img/favicon.ico`,
        },
      ],
    },
  },
  
  //Get the config from .env files
  runtimeConfig: {
    apiSecret: "123",
    public: {},
  },

  // auto import components
  components: [
    {
      path: "~/components",
      pathPrefix: false,
    },
  ],

  extends: [],

  css: [],

  build: {
    postcss: {
      postcssOptions: {
        plugins: {
          tailwindcss: {},
          autoprefixer: {},
        },
      },
    },
  },

  i18n: {
    locales: [
      {
        code: "en",
        files: ["en.json", "en-home.json"],
      },
    ],
    lazy: true,
    langDir: "../locales",
    defaultLocale: "en",
  },

  plugins: [{ src: "@/plugins/aos", ssr: false, mode: "client" }],
};

Following is my code in pages/[tags].vue where the queryContent returns empty list for the 1st load in production but works fine during 2nd reload:

<script setup>
//Get the tag name associated with the route
const route = useRoute();
const tag = route?.params?.tags;
console.log("Tag Obtained from URL : " + tag);

// Fetch all documents
const { data: docs } = await useAsyncData("docs", () => queryContent().find());

console.log("1. FOUND LENGTH : " + docs.value.length);

// Filter documents based on the tag
const filteredDocs = computed(() => {
  console.log("2. FOUND LENGTH : " + docs.value.length);
  if (!docs.value) return [];
  const matchingDocs = docs.value.filter((doc) =>
    doc.navigation?.tags?.includes(tag)
  );
  console.log("Matching PAGES : " + matchingDocs.length);
  return matchingDocs;
});
</script>

I saw many similar issues on the GitHub and tried the provided solution but none worked foe me:

https://github.com/nuxt/content/issues/2593
https://github.com/nuxt/content/issues/1762

How to fix the issue with Nuxt content queryContent in production after the Nuxt build?