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

Lazy load images in the Brave News V2 UI #15586

Merged
merged 4 commits into from
Oct 24, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

import * as React from 'react'
import * as Card from '../cardSizes'
import getBraveNewsController, * as BraveNews from '../../../../api/brave_news'
import * as BraveNews from '../../../../api/brave_news'
import { useUnpaddedImageUrl } from '../useUnpaddedImageUrl'

type Props = {
imageUrl?: string
Expand All @@ -14,60 +15,8 @@ type Props = {
onLoaded?: () => any
}

const cache: { [url: string]: string } = {}

export function useGetUnpaddedImage (paddedUrl: string | undefined, onLoaded?: () => any, useCache?: boolean) {
const [unpaddedUrl, setUnpaddedUrl] = React.useState('')

React.useEffect(() => {
const onReceiveUnpaddedUrl = (result: string) => {
if (useCache) cache[paddedUrl!] = result
setUnpaddedUrl(result)

if (onLoaded) window.requestAnimationFrame(() => onLoaded())
}

// Storybook method
// @ts-expect-error
if (window.braveStorybookUnpadUrl) {
// @ts-expect-error
window.braveStorybookUnpadUrl(paddedUrl)
.then(onReceiveUnpaddedUrl)
return
}

if (!paddedUrl) return

if (cache[paddedUrl]) {
onReceiveUnpaddedUrl(cache[paddedUrl])
return
}

let blobUrl: string
getBraveNewsController().getImageData({ url: paddedUrl })
.then(async (result) => {
if (!result.imageData) {
return
}

const blob = new Blob([new Uint8Array(result.imageData)], { type: 'image/*' })
blobUrl = URL.createObjectURL(blob)
onReceiveUnpaddedUrl(blobUrl)
})
.catch(err => {
console.error(`Error getting image for ${paddedUrl}.`, err)
})

// Only revoke the URL if we aren't using the cache.
return () => {
if (!useCache) URL.revokeObjectURL(blobUrl)
}
}, [paddedUrl])
return unpaddedUrl
}

export default function CardImage (props: Props) {
const unpaddedUrl = useGetUnpaddedImage(props.imageUrl, props.onLoaded)
const unpaddedUrl = useUnpaddedImageUrl(props.imageUrl, props.onLoaded)
const [isImageLoaded, setIsImageLoaded] = React.useState(false)
React.useEffect(() => {
if (unpaddedUrl) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export default function Configure () {
}

return (
<Grid>
<Grid id='brave-news-configure'>
<BackButtonContainer>
<Button onClick={() => setCustomizePage(null)}>
{BackArrow}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import * as React from 'react'
import styled from 'styled-components'
import { api } from '../../../../api/brave_news/news'
import Flex from '../../../Flex'
import { useGetUnpaddedImage } from '../cards/CardImage'
import FollowButton from './FollowButton'
import { getCardColor } from './colors'
import { usePublisher, usePublisherFollowed } from './Context'
import { useLazyUnpaddedImageUrl } from '../useUnpaddedImageUrl'

interface CardProps {
backgroundColor?: string
Expand Down Expand Up @@ -63,8 +63,13 @@ export default function FeedCard (props: {
const { followed, setFollowed } = usePublisherFollowed(props.publisherId)

const backgroundColor = publisher.backgroundColor || getCardColor(publisher.feedSource?.url || publisher.publisherId)
const coverUrl = useGetUnpaddedImage(publisher.coverUrl?.url, undefined, /* useCache= */true)
return <Flex direction="column" gap={8}>
const { url: coverUrl, elementRef } = useLazyUnpaddedImageUrl(publisher.coverUrl?.url, {
rootElement: document.getElementById('brave-news-configure'),
rootMargin: '0px 0px 200px 0px',
useCache: true
})

return <Flex direction="column" gap={8} ref={elementRef}>
<Card backgroundColor={backgroundColor} data-feed-card-is-followed={followed}>
{coverUrl && <CoverImage backgroundImage={coverUrl} />}
<StyledFollowButton following={followed} onClick={() => setFollowed(!followed)} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import * as React from 'react'
import styled from 'styled-components'
import { getLocale } from '$web-common/locale'
import Flex from '../../../Flex'
import { useGetUnpaddedImage } from '../cards/CardImage'
import { useChannelSubscribed, usePublisher, usePublisherFollowed } from './Context'
import { useLazyUnpaddedImageUrl } from '../useUnpaddedImageUrl'

interface Props {
publisherId: string
Expand Down Expand Up @@ -60,9 +60,13 @@ const ChannelNameText = styled.span`
`

function FavIcon (props: { src?: string }) {
const url = useGetUnpaddedImage(props.src, undefined, /* useCache= */true)
const { url, elementRef } = useLazyUnpaddedImageUrl(props.src, {
rootElement: document.getElementById('brave-news-configure'),
rootMargin: '0px 0px 100px 0px',
useCache: true
})
const [error, setError] = React.useState(false)
return <FavIconContainer>
return <FavIconContainer ref={elementRef}>
{url && !error && <img src={url} onError={() => setError(true)} />}
</FavIconContainer>
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright (c) 2022 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.

import * as React from 'react'
import getBraveNewsController from '../../../api/brave_news'

interface Options {
rootElement?: HTMLElement | null
rootMargin?: string
threshold?: number

useCache?: boolean
onLoaded?: () => any
}

const cache: { [url: string]: string } = {}
export function useUnpaddedImageUrl (paddedUrl: string | undefined, onLoaded?: () => any, useCache?: boolean) {
const [unpaddedUrl, setUnpaddedUrl] = React.useState('')

React.useEffect(() => {
const onReceiveUnpaddedUrl = (result: string) => {
if (useCache) cache[paddedUrl!] = result
setUnpaddedUrl(result)

if (onLoaded) window.requestAnimationFrame(() => onLoaded())
}

// Storybook method
// @ts-expect-error
if (window.braveStorybookUnpadUrl) {
// @ts-expect-error
window.braveStorybookUnpadUrl(paddedUrl)
.then(onReceiveUnpaddedUrl)
return
}

if (!paddedUrl) return
fallaciousreasoning marked this conversation as resolved.
Show resolved Hide resolved

if (cache[paddedUrl]) {
onReceiveUnpaddedUrl(cache[paddedUrl])
return
}

let blobUrl: string
getBraveNewsController().getImageData({ url: paddedUrl })
.then(async (result) => {
if (!result.imageData) {
return
}

const blob = new Blob([new Uint8Array(result.imageData)], { type: 'image/*' })
blobUrl = URL.createObjectURL(blob)
onReceiveUnpaddedUrl(blobUrl)
})
.catch(err => {
console.error(`Error getting image for ${paddedUrl}.`, err)
})

// Only revoke the URL if we aren't using the cache.
return () => {
if (!useCache) URL.revokeObjectURL(blobUrl)
}
}, [paddedUrl])
return unpaddedUrl
}

export function useLazyUnpaddedImageUrl (paddedUrl: string | undefined, options: Options) {
const [visible, setVisible] = React.useState(false)
const [elementRef, setElementRef] = React.useState<HTMLElement | null>(null)

React.useEffect(() => {
if (!elementRef) return

const observer = new IntersectionObserver(([intersectionInfo]) => {
fallaciousreasoning marked this conversation as resolved.
Show resolved Hide resolved
if (!intersectionInfo.isIntersecting) {
return
}
setVisible(true)
}, {
root: options.rootElement,
rootMargin: options.rootMargin,
threshold: options.threshold
})

observer.observe(elementRef)
return () => {
observer.disconnect()
}
}, [options.rootElement, elementRef])

return {
url: useUnpaddedImageUrl(visible ? paddedUrl : undefined, options.onLoaded, options.useCache) || cache[paddedUrl!],
elementRef: setElementRef
fallaciousreasoning marked this conversation as resolved.
Show resolved Hide resolved
}
}