import React, {createRef, RefObject, useEffect, useState} from 'react'; import {Image, View} from 'react-native'; import {MomentTagType, ProfilePreviewType} from '../../types'; import TaggDraggable from '../taggs/TaggDraggable'; import Draggable from './Draggable'; interface MomentTagsProps { editing: boolean; tags: MomentTagType[]; setTags: (tag: MomentTagType[]) => void; imageRef: RefObject; deleteFromList?: (user: ProfilePreviewType) => void; boundaries?: DraggableBoundaries; } interface DraggableBoundaries { top?: number; bottom?: number; left?: number; right?: number; } const MomentTags: React.FC = ({ editing, tags, setTags, imageRef, deleteFromList, boundaries, }) => { const [offset, setOffset] = useState([0, 0]); const [imageDimensions, setImageDimensions] = useState([0, 0]); const [maxZIndex, setMaxZIndex] = useState(1); const [draggableRefs, setDraggableRefs] = useState[]>([]); // [minXBoundary, maxXBoundary, minYBoundary, maxYBoundary] const [boundariesList, setBoundariesList] = useState([0, 0, 0, 0]); const updateTagPosition = (ref: RefObject, userId: string) => { if (ref !== null && ref.current !== null) { ref.current.measure( ( _fx: number, // location of ref relative to parent element _fy: number, _width: number, _height: number, px: number, // location of ref relative to entire screen py: number, ) => { const x = ((px - offset[0]) / imageDimensions[0]) * 100; const y = ((py - offset[1]) / imageDimensions[1]) * 100; setTags( tags.map((tag) => tag.user.id === userId ? { id: '', x, y, z: maxZIndex - 1, // TODO: change this user: tag.user, } : tag, ), ); }, ); } }; useEffect(() => { setDraggableRefs(tags.map((_) => createRef())); }, [tags]); useEffect(() => { setTimeout( () => { if (imageRef && imageRef.current) { imageRef.current.measure( ( fx: number, // location of ref relative to parent element fy: number, width: number, height: number, _x: number, // location of ref relative to entire screen _y: number, ) => { setOffset([fx, fy]); setImageDimensions([width, height]); }, ); } // Checks for and adds boundaries if (boundaries) { const newBounds = [...boundariesList]; if (boundaries.top) { newBounds[2] = boundaries.top; } if (boundaries.bottom) { newBounds[3] = boundaries.bottom; } if (boundaries.left) { newBounds[0] = boundaries.left; } if (boundaries.right) { newBounds[1] = boundaries.right; } setBoundariesList(newBounds); } }, editing ? 100 : 0, ); }, []); if (!tags) { return null; } return editing && deleteFromList ? ( <> {tags.map((tag, index) => ( { const currZIndex = maxZIndex; setMaxZIndex(currZIndex + 1); return currZIndex; }} onDragRelease={() => updateTagPosition(draggableRefs[index], tag.user.id) }> deleteFromList(tag.user)} /> ))} ) : ( <> {tags.map((tag, index) => ( null} /> ))} ); }; export default MomentTags;