11import React , { useEffect , useState } from 'react' ;
2+ import PropTypes from 'prop-types' ;
23import styled from 'styled-components' ;
34import { remSize } from '../../theme' ;
45
@@ -23,59 +24,42 @@ const CoordContainer = styled.div`
2324 }
2425` ;
2526
26- const CoordinateTracker = ( isPlaying ) => {
27+ const CoordinateTracker = ( { isPlaying, sketchReloaded } ) => {
2728 const [ coordinates , setCoordinates ] = useState ( { x : 0 , y : 0 } ) ;
2829
2930 useEffect ( ( ) => {
30- console . log ( 'we here' ) ;
31- let isListenerAttached = false ;
32- let mouseMoveHandler ;
3331 let canvas ;
32+ let mouseMoveHandler ;
3433
35- const waitForCanvas = ( ) => {
34+ const timeout = setTimeout ( ( ) => {
3635 const iFrame = document . getElementById ( 'previewIframe0' ) ;
37- canvas = iFrame . contentWindow . document . getElementById ( 'defaultCanvas0' ) ;
38- console . log ( 'iframe: ' , iFrame ) ;
39-
40- if ( canvas && ! isListenerAttached ) {
41- isListenerAttached = true ;
42- console . log ( 'Adding listener' ) ;
43-
44- mouseMoveHandler = ( event ) => {
45- console . log ( 'hellooooo' ) ;
46- const rect = canvas . getBoundingClientRect ( ) ;
47- const x = event . clientX - rect . left ;
48- const y = event . clientY - rect . top ;
49-
50- setCoordinates ( { x, y } ) ;
51- } ;
52-
53- console . log ( 'mouseMoveHandler' , mouseMoveHandler ) ;
54- console . log ( 'canvas' , canvas ) ;
36+ canvas = iFrame ?. contentWindow ?. document ?. getElementById (
37+ 'defaultCanvas0'
38+ ) ;
5539
56- document
57- . querySelector ( '#defaultCanvas0' )
58- . addEventListener ( 'mousemove' , ( ) => {
59- console . log ( 'Button clicked!' ) ;
60- mouseMoveHandler ( ) ;
61- } ) ;
62- // canvas.addEventListener('mousemove', mouseMoveHandler);
63- } else if ( ! canvas ) {
64- setTimeout ( waitForCanvas , 500 ) ;
40+ if ( ! canvas ) {
41+ console . warn ( 'Canvas not found.' ) ;
42+ return ;
6543 }
66- } ;
6744
68- waitForCanvas ( ) ;
45+ mouseMoveHandler = ( event ) => {
46+ const rect = canvas . getBoundingClientRect ( ) ;
47+ const x = event . clientX - rect . left ;
48+ const y = event . clientY - rect . top ;
49+ setCoordinates ( { x, y } ) ;
50+ } ;
51+
52+ canvas . addEventListener ( 'mousemove' , mouseMoveHandler ) ;
53+ } , 500 ) ;
6954
7055 return ( ) => {
71- if ( canvas && isListenerAttached ) {
72- console . log ( 'Removing listener' ) ;
56+ clearTimeout ( timeout ) ;
57+
58+ if ( canvas && mouseMoveHandler ) {
7359 canvas . removeEventListener ( 'mousemove' , mouseMoveHandler ) ;
74- canvas = null ;
75- isListenerAttached = false ;
7660 }
7761 } ;
78- } , [ isPlaying ] ) ;
62+ } , [ isPlaying , sketchReloaded ] ) ;
7963
8064 return (
8165 < CoordContainer >
@@ -87,4 +71,9 @@ const CoordinateTracker = (isPlaying) => {
8771 ) ;
8872} ;
8973
74+ CoordinateTracker . propTypes = {
75+ isPlaying : PropTypes . bool . isRequired ,
76+ sketchReloaded : PropTypes . bool . isRequired
77+ } ;
78+
9079export default CoordinateTracker ;
0 commit comments