From 7dabd48945934eb6eb6233b95277239f18baab67 Mon Sep 17 00:00:00 2001 From: Jorge Date: Mon, 6 Sep 2021 20:27:32 +0100 Subject: [PATCH] Components: add reset timeout to ColorPicker's copy functionality. --- .../src/ui/color-picker/color-display.tsx | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/components/src/ui/color-picker/color-display.tsx b/packages/components/src/ui/color-picker/color-display.tsx index fca50030c0a67..3a3d5097a8db3 100644 --- a/packages/components/src/ui/color-picker/color-display.tsx +++ b/packages/components/src/ui/color-picker/color-display.tsx @@ -7,7 +7,7 @@ import colorize, { ColorFormats } from 'tinycolor2'; * WordPress dependencies */ import { useCopyToClipboard } from '@wordpress/compose'; -import { useState } from '@wordpress/element'; +import { useState, useEffect, useRef } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; /** @@ -114,6 +114,7 @@ export const ColorDisplay = ( { enableAlpha, }: ColorDisplayProps ) => { const [ copiedColor, setCopiedColor ] = useState< string | null >( null ); + const copyTimer = useRef< number | undefined >(); const props = { color, enableAlpha }; const Component = getComponent( colorType ); const copyRef = useCopyToClipboard< HTMLDivElement >( @@ -134,8 +135,25 @@ export const ColorDisplay = ( { } } }, - () => setCopiedColor( colorize( color ).toHex8String() ) + () => { + if ( copyTimer.current ) { + clearTimeout( copyTimer.current ); + } + setCopiedColor( colorize( color ).toHex8String() ); + copyTimer.current = setTimeout( () => { + setCopiedColor( null ); + copyTimer.current = undefined; + }, 3000 ); + } ); + useEffect( () => { + // clear copyTimer on component unmount. + return () => { + if ( copyTimer.current ) { + clearTimeout( copyTimer.current ); + } + }; + }, [] ); return (