I am trying to build a tree in React wherein one can add nodes and connect them and move them around, like the included picture.
How does one go about doing this?
I am working with create-react-app
I have tried all sorts of things but I keep having trouble with event.clientX/event.pageX, it keeps giving me random values which results in the nodes flickering.
To me it makes most sense to have the node-moving functionality on the level of the tree but that approach gives this flickering problem.
How to prevent event.clientX from giving me random values?
The problem i normally have is the flickering of the sort in this codepen:
https://codesandbox.io/s/delicate-http-nnzx4?file=/src/App.js
(click and drag)
I have tried a number of things and the only way it works (altough buggy) is the way below where the node-moving functionality is on the level of the node:
import React, {useState,useEffect,useRef, useCallback, createRef} from 'react';
import "./PrinciplesTree.css"
function Line(props){
function clickhandler(e){
e.stopPropagation()
props.deletenodeconnection(props.firstpoint.node_number,props.secondpoint.node_number)
}
const firstpoint = props.firstpoint
const secondpoint = props.secondpoint
var x1 = firstpoint.anchor_pos.anchorposx
var y1 = firstpoint.anchor_pos.anchorposy
var x2 = secondpoint.anchor_pos.anchorposx
var y2 = secondpoint.anchor_pos.anchorposy
if (x2 < x1) {
var tmp;
tmp = x2 ; x2 = x1 ; x1 = tmp;
tmp = y2 ; y2 = y1 ; y1 = tmp;
}
var lineLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
var m = (y2 - y1) / (x2 - x1);
var degree = Math.atan(m) * 180 / Math.PI;
const divstyle = {transformOrigin: 'top left', transform: 'rotate(' + degree + 'deg)', width: lineLength + "px", height: 1 + 'px', background: 'black',
position: 'absolute', top: y1 + "px", left: x1 + "px"}
return <div className='line' style={divstyle} onClick={clickhandler}></div>
}
function Node(props) {
const [val, setval] = useState("Enter Principle");
const node_number = props.nodeN
const node_width = '150px'
const anchorel = useRef(null)
var offsetx = 0
var offsety = 0
let parentleft = 0
let parentright = 0
let parenttop = 0
let parentbottom = 0
const onclick = e =>{
e.stopPropagation();
const anchorpositionX = anchorel.current.getBoundingClientRect().left
const anchorpositionY = anchorel.current.getBoundingClientRect().top
const parentleft = e.target.parentElement.getBoundingClientRect().left
const parenttop = e.target.parentElement.getBoundingClientRect().top
const anchorpos = {anchorposx: anchorpositionX - parentleft, anchorposy: anchorpositionY - parenttop}
props.connectnode.current(node_number,anchorpos)
}
const movehandler = e => {
var newvalx = e.clientX-parentleft-offsetx
var newvaly = e.clientY-parenttop-offsety
if(((parentleft + newvalx) < parentright + 5 && (parentleft + newvalx) > parentleft - 5) &&
(parenttop + newvaly > parenttop - 5 && parenttop + newvaly < parentbottom + 5)){
props.updatenode(node_number,newvalx,newvaly)
}
}
const addmovehandler = e => {
const parent = e.target.parentElement
parentleft = parent.getBoundingClientRect().left
parentright = parent.getBoundingClientRect().right
parenttop = parent.getBoundingClientRect().top
parentbottom = parent.getBoundingClientRect().bottom
offsetx = e.clientX - e.target.getBoundingClientRect().left
offsety = e.clientY - e.target.getBoundingClientRect().top
document.addEventListener('mouseover',movehandler)
}
const removenodehandler = e =>{
const parent = e.target.parentElement
document.removeEventListener('mouseover',movehandler)
}
function edit(e){
e.stopPropagation();
if(e.key === 'Enter'){
setval(e.target.value)
}
}
return <div className='node' style = {{left: props.posX, top: props.posY, width: node_width}} onMouseDown={addmovehandler} onMouseUp = {removenodehandler} onClick = {onclick}>
<div className='anchor' ref={anchorel}></div>
<textarea className = 'principle' name = {val} onKeyDown={edit} placeholder = {val}></textarea>
<img src="cross.png" className='Cross' onClick={(e) => props.deletenode(node_number)}></img>
</div>
}
function PrinciplesTree() {
const [nodes, setnodes] = useState([]);
const [connectednodes, setconnectednodes] = useState([]);
const nodetoconnect = useRef(null)
const connectnoderef = useRef()
useEffect(() => {
setnodes([{key: 1, nodeN: 1, posX: 0, posY: 0, deletenode: deletenode, connectnode: connectnoderef, updatenode: updatenode}])
},[]);
const connectnode = (nodeN,anchorpos) => {
if(nodetoconnect.current == null){
nodetoconnect.current = {node_number: nodeN, anchor_pos: anchorpos}
}else if(nodetoconnect.current != null && nodeN != nodetoconnect.current.node_number )
{
const node_to_add = nodetoconnect.current
const firstnodenumber = nodetoconnect.current.node_number
const secondnodenumber = nodeN
var foundpair = false
connectednodes.forEach(connectednode => {
const firstnode = connectednode.first.node_number
const secondnode = connectednode.second.node_number
if((firstnode == firstnodenumber && secondnode == secondnodenumber) || (firstnode == secondnodenumber && secondnode == firstnodenumber)){
foundpair = true
}
})
const newnodetoconnect = {first: node_to_add, second: {node_number: nodeN, anchor_pos: anchorpos}}
if(foundpair == false){
setconnectednodes(connectednodes => [...connectednodes,newnodetoconnect])
}
nodetoconnect.current = null
}
}
connectnoderef.current = connectnode
function deletenodeconnection(node1,node2){
setconnectednodes(prevconnectednodes => {
return prevconnectednodes.filter(connectednodes => !(connectednodes.first.node_number == node1 && connectednodes.second.node_number == node2))
})
}
const deletenode = (NodeN) =>{
setnodes(prevnodes => {
return prevnodes.filter(node => node.nodeN !== NodeN)})
}
const updatenode = (NodeN,newposx,newposy)=> {
const updnode = {key: NodeN, nodeN: NodeN, posX: newposx, posY: newposy, deletenode: deletenode, connectnode: connectnoderef, updatenode: updatenode}
setnodes(nodes => (
nodes.map(node => {
if(node.nodeN == NodeN){
return updnode
}
else return node }
)))
}
function createnode(e){
var el = e.target
var posX=e.clientX-el.getBoundingClientRect().left
var posY=e.clientY-el.getBoundingClientRect().top
var newkey = 0;
nodes.forEach(node => {
if(node.key >= newkey){
newkey = parseInt(node.key) + 1
}
});
var newnode = {key: newkey, nodeN: nodes.length + 1, posX: posX, posY: posY, deletenode: deletenode, connectnode: connectnoderef, updatenode: updatenode}
setnodes(nodes => [...nodes, newnode]);
}
return <div onClick={createnode} className='TreeCanvas'>
{connectednodes.map(connectednode=> <Line firstpoint = {connectednode.first} secondpoint = {connectednode.second} deletenodeconnection={deletenodeconnection}/>)}
{nodes.map(node => <Node key = {node.key} nodeN = {node.nodeN} posX = {node.posX} posY = {node.posY} deletenode = {node.deletenode}
connectnode = {node.connectnode} updatenode = {node.updatenode}/>)}
</div>
}
export default PrinciplesTree;
Someone with the handle #wordswithjosh helped me a great deal on Reddit so I want to post his answer here for any people who might have the same question in the future.
Gotcha - I've had some difficulty in the past getting draggable components to update smoothly. Where I've found the most success is usually resisting the urge to use the onDrag or onMouseMove event in the component, instead just using the mouse movement event to remember the position of the cursor, and instead using requestAnimationFrame to actually visually move the component.
This seems like overkill at first, but when you want multiple components to visually update simultaneously, I've found that the most reliable pattern is something like this:
const TreeNode = () => {
const [originalLeft, setOriginalLeft] = useState(0); // very rarely is an initial value of 'undefined' desirable; this is one of those times
const [originalTop, setOriginalTop] = useState(0);
const [left, setLeft] = useState();
const [top, setTop] = useState();
const [originalMouseX, setOriginalMouseX] = useState(0);
const [originalMouseY, setOriginalMouseY] = useState(0);
const [newMouseX, setNewMouseX] = useState(0);
const [newMouseY, setNewMouseY] = useState(0);
const mutableFrameRef = useRef({ paused: true, lastFrame: null });
const selfRef = useRef(null);
const loop = () => {
// this shouldn't be necessary, but it's a failsafe to prevent
// runaway recursive function behavior I've experienced in the
// past when working with rAF
if (mutableFrameRef.current.paused) return;
// on every frame, set the new position of the div to its
// previous position plus the current offset of the mouse
setLeft(originalLeft + (newMouseX - originalMouseX));
setTop(originalY + (newMouseY - originalMouseY));
// this IS necessary, and is the default way of keeping a reference
// to the handle used to cancel the last requested frame
mutableFrameRef.current.lastFrame = requestAnimationFrame(loop);
};
// not destructuring these params for performance
const handleMouseMove = e => {
setNewMouseX(e.clientX);
setNewMouseY(e.clientY);
};
const handleMouseDown = ({ clientX, clientY }) => {
setOriginalMouseX(clientX);
setOriginalMouseY(clientY);
setNewMouseX(clientX);
setNewMouseY(clientY);
document.addEventListener('mousemove', handleMouseMove);
};
const handleMouseUp = ({ clientX, clientY }) => {
mutableFrameRef.paused = true;
cancelAnimationFrame(mutableFrameRef.current.lastFrame);
// one more time just to be sure
setLeft(originalLeft + (newMouseX - originalMouseX));
setTop(originalY + (newMouseY - originalMouseY));
document.removeEventListener('mousemove', handleMouseMove);
};
useEffect(() => {
// default both our original and "live" top left corner coordinates to what they are on first paint
const { x, y } = selfRef.current.getBoundingClientRect();
setOriginalLeft(x);
setOriginalTop(y);
setLeft(x);
setTop(y);
}, []);
return (
<div
ref={selfRef}
className='tree-node'
style={{
top,
left
}}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
draggable
>
// text stuff, tree node contents, etc - not relevant
</div>
);
};
Full disclosure, I haven't tested this exact config, I kinda wrote it live 😅 but I've used almost this exact pattern in the past, and I think you can get the idea - the main thing is that we only ask the browser to re-draw the div on every monitor refresh, which can drastically improve performance and help eliminate odd flickering.
You could, of course, avoid redrawing the div altogether by simply using the onDrag event to update the saved cursor position, and then update the actual drawn div location with onDragEnd, but I imagine the sort of "ghosting" behavior exhibited during the builtin HTML drag is not what you're looking for, and would not provide nearly as pretty of a user experience.
Related
Problem: I call playerPlaceShip (from a DOM interaction module) inside a game loop module. This lets the user hover the board, click to place the ship, and finally in the event handler call board.placeShip() (from the gameBoard module). This works in isolation, but when I add another playerPlaceShip call to place an additional ship, it executes immediately before the first ship can be placed by clicking.
Desired outcome: A way to wait until the click event from the first function call completes before the next function call begins.
What I've tried: Hours of unsuccessfully trying to write and use promises. Hours of reading about promises. Spent a lot of time unsuccessfully trying to rethink how the code is structured. It seems like the click event should be driving the next action, but I don't see how to do that without writing more and more function calls inside the click event handler, which would seem to take control of the game flow away from the game loop module and put it in the DOM interaction module.
Full modules on GitHub: https://github.com/Pete-Fowler/battleship/tree/player-place-ships/src/modules
Code excerpts:
// In game loop module after creating ships, players, and board objects:
// Render Board
renderBoard(p1Board, p1Box);
renderBoard(p2Board, p2Box);
// Player place ships - lets user hover and click board to place
playerPlaceShip(p1Board, p1Carrier);
playerPlaceShip(p1Board, p1Battleship); // this gets called too soon before click event from the first call completes
// In DOM module:
const clickToPlace = (e, board, ship) => {
let { x, y } = e.target.dataset;
x = parseInt(x, 10);
y = parseInt(y, 10)
board.place(ship, x, y, axis);
renderShadow(e, 'place', ship.length);
removeListeners();
}
// Main function for player to place ship
const playerPlaceShip = (board, ship) => {
const squares = document.querySelectorAll('#p1 .board .square');
narrative.textContent = `Lead your ${ship.type} into battle. Press X to steer.`;
squares.forEach(square => {
square.addEventListener('mouseover', (e) => renderShadow(e, 'fill', ship.length));
square.addEventListener('mouseout', (e) => renderShadow(e, 'clear', ship.length));
square.addEventListener('click', (e) => clickToPlace(e, board, ship));
});
window.addEventListener('keydown', (e) => {
if(e.key === 'x') {
switchAxis();
squares.forEach(square => square.classList.remove('hovered'));
renderShadow(lastCoords, 'fill', ship.length);
}
});
}
Thanks!
I wasn't able to checkout the branch, got a strange error: invalid path 'src/images/background.jpg:Zone.Identifier', maybe because of the colon : after jpg. So I downloaded the zip.
Otherwise I would have done a pull request, that would be easier for you to merge.
I added logic so that the ship is always inside the board, and created a custom event to trigger after place ship. There are comments, see if this will help you move on.
game.js
import gameBoard from "./gameBoard";
import player from "./player";
import makeShip from "./ship";
import { p1Box, p2Box, playerPlaceShip, placeShipEventName, AIPlaceShip, renderBoard, UIAttack } from "./DOM";
const startingShipCount = 5;
// SETUP
// Make game boards
const p1Board = gameBoard();
p1Board.init();
const p2Board = gameBoard();
p2Board.init();
// Make players
const p1 = player("Gustav", p1Board, "human");
const p2 = player("Terminator", p2Board, "AI");
// Make p1 ships
const p1Ptb = makeShip("patrolBoat");
const p1Sub = makeShip("sub");
const p1Destroyer = makeShip("destroyer");
const p1Battleship = makeShip("battleship");
const p1Carrier = makeShip("carrier");
// Make AI ships
const p2Ptb = makeShip("patrolBoat");
const p2Sub = makeShip("sub");
const p2Destroyer = makeShip("destroyer");
const p2Battleship = makeShip("battleship");
const p2Carrier = makeShip("carrier");
// Render Board
renderBoard(p1Board, p1Box);
renderBoard(p2Board, p2Box);
// AI place ships
p2Board.place(p2Ptb, 0, 1, "y");
p2Board.place(p2Sub, 2, 6, "y");
p2Board.place(p2Destroyer, 4, 2, "y");
p2Board.place(p2Battleship, 6, 6, "y");
p2Board.place(p2Carrier, 8, 4, "y");
renderBoard(p1Board, p1Box);
renderBoard(p2Board, p2Box);
//################################################
//###################### HANDLE placeShipPhase
//################################################
let countShipsPlaced = 0;
const handlePlaceShipPhase = () => {
countShipsPlaced++;
if (countShipsPlaced == startingShipCount) {
startGame();
} else {
playerPlaceShip(p1Board, p1Carrier);
}
};
//######################################################
//####### LISTENING to the custom event Place Ship
//######################################################
window.addEventListener(placeShipEventName, handlePlaceShipPhase);
// Player places ships
playerPlaceShip(p1Board, p1Carrier);
const startGame = () => {
alert("Game started, battle!");
};
// MAIN GAME LOOP - will need loop
// Player attack
// UIAttack(p2Board);
// AI attack
// Gameover - after exit loop
// The game loop should set up a new game by creating Players and Gameboards.
// For now just populate each Gameboard with predetermined coordinates. You can
// implement a system for allowing players to place their ships later.
// The game loop should step through the game turn by turn using only methods
// from other objects. If at any point you are tempted to write a new function
// inside the game loop, step back and figure out which class or module that
// function should belong to.
// Create conditions so that the game ends once one players ships have all
// been sunk. This function is appropriate for the Game module.
DOM.js
/* eslint-disable no-unused-expressions */
const p1Box = document.querySelector("#p1");
const p2Box = document.querySelector("#p2");
const narrative = document.querySelector("#narrative");
let axis = "y"; // used to render shadow in playerPlaceShip
let selectedSquares = [];
let lastCoords;
const boardSize = 10;
//save the current ship to be used in the "x" key event listender
let currentShip;
//moved outside of the placeship otherwise will add duplicated events
window.addEventListener("keydown", (e) => {
if (e.key.toLocaleLowerCase() === "x") {
const squares = document.querySelectorAll("#p1 .board .square");
switchAxis();
squares.forEach((square) => square.classList.remove("hovered"));
renderShadow(lastCoords, "fill", currentShip.length);
}
});
//#############################################
//##### CREATING the custom event Place Ship
//#############################################
const placeShipEventName = "playerplaceship";
const placeShipEvent = new Event(placeShipEventName);
// Helper functions for playerPlaceShip
const switchAxis = () => {
axis === "x" ? (axis = "y") : (axis = "x");
};
const renderShadow = (e, fill, length) => {
let { x, y } = e.target.dataset;
x = parseInt(x, 10);
y = parseInt(y, 10);
selectedSquares = [];
let count = countOfSquaresOutOfBoard(x, y, length);
//#### LOGIC TO RENDER SHIP ALWAYS INSIDE BOARD
for (let i = -count; i < length - count; i++) {
setSelectedSquares(x, y, i);
}
for (const el of selectedSquares) {
fill === "fill" ? el.classList.add("hovered") : el.classList.remove("hovered");
if (fill === "place") {
el.classList.add("placed");
}
}
lastCoords = e;
};
const removeListeners = () => {
const squares = document.querySelectorAll("#p1 .board .square");
squares.forEach((square) => {
square.replaceWith(square.cloneNode());
});
};
const clickToPlace = (shipSquare, board, ship) => {
let { x, y } = shipSquare.dataset;
x = parseInt(x, 10);
y = parseInt(y, 10);
board.place(ship, x, y, axis);
renderShadow(lastCoords, "place", ship.length);
removeListeners();
//#######################################################
//############# TRIGGERING the custom event place ship
//#########################################################
window.dispatchEvent(placeShipEvent);
console.log(board.getMap());
};
// Main function for player to place ship
const playerPlaceShip = (board, ship) => {
currentShip = ship;
const squares = document.querySelectorAll("#p1 .board .square");
narrative.textContent = `Lead your ${ship.type} into battle. Press X to steer.`;
squares.forEach((square) => {
square.addEventListener("mouseover", (e) => renderShadow(e, "fill", ship.length));
square.addEventListener("mouseout", (e) => renderShadow(e, "clear", ship.length));
square.addEventListener("click", (e) => clickToPlace(selectedSquares[0], board, ship));
});
};
const countOfSquaresOutOfBoard = (x, y, length) => {
let count = 0;
if (axis === "x") {
count = x + length - boardSize;
}
if (axis === "y") {
count = y + length - boardSize;
}
return count < 0 ? 0 : count;
};
const setSelectedSquares = (x, y, i) => {
if (axis === "x") {
selectedSquares.push(document.querySelector(`#p1 .square[data-x="${x + i}"][data-y="${y}"]`));
} else {
selectedSquares.push(document.querySelector(`#p1 .square[data-x="${x}"][data-y="${y + i}"]`));
}
};
// Lets AI place ship
const AIPlaceShip = (board) => {};
const renderBoard = (board, box) => {
// Clear old content prior to re-render if needed
let grid = document.querySelector(`#${box.id} .board`);
if (grid) {
grid.textContent = "";
} else {
grid = document.createElement("div");
grid.className = "board";
}
// Individual squares on board
for (let i = 0; i <= 9; i += 1) {
for (let j = 9; j >= 0; j -= 1) {
const square = document.createElement("div");
square.className = "square";
square.dataset.x = i;
square.dataset.y = j;
grid.append(square);
}
}
box.append(grid);
};
// Player attack phase - sends x, y from clicked square to board.incoming()
const attackCallback = (e, board) => {
const { x, y } = e.target.dataset;
board.incoming(x, y);
const squares = document.querySelectorAll("#p2 .square");
squares.forEach((el) => {
el.removeEventListener("click", attackCallback);
el.classList.remove("hoverable");
});
console.log(board.getMap());
};
// Player attack phase - adds click event listener and hover effect
const UIAttack = (board) => {
const squares = document.querySelectorAll("#p2 .square");
squares.forEach((el) => {
el.addEventListener("click", (e) => attackCallback(e, board));
el.classList.add("hoverable");
});
narrative.textContent = "Click to fire on the enemy fleet";
};
export { p1Box, p2Box, placeShipEventName, playerPlaceShip, AIPlaceShip, renderBoard, UIAttack };
I'm using TensorflowJs and react to test gesture based interfaces. I've mapped an image cursor to my mobile phone and when i move my mobile phone across a camera feed, it moves the image element accordingly.
An object detection model runs in a react component like this:
const runCoco = async () => {
const net = await cocossd.load();
console.log("COCOSSD model loaded.");
// Loop and detect hands
setInterval(() => {
detect(net);
}, 10);
};
useEffect(runCoco,[]);
//public variables
const webcamRef = useRef(null);
const canvasRef = useRef(null);
const xScalar = 2.5;
const yScalar = 1.7;
const yShift = 389.203119516;
I move the cursor element over a large button in my program and when I want to click on an element i bring in a plastic bottle into frame (this was just a quick way to get testing). When the bottle is detected I call document.elementFromPoint(x,y) and dispatch a click event onto the element below the cursor at that time.
const detect = async (net) => {
// Check data is available
if (
typeof webcamRef.current !== "undefined" &&
webcamRef.current !== null &&
webcamRef.current.video.readyState === 4
) {
// Get Video Properties
const cursor = document.getElementById('cursor');
const video = webcamRef.current.video;
const videoWidth = webcamRef.current.video.videoWidth;
const videoHeight = webcamRef.current.video.videoHeight;
// Set video width
webcamRef.current.video.width = videoWidth;
webcamRef.current.video.height = videoHeight;
// Make Detections
const obj = await net.detect(video);
//console.log(obj);
try
{
//all this manipulation below was just a good way I found to convert the bounding box outputs
//into comfortable larger x and y coordinates for the user to navigate with.
x = (-1 * (((obj[0]['bbox'][0] + obj[0]['bbox'][2] ) / 2))) + 640;
y = obj[0]['bbox'][1] - 200; ///200px higher than the top of the bounding box
x = x * xScalar;
y = (y * yScalar);
if (obj[0]['class'] === "cell phone" && obj[0]['score'] > 0.8 )
{
prevX = x;
prevY = y;
cursor.style.transform = `translate(${ x }px, ${ y }px)`;
}
else if ( obj[0]['class'] === "bottle" )
{
console.log("");
x = document.querySelector('#cursor').getBoundingClientRect().left;
y = document.querySelector('#cursor').getBoundingClientRect().top;
console.log( " Model Values: " + prevX + ", " + (prevY + yShift));
console.log( " Cursor Values: " + x + " " + y );
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
// x = 305.45550537109375;
// y = 271.7203674316406;
console.log( " Just before click: " + x + " " + y );
var el = document.elementFromPoint( Math.trunc(x), Math.trunc(y) );
console.log(" After click: " + x + " " + y)
el.dispatchEvent(ev);
}
}
catch (err)
{
console.error(err);
}
}
}
This is where the issue arises:
When I feed the literal values here, it works. the button is clicked and all is good.
x = 305.45550537109375;
y = 271.7203674316406;
var el = document.elementFromPoint( Math.trunc(x), Math.trunc(y) );
el.dispatchEvent(ev);
But if I feed it this way:
x = document.querySelector('#cursor').getBoundingClientRect().left;
y = document.querySelector('#cursor').getBoundingClientRect().top;
No click is registered, the dispatched event does nothing.
Here is an image of some console outputs I tried to debug it with:
The values barely differ so I really can't figure out why it doesn't work.
This is an image of a button and the cursor in the program, if it helps
I would like to add multiple photos from the Array in this code to the elements, but it adds just one photo from the Array to the first Element.
I tried adding for loop, but I dont know where to start and where to end the loop. Could you please take a look to the code using the link (codepen)?
thank you
let zoomLevel = 1;
const images = [
{
thumb: 'http://localhost:8080/links/works/Print/001.webp',
hires: 'http://localhost:8080/links/works/Print/001.webp'
},
{
thumb: 'https://tasvir-graphic.de/links/works/digital/unterwelt.webp',
hires: 'https://tasvir-graphic.de/links/works/digital/unterwelt.webp'
}
]
// set to random image
let img = images[Math.floor(Math.random() * images.length)];
image.getElementsByTagName('a')[0].setAttribute('href', img.hires);
image.getElementsByTagName('img')[0].setAttribute('src', img.thumb);
const preloadImage = url => {
let img = new Image();
img.src = url;
}
preloadImage(img.hires);
const enterImage = function(e) {
zoom.classList.add('show', 'loading');
clearTimeout(clearSrc);
let posX, posY, touch = false;
if (e.touches) {
posX = e.touches[0].clientX;
posY = e.touches[0].clientY;
touch = true;
} else {
posX = e.clientX;
posY = e.clientY;
}
You can check this better using Codepen HERE.
const image = document.querySelectorAll('.image');
/* Store the number of all elements with css class 'image' */
let imageElementsCount = image.length;
for (index = 0; index < imageElementsCount; index++)
{
let arrayElementPos = Math.floor(Math.random() * images.length);
/* Receive the requested element from array with image objects */
let imageObject = images[arrayElementPos];
preloadImage(imageObject.hires);
/* Assign received image properties to your html element */
image[index].getElementsByTagName('a')[0].setAttribute('href', imageObject.hires);
image[index].getElementsByTagName('img')[0].setAttribute('src', imageObject.thumb);
image[index].addEventListener('mouseover', enterImage);
image[index].addEventListener('touchstart', enterImage);
image[index].addEventListener('mouseout', leaveImage);
image[index].addEventListener('touchend', leaveImage);
image[index].addEventListener('mousemove', move);
image[index].addEventListener('touchmove', move);
image[index].addEventListener('wheel', e =>
{
e.preventDefault();
e.deltaY > 0 ? zoomLevel-- : zoomLevel++;
if (zoomLevel < 1) zoomLevel = 1;
if (zoomLevel > 5) zoomLevel = 5;
console.log(`zoom level: ${zoomLevel}`);
zoom.style.transform = `scale(${zoomLevel})`;
});
}
The loop is working until all founded divs got an assignment.
ToDos:
Remove in line
const image = document.querySelectorAll('.image')[0];
the [0].
Next step: Take a look into the body of for loop. Remove your lines of code in your original code
Thank you #Reporter, but I've allready done this editing my code for two days. :)
const zoo = document.querySelectorAll('.zoom');
const zooImg = document.querySelectorAll('.zoom-image');
const pic = document.querySelectorAll(".image");
let clearSrc;
let zoomLevel = 1;
const digiImgs = [{
thumb: 'https://tasvir-graphic.de/links/works/digital/MuZe.webp',
hires: 'https://tasvir-graphic.de/links/works/digital/MuZe.webp'
},
{
thumb: 'https://tasvir-graphic.de/links/works/digital/unterwelt.webp',
hires: 'https://tasvir-graphic.de/links/works/digital/unterwelt.webp'
},
{
thumb: 'https://tasvir-graphic.de/links/works/digital/takeCare.webp',
hires: 'https://tasvir-graphic.de/links/works/digital/takeCare.webp'
},
]
// set to random image
for (var i = 0; i < pic.length; i++) {
let img = digiImgs[i];
pic[i].getElementsByTagName('a')[0].setAttribute('href', img.hires);
pic[i].getElementsByTagName('img')[0].setAttribute('src', img.thumb);
const preloadImage = url => {
let img = new Image();
img.src = url;
}
preloadImage(img.hires);
const enterImage = function (e) {
var zoo = this.parentNode.childNodes[3];
zoo.classList.add('show', 'loading');
clearTimeout(clearSrc);
let posX, posY, touch = false;
if (e.touches) {
posX = e.touches[0].clientX;
posY = e.touches[0].clientY;
touch = true;
} else {
posX = e.clientX;
posY = e.clientY;
}
touch
?
zoo.style.top = `${posY - zoo.offsetHeight / 1.25}px` :
zoo.style.top = `${posY - zoo.offsetHeight / 2}px`;
zoo.style.left = `${posX - zoo.offsetWidth / 2}px`;
let originalImage = this.getElementsByTagName('a')[0].getAttribute('href');
var zoImg = this.parentNode.childNodes[3].childNodes[1];
zoImg.setAttribute('src', originalImage);
// remove the loading class
zoImg.onload = function () {
setTimeout(() => {
zoo.classList.remove('loading');
}, 500);
}
}
const leaveImage = function () {
// remove scaling to prevent non-transition
var zoImg = this.parentNode.childNodes[3].childNodes[1];
var zoo = this.parentNode.childNodes[3];
zoo.style.transform = null;
zoomLevel = 1;
zoo.classList.remove('show');
clearSrc = setTimeout(() => {
zoImg.setAttribute('src', '');
}, 250);
}
const move = function (e) {
e.preventDefault();
var zoImg = this.parentNode.childNodes[3].childNodes[1];
var zoo = this.parentNode.childNodes[3];
let posX, posY, touch = false;
if (e.touches) {
posX = e.touches[0].clientX;
posY = e.touches[0].clientY;
touch = true;
} else {
posX = e.clientX;
posY = e.clientY;
}
// move the zoom a little bit up on mobile (because of your fat fingers :<)
touch ?
zoo.style.top = `${posY - zoo.offsetHeight / 1.25}px` :
zoo.style.top = `${posY - zoo.offsetHeight / 2}px`;
zoo.style.left = `${posX - zoo.offsetWidth / 2}px`;
let percX = (posX - this.offsetLeft) / this.offsetWidth,
percY = (posY - this.offsetTop) / this.offsetHeight;
let zoomLeft = -percX * zoImg.offsetWidth + (zoo.offsetWidth / 2),
zoomTop = -percY * zoImg.offsetHeight + (zoo.offsetHeight / 2);
zoImg.style.left = `${zoomLeft}px`;
zoImg.style.top = `${zoomTop}px`;
}
pic[i].addEventListener('mouseover', enterImage);
pic[i].addEventListener('touchstart', enterImage);
pic[i].addEventListener('mouseout', leaveImage);
pic[i].addEventListener('touchend', leaveImage);
pic[i].addEventListener('mousemove', move);
pic[i].addEventListener('touchmove', move);
pic[i].addEventListener('wheel', e => {
var zoo = e.target.parentNode.parentNode.parentNode.childNodes[3];
console.log(zoo);
e.preventDefault();
e.deltaY > 0 ? zoomLevel-- : zoomLevel++;
if (zoomLevel < 1) zoomLevel = 1;
if (zoomLevel > 3) zoomLevel = 3;
console.log(`zoom level: ${zoomLevel}`);
zoo.style.transform = `scale(${zoomLevel})`;
});
}
but there is a problem with the touch. When I touch using mobile, the photo works like a link and opens the photo. How to use preventDefault Touch?
Im trying to build an audio progess bar with react hooks. I was following a tutorial with react class based components but got a little lost with refs.
How can I give my useRef variables an initial value of the div ref when the page loads?
As soon as I start playing then the I get an error saying cant read offsetwidth of null. Obviously timeline ref is null as it doesnt have an initial value. How can I connect it to the div with id of timeline in the useEffect hook?
const AudioPlayer = () => {
const url = "audio file";
const [audio] = useState(new Audio(url));
const [duration, setDuration] = useState(0);
const [currentTime, setCurrentTime] = useState(0)
let timelineRef = useRef()
let handleRef = useRef()
useEffect(() => {
audio.addEventListener('timeupdate', e => {
setDuration(e.target.duration);
setCurrentTime(e.target.currentTime)
let ratio = audio.currentTime / audio.duration;
let position = timelineRef.offsetWidth * ratio;
positionHandle(position);
})
}, [audio, setCurrentTime, setDuration]);
const mouseMove = (e) => {
positionHandle(e.pageX);
audio.currentTime = (e.pageX / timelineRef.offsetWidth) * audio.duration;
};
const mouseDown = (e) => {
window.addEventListener('mousemove', mouseMove);
window.addEventListener('mouseup', mouseUp);
};
const mouseUp = (e) => {
window.removeEventListener('mousemove', mouseMove);
window.removeEventListener('mouseup', mouseUp);
};
const positionHandle = (position) => {
let timelineWidth = timelineRef.offsetWidth - handleRef.offsetWidth;
let handleLeft = position - timelineRef.offsetLeft;
if (handleLeft >= 0 && handleLeft <= timelineWidth) {
handleRef.style.marginLeft = handleLeft + "px";
}
if (handleLeft < 0) {
handleRef.style.marginLeft = "0px";
}
if (handleLeft > timelineWidth) {
handleRef.style.marginLeft = timelineWidth + "px";
}
};
return (
<div>
<div id="timeline" ref={(timeline) => { timelineRef = timeline }}>
<div id="handle" onMouseDown={mouseDown} ref={(handle) => { handleRef = handle }} />
</div>
</div>
)
}
The useRef() hook returns a reference to an object, with the current property. The current property is the actual value useRef points to.
To use the reference, just set it on the element:
<div id="timeline" ref={timelineRef}>
<div id="handle" onMouseDown={mouseDown} ref={handleRef} />
And then to use it, you need to refer to the current property:
let position = current.timelineRef.offsetWidth * ratio;
And positionHandle - you shouldn't actually set styles on elements in React in this way. Use the setState() hook, and set the style using JSX.
const positionHandle = (position) => {
let timelineWidth = timelineRef.current.offsetWidth - handleRef.current.offsetWidth;
let handleLeft = position - timelineRef.current.offsetLeft;
if (handleLeft >= 0 && handleLeft <= timelineWidth) {
handleRef.current.style.marginLeft = handleLeft + "px";
}
if (handleLeft < 0) {
handleRef.current.style.marginLeft = "0px";
}
if (handleLeft > timelineWidth) {
handleRef.current.style.marginLeft = timelineWidth + "px";
}
};
In addition, the ref can be also used for other values, such as the new Audio(url), and be extracted from the current property:
const { current: audio } = useRef(new Audio(url));
I will attempt to keep this brief, but I am not 100% sure of the correct method of achieving what I am aiming for. I have been thrown in the deep end with React with not much training, so I have most likely been going about most of this component incorrectly, a point in the right direction will definitely help, I don't really expect for someone to completely redo my component for me as it's quite long.
I have a navigation bar SubNav, that finds the currently active item based upon the url/path, this will then move an underline element that inherits the width of the active element. To do this, I find the position of the active item and position accordingly. The same goes for when a user hovers over another navigation item, or when the window resizes it adjusts the position accordingly.
I also have it when at lower resolutions, when the nav gets cut off to have arrows appear to scroll left/right on the navigation to view all navigation items.
Also, if on a lower resolution and the currently active navigation item is off screen, the navigation will scroll to that item and then position the underline correctly.
This, currently works as I have it in my component, this issue is, I don't believe I have done this correctly, I am using a lodash function delay to delay at certain points (I guess to get the correct position of certain navigation items, as it isn't correct at the time of the functions call), which I feel is not the way to go. This is all based on how fast the page loads etc and will not be the same for each user.
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
400,
setArrowStyle(styling)
);
Without using the delay, the values coming back from my state are incorrect as they haven't been set yet.
My question is, how do I go about this correctly? I know my code below is a bit of a read but I have provided a CODESANBOX to play about with.
I have 3 main functions, that all sort of rely on one another:
getPostion()
This function finds the active navigation item, checks if it's within the viewport, if it is not, then it changes the left position of the navigation so it's the leftmost navigation item on the screen, and via setSizes(getSizes()) moves the underline directly underneath.
getSizes()
This is called as an argument within setSizes to update the sizes state, which returns the left and right boundaries of all navigation items
getUnderlineStyle()
This is called as an argument within setUnderLineStyle within the getSizes() function to update the position of the underline object in relation to the position of active navigation item grabbed from the sizes state, but I have to pass the sizesObj as an argument in setSizes as the state has not been set. I think this is where my confusion began, I think I was under the impression, that when I set the state, I could then access it. So, I started using delay to combat.
Below is my whole Component, but can be seen working in CODESANBOX
import React, { useEffect, useState, useRef } from "react";
import _ from "lodash";
import { Link, Route } from "react-router-dom";
import "../../scss/partials/_subnav.scss";
const SubNav = props => {
const subNavLinks = [
{
section: "Link One",
path: "link1"
},
{
section: "Link Two",
path: "link2"
},
{
section: "Link Three",
path: "link3"
},
{
section: "Link Four",
path: "link4"
},
{
section: "Link Five",
path: "link5"
},
{
section: "Link Six",
path: "link6"
},
{
section: "Link Seven",
path: "link7"
},
{
section: "Link Eight",
path: "link8"
}
];
const currentPath =
props.location.pathname === "/"
? "link1"
: props.location.pathname.replace(/\//g, "");
const [useArrows, setUseArrows] = useState(false);
const [rightArrow, updateRightArrow] = useState(false);
const [leftArrow, updateLeftArrow] = useState(false);
const [sizes, setSizes] = useState({});
const [underLineStyle, setUnderLineStyle] = useState({});
const [arrowStyle, setArrowStyle] = useState({});
const [activePath, setActivePath] = useState(currentPath);
const subNavRef = useRef("");
const subNavListRef = useRef("");
const arrowRightRef = useRef("");
const arrowLeftRef = useRef("");
let elsRef = Array.from({ length: subNavLinks.length }, () => useRef(null));
useEffect(
() => {
const reposition = getPosition();
subNavArrows(window.innerWidth);
if (!reposition) {
setSizes(getSizes());
}
window.addEventListener(
"resize",
_.debounce(() => subNavArrows(window.innerWidth))
);
window.addEventListener("resize", () => setSizes(getSizes()));
},
[props]
);
const getPosition = () => {
const activeItem = findActiveItem();
const itemHidden = findItemInView(activeItem);
if (itemHidden) {
const activeItemBounds = elsRef[
activeItem
].current.getBoundingClientRect();
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth =
arrowLeftRef.current !== "" && arrowLeftRef.current !== null
? arrowLeftRef.current.getBoundingClientRect().width
: arrowRightRef.current !== "" && arrowRightRef.current !== null
? arrowRightRef.current.getBoundingClientRect().width
: 30;
const activeItemPos =
activeItemBounds.left * -1 + arrowWidth + currentPos;
const styling = {
left: `${activeItemPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
400,
setArrowStyle(styling)
);
return true;
}
return false;
};
const findActiveItem = () => {
let activeItem;
subNavLinks.map((i, index) => {
const pathname = i.path;
if (pathname === currentPath) {
activeItem = index;
return true;
}
return false;
});
return activeItem;
};
const getSizes = () => {
const rootBounds = subNavRef.current.getBoundingClientRect();
const sizesObj = {};
Object.keys(elsRef).forEach(key => {
const item = subNavLinks[key].path;
const el = elsRef[key];
const bounds = el.current.getBoundingClientRect();
const left = bounds.left - rootBounds.left;
const right = rootBounds.right - bounds.right;
sizesObj[item] = { left, right };
});
setUnderLineStyle(getUnderlineStyle(sizesObj));
return sizesObj;
};
const getUnderlineStyle = (sizesObj, active) => {
sizesObj = sizesObj.length === 0 ? sizes : sizesObj;
active = active ? active : currentPath;
if (active == null || Object.keys(sizesObj).length === 0) {
return { left: "0", right: "100%" };
}
const size = sizesObj[active];
const styling = {
left: `${size.left}px`,
right: `${size.right}px`,
transition: `left 300ms, right 300ms`
};
return styling;
};
const subNavArrows = windowWidth => {
let totalSize = sizeOfList();
_.delay(
() => {
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
300,
setUseArrows(totalSize > windowWidth)
);
};
const sizeOfList = () => {
let totalSize = 0;
Object.keys(elsRef).forEach(key => {
const el = elsRef[key];
const bounds = el.current.getBoundingClientRect();
const width = bounds.width;
totalSize = totalSize + width;
});
return totalSize;
};
const onHover = active => {
setUnderLineStyle(getUnderlineStyle(sizes, active));
setActivePath(active);
};
const onHoverEnd = () => {
setUnderLineStyle(getUnderlineStyle(sizes, currentPath));
setActivePath(currentPath);
};
const scrollRight = () => {
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth = arrowRightRef.current.getBoundingClientRect().width;
const subNavOffsetWidth = subNavRef.current.clientWidth;
let nextElPos;
for (let i = 0; i < elsRef.length; i++) {
const bounds = elsRef[i].current.getBoundingClientRect();
if (bounds.right > subNavOffsetWidth) {
nextElPos = bounds.left * -1 + arrowWidth + currentPos;
break;
}
}
const styling = {
left: `${nextElPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
500,
setArrowStyle(styling)
);
};
const scrollLeft = () => {
const windowWidth = window.innerWidth;
// const lastItemInView = findLastItemInView();
const firstItemInView = findFirstItemInView();
let totalWidth = 0;
const hiddenEls = elsRef
.slice(0)
.reverse()
.filter((el, index) => {
const actualPos = elsRef.length - 1 - index;
if (actualPos >= firstItemInView) return false;
const elWidth = el.current.getBoundingClientRect().width;
const combinedWidth = elWidth + totalWidth;
if (combinedWidth > windowWidth) return false;
totalWidth = combinedWidth;
return true;
});
const targetEl = hiddenEls[hiddenEls.length - 1];
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth = arrowLeftRef.current.getBoundingClientRect().width;
const isFirstEl =
targetEl.current.getBoundingClientRect().left * -1 + currentPos === 0;
const targetElPos = isFirstEl
? targetEl.current.getBoundingClientRect().left * -1 + currentPos
: targetEl.current.getBoundingClientRect().left * -1 +
arrowWidth +
currentPos;
const styling = {
left: `${targetElPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
500,
setArrowStyle(styling)
);
};
const findItemInView = pos => {
const rect = elsRef[pos].current.getBoundingClientRect();
return !(
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth
);
};
const findLastItemInView = () => {
let lastItem;
for (let i = 0; i < elsRef.length; i++) {
const isInView = !findItemInView(i);
if (isInView) {
lastItem = i;
}
}
return lastItem;
};
const findFirstItemInView = () => {
let firstItemInView;
for (let i = 0; i < elsRef.length; i++) {
const isInView = !findItemInView(i);
if (isInView) {
firstItemInView = i;
break;
}
}
return firstItemInView;
};
return (
<div
className={"SubNav" + (useArrows ? " SubNav--scroll" : "")}
ref={subNavRef}
>
<div className="SubNav-content">
<div className="SubNav-menu">
<nav className="SubNav-nav" role="navigation">
<ul ref={subNavListRef} style={arrowStyle}>
{subNavLinks.map((el, i) => (
<Route
key={i}
path="/:section?"
render={() => (
<li
ref={elsRef[i]}
onMouseEnter={() => onHover(el.path)}
onMouseLeave={() => onHoverEnd()}
>
<Link
className={
activePath === el.path
? "SubNav-item SubNav-itemActive"
: "SubNav-item"
}
to={"/" + el.path}
>
{el.section}
</Link>
</li>
)}
/>
))}
</ul>
</nav>
</div>
<div
key={"SubNav-underline"}
className="SubNav-underline"
style={underLineStyle}
/>
</div>
{leftArrow ? (
<div
className="SubNav-arrowLeft"
ref={arrowLeftRef}
onClick={scrollLeft}
/>
) : null}
{rightArrow ? (
<div
className="SubNav-arrowRight"
ref={arrowRightRef}
onClick={scrollRight}
/>
) : null}
</div>
);
};
export default SubNav;
You can make use of useLayoutEffect hook to determine whether the values have been updated and take an action. Since you want to determine whether all the values has been updated, you need to compare old and new values in useEffect. You can refer to the below post to know how to write a usePrevious custom hook
How to compare oldValues and newValues on React Hooks useEffect?
const oldData = usePrevious({ rightArrow, leftArrow, sizes});
useLayoutEffect(() => {
const {rightArrow: oldRightArrow, leftArrow: oldLeftArrow, sizes: oldSizes } = oldData;
if(oldRightArrow !== rightArrow && oldLeftArrow !== leftArrow and oldSizes !== sizes) {
setArrowStyle(styling)
}
}, [rightArrow, leftArrow, sizes])
I think the reason of your delay is necessary here since you calculate based on rectangles of the first and the last element which are affected when you click on button and do animation of scrolling 500ms. So as a result your calculation needs to wait for animation to be done. change the number of animation and delay you will see the relation.
the style I meant.
#include transition(all 500ms ease);
In short, I think what you are using is the right way as long as you have animations related to the calculation.
setState takes an optional second argument which is a callback that executes after the state has been updated and the component has been re-rendered.
Another option is the componentDidUpdate lifecycle method.