Skip to content

Commit

Permalink
Merge pull request #889 from The-Commit-Company/replace-moment-with-d…
Browse files Browse the repository at this point in the history
…ayjs

perf: replaced moment with dayjs
  • Loading branch information
nikkothari22 authored Apr 26, 2024
2 parents 1ac1e6b + e198ce8 commit 30ae852
Show file tree
Hide file tree
Showing 16 changed files with 106 additions and 138 deletions.
3 changes: 2 additions & 1 deletion mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"cal-sans": "^1.0.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"dayjs": "^1.11.10",
"emoji-picker-element": "^1.21.1",
"firebase": "^10.9.0",
"frappe-react-sdk": "^1.5.1",
Expand Down Expand Up @@ -79,4 +80,4 @@
"@types/turndown": "^5.0.4",
"typescript": "^4.9.3"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { Message, PollMessage } from '../../../../../../types/Messaging/Message'
import { UserFields } from '@/utils/users/UserListProvider'
import { MessageSenderAvatar } from '../chat-view/MessageBlock'
import { IonText } from '@ionic/react'
import { DateObjectToTimeString } from '@/utils/operations/operations'
import parse from 'html-react-parser';
import { toHourMinuteAmPm } from '@/utils/operations/dateConversions';

type MessagePreview = { message: Message, user?: UserFields }

Expand All @@ -16,7 +16,7 @@ const MessagePreview = ({ message, user }: MessagePreview) => {
<div className='overflow-x-clip'>
<div className='flex items-end pb-1.5'>
<IonText className='font-bold text-zinc-50 text-sm'>{user?.full_name ?? message.owner}</IonText>
<IonText className='text-xs pl-1.5 text-zinc-500'>{DateObjectToTimeString(message.creation)}</IonText>
<IonText className='text-xs pl-1.5 text-zinc-500'>{toHourMinuteAmPm(message.creation)}</IonText>
</div>
{message.message_type === 'Text' && <div className='text-base line-clamp-3 text-ellipsis'>{parse(message.content ?? '')}</div>}
{message.message_type === 'Image' && <div className='flex items-center space-x-2'>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { memo, useContext, useMemo, useRef, useState } from 'react'
import { FileMessage, ImageMessage, Message, TextMessage, PollMessage } from '../../../../../../types/Messaging/Message'
import { IonIcon, IonSkeletonText, IonText } from '@ionic/react'
import { UserFields } from '@/utils/users/UserListProvider'
import { DateObjectToFormattedDateStringWithoutYear, DateObjectToTimeString } from '@/utils/operations/operations'
import { ChannelMembersContext } from '../ChatInterface'
import { openOutline } from 'ionicons/icons'
import { Haptics, ImpactStyle } from '@capacitor/haptics'
Expand All @@ -19,6 +18,7 @@ import { RiRobot2Fill } from 'react-icons/ri'
import { MdOutlineBarChart } from 'react-icons/md'
import { TiptapRenderer } from './components/TiptapRenderer/TiptapRenderer'
import PollMessageBlock from './components/PollMessage'
import { toDateMonthAtHourMinuteAmPm, toHourMinuteAmPm } from '@/utils/operations/dateConversions'

type Props = {
message: Message,
Expand Down Expand Up @@ -104,7 +104,7 @@ export const NonContinuationMessageBlock = ({ message, onMessageSelect, isScroll
<div className='flex items-baseline pb-1'>
<Text as='span' className='font-semibold' size='2'>{user?.full_name ?? message.owner}</Text>
{isBot && <Badge className='ml-2' color='gray'>Bot</Badge>}
<Text as='span' size='1' className='pl-1.5 text-gray-10'>{DateObjectToTimeString(message.creation)}</Text>
<Text as='span' size='1' className='pl-1.5 text-gray-10'>{toHourMinuteAmPm(message.creation)}</Text>
</div>
<MessageContent
message={message}
Expand Down Expand Up @@ -325,12 +325,11 @@ const ReplyBlock = ({ message }: { message: Message }) => {
}
}, [message])

const date = message ? new Date(message?.creation) : null
return <div className='px-2 py-1.5 my-2 rounded-e-sm bg-neutral-900 border-l-4 border-l-neutral-500'>
{message && <div>
<div className='flex items-baseline pb-1'>
<p className='text-foreground font-medium text-sm leading-normal tracking-normal'>{user?.full_name ?? message.owner}</p>
{date && <p className='text-xs text-foreground/60 font-normal pl-1.5'>on {DateObjectToFormattedDateStringWithoutYear(date)} at {DateObjectToTimeString(date)}</p>}
<p className='text-xs text-foreground/60 font-normal pl-1.5'>on {toDateMonthAtHourMinuteAmPm(message.creation)}</p>
</div>
{message.message_type === 'Text' && <div className='text-sm text-foreground/60 line-clamp-3'>{parse(message.content ?? '')}</div>}
{message.message_type === 'Image' && <div className='flex items-center space-x-2'>
Expand Down
11 changes: 3 additions & 8 deletions mobile/src/components/features/chat-space/useChatStream.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import { useFrappeDocumentEventListener, useFrappeEventListener, useFrappeGetCall, useFrappePostCall } from 'frappe-react-sdk'
import { RefObject, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { DateObjectToFormattedDateString } from '@/utils/operations/operations'
import { useDebounce } from '@/hooks/useDebounce'
import { Message } from '../../../../../types/Messaging/Message'
import { useIonViewWillLeave } from '@ionic/react'
import { UserContext } from '@/utils/auth/UserProvider'

const parseDateString = (date: string) => {
const dateObj = new Date(date)
return DateObjectToFormattedDateString(dateObj)
}
import { toDateMonthYear } from '../../../utils/operations/dateConversions'

interface GetMessagesResponse {
message: {
Expand Down Expand Up @@ -427,7 +422,7 @@ const useChatStream = (channelID: string, scrollRef: RefObject<HTMLIonContentEle
let currentDateTime = new Date(messages[messages.length - 1].creation.split('.')[0]).getTime()

messagesWithDateSeparators.push({
creation: parseDateString(currentDate),
creation: toDateMonthYear(currentDate),
message_type: 'date',
name: currentDate
})
Expand All @@ -442,7 +437,7 @@ const useChatStream = (channelID: string, scrollRef: RefObject<HTMLIonContentEle

if (messageDate !== currentDate) {
messagesWithDateSeparators.push({
creation: parseDateString(messageDate),
creation: toDateMonthYear(messageDate),
message_type: 'date',
name: messageDate
})
Expand Down
58 changes: 58 additions & 0 deletions mobile/src/utils/operations/dateConversions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import * as dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import advancedFormat from 'dayjs/plugin/advancedFormat'

dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.extend(advancedFormat)

const DEFAULT_TIME_ZONE = 'Asia/Kolkata'
//@ts-expect-error
export const SYSTEM_TIMEZONE = window.frappe?.boot?.time_zone?.system || DEFAULT_TIME_ZONE

//@ts-expect-error
export const USER_DATE_FORMAT = (window.frappe?.boot?.user?.defaults?.date_format?.toUpperCase() || window.frappe?.boot?.sysdefaults?.date_format?.toUpperCase()
|| 'DD/MM/YYYY')

export const FRAPPE_DATETIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
export const FRAPPE_DATE_FORMAT = 'YYYY-MM-DD'
export const FRAPPE_TIME_FORMAT = 'HH:mm:ss'

export const getDateObject = (timestamp: string): dayjs.Dayjs => {

return dayjs.tz(timestamp, SYSTEM_TIMEZONE)
}

/**
* Returns a date in the standard format that the user has set in their preferences
* @param date
* @returns
*/
export const toStandardDate = (date: string) => {

return getDateObject(date).format("DD/MM/YYYY")
}

/**
* Returns a date in DD MMM YYYY format
*/
export const toDateMonthYear = (date: string) => {

return getDateObject(date).format("Do MMMM YYYY")
}

/**
*
* @returns string in the format hh:mm AM/PM
* @example 08:15 PM or 12:00 AM
*/
export const toHourMinuteAmPm = (date: string, amPm: boolean = true) => {

return getDateObject(date).format(amPm ? "hh:mm A" : "hh:mm")
}

export const toDateMonthAtHourMinuteAmPm = (date: string) => {

return getDateObject(date).format("Do MMMM [at] hh:mm A")
}
46 changes: 0 additions & 46 deletions mobile/src/utils/operations/operations.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,5 @@
import { User } from "../../../../types/Core/User"

/**
* Utility to convert Date object to DD-MM-YYYY format
* @param date takes Javascript Date object
* @returns Date string in DD-MM-YYYY format
*/
export const DateObjectToDateString = (date: Date): string => {
return (date.getDate() < 10 ? date.getDate().toString().padStart(2, "0") : date.getDate()) + "-" + (date.getMonth() < 9 ? (date.getMonth() + 1).toString().padStart(2, "0") : date.getMonth() + 1) + "-" + date.getFullYear()
}

const MonthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]

/**
* Utility to convert Date object to DD MonthName YYYY format
* @param date takes Javascript Date object
* @returns Date string in DD MonthName YYYY format
* @example 1 January 2021
*/
export const DateObjectToFormattedDateString = (date: Date): string => {
return date.getDate() + " " + MonthNames[date.getMonth()] + " " + date.getFullYear()
}

/**
* Utility to convert Date object to DD MonthName YYYY format
* @param date takes Javascript Date object
* @returns Date string in DD MonthName YYYY format
* @example 1 January 2021
*/
export const DateObjectToFormattedDateStringWithoutYear = (date: Date): string => {
return date.getDate() + " " + MonthNames[date.getMonth()]
}

/**
* Utility to convert Date-Time object to hour:minute format
* @param date takes Javascript Date object
* @returns Time string in hour:minute format
* @example 08:15 PM or 12:00 AM
*/
export const DateObjectToTimeString = (date: string | Date): string => {
if (typeof date === 'string') {
date = new Date(date)
}
return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
}

/**
* Function to return extension of a file
* @param filename name of the file with extension
Expand Down
5 changes: 5 additions & 0 deletions mobile/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3488,6 +3488,11 @@ data-view-byte-offset@^1.0.0:
es-errors "^1.3.0"
is-data-view "^1.0.1"

dayjs@^1.11.10:
version "1.11.10"
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.10.tgz#68acea85317a6e164457d6d6947564029a6a16a0"
integrity sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ==

debug@^4.0.0, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.4, debug@~4.3.1, debug@~4.3.2:
version "4.3.4"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"
Expand Down
4 changes: 2 additions & 2 deletions raven-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@
"clsx": "^2.1.0",
"cmdk": "^0.2.1",
"cva": "npm:class-variance-authority",
"dayjs": "^1.11.10",
"downshift": "^8.3.1",
"emoji-picker-element": "^1.21.0",
"frappe-react-sdk": "^1.6.0",
"highlight.js": "^11.9.0",
"html-react-parser": "^5.1.8",
"js-cookie": "^3.0.5",
"lowlight": "^3.1.0",
"moment-timezone": "^0.5.45",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-dropzone": "^14.2.3",
Expand All @@ -61,4 +61,4 @@
"@types/turndown": "^5.0.4",
"typescript": "^5.3.3"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,10 @@ export const DeleteChannelModal = ({ onClose, onCloseParent, channelData }: Dele
Cancel
</Button>
</AlertDialog.Cancel>
<AlertDialog.Action>
<Button variant="solid" color="red" onClick={onSubmit} disabled={!allowDelete || deletingDoc}>
{deletingDoc && <Loader />}
{deletingDoc ? "Deleting" : "Delete"}
</Button>
</AlertDialog.Action>
<Button variant="solid" color="red" onClick={onSubmit} disabled={!allowDelete || deletingDoc}>
{deletingDoc && <Loader />}
{deletingDoc ? "Deleting" : "Delete"}
</Button>
</Flex>
</>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useFrappeDocumentEventListener, useFrappeEventListener, useFrappeGetCal
import { MutableRefObject, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useBeforeUnload, useLocation, useNavigate, useParams } from 'react-router-dom'
import { Message } from '../../../../../../types/Messaging/Message'
import { convertFrappeTimestampToUserTimezone } from '@/utils/dateConversions/utils'
import { getDateObject } from '@/utils/dateConversions/utils'
import { useDebounce } from '@/hooks/useDebounce'
import { UserContext } from '@/utils/auth/UserProvider'

Expand Down Expand Up @@ -439,7 +439,7 @@ const useChatStream = (scrollRef: MutableRefObject<HTMLDivElement | null>) => {
let currentDateTime = new Date(messages[messages.length - 1].creation.split('.')[0]).getTime()

messagesWithDateSeparators.push({
creation: convertFrappeTimestampToUserTimezone(`${currentDate} 00:00:00`).format('Do MMMM YYYY'),
creation: getDateObject(`${currentDate} 00:00:00`).format('Do MMMM YYYY'),
message_type: 'date',
name: currentDate
})
Expand All @@ -454,7 +454,7 @@ const useChatStream = (scrollRef: MutableRefObject<HTMLDivElement | null>) => {

if (messageDate !== currentDate) {
messagesWithDateSeparators.push({
creation: convertFrappeTimestampToUserTimezone(`${messageDate} 00:00:00`).format('Do MMMM YYYY'),
creation: getDateObject(`${messageDate} 00:00:00`).format('Do MMMM YYYY'),
message_type: 'date',
name: messageDate
})
Expand Down
1 change: 0 additions & 1 deletion raven-app/src/hooks/useCurrentRavenUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ const useCurrentRavenUser = () => {
{
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnMount: false,
shouldRetryOnError: false,
revalidateOnReconnect: true
}
Expand Down
8 changes: 0 additions & 8 deletions raven-app/src/utils/dateConversions/MomentConverter.tsx

This file was deleted.

44 changes: 5 additions & 39 deletions raven-app/src/utils/dateConversions/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { lazy, Suspense } from "react";

const MomentConverter = lazy(() => import("./MomentConverter"));
import { getDateObject } from "./utils";

interface Props {
date: string;
Expand All @@ -12,31 +10,15 @@ interface Props {
*/
export const StandardDate = (props: Props) => {

const parseDateString = (date: string) => {
const dateObj = new Date(date)
return dateObj.toLocaleDateString('en-GB', { day: 'numeric', month: 'numeric', year: 'numeric' })
}
return (
<Suspense fallback={parseDateString(props.date)}>
<MomentConverter {...props} />
</Suspense>
)
return getDateObject(props.date).format("DD/MM/YYYY")
}

/**
* Returns a date in DD MMM YYYY format
*/
export const DateMonthYear = (props: Props) => {

const parseDateString = (date: string) => {
const dateObj = new Date(date)
return dateObj.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })
}
return (
<Suspense fallback={parseDateString(props.date)}>
<MomentConverter {...props} format="Do MMMM YYYY" />
</Suspense>
)
return getDateObject(props.date).format("Do MMMM YYYY")
}

interface HourMinuteAmPmProps extends Props {
Expand All @@ -49,26 +31,10 @@ interface HourMinuteAmPmProps extends Props {
*/
export const HourMinuteAmPm = ({ amPm = true, date }: HourMinuteAmPmProps) => {

const parseDateString = (d: string) => {
const dateObj = new Date(d)
return dateObj.toLocaleTimeString('en-GB', { hour: 'numeric', minute: 'numeric', hour12: amPm })
}
return (
<Suspense fallback={parseDateString(date)}>
<MomentConverter date={date} format={amPm ? "hh:mm A" : "hh:mm"} />
</Suspense>
)
return getDateObject(date).format(amPm ? "hh:mm A" : "hh:mm")
}

export const DateMonthAtHourMinuteAmPm = (props: Props) => {

const parseDateString = (date: string) => {
const dateObj = new Date(date)
return dateObj.toLocaleDateString('en-GB', { month: 'long', day: 'numeric' }) + " at " + dateObj.toLocaleTimeString('en-GB', { hour: 'numeric', minute: 'numeric', hour12: true })
}
return (
<Suspense fallback={parseDateString(props.date)}>
<MomentConverter {...props} format="Do MMMM \at hh:mm A" />
</Suspense>
)
return getDateObject(props.date).format("Do MMMM [at] hh:mm A")
}
Loading

0 comments on commit 30ae852

Please sign in to comment.