Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance TLDR Button Visibility for currently playing topic #1310

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cypress/e2e/trendingTopics/trendingTopics.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ describe('test trending topics', () => {
const responseBody = interception.response.body
cy.get('.list').should('exist')
for (let i = 0; i < responseBody.length; i++) {
cy.contains('.list', `#${responseBody[i].name}`).should('exist')
cy.contains('.list', `${responseBody[i].name}`).should('exist')
}

cy.contains(`#${responseBody[0].name}`).eq(0).click()
cy.contains(`${responseBody[0].name}`).eq(0).click()

//wait for search result
cy.wait('@search')
Expand Down
3 changes: 3 additions & 0 deletions public/svg-icons/HashTag.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import React from 'react'
import { BriefDescription } from '..'
import { useAppStore } from '../../../../../../stores/useAppStore'

window.React = React

Expand All @@ -13,23 +14,46 @@ jest.mock('~/stores/useModalStore', () => ({
}),
}))

jest.mock('~/stores/useAppStore', () => ({
useAppStore: jest.fn(),
}))

jest.mock('~/components/Icons/PauseIcon', () => jest.fn(() => <div data-testid="pause-icon" />))
jest.mock('~/components/Icons/SoundIcon', () => jest.fn(() => <div data-testid="listen-icon" />))

const useAppStoreMock = useAppStore as jest.MockedFunction<typeof useAppStore>

describe('BriefDescription Component Tests', () => {
const trendMock = {
audio_EN: 'fake-audio-url',
tldr_topic: 'Test Topic',
tldr: '',
}

const props = {
onClose: jest.fn(),
trend: trendMock,
selectTrending: jest.fn(),
}

beforeEach(() => {
useAppStoreMock.mockReturnValue({ currentPlayingAudio: { current: null }, setCurrentPlayingAudio: jest.fn() })
})

afterEach(() => {
jest.clearAllMocks()
})

it('renders title, audio button, and tldr', () => {
render(<BriefDescription onClose={() => null} trend={trendMock} />)
render(<BriefDescription {...props} />)

expect(screen.getByText('Test Topic')).toBeInTheDocument()

expect(screen.getByText('Listen')).toBeInTheDocument()
})

it('toggles play/pause on audio button click', () => {
render(<BriefDescription onClose={() => null} trend={trendMock} />)
render(<BriefDescription {...props} />)

const handleClick = jest.fn()

Expand All @@ -42,10 +66,50 @@ describe('BriefDescription Component Tests', () => {
}, 0)
})

it('ensures that listen Icon only display if the audio is not currently playing in the background', () => {
const { getByTestId, getByText } = render(<BriefDescription {...props} />)

expect(getByTestId('listen-icon')).toBeInTheDocument()
expect(getByText('Listen')).toBeInTheDocument()
})

it('ensures that pause icon only displays if the audio is playing in the background', () => {
const mockCurrentPlayingAudio = { current: { src: trendMock.audio_EN, paused: false } }

useAppStoreMock.mockReturnValue({ currentPlayingAudio: mockCurrentPlayingAudio, setCurrentPlayingAudio: jest.fn() })

const { getByTestId, getByText } = render(<BriefDescription {...props} />)

expect(getByTestId('pause-icon')).toBeInTheDocument()
expect(getByText('Pause')).toBeInTheDocument()
})

it('ensures that clicking play in TLDR modal stops current background audio and starts new audio', async () => {
const setCurrentPlayingAudioMock = jest.fn()

useAppStoreMock.mockReturnValue({
currentPlayingAudio: { current: { src: 'random-audio-file', paused: false, pause: jest.fn() } },
setCurrentPlayingAudio: setCurrentPlayingAudioMock,
})

const { getByRole, container } = render(<BriefDescription {...props} />)

const listenButton = getByRole('button', { name: /Listen/i })

expect(listenButton).toBeInTheDocument()

fireEvent.click(listenButton)

waitFor(async () => {
expect(setCurrentPlayingAudioMock).toHaveBeenCalledWith(null)
expect(container.querySelector('audio')?.paused).toBe(true)
})
})

it('should call onClose when closing the modal', () => {
const onCloseMock = jest.fn()

render(<BriefDescription onClose={() => null} trend={trendMock} />)
render(<BriefDescription {...props} />)

fireEvent.keyDown(window, { key: 'Escape' })

Expand Down
94 changes: 70 additions & 24 deletions src/components/App/SideBar/Trending/BriefDescriptionModal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Button } from '@mui/material'
import clsx from 'clsx'
import { FC, useCallback, useEffect, useRef, useState } from 'react'
import Markdown from 'react-markdown'
import styled from 'styled-components'
Expand All @@ -8,8 +9,10 @@ import SoundIcon from '~/components/Icons/SoundIcon'
import { BaseModal } from '~/components/Modal'
import { Flex } from '~/components/common/Flex'
import { Text } from '~/components/common/Text'
import { useAppStore } from '~/stores/useAppStore'
import { useModal } from '~/stores/useModalStore'
import { Trending } from '~/types'
import { colors } from '~/utils'

type Props = {
trend: Trending
Expand All @@ -20,19 +23,18 @@ type Props = {
export const BriefDescription: FC<Props> = ({ trend, onClose, selectTrending }) => {
const [isPlaying, setIsPlaying] = useState(false)
const { close } = useModal('briefDescription')
const { currentPlayingAudio, setCurrentPlayingAudio } = useAppStore((s) => s)

const audioRef = useRef<HTMLVideoElement | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)

const handleLearnMore = () => {
selectTrending(trend.name)
}
const handleLearnMore = () => selectTrending(trend.name)

const handleClose = useCallback(() => {
onClose()
close()
}, [onClose, close])

const togglePlay = () => {
const handleToggle = () => {
if (audioRef.current) {
if (isPlaying) {
audioRef.current.pause()
Expand All @@ -42,8 +44,19 @@ export const BriefDescription: FC<Props> = ({ trend, onClose, selectTrending })

setIsPlaying(!isPlaying)
}
}

const togglePlay = () => {
const isBackgroundAudioPlaying = !currentPlayingAudio?.current?.paused

if (isBackgroundAudioPlaying) {
currentPlayingAudio?.current?.pause()
setCurrentPlayingAudio(null)
}

setIsPlaying(!isPlaying)
if (currentPlayingAudio?.current?.src !== trend.audio_EN || !isBackgroundAudioPlaying) {
handleToggle()
}
}

useEffect(() => {
Expand All @@ -54,36 +67,40 @@ export const BriefDescription: FC<Props> = ({ trend, onClose, selectTrending })
}
}, [handleClose])

const showPlayBtn =
(currentPlayingAudio?.current?.src === trend.audio_EN && !currentPlayingAudio?.current?.paused) || isPlaying

return (
<BaseModal id="briefDescription" kind="regular" noWrap onClose={handleClose}>
{trend.audio_EN ? (
<>
<Flex direction="row" justify="flex-start" m={20}>
<Button
<StyledHeader>
<StyleButton
className={clsx('default', { play: showPlayBtn })}
onClick={togglePlay}
size="small"
startIcon={isPlaying ? <PauseIcon /> : <SoundIcon />}
style={{ marginRight: '10px' }}
startIcon={showPlayBtn ? <PauseIcon /> : <SoundIcon />}
>
Listen
</Button>
{showPlayBtn ? 'Pause' : 'Listen'}
</StyleButton>

<Button onClick={handleLearnMore} size="small" startIcon={<BubbleChartIcon />}>
<StyleButton className="default" onClick={handleLearnMore} size="small" startIcon={<BubbleChartIcon />}>
Learn More
</Button>
</Flex>

</StyleButton>
</StyledHeader>
<StyledAudio ref={audioRef} src={trend.audio_EN}>
<track kind="captions" />
</StyledAudio>
</>
) : null}
<Title>{trend.tldr_topic ?? trend.name}</Title>
<ScrollableContent>
<Flex>
<StyledText>{trend.tldr && <Markdown>{trend.tldr}</Markdown>}</StyledText>
</Flex>
</ScrollableContent>
<Flex mt={75}>
<Title>{trend.tldr_topic ?? trend.name}</Title>
<ScrollableContent>
<Flex>
<StyledText>{trend.tldr && <Markdown>{trend.tldr}</Markdown>}</StyledText>
</Flex>
</ScrollableContent>
</Flex>
</BaseModal>
)
}
Expand Down Expand Up @@ -111,6 +128,35 @@ const Title = styled(Text)`
`

const StyledAudio = styled.audio`
height: 0;
width: 0;
display: none;
`

const StyleButton = styled(Button)`
&& {
&.default {
font-size: 13px;
font-weight: 500;
font-family: Barlow;
padding: 12px, 16px, 12px, 10px;

&.play {
color: ${colors.BG3};
background-color: ${colors.white};
}
}
}
`

const StyledHeader = styled(Flex)`
top: 0px;
position: absolute;
border-radius: 16px 16px 0px 0px;
padding: 0px 12px;
width: 100%;
height: 60px;
display: flex;
flex-direction: row;
align-items: center;
background-color: ${colors.BG3};
gap: 10px;
`
61 changes: 33 additions & 28 deletions src/components/App/SideBar/Trending/__tests__/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import React from 'react'
import { Trending } from '..'
import * as fetchGraphData from '../../../../../network/fetchGraphData'
import { useAppStore } from '../../../../../stores/useAppStore'
import { useDataStore } from '../../../../../stores/useDataStore'
import { useModal } from '../../../../../stores/useModalStore'
import * as utils from '../../../../../utils/trending'
Expand All @@ -30,8 +31,13 @@ jest.mock('~/stores/useDataStore', () => ({
useDataStore: jest.fn(),
}))

jest.mock('~/stores/useAppStore', () => ({
useAppStore: jest.fn(),
}))

const mockedGetTrends = jest.spyOn(fetchGraphData, 'getTrends')
const mockedUseDataStore = useDataStore as jest.MockedFunction<typeof useDataStore>
const useAppStoreMock = useAppStore as jest.MockedFunction<typeof useAppStore>
const mockedUseModal = useModal as jest.MockedFunction<typeof useModal>
const availableModal = ['briefDescription', 'addContent']

Expand All @@ -42,9 +48,8 @@ const mockTrends = [

describe('Trending Component', () => {
beforeEach(() => {
jest.clearAllMocks()

mockedUseDataStore.mockReturnValue({ trendingTopics: mockTrends, setTrendingTopics: jest.fn() })
useAppStoreMock.mockReturnValue({ currentPlayingAudio: { current: null }, setCurrentPlayingAudio: jest.fn() })
})

it('asserts that the component renders correctly', () => {
Expand Down Expand Up @@ -74,33 +79,10 @@ describe('Trending Component', () => {
const { getByText } = render(<Trending />)

mockTrends.forEach(({ name }) => {
expect(getByText(`#${name}`)).toBeInTheDocument()
expect(getByText(`${name}`)).toBeInTheDocument()
})
})

it('ensures that the "Add Content" button calls the openContentAddModal function', () => {
mockedUseDataStore.mockReturnValue({ trendingTopics: [], setTrendingTopics: jest.fn() })

const loading = false

jest.spyOn(React, 'useState').mockImplementationOnce(() => [loading, jest.fn()])

const { getByText, getByRole } = render(<Trending />)

expect(getByText('No new trending topics in the last 24 hours')).toBeInTheDocument()

expect(getByRole('button', { name: 'Add Content' })).toBeInTheDocument()

fireEvent.click(getByRole('button', { name: 'Add Content' }))

const { open: openAddContentMock } = mockedUseModal('addContent')

expect(mockedUseModal).toHaveBeenCalledWith('addContent')
;(async () => {
await waitFor(() => expect(openAddContentMock).toHaveBeenCalled())
})()
})

it('confirms the rendering of the BriefDescriptionModal when a TLDR button is clicked', () => {
mockedUseDataStore.mockReturnValue({ trendingTopics: [mockTrends[0]], setTrendingTopics: jest.fn() })

Expand Down Expand Up @@ -140,7 +122,7 @@ describe('Trending Component', () => {

const { getByText } = render(<Trending />)

fireEvent.click(getByText(`#${mockTrends[0].name}`))
fireEvent.click(getByText(`${mockTrends[0].name}`))
;(async () => {
await waitFor(() => expect(mockedSelectTrendingTopic).toHaveBeenCalled())
})()
Expand All @@ -153,7 +135,7 @@ describe('Trending Component', () => {

const { getByText } = render(<Trending />)

fireEvent.click(getByText(`#${mockTrends[0].name}`))
fireEvent.click(getByText(`${mockTrends[0].name}`))
;(async () => {
await waitFor(() => {
const searchInput = screen.getByPlaceholderText('Search') as HTMLInputElement
Expand All @@ -172,4 +154,27 @@ describe('Trending Component', () => {
// Assert that scrollbar has correct width
expect(scrollbar).toHaveStyle('width: 3')
})

it('ensures that the "Add Content" button calls the openContentAddModal function', () => {
mockedUseDataStore.mockReturnValue({ trendingTopics: [], setTrendingTopics: jest.fn() })

const loading = false

jest.spyOn(React, 'useState').mockImplementation(() => [loading, jest.fn()])

const { getByText, getByRole } = render(<Trending />)

expect(getByText('No new trending topics in the last 24 hours')).toBeInTheDocument()

expect(getByRole('button', { name: 'Add Content' })).toBeInTheDocument()

fireEvent.click(getByRole('button', { name: 'Add Content' }))

const { open: openAddContentMock } = mockedUseModal('addContent')

expect(mockedUseModal).toHaveBeenCalledWith('addContent')
;(async () => {
await waitFor(() => expect(openAddContentMock).toHaveBeenCalled())
})()
})
})
Loading
Loading