element-call/src/GridDemo.jsx

387 lines
10 KiB
React
Raw Normal View History

2021-08-11 16:02:40 -07:00
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useDrag } from "react-use-gesture";
2021-08-16 16:18:45 -07:00
import { useSprings, animated } from "@react-spring/web";
2021-08-11 16:02:40 -07:00
import styles from "./GridDemo.module.css";
2021-08-12 16:25:10 -07:00
import useMeasure from "react-use-measure";
2021-08-16 16:18:45 -07:00
import moveArrItem from "lodash-move";
2021-08-11 16:02:40 -07:00
2021-08-16 15:06:12 -07:00
function isInside([x, y], targetTile) {
2021-08-13 16:27:19 -07:00
const left = targetTile.x;
const top = targetTile.y;
const bottom = targetTile.y + targetTile.height;
const right = targetTile.x + targetTile.width;
2021-08-16 15:06:12 -07:00
if (x < left || x > right || y < top || y > bottom) {
2021-08-13 16:27:19 -07:00
return false;
}
return true;
}
function getTilePositions(tileCount, gridBounds) {
const newTilePositions = [];
const { width: gridWidth, height: gridHeight } = gridBounds;
const gap = 8;
if (tileCount > 0) {
const aspectRatio = gridWidth / gridHeight;
let columnCount, rowCount;
if (aspectRatio < 1) {
if (tileCount <= 4) {
columnCount = 1;
rowCount = tileCount;
} else if (tileCount <= 12) {
columnCount = 2;
rowCount = Math.ceil(tileCount / 2);
}
} else {
if (tileCount === 1) {
columnCount = 1;
rowCount = 1;
} else if (tileCount === 2) {
columnCount = 2;
rowCount = 1;
} else if (tileCount <= 4) {
columnCount = 2;
rowCount = 2;
} else if (tileCount <= 6) {
columnCount = 3;
rowCount = 2;
} else if (tileCount <= 8) {
columnCount = 4;
rowCount = 2;
} else if (tileCount <= 10) {
columnCount = 5;
rowCount = 2;
} else if (tileCount <= 12) {
columnCount = 4;
rowCount = 3;
}
}
2021-08-11 16:02:40 -07:00
let tileHeight = Math.round((gridHeight - gap * (rowCount + 1)) / rowCount);
let tileWidth = Math.round(
(gridWidth - gap * (columnCount + 1)) / columnCount
);
2021-08-13 16:27:19 -07:00
const tileAspectRatio = tileWidth / tileHeight;
2021-08-12 16:25:10 -07:00
if (tileAspectRatio > 16 / 9) {
tileWidth = (16 * tileHeight) / 9;
}
2021-08-13 12:27:00 -07:00
for (let i = 0; i < tileCount; i++) {
const verticalIndex = Math.floor(i / columnCount);
const top = verticalIndex * tileHeight + (verticalIndex + 1) * gap;
2021-08-12 16:25:10 -07:00
let rowItemCount;
2021-08-12 16:25:10 -07:00
if (verticalIndex + 1 === rowCount && tileCount % rowCount !== 0) {
rowItemCount = Math.floor(tileCount / rowCount);
2021-08-13 13:02:24 -07:00
} else {
rowItemCount = Math.ceil(tileCount / rowCount);
2021-08-13 13:02:24 -07:00
}
2021-08-13 12:27:00 -07:00
const horizontalIndex = i % columnCount;
const totalRowGapWidth = (rowItemCount + 1) * gap;
const totalRowTileWidth = rowItemCount * tileWidth;
const rowLeftMargin = Math.round(
(gridWidth - (totalRowTileWidth + totalRowGapWidth)) / 2
2021-08-13 13:02:24 -07:00
);
const left =
tileWidth * horizontalIndex +
rowLeftMargin +
(horizontalIndex + 1) * gap;
newTilePositions.push({
width: tileWidth,
height: tileHeight,
x: left,
y: top,
});
}
}
2021-08-13 12:27:00 -07:00
return newTilePositions;
}
2021-08-13 12:27:00 -07:00
export function VideoGrid({ participants }) {
const [{ tiles, tilePositions }, setTileState] = useState({
tiles: [],
tilePositions: [],
});
const draggingTileRef = useRef(null);
2021-08-13 12:27:00 -07:00
// Contains tile indices
// Tiles are displayed in the order that they appear
const tileOrderRef = useRef([]);
2021-08-13 12:27:00 -07:00
const [gridRef, gridBounds] = useMeasure();
2021-08-13 12:27:00 -07:00
useEffect(() => {
setTileState(({ tiles }) => {
const newTiles = [];
const removedTileKeys = [];
2021-08-12 16:25:10 -07:00
for (const tile of tiles) {
const participant = participants.find(
(participant) => participant.userId === tile.key
2021-08-12 16:25:10 -07:00
);
2021-08-13 12:27:00 -07:00
if (participant) {
// Existing tiles
newTiles.push({
key: participant.userId,
participant: participant,
remove: false,
});
} else {
// Removed tiles
removedTileKeys.push(tile.key);
newTiles.push({
key: tile.key,
participant: tile.participant,
remove: true,
});
}
}
2021-08-16 16:18:45 -07:00
for (const participant of participants) {
if (newTiles.some(({ key }) => participant.userId === key)) {
continue;
}
2021-08-13 12:27:00 -07:00
// Added tiles
newTiles.push({
key: participant.userId,
participant,
remove: false,
});
2021-08-13 12:27:00 -07:00
tileOrderRef.current.push(tileOrderRef.current.length);
}
2021-08-13 16:27:19 -07:00
if (removedTileKeys.length > 0) {
// TODO: There's a race condition in this nested set state when you quickly add/remove
setTimeout(() => {
setTileState(({ tiles }) => {
const newTiles = tiles.filter(
(tile) => !removedTileKeys.includes(tile.key)
);
const removedTileIndices = removedTileKeys.map((tileKey) =>
tiles.findIndex((tile) => tile.key === tileKey)
);
tileOrderRef.current = tileOrderRef.current.filter(
(index) => !removedTileIndices.includes(index)
);
return {
tiles: newTiles,
tilePositions: getTilePositions(newTiles, gridBounds),
};
});
}, 250);
}
2021-08-16 15:06:12 -07:00
return {
tiles: newTiles,
tilePositions: getTilePositions(newTiles.length, gridBounds),
2021-08-16 15:06:12 -07:00
};
2021-08-13 13:02:24 -07:00
});
}, [participants, gridBounds]);
2021-08-13 12:27:00 -07:00
2021-08-13 13:02:24 -07:00
const animate = useCallback(
2021-08-16 16:18:45 -07:00
(tileIndex) => {
const tileOrder = tileOrderRef.current;
const order = tileOrder.indexOf(tileIndex);
const tile = tiles[tileIndex];
2021-08-16 16:18:45 -07:00
const tilePosition = tilePositions[order];
2021-08-13 12:27:00 -07:00
const draggingTile = draggingTileRef.current;
const dragging = draggingTile && tile.key === draggingTile.key;
const remove = tile.remove;
2021-08-13 12:27:00 -07:00
if (dragging) {
return {
width: tilePosition.width,
height: tilePosition.height,
2021-08-16 16:18:45 -07:00
x: draggingTile.offsetX + draggingTile.x,
y: draggingTile.offsetY + draggingTile.y,
2021-08-13 12:27:00 -07:00
scale: 1.1,
opacity: 1,
2021-08-13 12:27:00 -07:00
zIndex: 1,
shadow: 15,
immediate: (key) => key === "zIndex" || key === "x" || key === "y",
from: {
scale: 0,
opacity: 0,
},
reset: false,
2021-08-13 12:27:00 -07:00
};
} else {
return {
...tilePosition,
scale: remove ? 0 : 1,
opacity: remove ? 0 : 1,
2021-08-13 12:27:00 -07:00
zIndex: 0,
shadow: 1,
immediate: false,
from: {
scale: 0,
opacity: 0,
},
reset: false,
2021-08-12 16:25:10 -07:00
};
}
2021-08-13 12:27:00 -07:00
},
[tiles, tilePositions]
2021-08-13 12:27:00 -07:00
);
2021-08-12 16:25:10 -07:00
2021-08-16 16:18:45 -07:00
const [springs, api] = useSprings(tiles.length, animate, [
tilePositions,
tiles,
]);
const bind = useDrag(({ args: [key], active, xy, movement }) => {
const tileOrder = tileOrderRef.current;
2021-08-13 16:27:19 -07:00
2021-08-16 16:18:45 -07:00
const dragTileIndex = tiles.findIndex((tile) => tile.key === key);
const dragTile = tiles[dragTileIndex];
2021-08-13 16:27:19 -07:00
2021-08-16 16:18:45 -07:00
const dragTileOrder = tileOrder.indexOf(dragTileIndex);
2021-08-13 16:27:19 -07:00
2021-08-16 15:06:12 -07:00
const cursorPosition = [xy[0] - gridBounds.left, xy[1] - gridBounds.top];
2021-08-13 16:27:19 -07:00
2021-08-16 16:18:45 -07:00
for (
let hoverTileIndex = 0;
hoverTileIndex < tiles.length;
hoverTileIndex++
) {
const hoverTile = tiles[hoverTileIndex];
const hoverTileOrder = tileOrder.indexOf(hoverTileIndex);
const hoverTilePosition = tilePositions[hoverTileOrder];
if (hoverTile.key === key) {
2021-08-16 15:06:12 -07:00
continue;
}
2021-08-13 16:27:19 -07:00
2021-08-16 15:06:12 -07:00
if (isInside(cursorPosition, hoverTilePosition)) {
2021-08-16 16:18:45 -07:00
tileOrderRef.current = moveArrItem(
tileOrder,
dragTileOrder,
hoverTileOrder
);
2021-08-16 15:06:12 -07:00
break;
}
}
2021-08-13 12:27:00 -07:00
if (active) {
2021-08-16 16:18:45 -07:00
if (!draggingTileRef.current) {
const tilePosition = tilePositions[dragTileOrder];
draggingTileRef.current = {
key: dragTile.key,
offsetX: tilePosition.x,
offsetY: tilePosition.y,
};
}
draggingTileRef.current.x = movement[0];
draggingTileRef.current.y = movement[1];
2021-08-13 12:27:00 -07:00
} else {
draggingTileRef.current = null;
}
2021-08-16 16:18:45 -07:00
api.start(animate);
2021-08-11 16:02:40 -07:00
});
return (
<div className={styles.grid} ref={gridRef}>
{springs.map(({ shadow, ...style }, i) => {
const tileIndex = tileOrderRef.current[i];
const tile = tiles[tileIndex];
return (
<ParticipantTile
{...bind(tile.key)}
key={tile.key}
style={{
boxShadow: shadow.to(
(s) => `rgba(0, 0, 0, 0.5) 0px ${s}px ${2 * s}px 0px`
),
...style,
}}
{...tile}
/>
);
})}
2021-08-11 16:02:40 -07:00
</div>
);
}
function ParticipantTile({ style, participant, remove, ...rest }) {
2021-08-11 16:02:40 -07:00
const videoRef = useRef();
useEffect(() => {
if (participant.stream) {
videoRef.current.srcObject = participant.stream;
2021-08-11 16:02:40 -07:00
videoRef.current.play();
} else {
videoRef.current.srcObject = null;
}
}, [participant.stream]);
2021-08-11 16:02:40 -07:00
return (
<animated.div className={styles.participantTile} style={style} {...rest}>
<div className={styles.participantName}>{participant.userId}</div>
2021-08-11 16:02:40 -07:00
<video ref={videoRef} playsInline />
</animated.div>
);
}
export function GridDemo() {
const participantKey = useRef(0);
const [stream, setStream] = useState();
const [participants, setParticipants] = useState([]);
const startWebcam = useCallback(async () => {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
setStream(stream);
setParticipants([{ stream, userId: participantKey.current++ }]);
}, []);
const addParticipant = useCallback(() => {
setParticipants((participants) => [
...participants,
{ stream: stream.clone(), userId: participantKey.current++ },
]);
}, [stream]);
const removeParticipant = useCallback((key) => {
setParticipants((participants) =>
participants.filter((participant) => participant.userId !== key)
);
}, []);
return (
<div className={styles.gridDemo}>
<div className={styles.buttons}>
{!stream && <button onClick={startWebcam}>Start Webcam</button>}
{stream && participants.length < 12 && (
<button onClick={addParticipant}>Add Tile</button>
)}
{stream && participants.length > 0 && (
<button
onClick={() =>
removeParticipant(participants[participants.length - 1].userId)
}
>
Remove Tile
</button>
)}
</div>
<VideoGrid participants={participants} />
</div>
);
}