Skip to content

Commit

Permalink
Merge pull request #1210 from Ekep-Obasi/fix/error-on-initial-loading…
Browse files Browse the repository at this point in the history
…-for-new-graph

fix: corrected computation of `splashDataLoaded`
  • Loading branch information
Rassl authored Apr 16, 2024
2 parents 3b9bef7 + 8068339 commit 6b0df12
Show file tree
Hide file tree
Showing 14 changed files with 103 additions and 75 deletions.
4 changes: 4 additions & 0 deletions src/components/App/AppBar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import { media } from '~/utils/media'
export const AppBar = () => {
const appMetaData = useAppStore((s) => s.appMetaData)

if (!appMetaData) {
return null
}

return (
<Header>
<TitleWrapper>
Expand Down
4 changes: 4 additions & 0 deletions src/components/App/SecondarySidebar/About/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export const About = () => {
const [isAdmin] = useUserStore((s) => [s.isAdmin])
const appMetaData = useAppStore((s) => s.appMetaData)

if (!appMetaData) {
return null
}

return (
<Wrapper align="stretch" direction="column" justify="flex-end">
<Heading align="center" direction="row" justify="space-between">
Expand Down
7 changes: 0 additions & 7 deletions src/components/App/Splash/constants.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import { TAboutParams } from '~/network/fetchSourcesData'

export const initialAboutState = {
description: '',
mission_statement: '',
search_term: '',
title: '',
}

export const initialMessageData = [
{
label: 'New Content',
Expand Down
89 changes: 34 additions & 55 deletions src/components/App/Splash/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
/* eslint-disable react/display-name */
import { LinearProgress } from '@mui/material'
import { memo, PropsWithChildren, useEffect, useMemo, useState } from 'react'
import { memo, PropsWithChildren, useCallback, useEffect, useState } from 'react'
import styled from 'styled-components'
import { Flex } from '~/components/common/Flex'
import { Text } from '~/components/common/Text'
import { StatsConfig } from '~/components/Stats'
import { getAboutData, getStats, TStatParams } from '~/network/fetchSourcesData'
import { getAboutData, getStats } from '~/network/fetchSourcesData'
import { useAppStore } from '~/stores/useAppStore'
import { useDataStore } from '~/stores/useDataStore'
import { TStats } from '~/types'
import { colors, formatNumberWithCommas } from '~/utils'
import { colors, formatSplashMessage, formatStatsResponse } from '~/utils'
import { AnimatedTextContent } from './animated'
import { initialMessageData, Message } from './constants'
import { SphereAnimation } from './SpiningSphere'
Expand All @@ -21,81 +19,62 @@ export const Splash = memo(({ children }: PropsWithChildren) => {
const { appMetaData, setAppMetaData } = useAppStore((s) => s)
const { stats, setStats, isFetching } = useDataStore((s) => s)

useEffect(() => {
const run = async () => {
try {
const fetchData = useCallback(async () => {
try {
if (!appMetaData) {
const aboutResponse = await getAboutData()

setAppMetaData(aboutResponse)
} catch (error) {
setProgress(100)

setIsLoading(false)
}
}

run()
}, [setIsLoading, setAppMetaData, stats])

useEffect(() => {
const run = async () => {
const statsReponse = await getStats()

const updatedStats: TStats = {}
if (!stats) {
const statsResponse = await getStats()

StatsConfig.forEach(({ key, dataKey }) => {
updatedStats[key as keyof TStats] = formatNumberWithCommas(statsReponse[dataKey as keyof TStatParams] ?? 0)
})
const updatedStats = formatStatsResponse(statsResponse)

setStats(updatedStats)
setStats(updatedStats)

const messageData = initialMessageData.map(({ dataKey, ...rest }) => ({
...rest,
value: formatNumberWithCommas(statsReponse[dataKey as keyof TStatParams] ?? 0),
}))
const messageData = formatSplashMessage(statsResponse)

setMessage(messageData)
}
setMessage(messageData)
}
} catch {
setIsLoading(false)

if (!stats) {
run()
setProgress(100)
}
}, [stats, setMessage, setStats])

const splashDataLoaded = useMemo(
() => Object.values(appMetaData).some((value) => !!value) && message.some(({ value }) => !!value),
[appMetaData, message],
)
}, [appMetaData, setAppMetaData, setStats, stats])

useEffect(() => {
fetchData()

let timeoutId: NodeJS.Timeout
let intervalId: NodeJS.Timer

if (!isFetching && message && appMetaData) {
// increase progress fro 0 to 50% after all data is fetched
setProgress((prev) => (!prev ? 50 : prev))

if (!isFetching && splashDataLoaded) {
setProgress(50)
intervalId = setInterval(() => {
setProgress((prev) => (prev >= 100 ? 100 : prev + Math.floor(Math.random() * 4)))
}, 100)

timeoutId = setTimeout(() => setIsLoading(false), 5000)
}

return () => clearTimeout(timeoutId)
}, [isFetching, setIsLoading, splashDataLoaded])

useEffect(() => {
const intervalId = setInterval(() => {
if (splashDataLoaded) {
setProgress((prev) => (prev >= 100 ? 100 : prev + Math.floor(Math.random() * 4)))
}
}, 100)

return () => clearInterval(intervalId)
}, [splashDataLoaded])
return () => {
clearTimeout(timeoutId)
clearInterval(intervalId)
}
}, [appMetaData, fetchData, isFetching, message, stats])

if (!splashDataLoaded) {
if (!message.some(({ value }) => !!value) || !appMetaData) {
return null
}

return (
<SplashWrapper>
{isLoading && splashDataLoaded ? (
{isLoading ? (
<Wrappper align="center" direction="row" justify="center">
<SphereAnimation />
<Flex style={{ color: colors.white }}>
Expand Down
4 changes: 4 additions & 0 deletions src/components/AppNew/AppBar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import { media } from '~/utils/media'
export const AppBar = () => {
const appMetaData = useAppStore((s) => s.appMetaData)

if (!appMetaData) {
return null
}

return (
<Header>
<TitleWrapper>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export const SettingsView: React.FC<Props> = ({ onClose }) => {
{isAdmin && (
<>
<TabPanel index={0} value={value}>
<General initialValues={appMetaData} />
{appMetaData && <General initialValues={appMetaData} />}
</TabPanel>
</>
)}
Expand Down
4 changes: 4 additions & 0 deletions src/components/AppNew/SecondarySidebar/About/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export const About = () => {
const [isAdmin] = useUserStore((s) => [s.isAdmin])
const appMetaData = useAppStore((s) => s.appMetaData)

if (!appMetaData) {
return null
}

return (
<Wrapper align="stretch" direction="column" justify="flex-end">
<Heading align="center" direction="row" justify="space-between">
Expand Down
2 changes: 1 addition & 1 deletion src/components/AppNew/Splash/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export const Splash = memo(({ handleLoading }: Props) => {
<SphereAnimation />
<Flex style={{ color: colors.white }}>
<TitleWrapper>
{appMetaData.title && <Text className="title">{appMetaData.title}</Text>}
{appMetaData && <Text className="title">{appMetaData.title}</Text>}
<Text className="subtitle">Second Brain</Text>
</TitleWrapper>
<LinearProgress color="inherit" sx={{ my: 1.75, height: '2px' }} value={progress} variant="determinate" />
Expand Down
2 changes: 1 addition & 1 deletion src/components/SettingsModal/SettingsView/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const SettingsView: React.FC<Props> = ({ onClose }) => {
</SettingsHeader>
{tabs.map((tab, index) => (
<TabPanel key={tab.label} index={index} value={value}>
<tab.component initialValues={appMetaData} onClose={onClose} />
{appMetaData && <tab.component initialValues={appMetaData} onClose={onClose} />}
</TabPanel>
))}
</Wrapper>
Expand Down
18 changes: 11 additions & 7 deletions src/components/Stats/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,21 @@ import { TStatParams, getStats } from '~/network/fetchSourcesData'
import { useDataStore } from '~/stores/useDataStore'
import { useUserStore } from '~/stores/useUserStore'
import { TStats } from '~/types'
import { formatBudget, formatNumberWithCommas } from '~/utils'
import { formatBudget, formatStatsResponse } from '~/utils'
import { colors } from '~/utils/colors'
import DocumentIcon from '../Icons/DocumentIcon'
import EpisodeIcon from '../Icons/EpisodeIcon'
import { Flex } from '../common/Flex'

export const StatsConfig = [
interface StatConfigItem {
name: string
icon: JSX.Element
key: keyof TStats
dataKey: keyof TStatParams
mediaType: string
}

export const StatsConfig: StatConfigItem[] = [
{
name: 'Nodes',
icon: <NodesIcon />,
Expand Down Expand Up @@ -75,11 +83,7 @@ export const Stats = () => {
const data = await getStats()

if (data) {
const updatedStats: TStats = {}

StatsConfig.forEach(({ key, dataKey }) => {
updatedStats[key as keyof TStats] = formatNumberWithCommas(data[dataKey as keyof TStatParams] ?? 0)
})
const updatedStats = formatStatsResponse(data)

setStats(updatedStats)
}
Expand Down
2 changes: 2 additions & 0 deletions src/network/fetchSourcesData/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ export type TStatParams = {
num_tweet: number
num_twitter_space: number
num_video: number
num_documents: number
[key: string]: number
}

export type TPriceParams = {
Expand Down
5 changes: 2 additions & 3 deletions src/stores/useAppStore/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { create } from 'zustand'
import { initialAboutState } from '~/components/App/Splash/constants'
import { TAboutParams } from '~/network/fetchSourcesData'

export type SecondarySidebarActiveTab = '' | 'sentiment' | 'sources' | 'about'
Expand All @@ -14,7 +13,7 @@ export type AppStore = {
transcriptIsOpen: boolean
flagErrorIsOpen: boolean
relevanceIsSelected: boolean
appMetaData: TAboutParams
appMetaData: TAboutParams | null
clearSearch: () => void
setCurrentSearch: (_: string) => void
setSearchFormValue: (_: string) => void
Expand All @@ -36,7 +35,7 @@ const defaultData = {
sidebarIsOpen: true,
theme: 'light' as const,
transcriptIsOpen: false,
appMetaData: initialAboutState,
appMetaData: null,
}

export const useAppStore = create<AppStore>((set, get) => ({
Expand Down
3 changes: 3 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { extractUuidAndHost } from './auth'
import { formatDate } from './formatDate'
import { formatNumberWithCommas } from './formatStats'
import { generateAuthQueryParam, getSignedMessageFromRelay } from './getSignedMessage'
import { formatSplashMessage, formatStatsResponse } from './splash'
import { getTrendingTopic, showPlayButton } from './trending'
import { videoTimeToSeconds } from './videoTimetoSeconds'

Expand All @@ -38,6 +39,8 @@ export {
formatDate,
formatDescription,
formatNumberWithCommas,
formatSplashMessage,
formatStatsResponse,
formatTimestamp,
generateAuthQueryParam,
getLSat,
Expand Down
32 changes: 32 additions & 0 deletions src/utils/splash/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { initialMessageData } from '~/components/App/Splash/constants'
import { StatsConfig } from '~/components/Stats'
import { TStatParams } from '~/network/fetchSourcesData'
import { TStats } from '~/types'
import { formatNumberWithCommas } from '../formatStats'

/**
* Formats the statistics response object.
* @param statsRespons {TStatParams} The statistics response object from /stats to format.
* @returns {TStats} The formatted statistics object.
*/

export const formatStatsResponse = (statsResponse: TStatParams): TStats =>
StatsConfig.reduce((updatedStats: TStats, { key, dataKey }) => {
const formattedValue = formatNumberWithCommas(statsResponse[dataKey] ?? 0)

return { ...updatedStats, [key]: formattedValue }
}, {})

/**
* Formats the splash message based on the statistics response.
* @param statsRespons {TStatParams} The statistics response object from /stats to format.
* @returns The formatted splash message array.
*/

export const formatSplashMessage = (statsResponse: TStatParams) =>
// Map over initialMessageData to format each message
initialMessageData.map(({ dataKey, ...rest }) => ({
// Spread the rest of the properties and add the formatted value
...rest,
value: formatNumberWithCommas(statsResponse[dataKey] ?? 0),
}))

0 comments on commit 6b0df12

Please sign in to comment.