From 7f13c37c736630a51d32d789d14a09eb0adfbd5a Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Tue, 14 Sep 2021 12:16:09 +0100 Subject: [PATCH] Components: add reset timeout to ColorPicker's copy functionality. (#34601) --- .../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 fca50030c0a67e..3a3d5097a8db31 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 (