From 449a6275621e3e0cc4e4f318e9f0a2afa583c698 Mon Sep 17 00:00:00 2001 From: Jaya Krishna Date: Fri, 16 May 2025 18:07:44 +0530 Subject: [PATCH 1/2] feat: add default time for time component --- packages/sdk-components-react/src/time.tsx | 43 ++++++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/packages/sdk-components-react/src/time.tsx b/packages/sdk-components-react/src/time.tsx index 44df0070c87c..0146ec3d6be6 100644 --- a/packages/sdk-components-react/src/time.tsx +++ b/packages/sdk-components-react/src/time.tsx @@ -1,4 +1,10 @@ -import { forwardRef, type ComponentProps, type ElementRef } from "react"; +import { + forwardRef, + useEffect, + useState, + type ComponentProps, + type ElementRef, +} from "react"; const languages = [ "af", @@ -281,7 +287,15 @@ type Country = (typeof countries)[number]; type DateStyle = Intl.DateTimeFormatOptions["dateStyle"] | "none"; type TimeStyle = Intl.DateTimeFormatOptions["timeStyle"] | "none"; -const INITIAL_DATE_STRING = "dateTime attribute is not set"; +const createInitialDate = () => { + const date = new Date(); + date.setSeconds(0); + date.setMilliseconds(0); + return date; +}; + +const INITIAL_DATE_STRING = + typeof window === "undefined" ? createInitialDate() : null; const INVALID_DATE_STRING = ""; const DEFAULT_LANGUAGE = "en"; @@ -365,6 +379,9 @@ export const Time = forwardRef, TimeProps>( }, ref ) => { + const [clientSideDate, setClientSideDate] = useState( + null + ); const locale = `${languageOrDefault(language)}-${countryOrDefault( country )}`; @@ -374,8 +391,21 @@ export const Time = forwardRef, TimeProps>( timeStyle: timeStyleOrUndefined(timeStyle), }; + useEffect(() => { + if (dateTime === INITIAL_DATE_STRING) { + setClientSideDate(new Date()); + } + }, [dateTime]); + + const dateToUse = + typeof window !== "undefined" && + clientSideDate !== null && + dateTime === INITIAL_DATE_STRING + ? clientSideDate + : dateTime; + const datetimeString = - dateTime === null ? INVALID_DATE_STRING : dateTime.toString(); + dateToUse === null ? INVALID_DATE_STRING : dateToUse.toString(); const date = parseDate(datetimeString); let formattedDate = datetimeString; @@ -389,7 +419,12 @@ export const Time = forwardRef, TimeProps>( } return ( -