how to add Realtime audio chat between players in web based multiplayer game?

I had idea to build web based game in which players also can talk to each other.
i fond one solution for text based real time chat using deepstream server , but its currently not maintained by team so i decided to drop using deepstream server idea.

if you have any solution to share Realtime audio and chat between users (same as multiplayer games freefire etc.) in web based app or game help me out.

please make sure you are suggesting scalable solution.

Vue Carousel 3D slider not working properly

I am adding vue carousel 3d into my project. However it takes space for slider to display but cannot see slider there. I wanted to inspect and right click on it , the slider suddenly stars showing. When I refresh the page, again it disappears. I don’t know what to do and whats the problem with that. Can anyone please explain how to solve this issue? Thanks.

App.vue

<template>
  <div id="app" class="wrapper">
    <div class="box">
      <!-- <h3>Controls visible</h3> -->

      <carousel-3d :controls-visible="true">
        <slide v-for="(slide, i) in slides" :index="i" :key="i">
          <img :src="slide.src">

        </slide>
        <!-- <slide :index="0" :key="0"><p>a</p></slide>
        <slide :index="1" :key="1"><p>b</p></slide>
        <slide :index="2" :key="2"><p>c</p></slide> -->
        <!-- <slide :index="3"><p>a</p></slide> -->
      </carousel-3d>
    </div>
  </div>
</template>
<script>
import Carousel3d from "./Carousel3d.vue";
import Slide from "./Slide.vue";

const slides = [
  {
    title: 'Slide 1',
    desc: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim, maxime.',
    src: 'https://placehold.it/360x270'
  },
  {
    title: 'Slide 2',
    desc: 'Lorem ipsum dolor sit amet ',
    src: 'https://placehold.it/360x270'
  },
  {
    title: 'Slide 3',
    desc: 'abcd ',
    src: 'https://placehold.it/360x270'
  },
]

export default {
  name: 'App',
  components: {
    Carousel3d,
    Slide
  },
  data () {
    return {
      slides: slides,
      slideCount: 3
    }
  },
 }
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

How to customize MUI React Component?

I’m building an application in React, using React MUI Components.

In my RecipeReviewCard.js, I’ve copied the source code from MUI website.
It look’s like this:

import * as React from "react";
import { styled } from "@mui/material/styles";
import Card from "@mui/material/Card";
import CardHeader from "@mui/material/CardHeader";
import CardMedia from "@mui/material/CardMedia";
import CardContent from "@mui/material/CardContent";
import CardActions from "@mui/material/CardActions";
import Collapse from "@mui/material/Collapse";
import Avatar from "@mui/material/Avatar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import { red } from "@mui/material/colors";
import FavoriteIcon from "@mui/icons-material/Favorite";
import ShareIcon from "@mui/icons-material/Share";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import MoreVertIcon from "@mui/icons-material/MoreVert";

const ExpandMore = styled((props) => {
  const { expand, ...other } = props;
  return <IconButton {...other} />;
})(({ theme, expand }) => ({
  transform: !expand ? "rotate(0deg)" : "rotate(180deg)",
  marginLeft: "auto",
  transition: theme.transitions.create("transform", {
    duration: theme.transitions.duration.shortest,
  }),
}));

export default function RecipeReviewCard() {
  const [expanded, setExpanded] = React.useState(false);

  const handleExpandClick = () => {
    setExpanded(!expanded);
  };

  return (
    <Card sx={{ maxWidth: 345 }}>
      <CardHeader
        avatar={
          <Avatar sx={{ bgcolor: red[500] }} aria-label="recipe">
            R
          </Avatar>
        }
        action={
          <IconButton aria-label="settings">
            <MoreVertIcon />
          </IconButton>
        }
        title="Shrimp and Chorizo Paella"
        subheader="September 14, 2016"
      />
      <CardMedia
        component="img"
        height="194"
        image="/static/images/cards/paella.jpg"
        alt="Paella dish"
      />
      <CardContent>
        <Typography variant="body2" color="text.secondary">
          This impressive paella is a perfect party dish and a fun meal to cook
          together with your guests. Add 1 cup of frozen peas along with the
          mussels, if you like.
        </Typography>
      </CardContent>
      <CardActions disableSpacing>
        <IconButton aria-label="add to favorites">
          <FavoriteIcon />
        </IconButton>
        <IconButton aria-label="share">
          <ShareIcon />
        </IconButton>
        <ExpandMore
          expand={expanded}
          onClick={handleExpandClick}
          aria-expanded={expanded}
          aria-label="show more"
        >
          <ExpandMoreIcon />
        </ExpandMore>
      </CardActions>
      <Collapse in={expanded} timeout="auto" unmountOnExit>
        <CardContent>
          <Typography paragraph>Method:</Typography>
          <Typography paragraph>
            Heat 1/2 cup of the broth in a pot until simmering, add saffron and
            set aside for 10 minutes.
          </Typography>
          <Typography paragraph>
            Heat oil in a (14- to 16-inch) paella pan or a large, deep skillet
            over medium-high heat. Add chicken, shrimp and chorizo, and cook,
            stirring occasionally until lightly browned, 6 to 8 minutes.
            Transfer shrimp to a large plate and set aside, leaving chicken and
            chorizo in the pan. Add pimentón, bay leaves, garlic, tomatoes,
            onion, salt and pepper, and cook, stirring often until thickened and
            fragrant, about 10 minutes. Add saffron broth and remaining 4 1/2
            cups chicken broth; bring to a boil.
          </Typography>
          <Typography paragraph>
            Add rice and stir very gently to distribute. Top with artichokes and
            peppers, and cook without stirring, until most of the liquid is
            absorbed, 15 to 18 minutes. Reduce heat to medium-low, add reserved
            shrimp and mussels, tucking them down into the rice, and cook again
            without stirring, until mussels have opened and rice is just tender,
            5 to 7 minutes more. (Discard any mussels that don’t open.)
          </Typography>
          <Typography>
            Set aside off of the heat to let rest for 10 minutes, and then
            serve.
          </Typography>
        </CardContent>
      </Collapse>
    </Card>
  );
}

Then, In my UserPanel.js component, I’m importing this component.

const UserPanel = () => {
  let history = useHistory();

  useEffect(() => {
    let authToken = sessionStorage.getItem("AuthToken");

    if (authToken) {
      history.push("/userpanel");
    }

    if (!authToken) {
      history.push("/login");
    }
  }, []);

  const handleLogout = () => {
    sessionStorage.removeItem("AuthToken");
    history.push("/login");
  };

  return (
    <>
      {/* <Sidebar /> */}
      <RecipeReviewCard></RecipeReviewCard>
    </>
  );
};

export default UserPanel;

Is there any way to customize for example the text placed in in my UserPanel.js component via props?
Or any diffrent element from MUI Component?
Without creating and duplicating the MUI component?

How to prevent an eventListner for the first time on pageLoad In JS

i have used preventDefault() but thats not working
here is My Code

btnBookNameSearch.addEventListener("click", (e) => {
    e.preventDefault();
    const searchValue = btnBookNameSearch.value.toLowerCase().trim();
 
    allPgBooks.forEach((product) => {
        if (product.name == searchValue) {
            allPgBooksE2.innerHTML = '';
            if (allPgBooksE2) { 

there is a mistake i am doing in the first two line of code above but idk how to fixenter image description here

Puppeteer screenshot ignoring parameters

I am creating a function on AWS Lambda to take screenshots of websites and save the resulting image to S3. The function is successfully creating a screenshot and saving to S3, however it is ignoring the parameters given to the page.screenshot() function and just using defaults.

const chromium = require('chrome-aws-lambda');
const aws = require('aws-sdk');

var s3 = new aws.S3();

exports.handler = async (event, context, callback) => {
  let result = null;
  let resultKey = null;
  let browser = null;

  try {
    resultKey = event.url.replace(/[W_]+/g,"_") + '.png';
    
    browser = await chromium.puppeteer.launch({
      args: chromium.args,
      defaultViewport: chromium.defaultViewport,
      executablePath: await chromium.executablePath,
      headless: chromium.headless,
      ignoreHTTPSErrors: true,
    });

    let page = await browser.newPage();

    await page.goto(event.url || 'https://example.com');

    result = await page.screenshot({
      type: 'jpeg',
      fullpage: true
    });
    
     // Image ready. Send to S3
     var params = {
       Bucket: 'mybucket',
       Key: resultKey,
       Body: result
      };
      s3.putObject(params, function(err, data) {
        if (err) {
          console.error(err, err.stack);
        } else {
          console.log(data);
        }
      });
  } catch (error) {
    return callback(error);
  } finally {
    if (browser !== null) {
      await browser.close();
    }
  }

  return callback(null, result);
};

So the image created ignores the type and fullpage parameters, and creates a .png image that is not fullpage.

What am I doing wrong?

Reload a wordpress page with javascript

I need to build a charts with chartjs library.

I’ve got a strange behavior with firefox : the charts behaves randomly :

  • sometimes it’s OK and sometimes I need to click several time on my button

is anyone know a method in javascript to force the reload via a simple button like this? :

<a href="javascript:window.location.reload(true)" class="refresh">Refresh the page</a>

Call a classes function from within window scope

I have a simple class,

class TestClass {
   init() {
       this.loadGoogle();
   }
   
   initializeSearch() {
       alert("here");
   }
   
   loadGoogle() {
       const script = document.createElement('script');
        script.src = 'https://maps.googleapis.com/maps/api/js?key={MY_KEY}&libraries=places&callback=initMap';
        script.async = true;

        window.initMap = () => {
        //JS API IS LOADED
            this.initializeSearch();
        };

        document.head.append(script);
   }
}

I am having trouoble calling the intializeSearch method when the callback is fired. I am assuming it’s because this is out of scope? Can I bring this into the scope of the window global?

Passing props via spread operator in React

Using React I have a component that I need to pass an ‘id’ prop to render an id on the html anchor. Starting at the lowest return level for this anchor point and working up we have:

// links.jsx
export const myLink = ({children, location, ...props}) => {
  const href = "mydomain.com" + location;
  return (
    <a href={href} {...props}>{children}</a>
  )
}

//components.jsx
export const Block = ({linkLocation, htmlId, children, externalLink: isExternalLink}) => {
  const EditLink = isExternalLink ? Link1 : Link2;
  return <div className="outer-div">
    <div className="inner-div">
      {children}
    </div>
 
    <EditLink location={editLocation} id={htmlId}>{translate('edit')}</EditLink>
  </div>
}

export const Summary = ({info1, info2, info3}) => {
  return <SummaryBlock htmlId={'i-am-id-' + info2}>
    <div>{info1}</div>
    <div>{info2}</div>
    <div>{info3}</div>
  </SummaryBlock>
}

That htmlId is what I’m seeking to pass up to myLink to assign the anchor’s id attribute yet on page render it doesn’t appear. Is it because id’s are protected/special? Do I need to assign the spread operator on props to the EditLink component? Am I missing a passing point somewhere? I’m especially confused because similar questions show the spread operator as being just the right thing to do what I’m seeking.

Guidance would be much appreciated!

Webpack 5 & Vue 3 – CSS Tree Shake

I’m developing a UI component library using Vue 3, SCSS and Webpack 5. The library consists of serval components (button, input, form etc) having a scoped SCSS each.

After installing the library in my main project (also built with Vue 3 & Webpack 5), I’m importing only a single component (button) into it. However, after the build finished (CSS build) I see other components’s CSS are included in the build as well. I should mention The JS tree shaking do working.

I want to reduce my bundle size to include only the CSS of the imported components.

An example for button component in my build file:

var script$4 = defineComponent({
    name: "SButton",
    props: {
        stype: {
            type: String,
            default: "primary"
        },
        type: {
            type: String,
            default: "button"
        }
    }
});

const _withId$4 = /*#__PURE__*/withScopeId("data-v-7a74475b");

const render$4 = /*#__PURE__*/_withId$4((_ctx, _cache, $props, $setup, $data, $options) => {
  return (openBlock(), createBlock("button", {
    class: ["s-button", _ctx.stype],
    type: _ctx.type
  }, [
    renderSlot(_ctx.$slots, "default")
  ], 10 /* CLASS, PROPS */, ["type"]))
});

var css_248z$6 = "html {n  --sbutton-general-icon-padding: 9px;n  --sbutton-general-icon-width: 36px;n  --sbutton-general-icon-height: 36px;n  --sbutton-width: 100%;n  --sbutton-min-height: 56px;n  --sbutton-line-height: 32px;n}n@media (min-width: 992px) {n  html {n    --sbutton-general-icon-padding: 7px;n    --sbutton-general-icon-width: 32px;n    --sbutton-general-icon-height: 32px;n    --sbutton-width: auto;n    --sbutton-min-height: 46px;n    --sbutton-line-height: 22px;n  }n}";
styleInject(css_248z$6);

Why does JS say addEventListener is not a function? [duplicate]

I am building a Flask app that also uses JS and I encountered an error. I am building a timer which will play and pause as the user clicks on each respective button. I built it a few months ago and it was working, but I didn’t finish it. Now, I want to finish it but the error occurs. The error is,

play.addEventListener is not a function
    at timer (index.js:26)
    at index.js:84

Here is my code:

const timer = () => {
  const song = document.querySelectorAll(".song");
  const play = document.querySelectorAll(".play");
  const reset = document.querySelectorAll(".reset");

  // Time display
  const minuteDisplay = document.querySelectorAll(".minute");
  const secondDisplay = document.querySelectorAll(".second");

  //Duration
  // const formDuration = document.getElementById("duration").value;
  const formDuration = 20;
  let duration = formDuration * 60;

  let displayMinutes = ("0" + Math.floor(duration / 60)).slice(-2);
  let displaySeconds = ("0" + Math.floor(duration % 60)).slice(-2);

  for (const mdisplay in minuteDisplay) {
    mdisplay.textContent = `${displayMinutes}`;
  }

  for (const sdisplay in secondDisplay) {
    sdisplay.textContent = `${displaySeconds}`;
  }

  play.addEventListener("click", () => { //This is the error
    checkPlaying(song);
  });

  const checkPlaying = (song) => {
    if (song.paused) {
      song.play();
      play.textContent = `Pause`;
      play.classList.toggle("btn-active");
    } else {
      song.pause();
      play.innerHTML = `Play`;
      play.classList.remove("btn-active");
    }
  };

  song.ontimeupdate = () => {
    let currentTime = song.currentTime;
    let elapsed = duration - currentTime;
    let seconds = Math.floor(elapsed % 60);
    let minutes = Math.floor(elapsed / 60);

    // Edit time display
    formatMinutes = ("0" + minutes).slice(-2);
    formatSeconds = ("0" + seconds).slice(-2);
    minuteDisplay.textContent = `${formatMinutes}`;
    secondDisplay.textContent = `${formatSeconds}`;

    reset.addEventListener("click", () => {
      song.pause();
      song.currentTime = 0;
      play.innerHTML = `Play`;
      play.classList.remove("btn-active");
      if (reset.classList.contains("btn-active")) return;
      reset.classList.add("btn-active");
      // remove class after 2 seconds
      setTimeout(() => {
        reset.classList.remove("btn-active");
      }, 150);
    });

    if (currentTime >= duration) {
      song.pause();
      song.currentTime = 0;
      play.innerHTML = "Play";
      play.classList.remove("btn-active");
    }
  };
};

timer();

My timer is based on a song, and when the song pauses, the timer should too. The same should happen when the song is reset or played. Any feedback will be greatly appreciated. Thankyou!

NextAuth How to Role-Based Authentification?

I came across the following issue.
As at https://next-auth.js.org/v3/getting-started/client#custom-client-session-handling explained,I can simple add an authentification check to each website by adding the
AdminDashboard.auth = true
to every page i want it.

But as roughly explained in the docs

AdminDashboard.auth = 
{
  role: "admin",
  loading: <AdminLoadingSkeleton />,
  unauthorized: "/login-with-different-user", // redirect to this url
}

this should make it possible to simply add a role-based-auth to each website so my question is:

How would this work? I’ve tried it out by changing the role: “admin” to role_id: 1, as I use role_id’s in my session but it won’t work and does not throw any errors.

Any ideas?

Force eager image loading on mobile browsers

On my website, I have several images with an onload and onerror callback

<img onload="imgCallback()" onerror="imgCallback()" class="article-img" src=":assets:/price/12-2.jpg" alt="A chart showing vitamin and mineral content of liver, kidney, spleen, heart, broccoli, kale, banana and apple" />

Some initialization is only done after all images have loaded because I need the full height of the container element after all images are shown.

This works fine on my desktop, however, it seems to not work on some mobile browsers. I have tested this on my Android Chrome browser and it seems to only load images lazily after I scroll far enough down, delaying page initialization that is expected to happen on the initial loading of the website.

I can’t really think of any other way of solving this as I need the full width of the container post image loading, something I don’t know statically, therefore I am asking if there is a way to signal to the browser that it should eagerly load images?

regex -digits and special symbols are only allowed in input

I have 2 input fields in my form (for phone number) and I should validateRe these inputs. Digits 0-9 and ()+- are only allowed and number of digits should be between 5 and 11 only {5,11}. I try to use method replace. Could you explain, how it works ?

formPhone.forEach(element => {
            element.addEventListener("input", (e) => {
               e.target.value = e.target.value.replace(/[^d()+-]{5,9}/g, '');

            })
        })

Cannot not connect to SMTP Sendinblue x Strapi

I’m currently looking to send email with my strapi backend.
I follow this tutorial to make it work.
In short, the tutorial tell you to install strapi-provider-email-nodemailer that is provider agnostic.

Now, I get an error Error: can not connect to any SMTP server,
I don’t understand why because I made everything the same as it’s recommended in the tutorial…

Here is my plugin file :

module.exports = ({ env }) => ({
    // ...
    email: {
      provider: env('EMAIL_PROVIDER'),
      providerOptions: {
        host: env('EMAIL_SMTP_HOST', 'smtp.example.com'),
        port: env('EMAIL_SMTP_PORT', 587),
        auth: {
          user: env('EMAIL_SMTP_USER'),
          pass: env('EMAIL_SMTP_PASS'),
        },
      },
      settings: {
        defaultFrom: env('EMAIL_ADDRESS_FROM'),
        defaultReplyTo: env('EMAIL_ADDRESS_REPLY'),
      },
    },
    // ...
  })

and this is my .env file :

EMAIL_PROVIDER=nodemailer
EMAIL_SMTP_HOST=smtp-relay.sendinblue.com
EMAIL_SMTP_PORT=587
[email protected]
EMAIL_SMTP_PASS=mypassword
[email protected]
[email protected]

If somebody as an idea…
Thanks a lot.

spservices.js is returning this error:- Uncaught (in > promise) TypeError: Cannot read properties of undefined (reading > ‘LookupList’)

Inside our SPFx SharePoint online web part we have the following code inside the spservices.js code:-

spservices.prototype.getLookupFieldOptions = function (siteUrl, listId, fieldInternalName) {
        return __awaiter(this, void 0, void 0, function () {
            var fieldOptions, web, results, options, _i, options_1, option, error_14;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        fieldOptions = [];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, , 6]);
                        web = new Web(siteUrl);
                        return [4 /*yield*/, web.lists.getById(listId)
                                .fields.usingCaching()
                                .filter("InternalName eq '" + fieldInternalName + "'")
                                .select("LookupList", "LookupWebId", "LookupField")
                                .top(1)
                                .get()];
                    case 2:
                        results = _a.sent();
                        if (!results) return [3 /*break*/, 4];
                        return [4 /*yield*/, web.lists.getById(results[0].LookupList)
                                .items.usingCaching()
                                .select("ID", results[0].LookupField)
                                .getAll()];
                    case 3:
                        options = _a.sent();
                        if (options && options.length > 0) {
                            for (_i = 0, options_1 = options; _i < options_1.length; _i++) {
                                option = options_1[_i];
                                fieldOptions.push({
                                    key: option.ID,
                                    text: option[results[0].LookupField]
                                });
                            }
                        }
                        _a.label = 4;
                    case 4: return [3 /*break*/, 6];
                    case 5:
                        error_14 = _a.sent();
                        return [2 /*return*/, Promise.reject(error_14)];
                    case 6: return [2 /*return*/, fieldOptions];
                }
            });
        });
    };

but on runtime the SPFx web part will return this error and it will keep loading forever:-

calendar-web-part_a87ac4ce95dc9057c9f00ccd9727c133.js:1 Uncaught (in
promise) TypeError: Cannot read properties of undefined (reading
‘LookupList’)

this is the code which is returning the error:-

return [4 /*yield*/, web.lists.getById(results[0].LookupList)

as follow:-

enter image description here

any advice on this please?