From f7966035392675e8670914f1df81cda9084c2cbe Mon Sep 17 00:00:00 2001
From: Michael <michael.foiani@gmail.com>
Date: Wed, 8 Jun 2022 14:24:09 -0400
Subject: Refactor code, but there is a bug. May go back.

---
 .../views/nodes/RecordingBox/ProgressBar.tsx       | 147 +++++++++++++--------
 1 file changed, 91 insertions(+), 56 deletions(-)

(limited to 'src/client/views/nodes/RecordingBox/ProgressBar.tsx')

diff --git a/src/client/views/nodes/RecordingBox/ProgressBar.tsx b/src/client/views/nodes/RecordingBox/ProgressBar.tsx
index 34a771367..fbb5e8a8b 100644
--- a/src/client/views/nodes/RecordingBox/ProgressBar.tsx
+++ b/src/client/views/nodes/RecordingBox/ProgressBar.tsx
@@ -2,7 +2,7 @@ import { resolveTxt } from 'dns';
 import { videointelligence } from 'googleapis/build/src/apis/videointelligence';
 import { isInteger } from 'lodash';
 import * as React from 'react';
-import { useEffect, useState, useCallback, useRef } from "react"
+import { useEffect, useState, useCallback, useRef, useMemo } from "react"
 import "./ProgressBar.scss"
 import { MediaSegment } from './RecordingView';
 
@@ -11,33 +11,52 @@ interface ProgressBarProps {
   setVideos,
 }
 
+interface SegmentBox {
+  endTime: number,
+  startTime: number,
+  order: number,
+}
+interface CurrentHover {
+  index: number,
+  minX: number,
+  maxX: number
+}
+
 export function ProgressBar(props: ProgressBarProps) {
 
   const progressBarRef = useRef<HTMLDivElement | null>(null)
 
   // array for the order of video segments
   const [segments, setSegments] = useState<JSX.Element[]>([]);
-  const [ordered, setOrdered] = useState<Object[]>([]);
+  const [ordered, setOrdered] = useState<SegmentBox[]>([]);
 
-  const [clicked, setClicked] = useState<number>(-1);
+  const [dragged, setDragged] = useState<number>(-1);
 
   // const totalTime = useMemo(() => props.videos.lastElement().endTime, [props.videos])
 
   const totalTime = () => props.videos.lastElement().endTime
+  // const memoTotal = useMemo(totalTime, [props.videos])
 
   useEffect(() => {
-    const segmentsJSX = ordered.map((vid, i) =>
-        <div id={`segment-${i.toString()}`} className={ clicked === i ? 'segment-hide' : 'segment'} style={{ width: `${((vid.endTime - vid.startTime) / totalTime()) * 100}%` }}>{vid.order}</div>);
+    const segmentsJSX = ordered.map((seg, i) =>
+        <div id={`segment-${i.toString()}`} className={ dragged === i ? 'segment-hide' : 'segment'} style={{ width: `${((seg.endTime - seg.startTime) / totalTime()) * 100}%` }}>{seg.order}</div>);
       
     setSegments(segmentsJSX)
-  }, [clicked, ordered])
+  }, [dragged, ordered])
 
   useEffect(() => {
-    setOrdered(props.videos.map((vid, order) => {
-    //const { endTime, startTime } = vid
-      // TODO: not tranfer the blobs around
-      return { ...vid, order };
-    }))
+    const order = props.videos.length
+    if (order) {
+      const { endTime, startTime } = props.videos.lastElement();
+      setOrdered(prevOrdered => {
+        return [...prevOrdered, { endTime, startTime , order }];
+      });
+    }
+    // }props.videos.map((vid, order) => {
+    // //const { endTime, startTime } = vid
+    //   // TODO: not tranfer the blobs around
+    //   return { ...vid, order };
+    // }))
   }, [props.videos]);
 
 
@@ -60,12 +79,10 @@ export function ProgressBar(props: ProgressBarProps) {
       //       }
       // }
   
-  const updateLastHover = (index) => {
-        // id for segment is like 'segment-1' or 'segment-10'
-    const segId = index
-    console.log(segId)
+  const updateLastHover = (segId: number): CurrentHover | null => {
+    // get the segId of the segment that will become the new bounding area
     const rect = progressBarRef.current?.children[segId].getBoundingClientRect()
-    console.log(rect)
+    if (rect == null) return null
     return {
       index: segId,
       minX: rect.x,
@@ -73,51 +90,46 @@ export function ProgressBar(props: ProgressBarProps) {
     }
   }
   
-  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) =>{
-    // e.persist()
-    // console.log('event', e)
+  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
+    console.log('pointer down')
     // don't move the videobox element
     e.stopPropagation()
 
-    const progressBar = progressBarRef.current
-    if (progressBar == null) return
-    console.log('progressbar', progressBar)
-    
-    // progressBar.addEventListener('pointermove', updateSegmentOrder)
-
-
+    // get the segment the user clicked on to be dragged
     const clickedSegment = e.target as HTMLDivElement & EventTarget
 
+    // get the profess bar ro add event listeners
+    // don't do anything if null
+    const progressBar = progressBarRef.current
+    if (progressBar == null || clickedSegment.id === progressBar.id) return
+    progressBar.setPointerCapture(e.pointerId)
+
     const rect = clickedSegment.getBoundingClientRect()
-    setClicked(parseInt(clickedSegment.id.split('-')[1]))
-    let lastHover = {
-      index: parseInt(clickedSegment.id.split('-')[1]),
+    // id for segment is like 'segment-1' or 'segment-10', 
+    // so this works to get the id
+    const segId = parseInt(clickedSegment.id.split('-')[1])
+    // set the selected segment to be the one dragged
+    setDragged(segId)
+
+    // this is the logic for storing the lower X bound and upper X bound
+    // to know whether a swap is needed between two segments
+    let lastHover: CurrentHover = {
+      index: segId,
       minX: rect.x,
       maxX: rect.x + rect.width,
     }
 
-    // clickedSegment.style.backgroundColor = `inherit`;
-    const dot = document.createElement("div")
-    dot.classList.add("segment-selected")
-    dot.style.transitionDuration = '0s';
-    dot.style.position = 'absolute';
-    dot.style.zIndex = '999';
-    dot.style.width = `${rect.width}px`;
-    dot.style.height = `${rect.height}px`;
-    document.body.append(dot)
-    const dragSegment = (event: PointerEvent): void => {
-      // event.stopPropagation()
-        dot.style.left = `${event.clientX - rect.width/2}px`;
-        dot.style.top = `${event.clientY - rect.height/2}px`;
-     }
+    // create the div element that tracks the cursor
+    const detchedSegment = document.createElement("div")
+    initDeatchSegment(detchedSegment, rect);
 
-    const updateSegmentOrder = (event: PointerEvent): void => {
+    function updateSegmentOrder(event: PointerEvent): void{
       event.stopPropagation();
 
-      dragSegment(event)
+      followCursor(event, detchedSegment, rect)
 
       const oldIndex = lastHover.index
-      const swapSegments = (newIndex) => {
+      const swapSegments = (newIndex: number) => {
         if (newIndex == null) return
         setOrdered(prevOrdered => {
           const cpy = [...prevOrdered]
@@ -125,32 +137,55 @@ export function ProgressBar(props: ProgressBarProps) {
           cpy[newIndex] = prevOrdered[oldIndex]
           return cpy
         })
-        setClicked(newIndex)
+        setDragged(newIndex)
       }
 
       const curX = event.clientX;
       if (curX < lastHover.minX && lastHover.index > 0) {
         swapSegments(lastHover.index - 1)
-        lastHover = updateLastHover(lastHover.index - 1)
+        lastHover = updateLastHover(lastHover.index - 1) ?? lastHover
       }
       else if (curX > lastHover.maxX && lastHover.index < segments.length - 1) {
         swapSegments(lastHover.index + 1)
-        lastHover = updateLastHover(lastHover.index + 1)
+        lastHover = updateLastHover(lastHover.index + 1) ?? lastHover
       }
      }
 
-    progressBar.setPointerCapture(e.pointerId)
     progressBar.addEventListener('pointermove', updateSegmentOrder)
-    progressBar.addEventListener('pointerup', (event) => {
-      progressBar.removeEventListener('pointermove', updateSegmentOrder), { once: true }
+    progressBar.addEventListener('pointerup', () => {
+      progressBar.removeEventListener('pointermove', updateSegmentOrder), { once : true }
       // clickedSegment.style.position = clickedSegment.style.zIndex = 'inherit';
       // progressBar.removeEventListener('pointermove', updateSegmentOrder), { once: true }
       // clickedSegment.style.backgroundColor = 'red';
-      setClicked(-1);
-      // updateSegmentOrder(event);
-      dot.remove();
-    })
+      console.log('removed dot')
+      detchedSegment.remove()
+      setDragged(-1);
+    }, { once: true })
+  }
+
+
+  const initDeatchSegment = (dot: HTMLDivElement, rect: DOMRect) => {
+    dot.classList.add("segment-selected")
+    dot.style.transitionDuration = '0s';
+    dot.style.position = 'absolute';
+    dot.style.zIndex = '999';
+    dot.style.width = `${rect.width}px`;
+    dot.style.height = `${rect.height}px`;
+    dot.style.left = `${rect.x}px`;
+    dot.style.top = `${rect.y}px`;
+    document.body.append(dot)
+  }
+  const cleanupDetachSegment = (dot: HTMLDivElement) => {
+    dot.remove()
   }
+  const followCursor = (event: PointerEvent, dot: HTMLDivElement, rect: DOMRect): void => {
+    // event.stopPropagation()
+    // const { width, height } = dot.getBoundingClientRect()
+    const { width, height } = rect;
+    dot.style.left = `${event.clientX - width/2}px`;
+    dot.style.top = `${event.clientY - height/2}px`;
+  }
+
 
       return (
         <div className="progressbar" id="progressbar" onPointerDown={onPointerDown} ref={progressBarRef}>
-- 
cgit v1.2.3-70-g09d2

