From 83bc8d2352587a6929db2fae7e27d23d60273f31 Mon Sep 17 00:00:00 2001 From: achorein Date: Tue, 19 Sep 2023 10:38:29 +0200 Subject: [PATCH] feat: detect path change --- src/components/SketchCanvas/SketchCanvas.tsx | 14 ++++++++++++-- src/components/SketchCanvas/types.ts | 1 + 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/components/SketchCanvas/SketchCanvas.tsx b/src/components/SketchCanvas/SketchCanvas.tsx index fa9a1f7..f4f318b 100644 --- a/src/components/SketchCanvas/SketchCanvas.tsx +++ b/src/components/SketchCanvas/SketchCanvas.tsx @@ -5,7 +5,7 @@ import { useCanvasRef, useTouchHandler, } from '@shopify/react-native-skia'; -import React, { forwardRef, useImperativeHandle } from 'react'; +import React, { forwardRef, useEffect, useImperativeHandle } from 'react'; import { useSketchPaths } from '../hooks'; import { STROKE_COLOR, STROKE_STYLE, STROKE_WIDTH } from './constants'; import { SketchCanvasProps, SketchCanvasRef, ImageFormat } from './types'; @@ -20,6 +20,7 @@ const SketchCanvas = forwardRef( children, topChildren, isSynced = true, + onPathsLengthChange, }, frwdRef ) => { @@ -28,12 +29,14 @@ const SketchCanvas = forwardRef( useImperativeHandle(frwdRef, () => ({ undo: () => { + onPathsLengthChange?.(paths.current.length - 1); paths.current.pop(); setPathsLength((prevPathLength) => prevPathLength - 1); }, clear: () => { paths.current.length = 0; setPathsLength(0); + onPathsLengthChange?.(0); }, addPath: (path) => { paths.current.push(path); @@ -60,6 +63,10 @@ const SketchCanvas = forwardRef( }, })); + useEffect(() => { + onPathsLengthChange?.(paths.current.length); + }, [paths, onPathsLengthChange]); + const touchHandler = useTouchHandler({ onStart: ({ x, y }) => { const newPath = Skia.Path.Make(); @@ -76,7 +83,10 @@ const SketchCanvas = forwardRef( onActive: ({ x, y }) => { paths.current.at(-1)?.path.lineTo(x, y); }, - onEnd: () => forceUpdate(), + onEnd: () => { + onPathsLengthChange?.(paths.current.length); + forceUpdate(); + }, }); return ( diff --git a/src/components/SketchCanvas/types.ts b/src/components/SketchCanvas/types.ts index ba824ab..37cd68f 100644 --- a/src/components/SketchCanvas/types.ts +++ b/src/components/SketchCanvas/types.ts @@ -40,6 +40,7 @@ export interface SketchCanvasProps { isSynced?: boolean; children?: React.ReactNode; topChildren?: React.ReactNode; + onPathsLengthChange?: (value: number) => void; } export type StrokeStyle = 'stroke' | 'fill';