Video Seek Scroll (60FPS)

Trying to achieve an effect of seeking through a video when the page is scrolled. This has been achieved by exporting all frames of the video to JPEG images, pre-loading the images, and rendering them to a canvas. However, this approach uses a lot of bandwidth and takes a long time to load on slow networks.

Trying to achieve the same effect by rendering a video to a canvas does not play as smoothly as the image-based approach.

Here is a working demo with the video-based approach:

https://codesandbox.io/s/infallible-chaum-grvi0r?file=/index.html

Since HTMLMediaElement.fastSeek() doesn’t have widespread browser coverage, how can one achieve a realtime playback rate of 30-60 FPS?

Here is the relevant code for the effect (see CSB link above for the full code):

const video = document.querySelector("video");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

(function tick() {
  requestAnimationFrame(tick);

  const { scrollHeight, clientHeight, scrollTop } = document.body;
  const maxScroll = scrollHeight - clientHeight;
  const scrollProgress = scrollTop / maxScroll;

  canvas.width = document.body.clientWidth;
  canvas.height = document.body.clientHeight;

  // This is the line that causes the issue
  video.currentTime = video.duration * scrollProgress;

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
})();

Date and Time Booking Calendar

example booking image I’m trying to create booking system that allows you to pick the date and time like the image above. Does anyone know how I can recreate this or find one like this that is free?

I tried using the demo version and changing the code based off of my website’s design, but the code wouldn’t even load into my project.

Chrome Extension Refused to Load because it violates the following Content Security Policy

I am trying to load a Chrome Extension with React, but I keep getting the following error:

Refused to load the script ‘https://code.jquery.com/jquery-3.2.1.slim.min.js’ because it violates the following Content Security Policy directive: “script-src ‘self'”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.

Does anyone know how to fix this? Thank you.

Manifest.json

{
  "manifest_version": 3, 
  "name": "Reminder-App",
  "version": "0.1.0",
  "description": "Reminder app for all your tasks",
  "action": {
    "default_popup": "index.html",
    "default_title": "Reminder App"
  },
  "host_permissions": [
    "https://www.google.com/*"
  ]
}

Index.html

 <script
    src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
    integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
    crossorigin="anonymous"
  ></script>

Canvas object property is not updating; used useState (Fabricjs with react)

I am using FabricJS with React, and I am able to add objects easily to the canvas but facing problems when trying to manipulate objects’ properties, For example, I have recreated my issue in below code:

const {useEffect, useState} = React;


const App = () => {
 const [canvas, setCanvas] = useState('');
  const [draw, setDraw]= useState(true);

  useEffect(() => {
    setCanvas(initCanvas());
  }, []);

  //initialize canvas
  const initCanvas = () => (
    new fabric.Canvas('canvas', {
      height: 600,
      width: 800,
      backgroundColor: 'pink',
      isDrawingMode: draw,
      selection:false,
    })
  )

  //add Rectangle to Canvas
  const addRect = canvas => {
    const rect = new fabric.Rect({
      height: 280,
      width: 200,
      fill: 'yellow',
    });
    canvas.add(rect);
    canvas.renderAll();
  }

  //Toggle Draw on Canvas
  const toggleDraw = () => {
    if(draw){
      setDraw(false)
      return
    }
    if(!draw){
      setDraw(true)
      return
    }

  }

  return(
    <div><center>
      <h1>Editor</h1>
      <button onClick={() => addRect(canvas)}>Rectangle</button>
      <button onClick={toggleDraw}> Toggle Draw </button>
      <br></br>
      <br></br>
      <canvas id="canvas" />
      </center>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('app'));

where I am trying to toggle draw by changing canvas object property isDrawingMode to true and false Please help, Thanks.

Node.js Lighthouse custom Gatherer/Audit – Protocol error (Runtime.evaluate): Object reference chain is too long

I am trying to implement custom audits using the lighthouse library lighthouse and executing some Javascript commands within the Gatherer I get the following error:

Protocol error (Runtime.evaluate): Object reference chain is too long

In detail I have the following Gatherer:

'use strict';
const { Gatherer } = require('lighthouse');

class customGatherer extends Gatherer {
 afterPass(options, loadData) {
    const expression = `window.document.getElementsByTagName('*')`;

    const driver = options.driver;

    return driver.evaluateAsync(expression);
 }
}

module.exports = customGatherer;

That with the expression defined above triggers the problem.
There seems to be too much information and I can’t manage it. I’m testing the command on a web page and it returns 1059 collections (HTMLCollection(1059)).

When I run the lighthouse command to inspect a page, the warning is created and the result cannot be manipulated within the audit:

LH:Runner:warn customGatherer, required by audit my-custom-audit, encountered an error: Protocol error (Runtime.evaluate): Object reference chain is too long +0ms

NB: In the lighthouse log i can see also this error:

 LH:method <= browser ERR:error Runtime.evaluate  +24ms

I need to have a Gatherer that returns all HTMLCollection elements in order to compute them to get all the fonts on the page.
How can I get around this problem?

How to compare 2 elements inside 2 arrays? I would use the below its only for when comparing to a single value

This is not quite the function for it. How can you Loop thru each array to compare values? Or should these data structures be different? Or transformed first?

var result = videos.filter(function(videos, index) {return videos["userID"] === blocked.documentID })

Here’s the data being compared. Goal is to compare userID with DocumentID.

const videos = [
  {
    userID: "5lyU0TCyqRcTD3y7Rs2FGV8h2Sd2",
    name: "Wedge Antilles",
    faction: "Rebels"
  },
  {
    userID: "8",
    name: "Ciena Ree",
    faction: "Empire"
  },
  {
    userID: "40",
    name: "userIDen Versio",
    faction: "Empire"
  },
  {
    userID: "66",
    name: "Thane Kyrell",
    faction: "Rebels"
  }
];

const blocked = [
  {
    id: 2,
    name: "Wedge Antilles",
    documentID: "5lyU0TCyqRcTD3y7Rs2FGV8h2Sd2"
  },
  {
    id: 8,
    name: "Ciena Ree",
    documentID: "Empire"
  },
  {
    id: 40,
    name: "Iden Versio",
    documentID: "Empire"
  },
  {
    id: 66,
    name: "Thane Kyrell",
    documentID: "Rebels"
  }
];

How to display data from Firestore? (React)

How can I put the data from firestore into my html?

Im making a ToDo list app project and this is my function for making tasks:

const Task = async (name, desc, dueDate) => {
    return await setDoc(doc(db, "projects", name), {
        name,
        id: crypto.randomUUID(),
        desc,
        dueDate,
        completed: false
    })
}

the probelm I have is that to my understanding you cant use promises in components and if I want to get data from the database it uses promises, so how am I gonna do it then?

I tried doing this:

function App() {
  
  const taskRef = doc(db, "projects", "first task")
  const taskSnap = getDoc(taskRef)

  return (
    <div>
    {taskSnap.data()}
    </div>
  )
}

but the taskSnap is a pending promise, and I cant use async / await in the App component

I have a very silly problem, can someone tell me how to assign the outer variable, the data from an async function in the following code

    let data1;

    const handleGetServices = async () => {
    const resp = await getServiceConf({ doctorId: oid });
    const { success, data } = resp;
    data1 = data;
   }
   console.log(data1) // it is coming undefined

 

why is it undefined, how can I achieve what i want…and assign the value of data to data1(the outer variable) here

Vue component not implementing in laravel project?

I am trying to get my vue component to render the messages from my database in laravel blade file and it is not rendering for some reason. I am using this Github repo https://github.com/kevilondo/group-chat, as an example to implement into my project. Now it is submitting to the database as I can see the data in the database and it is posting well, but the messages are not showing.

I have very limited experience in vue js by the way.

The error I am getting in the console is Uncaught TypeError: Cannot read properties of undefined (reading ‘prototype’).

This is what my app.js file looks like:

import Alpine from "alpinejs";

window.Alpine = Alpine;

const { default: axios } = require('axios');
const { default: Echo } = require('laravel-echo');
require('./bootstrap');

Alpine.start();
window.Vue = require('vue');

Vue.prototype.$userId = document.querySelector("meta[name='user-id']").getAttribute('content');
import VueChatScroll from 'vue-chat-scroll'

Vue.use(VueChatScroll)
Vue.component('message', require('./components/message.vue').default);


const app = new Vue({
    el: '#app',
    mounted(){

        //we assign the value of this to this variable in order to access the value of chat inside data inside our http request
        var vm = this

        //we get the group id in the url
        const url = window.location.href;
        const groupId = url.split("/").slice(-1)[0];
        vm.groupId = groupId;

        axios.get('/show_messages/' + groupId)
            .then(res => {
                //push every message one by one
                res.data.messages.map(message => {
                    vm.chat.push(message)
                    //console.log(vm);
                });
            })
            .catch(error => {
                console.log(error)
            })

        window.Echo.private('message-channel')
            .listen('MessageEvent', (e) => {
                vm.chat.push(e.message)
            });
    },
    data: {
        message: '',
        groupId: null,
        chat: [

        ],
    },
    methods: {
        send_message (event) {
            event.preventDefault();

            let token = document.head.querySelector('meta[name="csrf-token"]');

            axios.post('/send_message/'+ this.groupId, {message: this.message}, {'X-CSRF-TOKEN': token})
                .then(res => {
                    this.message = ''
                })
                .catch(error => {
                    console.log(error)
                })
        }
    }

});

This is what the bootstrap file looks like:

window._ = require('lodash');

try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');
    require('bootstrap');
} catch (e) {}

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});

This is what the Message.vue looks like:

<template>
  <div v-if="user_id !== this.$userId" class="container card bg-info mb-4 float-start" style="width: 58%;">
    <p>{{message}}</p>

    <p> <span class="text-danger">{{name}}</span> <small>{{formatDate}}</small></p>
  </div>

  <div v-else class="container card bg-default mb-4 float-end" style="width: 58%;">
    <p>{{message}}</p>
    <p> <span class="text-danger">You</span> <small>{{formatDate}}</small></p>
  </div>
</template>

<script>
export default {
  props: ['user_id', 'userLoggedIn', 'name', 'message', 'created_at'],
  mounted() {
    //
  },
  computed: {
    formatDate(){
      //we convert the text into a date

      let dateAndTime = new Date(this.created_at);

      let year = dateAndTime.getFullYear();

      let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];

      let month = months[dateAndTime.getMonth()];

      let day = dateAndTime.getDate();

      let time = dateAndTime.getHours() + ':' + dateAndTime.getMinutes();

      return `${day}  ${month}  ${year}  ${time}`

    }
  }
}
</script>

Relevant part of show.blade.php:

 <div class="card-body container">
                    <div class="message-container mb-5" id="message-container" style="overflow-y: scroll; height:400px;" v-chat-scroll>
                        <message v-for="(message, id) in chat "
                        v-bind:key="id"
                        v-bind:message = "message.message"
                        v-bind:name = "message.user.name"
                        v-bind:user_id = "message.user.id"
                        v-bind:created_at = "message.created_at"
                        >
                        </message>
                    </div>

                    <form action="/send_message/{{$group->id}}" method="post" v-on:submit='send_message'>
                        @csrf

                        <textarea name="message" id="message" v-model="message" class="col-md-12 form-control @error('message') is-invalid @enderror" cols="20" rows="5"></textarea>
                        @error('message')
                            <span class="invalid-feedback" role="alert">
                                <strong>{{$message}}</strong>
                            </span>
                        @enderror
                        <button class="btn btn-primary" type="submit">Send message</button>
                    </form>

app.blade.php file:

 <body class="font-sans antialiased">
    <div id="app">

    <div class="min-h-screen bg-gray-100">
            @include('layouts.navigation')

            <!-- Page Heading -->
            <header class="bg-white shadow">
                <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
                </div>
            </header>

            <!-- Page Content -->
            <main>
                @yield('content')


            </main>
        </div>
{{--    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>--}}
</div>
<script src="{{asset('js/bootstrap.js')}}"></script>
<script src="{{asset('js/app.js')}}"></script>
</body>

Controller method :

public function show_messages($id)
    {
        $group = Group::find($id);

        $messages = $group->group_messages()->with(['group', 'user'])->get();

        $user_loggedIn = auth()->user();

        return ['messages' => $messages, 'user_loggedIn' => $user_loggedIn];
    }

querySelector to find a DOM element which has particular text anywhere inside its tree

<div>
    <card class="card-class">
        <header class="header-class">Title 1</header>
    </card>
    <div>Stuff</div>
    <card class="card-class"> <-- This one
        <header class="header-class">Title 2</header>
    </card>
    <div>More stuff?</div>
    <card class="card-class">
        <header class="header-class">Title 3</header>
    </card>
</div>

I would like to pull out the DOM element as noted in the example using 2 conditions. The dom element I am interested in has a class card-class and somewhere inside this DOM element there is an element with class header-class which has a title inside.

I need to get a particular card BY the title text. So in this example I want the card element with ‘Title 2’. Is there any way to ahcieve this with just a selector rather than javascript?

Is it better to send data from server before rendering or to perform API calls client-side?

I have a simple question, I have a complex web app to develop, and I hesitate between two concepts :

  1. When a server recieves a GET on a page, it makes all the SQL requests, and renders the EJS page, giving all data as an argument.

  2. When a server receieves a GET on a page, it simply renders the EJS page, but the scripts associated to that page (jQuery) will make the needed requests to my server’s REST API, rendering the result afterwards.

How is it usually done in the web dev world ?

Thanks for your help

how to add and remove text with javascript on a multi-p

i tried to add and remove the text of a box clicking on a different series of p this is the code. click1 is associated by text1 and same click2 text2 ecc. the goal i want to achieve is click on click1 and the only text that appears is text1 same thing for click2 text2 ecc.

let container = document.querySelector(".container");
container.addEventListener("click", ({
  target
}) => {
  if (target.nodeName !== "P") return; // return if p is not clicked
  Array.from(document.querySelectorAll(".container1>p")).forEach(p => p.classList.remove("active1")); // make the others inactive
  target.classList.toggle("active1");
})
   .container1 p {
     display: none;
    }
    
    .container1 p.active1 {
      display:initial;
    }
 <div class="container">
            <p class="active">click1</p>
            <p>click2</p>
            <p>click3 </p>
            <p>click4</p>
            <p>click5</p>
        </div>
        <div class="container1">
            <p class="active1">
              text1
            </p>
            <p>
              text 2             
            </p>
              <p>
              text 3            
            </p> 
            <p>
              text 4             
            </p>
         </div>

Outputting raw HTML stored in an object in React

Problem – I see raw HTML code outputted as a string. Currently th data is stored in an object

Data

const data = [
  {
   title: "Hello"
   body: "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean est mauris, tempor at aliquam vitae, mattis iaculis ex. Donec suscipit enim non nisi maximus, vel tincidunt ex accumsan</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean est mauris, tempor at aliquam vitae, mattis iaculis ex. Donec suscipit enim non nisi maximus, vel tincidunt ex accumsan</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean est mauris, tempor at aliquam vitae, mattis iaculis ex. Donec suscipit enim non nisi maximus, vel tincidunt ex accumsan</p>"
   }
]

Child component

<div>
<h3>{props.title}</h3>
{props.body}
</div>

Heres what gets outputted in browser (includes <p>)

Hello

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean est mauris, tempor at aliquam vitae, mattis iaculis ex. Donec suscipit enim non nisi maximus, vel tincidunt ex accumsan</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean est mauris, tempor at aliquam vitae, mattis iaculis ex. Donec suscipit enim non nisi maximus, vel tincidunt ex accumsan</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean est mauris, tempor at aliquam vitae, mattis iaculis ex. Donec suscipit enim non nisi maximus, vel tincidunt ex accumsan</p>

How can I render the content so that the

is interpreted as a html element in the browser and not a string?