|
| 1 | +/** |
| 2 | + * Copyright (c) 2023-present Plane Software, Inc. and contributors |
| 3 | + * SPDX-License-Identifier: AGPL-3.0-only |
| 4 | + * See the LICENSE file for details. |
| 5 | + */ |
| 6 | + |
| 7 | +import { useMemo } from "react"; |
| 8 | +import type { IUser } from "@plane/types"; |
| 9 | +import { useCurrentTime } from "@/hooks/use-current-time"; |
| 10 | + |
| 11 | +export type TGreeting = "morning" | "afternoon" | "evening"; |
| 12 | + |
| 13 | +export const useGreeting = (user: IUser) => { |
| 14 | + const { currentTime } = useCurrentTime(); |
| 15 | + |
| 16 | + const userTimezone = useMemo(() => { |
| 17 | + if (!user?.user_timezone) return undefined; |
| 18 | + try { |
| 19 | + new Intl.DateTimeFormat(undefined, { timeZone: user.user_timezone }); |
| 20 | + return user.user_timezone; |
| 21 | + } catch (e) { |
| 22 | + console.warn( |
| 23 | + `[useGreeting] Invalid user_timezone "${user.user_timezone}", falling back to browser timezone.`, |
| 24 | + e |
| 25 | + ); |
| 26 | + return undefined; |
| 27 | + } |
| 28 | + }, [user?.user_timezone]); |
| 29 | + |
| 30 | + const hour = new Intl.DateTimeFormat("en-US", { |
| 31 | + timeZone: userTimezone, |
| 32 | + hourCycle: "h23", |
| 33 | + hour: "numeric", |
| 34 | + }).format(currentTime); |
| 35 | + |
| 36 | + const date = new Intl.DateTimeFormat("en-US", { |
| 37 | + timeZone: userTimezone, |
| 38 | + month: "short", |
| 39 | + day: "numeric", |
| 40 | + }).format(currentTime); |
| 41 | + |
| 42 | + const weekDay = new Intl.DateTimeFormat("en-US", { |
| 43 | + timeZone: userTimezone, |
| 44 | + weekday: "long", |
| 45 | + }).format(currentTime); |
| 46 | + |
| 47 | + const timeString = new Intl.DateTimeFormat("en-US", { |
| 48 | + timeZone: userTimezone, |
| 49 | + hourCycle: "h23", |
| 50 | + hour: "2-digit", |
| 51 | + minute: "2-digit", |
| 52 | + }).format(currentTime); |
| 53 | + |
| 54 | + const hourNum = parseInt(hour, 10); |
| 55 | + // 5–11: morning, 12–16: afternoon, 17–4: evening |
| 56 | + const greeting: TGreeting = |
| 57 | + hourNum >= 5 && hourNum < 12 ? "morning" : hourNum >= 12 && hourNum < 17 ? "afternoon" : "evening"; |
| 58 | + |
| 59 | + return { greeting, timeString, weekDay, date }; |
| 60 | +}; |
0 commit comments