how can I get the initial width and height of an element in a React functional component

I am trying to add and remove rows and columns, with the corresponding sizees of the elements added within them. It works for the most part, however, when I first open the application instead of giving me the sizes of the elements, i.e 100px x 300px , it gives me undefinedpx x undefinedpx . After a minute or two of me saving my code it’ll change into the desired sizes I want, but initially it gives me undefined. Typescript is telling me that the div element I am referencing to is either of type Element | null , however this is not suited for resizeObserver.observe(div!);, because it’s type is just Element, unless I put it in an if else statement, but still I dont know what to do with that undefined value and why the measurements are showing up delayed.

import Burger from "./icons/Burger";
import { useState, useEffect, useRef } from "react";
import "./App.scss";

const App = (): JSX.Element => {
  const [rows, setRows] = useState<number>(0);
  const [columns, setColumns] = useState<number>(0);
  const [sidebar, setSidebar] = useState<boolean>(true);
  const [height, setHeight] = useState<number>();
  const [width, setWidth] = useState<number>();
  const elementRef = useRef(null);

  useEffect(() => {
    const div = document.querySelector(".viewport");
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        setHeight(Math.ceil(entry.contentRect.width));
        setWidth(Math.ceil(entry.contentRect.height));
      }
    });

    if (!div) {
      return;
    } else {
      resizeObserver.observe(div!);
    }
  }, [height, width]);

  const handleRowCount = (int: number) => {
    setRows(int);
  };
  const handleColumnCount = (int: number) => {
    setColumns(int);
  };

  const handleSidebar = (boolean: boolean) => {
    setSidebar(boolean);
  };

  let totalBoxes = Array.from({ length: rows * columns });
  let boxesArr = Object.keys(totalBoxes);

  return (
    <div className="app-container">
      <Burger
        rowCount={handleRowCount}
        columnCount={handleColumnCount}
        sidebarState={handleSidebar}
      />

      <div
        id="grid"
        style={{
          gridTemplateColumns: `repeat(${columns}, 1fr)`,
          width: sidebar ? "calc(100vw - 100px)" : "calc(100vw - 200px)",
        }}
      >
        {boxesArr.map((_, index) => (
          <div key={index} className="viewport" ref={elementRef}>
            {`${height}px x ${width}px`}
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;

Componentization in Django apps using custom template tags with script tag

I’m developing a Django project, comprising of several apps.
I have a base app that contains global stuff, such as CSS, JS, custom template tags (I will call them CTTs from now on), etc.

The thing is, I would like to have some CTTs that include HTML and script tags with JS code (eg. autocomplete inputs, delete button with confirmation modal, etc). My intention here is to have self-contained components to be plugged all across the project.

My concern is if this would be a good practice, as I would not separate JS code in ‘.js’ files and stuff. I tend to think that this would be ok, as the behaviour provided by JS code would be in a certain way incapsulated in the CTTs.

Would like to hear opinions about this =)

How can I dynamically change the color of a timeline’s progress bar based on the provided percentage values using HTML, CSS, and JavaScript?

I’m currently working on a timeline that represents progress, and I have a set of data points with corresponding percentage values. The timeline is styled using HTML and CSS, with a :before pseudo-element serving as the progress bar. Each data point is represented by a .timeline-item element.

I want to dynamically fill the color of this progress bar based on the value provided in the data.

I’m looking for guidance on how to dynamically change the color of the progress bar in the timeline based on the percentage values provided in the data. What would be the best approach to achieve this?

Code Snippet

const timelineData = [
  {percentage: '0%', date: '1-1-2020', title: 'Mussum ipsum cacilds 1', content: 'Content 1' },
  {percentage: '20%', date: '2-1-2020', title: 'Mussum ipsum cacilds 2', content: 'Content 2' },
  {percentage: '40%', date: '3-1-2020', title: 'Mussum ipsum cacilds 3', content: 'Content 3' },
  {percentage: '60%', date: '4-1-2020', title: 'Mussum ipsum cacilds 4', content: 'Content 4' },
  {percentage: '80%', date: '5-1-2020', title: 'Mussum ipsum cacilds 5', content: 'Content 5' },
    ];

  function generateTimelineItems() {
  const timelineContainer = document.getElementById('custom-timeline');

  timelineData.forEach(item => {
  const listItem = document.createElement('li');
  listItem.className = 'timeline-item';

  //  Convert percentage to a numeric value
  const percentage = parseInt(item.percentage, 10);

  listItem.style.width = `${percentage}%`;

  const progressBar = document.createElement('div');
  progressBar.className = 'progress-bar';
  progressBar.style.width = `${percentage}%`;

  const panel = document.createElement('div');
  panel.className = 'timeline-panel';
  panel.innerHTML = `
                <div class="timeline-heading">
                    <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> ${item.date}</small></p>
                </div>

                <p class="text-center"><strong>${item.percentage}</strong></p>
            `;
  listItem.appendChild(panel);

  timelineContainer.appendChild(listItem);
      });
    }

  generateTimelineItems();
.timeline,
    .timeline-horizontal {
  list-style: none;
  padding: 20px;
  position: relative;
  width: 100%;

    }

    .timeline:before {
  top: 0;
  bottom: 0;
  position: absolute;
  content: " ";
  width: 10px;
  background-color: transparent;
  left: 50%;
  margin-left: -5px;
  border: 10px solid #ccc;
  Set the color for the empty part of the progress bar */
  border-radius: 5px;
    }



    .timeline .timeline-item {
  margin-bottom: 20px;
  position: relative;

    }

    .timeline .timeline-item:before,
    .timeline .timeline-item:after {
  content: "";
  display: table;
    }

    .timeline .timeline-item:after {
  clear: both;
    }

    .timeline .timeline-item .timeline-panel {
  position: relative;
  max-width: 150px;
  width: 150px;
  border: 1px solid #c0c0c0;
  background: #ffffff;
  border-radius: 2px;
  padding: 20px;
      -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
    }

    .timeline .timeline-item .timeline-panel:before {
  position: absolute;
  top: 26px;
  display: inline-block;
  border-top: 16px solid transparent;
  border-left: 16px solid #c0c0c0;
  border-right: 0 solid #c0c0c0;
  border-bottom: 16px solid transparent;
  content: " ";
    }

    .timeline-horizontal {
  list-style: none;
  position: relative;
  padding: 20px 0px 20px 0px;
  display: inline-block;
    }

    .timeline-horizontal:before {
  height: 3px;
  top: auto;
  bottom: 26px;
  left: 56px;
  right: 0;
  width: 100%;
  margin-bottom: 20px;
    }

    .timeline-horizontal .timeline-item {
  display: table-cell;
  height: 280px;
  float: none !important;
  padding-left: 0px;
  padding-right: 0px;
  margin: 0 auto;
  vertical-align: bottom;
    }

    .timeline-horizontal .timeline-item .timeline-panel {
  top: auto;
  bottom: 64px;
  display: inline-block;
  float: none !important;
  left: 0 !important;
  right: 0 !important;
  width: 100%; */
  width: 320px;
  margin-bottom: 5px;

    }

    .timeline-horizontal .timeline-item .timeline-panel:before {
  top: auto;
  bottom: -16px;
  left: 28px !important;
  right: auto;
  border-right: 16px solid transparent !important;
  border-top: 16px solid #c0c0c0 !important;
  border-bottom: 0 solid #c0c0c0 !important;
  border-left: 16px solid transparent !important;
    }

    .timeline-horizontal .timeline-item:before,
    .timeline-horizontal .timeline-item:after {
  display: none;
    }

    .timeline-horizontal .timeline-item .timeline-badge {
  top: auto;
  bottom: 0px;
  left: 43px;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div style="display: inline-block; width: 100%; overflow-y: auto">
        <ul class="timeline timeline-horizontal" id="custom-timeline"></ul>
      </div>
    </div>
  </div>
</div>

Why does a Jest spy break when the tested file’s import of the spied function is destructured?

Test file:

const webhook = require('../../../../../../src/lib/apis/webhook');

const internalFunc = jest.spyOn(webhook, 'handleWebhookCreation').mockImplementation(() => {
   return expectedReturn;
});

File being tested:

const { handleWebhookCreation } = require('../../../apis/webhook');

const createWebhook = async (req, res) => {
    for (const webhook of payload) {
      results.push(await handleWebhookCreation(webhook, t));
    }
};

This does not work. The normal function is called, not a mocked/spied version

I then found out, this fixes it, instead of destructuring the method, get entire object then call it as such with the following changes

const _webhook = require('../../../apis/webhook');
...
results.push(await _webhook.handleWebhookCreation(webhook, t));

Now the spy/mocking is correctly done in my unit test

I have no idea why this is, would anyone know why?

How to get the id of the element that the text caret is currently on?

Basically, this webpage will allow users to make documents (of some sort) using contentEditable div’s called block’s. The problem is that the user will more than likely need multiple blocks, as a block is an equivalent to sentence/line or a heading or a sub-heading etc. I need to get the id of the block that the text caret is currently on, so I can prevent the user from accidentally deleting the default block. I’ve added a ‘keydown’ event listener to the container of the blocks, and basically it actively checks if the backspace key is pressed. If the caret is at the beginning of the block and backspace is pressed then the block is deleted. Here is my relevant Javascript:

function findClosestAncestor(element, className) {
    while (element && (!element.classList || !element.classList.contains(className))) {
        element = element.parentElement;
        console.log(element);
    }
    return element;
}
pageContainer.addEventListener('keydown', function (e) {
    const selection = window.getSelection();
    const range = selection.getRangeAt(0);

    if (e.key === 'Enter') {
      // Prevent the default behavior (new line) to avoid the creation of a new div
      e.preventDefault();
      blockMaker();
    }

    if (e.key === 'Backspace') {
        console.log(blockIndex);
        const block = pageContainer.querySelector('.block');
        console.log(block, range.startOffset);

        if (document.caretPositionFromPoint) {
            caretPosition = document.caretPositionFromPoint(e.clientX, e.clientY);
            var containerElement = caretPosition.offsetNode.parentElement;
            var containerId = containerElement.id;
            console.log(containerID);
        } else if (document.elementFromPoint) {
            // Use WebKit-proprietary fallback method
            caretRange = document.caretRangeFromPoint(e.clientX, e.clientY);
            console.log(caretRange);
            var containerElement = findClosestAncestor(caretRange.startContainer, 'block');
            console.log(containerElement);
            var containerId = containerElement.id;
            console.log(containerId);    
        }
        
        if (containerId === "block-container1" && range.startOffset === 0) {
            // Prevent the default behavior of the backspace key
            e.preventDefault();
            console.log("Cannot delete the first block.");
        }else if(range.startOffset === 0){
            var blockId = ("block-container"+blockIndex);
            var blockToBeDeleted = document.getElementById(blockId);
            blockToBeDeleted.parentNode.removeChild(blockToBeDeleted);
            blockIndex--;
            const blocks = document.querySelectorAll('.block');
            var currentBlock = blocks[blockIndex - 1];
            currentBlock.focus();
        }
    }
});

My version of chrome doesn’t support document.caretPositionFromPoint and when I try the depreciated version it returns this li tag which is inside another div above the pageContainer Div. I don’t understand why, and I’ve tried making this function findClosestAncestor(), but that just returns the whole page.Is there another way to approach finding the element that the text caret is in? As I do not like this way, because I don’t fully understand what’s going on.

Set variable to contents of file using fetch in JavaScript [duplicate]

I want to save the contents of a JSON file hosted on the web to a variable so I can access it more easily.

I tried this:

let tempInfo;
const info = (function getInfo() {
    fetch('https://mesure.x10.mx/twelve-of-code/not-an-api/challenges/information.json')
        .then(res => res.text())
        .then(text => {
            tempInfo = text;
        })
    return tempInfo;
})();
alert(info);

… and it just alerts “undefined” each time

map and filter is outputting an array of outcomes and not expected value

I am a little confused on the output of my variable ‘ready’ where I was hoping it will take the correct value from the json, which I was expecting to be ‘true’ but comes back with an array ['false', 'true'] and so it doesn’t go into the condition set. Does anyone know what it’s displaying an array with possible outcomes and not the value which I expect to be true?

Example JSON

{
      "data": {
        "competition": [
          {
            "events": [
              {
                "field": [
                  {
                    "ready": "true",
                    "__typename": "Field"
                  },
                  {
                    "ready": "true",
                    "__typename": "Field"
                  },
                  {
                    "ready": "true",
                    "__typename": "Field"
                  }
                ],
                "__typename": "Event"
              },
              {
                "field": [
                  {
                    "ready": "true",
                    "__typename": "Field"
                  },
                  {
                    "ready": "true",
                    "__typename": "Field"
                  },
                  {
                    "ready": "true",
                    "__typename": "Field"
                  }
                ],
                "__typename": "Event"
              }
            ],
            "__typename": "Competition"
          }
        ]
      }
    }

Code:

export function dailyListConverter(list) {
      const ready = JSON.parse(list)
        .data.competition[0].events.filter((event) => event.field)
        .map((event) => event.field[0].ready);
      if (ready === "true") {
console.log("I'M HERE")
      }
      console.log("OUTSIDE CONDITIONS")
}

Is there a way to send large chunk of data over BLE in JavaScript?

I’m trying to send an image (15000 byte) to a BLE peripheral.

After searching I only found p5.ble.js library that supports BLE in JavaScript.

function setup() {
    myBLE = new p5ble();

    // Create a 'Write' button
    const writeButton = createButton('Write');
    // writeButton.position(input.x + input.width + 15, 100);
    writeButton.mousePressed(writeToBle);

    for(let i = 0; i < 15000; i++)
    {
      img[i] = i;
      // console.log(img[i]);
    }
}


function writeToBle() {
  var str1 = new TextDecoder().decode(img.slice(0,127));

  // sending 2nd chunk
setTimeout(function(){
    var str2 = new TextDecoder().decode(img.slice(128,255)); // this just result in garbage
      myBLE.write(myCharacteristic, str2);
    }, 1000);

    // sending first chunk
    myBLE.write(myCharacteristic, str1);
    // myBLE.write(myCharacteristic, img.slice(0,127)); // this doesn't send
}

This is my first JavaScript code (and it is just a modification of an example code from p5 ble).

With this code I can send str1 without any problems. I receive the right data and the right number of bytes.

But for some reason when sending str2 I receive around 500 bytes instead of 128 bytes and the data is just a repetition of these numbers 239, 191, 189!

What I’m doing wrong here?

Is there a better alternative for p5.ble library?

Invalid hook call problem. Hooks can only be called inside of the body of a function component

i want to create todo app using react i use the useContext hook but i get the following problem

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

import { useState } from 'react'
import TodoStore from './Hooks/TodoStore'
import './App.css'
import TodosForm from './Component/TodosForm'
import Tasks from './Component/Tasks'
function App() {
const [todolist,setTodoList]=useState([]);
const fillTodoList=(todo)=>{
  setTodoList([todo,...todolist])
}
  return (
    <TodoStore.Provider value={setTodoList}>
    <TodosForm fillTodoList={fillTodoList} />
    <Tasks alltasks={todolist} setList={setTodoList}/>
    </TodoStore.Provider>
  )
}

export default App

import React from 'react'
import Completed from '../Operations/Completed'
import deleteTask from '../Operations/deleteTask'

function Tasks(props) {
  return (
    <div>
        {
            props.alltasks.map((item)=><div  key={item.id}>
            <span onClick={()=>Completed(item.id,props.alltasks)}>{item.text}</span>
            <button onClick={()=>deleteTask(item.id,props.alltasks)}>X</button>
            </div>)
        }
       
    </div>
  )
}

export default Tasks
import { useContext } from "react"
import TodoStore from "../Hooks/TodoStore"
const deleteTask=(id,alltasks)=>{
const {setList}=useContext(TodoStore);
const result=alltasks.filter((item)=>item.id!=id)
setList([...result])
}
export default deleteTask


Show window.confirm for prevent changing the URL

Needs to prevent changing url from my component. So, nees to show a message, and if user choose cancel – don’t change the URL, if OK – change the URL. How I can make this logic in next 13.4

It’s my current logic, but it doesn’t work. I even don’t see the window.confirm message

useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const mess = window.confirm('Are you sure you want to leave?');
event.returnValue = mess;
if (!mess) {
event.preventDefault();
>       }
>     };

window.addEventListener('beforeunload', handleBeforeUnload);

return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
>     };

Disable photo preview when taking an image trough browser

I have a button that when clicked opens the camera of the device and allows the user to take a photo and then upload it. However, when photo is taken a preview of it is shown on the display and there are Retake & Submit buttons (This is behavior in IOS). Is there a way to stop this from happening and straight up close the camera, and upload the photo after the user presses the shutter button?

Here is the code I am using to invoke the camera:

          $('#cameraInput').on('change', function(e) {
                handleFileSelect(e);
            });
        
            function handleFileSelect(event) {
                const input = event.target;
        
                if (!input.files || !input.files[0]) {
                    return;
                }
        
                const reader = new FileReader();
        
                reader.onload = function(e) {
                    // Upload the image to your server immediately
                    uploadImageToServer(e.target.result);
                };
        
                reader.readAsDataURL(input.files[0]);
            }

If that is not possible is there an alternative? Like some kind of JS library that will show the camera feed directly in the browser but still have the basic controls like changing the lens the camera uses, enabling/disabling the flash?

Quasar VUE_PROD_HYDRATION_MISMATCH_DETAILS is not defined

Im using quasar together with Vite. After installing quasar with yarn create quasar I get the following warning in the console.

__VUE_PROD_HYDRATION_MISMATCH_DETAILS__ is not explicitly defined.
 You are running the esm-bundler build of Vue, which expects these 
compile-time feature flags to be globally injected via the bundler 
config in order to get better tree-shaking in the production 
bundle.

How can I get rid of it? I cannot find any information on where I shall define this in Quasar Framework

How to recovery a publickey with “js-ethereum-cryptography” version 2.0

I have a problem with the method “recoverPublicKey()” in the latest version of “js-ethereum-cryptography”. In my code snippet, which I am sharing with you here, I can get the values of “{ r, s, recovery }”, but I cannot recover the public key, I get the “undefined” error on my browser. Thanks for your help!

app.post("/send", (req, res) => {
  const { sender, recipient, amount, signature } = req.body;
  const { r, s, recovery } = signature;
  const publicKey = secp.secp256k1.recoverPublicKey({ r, s, recovery }, sender);
  console.log(publicKey.toString());

I’m making a text based solitaire and I’m new to JS I wrote some code that works fine but my programmer friend says that its a miracle the code works?

    //Table
    var tableau = [[], [], [], [], [], [], []];

    function debugTableau(){ //Function to print out the tableau array to the console
        for (var column in tableau){
            for (var card in column){
                printToTerminal(tableau[column[card]]);
            }
        }
    }

    //Project hosted[ here](https://solitaire.theohaines.xyz)

The code works perfectly fine but my programmer friend tells me its a miracle the code works, can anybody tell me why?