refactor: picture view masonry (#588)

* store

* update

Signed-off-by: Innei <i@innei.in>

* resize

Signed-off-by: Innei <i@innei.in>

* cleanup

Signed-off-by: Innei <i@innei.in>

* fix(ci): auto fix

Signed-off-by: Innei <i@innei.in>

* chore: update

Signed-off-by: Innei <i@innei.in>

* update

Signed-off-by: Innei <i@innei.in>

---------

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-09-23 20:59:44 +08:00
committed by GitHub
parent 2ae12c9d2b
commit d19d5c13d6
11 changed files with 613 additions and 290 deletions
@@ -36,7 +36,13 @@ jobs:
- name: Run formatter
run: pnpm run format
- name: Check for changes
id: check_changes
run: |
git diff --exit-code || echo "has_changes=true" >> $GITHUB_ENV
- name: Commit and push changes
if: steps.check_changes.outputs.has_changes == 'true' || env.has_changes == 'true'
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "chore: auto-fix linting and formatting issues"
@@ -44,23 +50,14 @@ jobs:
file_pattern: "."
- name: Add PR comment
if: steps.check_changes.outputs.has_changes == 'true' || env.has_changes == 'true'
uses: actions/github-script@v7
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
const hasChanges = await github.rest.pulls.listFiles({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
}).then(response => response.data.length > 0);
const message = hasChanges
? 'Linting and formatting issues were automatically fixed. Please review the changes.'
: 'No linting or formatting issues were found.';
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: message
body: 'Linting and formatting issues were automatically fixed. Please review the changes.'
});
+1 -1
View File
@@ -8,7 +8,6 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@egjs/react-infinitegrid": "4.12.0",
"@egoist/tipc": "0.3.2",
"@electron-toolkit/preload": "^3.0.1",
"@follow/electron-main": "workspace:*",
@@ -71,6 +70,7 @@
"lethargy": "1.0.9",
"linkedom": "^0.18.5",
"lodash-es": "4.17.21",
"masonic": "4.0.1",
"nanoid": "5.0.7",
"ofetch": "1.4.0",
"path-to-regexp": "8.1.0",
+10 -8
View File
@@ -1,4 +1,5 @@
import { Avatar, AvatarFallback, AvatarImage } from "@radix-ui/react-avatar"
import { m } from "framer-motion"
import type { ReactNode } from "react"
import { forwardRef, useMemo } from "react"
@@ -145,7 +146,7 @@ export function FeedIcon({
ImageElement = (
<PlatformIcon url={siteUrl} style={sizeStyle} className={cn("center mr-2", className)}>
<img style={sizeStyle} />
<m.img style={sizeStyle} initial={{ opacity: 0 }} animate={{ opacity: 1 }} />
</PlatformIcon>
)
break
@@ -158,7 +159,12 @@ export function FeedIcon({
})
ImageElement = (
<PlatformIcon url={image} style={sizeStyle} className={cn("center mr-2", className)}>
<img className={cn("mr-2", className)} style={sizeStyle} />
<m.img
className={cn("mr-2", className)}
style={sizeStyle}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
/>
</PlatformIcon>
)
break
@@ -207,11 +213,7 @@ export function FeedIcon({
if (fallback && !!finalSrc) {
return (
<Avatar className="shrink-0">
<AvatarImage
className="rounded-sm object-cover duration-200 animate-in fade-in-0"
asChild
src={finalSrc}
>
<AvatarImage className="rounded-sm object-cover" asChild src={finalSrc}>
{ImageElement}
</AvatarImage>
<AvatarFallback asChild>{fallbackIcon}</AvatarFallback>
@@ -224,7 +226,7 @@ export function FeedIcon({
// Else
return (
<Avatar className="shrink-0">
<AvatarImage className="duration-200 animate-in fade-in-0" asChild src={finalSrc}>
<AvatarImage asChild src={finalSrc}>
{ImageElement}
</AvatarImage>
<AvatarFallback>
+212
View File
@@ -0,0 +1,212 @@
import { clearRequestTimeout, requestTimeout } from "@essentials/request-timeout"
import { useWindowSize } from "@react-hook/window-size"
import { useForceUpdate } from "framer-motion"
import { throttle } from "lodash-es"
import type { ContainerPosition, MasonryProps, MasonryScrollerProps, Positioner } from "masonic"
import { createResizeObserver, useMasonry, usePositioner, useScrollToIndex } from "masonic"
import * as React from "react"
import { useScrollViewElement } from "./scroll-area/hooks"
/**
* A "batteries included" masonry grid which includes all of the implementation details below. This component is the
* easiest way to get off and running in your app, before switching to more advanced implementations, if necessary.
* It will change its column count to fit its container's width and will decide how many rows to render based upon
* the height of the browser `window`.
*
* @param props
*/
export const Masonry = <Item,>(props: MasonryProps<Item>) => {
const [scrollTop, setScrollTop] = React.useState(0)
const [isScrolling, setIsScrolling] = React.useState(false)
const scrollElement = useScrollViewElement()
const fps = props.scrollFps || 12
React.useEffect(() => {
if (!scrollElement) return
const scrollTimer: number | null = null
const handleScroll = throttle(() => {
setIsScrolling(true)
setScrollTop(scrollElement.scrollTop)
}, 1000 / fps)
scrollElement.addEventListener("scroll", handleScroll)
return () => {
scrollElement.removeEventListener("scroll", handleScroll)
if (scrollTimer) {
clearTimeout(scrollTimer)
}
}
}, [fps, scrollElement])
const didMount = React.useRef(0)
React.useEffect(() => {
if (didMount.current === 1) setIsScrolling(true)
let didUnsubscribe = false
const to = requestTimeout(
() => {
if (didUnsubscribe) return
// This is here to prevent premature bail outs while maintaining high resolution
// unsets. Without it there will always bee a lot of unnecessary DOM writes to style.
setIsScrolling(false)
},
40 + 1000 / fps,
)
didMount.current = 1
return () => {
didUnsubscribe = true
clearRequestTimeout(to)
}
}, [fps, scrollTop])
const containerRef = React.useRef<null | HTMLElement>(null)
const windowSize = useWindowSize({
initialWidth: props.ssrWidth,
initialHeight: props.ssrHeight,
})
const containerPos = useContainerPosition(containerRef, windowSize)
const nextProps = Object.assign(
{
offset: containerPos.offset,
width: containerPos.width || windowSize[0],
height: containerPos.height || windowSize[1],
containerRef,
},
props,
) as any
// Workaround for https://github.com/jaredLunde/masonic/issues/12
const itemCounter = React.useRef<number>(props.items.length)
let shrunk = false
if (props.items.length !== itemCounter.current) {
if (props.items.length < itemCounter.current) shrunk = true
itemCounter.current = props.items.length
}
nextProps.positioner = usePositioner(nextProps, [shrunk && Math.random()])
nextProps.resizeObserver = useResizeObserver(nextProps.positioner)
nextProps.scrollTop = scrollTop
nextProps.isScrolling = isScrolling
nextProps.height = window.innerHeight
const scrollToIndex = useScrollToIndex(nextProps.positioner, {
height: nextProps.height,
offset: containerPos.offset,
align: typeof props.scrollToIndex === "object" ? props.scrollToIndex.align : void 0,
})
const index =
props.scrollToIndex &&
(typeof props.scrollToIndex === "number" ? props.scrollToIndex : props.scrollToIndex.index)
React.useEffect(() => {
if (index !== void 0) scrollToIndex(index)
}, [index, scrollToIndex])
return React.createElement(MasonryScroller, nextProps)
}
function MasonryScroller<Item>(
props: MasonryScrollerProps<Item> & {
scrollTop: number
isScrolling: boolean
},
) {
// We put this in its own layer because it's the thing that will trigger the most updates
// and we don't want to slower ourselves by cycling through all the functions, objects, and effects
// of other hooks
// const { scrollTop, isScrolling } = useScroller(props.offset, props.scrollFps)
// This is an update-heavy phase and while we could just Object.assign here,
// it is way faster to inline and there's a relatively low hit to he bundle
// size.
return useMasonry<Item>({
scrollTop: props.scrollTop,
isScrolling: props.isScrolling,
positioner: props.positioner,
resizeObserver: props.resizeObserver,
items: props.items,
onRender: props.onRender,
as: props.as,
id: props.id,
className: props.className,
style: props.style,
role: props.role,
tabIndex: props.tabIndex,
containerRef: props.containerRef,
itemAs: props.itemAs,
itemStyle: props.itemStyle,
itemHeightEstimate: props.itemHeightEstimate,
itemKey: props.itemKey,
overscanBy: props.overscanBy,
height: props.height,
render: props.render,
})
}
function useContainerPosition(
elementRef: React.MutableRefObject<HTMLElement | null>,
deps: React.DependencyList = [],
): ContainerPosition & {
height: number
} {
const [containerPosition, setContainerPosition] = React.useState<
ContainerPosition & {
height: number
}
>({
offset: 0,
width: 0,
height: 0,
})
React.useLayoutEffect(() => {
const { current } = elementRef
if (current !== null) {
let offset = 0
let el = current
do {
offset += el.offsetTop || 0
el = el.offsetParent as HTMLElement
} while (el)
if (offset !== containerPosition.offset || current.offsetWidth !== containerPosition.width) {
setContainerPosition({
offset,
width: current.offsetWidth,
height: current.offsetHeight,
})
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
React.useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
setContainerPosition((prev) => ({
...prev,
width: elementRef.current?.offsetWidth || 0,
}))
})
resizeObserver.observe(elementRef.current as HTMLElement)
return () => {
resizeObserver.disconnect()
}
}, [containerPosition, elementRef])
return containerPosition
}
function useResizeObserver(positioner: Positioner) {
const [forceUpdate] = useForceUpdate()
const resizeObserver = createResizeObserver(positioner, throttle(forceUpdate, 1000 / 12))
// Cleans up the resize observers when they change or the
// component unmounts
React.useEffect(() => () => resizeObserver.disconnect(), [resizeObserver])
return resizeObserver
}
@@ -9,6 +9,8 @@ export const useMasonryItemWidth = () => useContext(MasonryItemWidthContext)
export const MasonryItemsAspectRatioContext = createContextSelector({} as Record<string, number>)
export const MasonryIntersectionContext = createContext<IntersectionObserver>(null!)
export const useMasonryItemRatio = (url: string) =>
useContextSelector(MasonryItemsAspectRatioContext, (ctx) => ctx[url])
@@ -1,5 +1,7 @@
import { useLayoutEffect } from "foxact/use-isomorphic-layout-effect"
import { AnimatePresence, m } from "framer-motion"
import type { PropsWithChildren } from "react"
import { memo, useEffect, useState } from "react"
import { memo, useContext, useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import { SwipeMedia } from "~/components/ui/media/SwipeMedia"
@@ -13,9 +15,10 @@ import { useImageDimensions } from "~/store/image"
import { usePreviewMedia } from "../../../components/ui/media/hooks"
import { EntryItemWrapper } from "../layouts/EntryItemWrapper"
import { GridItem } from "../templates/grid-item-template"
import { GridItem, GridItemFooter } from "../templates/grid-item-template"
import type { UniversalItemProps } from "../types"
import {
MasonryIntersectionContext,
useMasonryItemRatio,
useMasonryItemWidth,
useSetStableMasonryItemRatio,
@@ -71,20 +74,39 @@ export const PictureWaterFallItem = memo(function PictureWaterFallItem({
const isActive = useRouteParamsSelector(({ entryId }) => entryId === entry?.entries.id)
const previewMedia = usePreviewMedia()
const itemWidth = useMasonryItemWidth()
const [ref, setRef] = useState<HTMLDivElement | null>(null)
const intersectionObserver = useContext(MasonryIntersectionContext)
useLayoutEffect(() => {
if (ref) {
intersectionObserver.observe(ref)
}
return () => {
if (ref) {
intersectionObserver.unobserve(ref)
}
}
}, [ref, intersectionObserver])
const [isMouseEnter, setIsMouseEnter] = useState(false)
if (!entry) return null
return (
<EntryItemWrapper
view={FeedViewType.Pictures}
entry={entry}
itemClassName="group hover:bg-theme-item-hover rounded-md"
<div
ref={setRef}
data-entry-id={entryId}
onMouseEnter={() => setIsMouseEnter(true)}
onMouseLeave={() => setIsMouseEnter(false)}
>
<GridItem
wrapperClassName="p-0 h-full flex flex-col"
entryId={entryId}
entryPreview={entryPreview}
translation={translation}
<EntryItemWrapper
view={FeedViewType.Pictures}
entry={entry}
itemClassName="group hover:bg-theme-item-hover rounded-md"
style={{
width: itemWidth,
}}
>
{entry.entries.media && entry.entries.media.length > 0 ? (
<MasonryItemFixedDimensionWrapper url={entry.entries.media[0].url}>
@@ -94,10 +116,32 @@ export const PictureWaterFallItem = memo(function PictureWaterFallItem({
proxySize={proxySize}
imgClassName="object-cover"
uniqueKey={entryId}
onPreview={(media, i) => {
previewMedia(media, i)
}}
onPreview={previewMedia}
/>
<AnimatePresence>
{isMouseEnter && (
<m.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 10 }}
className="absolute inset-x-0 -bottom-px z-[3] overflow-hidden rounded-b-md pb-1"
key="footer"
>
<div className="absolute inset-x-0 bottom-0 h-[56px]" style={maskStyle}>
<div className="absolute inset-x-0 bottom-0 h-[56px] bg-gradient-to-t from-black/80 to-transparent" />
</div>
<GridItemFooter
entryId={entryId}
entryPreview={entryPreview}
translation={translation}
titleClassName="!text-white"
descriptionClassName="!text-white/80"
timeClassName="!text-white/60"
/>
</m.div>
)}
</AnimatePresence>
</MasonryItemFixedDimensionWrapper>
) : (
<div className="center aspect-video flex-col gap-1 rounded-md bg-muted text-xs text-muted-foreground">
@@ -105,11 +149,14 @@ export const PictureWaterFallItem = memo(function PictureWaterFallItem({
No media available
</div>
)}
</GridItem>
</EntryItemWrapper>
</EntryItemWrapper>
</div>
)
})
const maskStyle = {
maskImage: "linear-gradient(rgba(255, 255, 255, 0) 0%, rgb(255, 255, 255) 10px)",
}
const MasonryItemFixedDimensionWrapper = (
props: PropsWithChildren<{
url: string
@@ -129,14 +176,18 @@ const MasonryItemFixedDimensionWrapper = (
setItemStableRatio(url, stableRadio)
}, [setItemStableRatio, stableRadio, url])
const style = useMemo(
() => ({
width: itemWidth,
height: itemWidth / stableRadioCtx,
}),
[itemWidth, stableRadioCtx],
)
if (!style.height) return null
return (
<div
className="relative flex h-full gap-2 overflow-x-auto"
style={{
width: itemWidth,
height: itemWidth / stableRadioCtx,
}}
>
<div className="relative flex h-full gap-2 overflow-x-auto overflow-y-hidden" style={style}>
{children}
</div>
)
@@ -153,13 +204,13 @@ export const PictureItemSkeleton = (
</div>
<div className="relative flex-1 px-2 pb-3 pt-1 text-sm">
<div className="relative mb-1 mt-1.5 truncate font-medium leading-none">
<Skeleton className="h-4 w-3/4 " />
<Skeleton className="h-4 w-3/4" />
</div>
<div className="mt-1 flex items-center gap-1 truncate text-[13px]">
<Skeleton className="mr-0.5 size-4" />
<Skeleton className="h-3 w-1/2 " />
<Skeleton className="h-3 w-1/2" />
<span className="text-zinc-500">·</span>
<Skeleton className="h-3 w-12 " />
<Skeleton className="h-3 w-12" />
</div>
</div>
</div>
@@ -1,10 +1,12 @@
import { MasonryInfiniteGrid } from "@egjs/react-infinitegrid"
import { debounce, throttle } from "lodash-es"
import type { CSSProperties, FC, PropsWithChildren } from "react"
import { memo, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
import { useSingleton } from "foxact/use-singleton"
import { throttle } from "lodash-es"
import type { RenderComponentProps } from "masonic"
import { useInfiniteLoader } from "masonic"
import type { FC } from "react"
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
import { useEventCallback } from "usehooks-ts"
import { useGeneralSettingKey } from "~/atoms/settings/general"
import { Masonry } from "~/components/ui/Masonry"
import { useScrollViewElement } from "~/components/ui/scroll-area/hooks"
import { nextFrame } from "~/lib/dom"
import { FeedViewType } from "~/lib/enum"
@@ -14,6 +16,7 @@ import { imageActions } from "~/store/image"
import { batchMarkRead } from "../hooks"
import { EntryItemSkeleton } from "../item"
import {
MasonryIntersectionContext,
MasonryItemsAspectRatioContext,
MasonryItemsAspectRatioSetterContext,
MasonryItemWidthContext,
@@ -51,9 +54,11 @@ const getCurrentColumn = (w: number) => {
return columns
}
const gutter = 24
export const PictureMasonry: FC<MasonryProps> = (props) => {
const { data } = props
const cacheMap = useSingleton(() => new Map<string, object>()).current
const [isInitDim, setIsInitDim] = useState(false)
const [isInitLayout, setIsInitLayout] = useState(false)
const [currentItemWidth, setCurrentItemWidth] = useState(0)
@@ -74,12 +79,13 @@ export const PictureMasonry: FC<MasonryProps> = (props) => {
}, [])
const containerRef = useRef<HTMLDivElement>(null)
const [currentColumn, setCurrentColumn] = useState(1)
useLayoutEffect(() => {
const $warpper = containerRef.current
if (!$warpper) return
const handler = () => {
const column = getCurrentColumn($warpper.clientWidth)
setCurrentItemWidth(Math.trunc($warpper.clientWidth / column - 20))
setCurrentItemWidth(Math.trunc($warpper.clientWidth / column - gutter))
setCurrentColumn(column)
@@ -87,7 +93,7 @@ export const PictureMasonry: FC<MasonryProps> = (props) => {
setIsInitLayout(true)
})
}
const recal = throttle(handler, 50)
const recal = throttle(handler, 1000 / 12)
let previousWidth = $warpper.offsetWidth
const resizeObserver = new ResizeObserver((entries) => {
@@ -108,146 +114,105 @@ export const PictureMasonry: FC<MasonryProps> = (props) => {
}
}, [])
const items = useMemo(() => {
const result = data.map((entryId) => {
const cache = cacheMap.get(entryId)
if (cache) {
return cache
}
const ret = { entryId }
cacheMap.set(entryId, ret)
return ret
}) as { entryId: string; cache?: object }[]
if (props.hasNextPage) {
for (let i = 0; i < 10; i++) {
result.push({
entryId: `placeholder${i}`,
})
}
}
return result
}, [cacheMap, data, props.hasNextPage])
const [masonryItemsRadio, setMasonryItemsRadio] = useState<Record<string, number>>({})
const maybeLoadMore = useInfiniteLoader(props.endReached, {
isItemLoaded: (index, items) => !!items[index],
minimumBatchSize: 32,
threshold: 3,
})
const scrollElement = useScrollViewElement()
const [intersectionObserver, setIntersectionObserver] = useState<IntersectionObserver>(null!)
useEffect(() => {
if (!scrollElement) return
const observer = new IntersectionObserver(
(entries) => {
const entryIds: string[] = []
entries.forEach((entry) => {
if (entry.intersectionRatio >= 0.5) {
entryIds.push((entry.target as HTMLDivElement).dataset.entryId as string)
}
})
batchMarkRead(entryIds)
},
{
rootMargin: "0px",
threshold: 1,
root: scrollElement,
},
)
setIntersectionObserver(observer)
return () => {
observer.disconnect()
}
}, [scrollElement])
return (
<div ref={containerRef} className="p-4">
<MasonryItemWidthContext.Provider value={currentItemWidth}>
{isInitDim && isInitLayout && (
<PictureMasonryImpl
{...props}
column={currentColumn}
restoreDimensions={restoreDimensions}
/>
)}
</MasonryItemWidthContext.Provider>
{isInitDim && isInitLayout && (
<MasonryItemWidthContext.Provider value={currentItemWidth}>
<MasonryItemsAspectRatioContext.Provider value={masonryItemsRadio}>
<MasonryItemsAspectRatioSetterContext.Provider value={setMasonryItemsRadio}>
<MasonryIntersectionContext.Provider value={intersectionObserver}>
<Masonry
items={items}
columnGutter={gutter}
columnWidth={currentItemWidth}
columnCount={currentColumn}
overscanBy={2}
render={render}
onRender={maybeLoadMore}
itemKey={itemKey}
/>
</MasonryIntersectionContext.Provider>
</MasonryItemsAspectRatioSetterContext.Provider>
</MasonryItemsAspectRatioContext.Provider>
</MasonryItemWidthContext.Provider>
)}
</div>
)
}
const itemKey = (item: { entryId: string }) => item.entryId
const render: React.ComponentType<
RenderComponentProps<{
entryId: string
}>
> = ({ data }) => {
if (data.entryId.startsWith("placeholder")) {
return <LoadingSkeletonItem />
}
return <PictureWaterFallItem entryId={data.entryId} />
}
interface MasonryProps {
data: string[]
endReached: () => Promise<any>
hasNextPage: boolean
}
const PictureMasonryImpl = ({
data,
endReached,
hasNextPage,
restoreDimensions,
column,
}: MasonryProps & {
restoreDimensions: () => Promise<void>
column: number
}) => {
const masonryRef = useRef<MasonryInfiniteGrid>(null)
const $scroll = useScrollViewElement()
const currentItemWidth = useContext(MasonryItemWidthContext)
const itemStyle: CSSProperties = useMemo(() => ({ width: currentItemWidth }), [currentItemWidth])
const [masonryItemsRadio, setMasonryItemsRadio] = useState<Record<string, number>>({})
const scrollMarkUnread = useGeneralSettingKey("scrollMarkUnread")
const inViewMarkRead = useGeneralSettingKey("renderMarkUnread")
const handleScroll = useEventCallback(
debounce(() => {
if (!scrollMarkUnread) return
const $masonryRef = masonryRef.current
if (!$masonryRef) return
const items = $masonryRef.getVisibleItems()
const first = items[0]
if (!first) return
const itemIndex = first.element?.dataset.index
if (itemIndex === undefined) return
const prevIndex = +itemIndex - 1
if (Number.isNaN(prevIndex)) return
if (prevIndex < 0) return
const markReadIdsSlice = data.slice(0, prevIndex + 1)
batchMarkRead(markReadIdsSlice)
}, 100),
)
return (
<MasonryItemsAspectRatioContext.Provider value={masonryItemsRadio}>
<MasonryItemsAspectRatioSetterContext.Provider value={setMasonryItemsRadio}>
<MasonryInfiniteGrid
ref={masonryRef}
onRenderComplete={useEventCallback((e) => {
if (!inViewMarkRead) {
return
}
const entryIds: string[] = []
for (const mount of e.mounted) {
const index = +(mount.element?.dataset.index as string)
if (Number.isNaN(index)) return
const entryId = data[index]
if (!entryId) continue
entryIds.push(entryId)
}
batchMarkRead(entryIds)
})}
placeholder={<LoadingSkeletonItem itemStyle={itemStyle} />}
onRequestAppend={(e) => {
if (!hasNextPage) return
e.wait()
const nextGroupKey = (+e.groupKey! || 0) + 1
e.currentTarget.appendPlaceholders(10, nextGroupKey)
endReached()
.then(restoreDimensions)
.finally(() => {
e.ready()
})
}}
onChangeScroll={handleScroll}
scrollContainer={$scroll}
gap={{ vertical: 24 }}
column={column}
>
{data.map((entryId, index) => (
<ItemWrapper
data-grid-groupkey={(index / 5) | 0}
data-index={index}
itemStyle={itemStyle}
key={entryId}
entryId={entryId}
>
<PictureWaterFallItem entryId={entryId} />
</ItemWrapper>
))}
</MasonryInfiniteGrid>
</MasonryItemsAspectRatioSetterContext.Provider>
</MasonryItemsAspectRatioContext.Provider>
)
}
const LoadingSkeletonItem = ({ itemStyle }: { itemStyle: CSSProperties }) => (
<div style={itemStyle}>
<EntryItemSkeleton count={1} view={FeedViewType.Pictures} />
</div>
)
const ItemWrapperImpl = ({
itemStyle,
style,
children,
entryId,
...rest
}: {
itemStyle: CSSProperties
entryId: string
} & React.HtmlHTMLAttributes<HTMLDivElement> &
PropsWithChildren) => (
<div
style={{
...style,
...itemStyle,
}}
{...rest}
>
{children}
</div>
)
const ItemWrapper = memo(ItemWrapperImpl)
const LoadingSkeletonItem = () => <EntryItemSkeleton count={1} view={FeedViewType.Pictures} />
@@ -165,11 +165,15 @@ export const useEntriesByView = ({
setMergedEntries({ ...mergedEntries, [view]: entryIds })
}, [entryIdsAsDeps])
const sortEntries = isCollection
? sortEntriesIdByStarAt(mergedEntries[view])
: isList
? sortEntriesIdByEntryInsertedAt(mergedEntries[view])
: sortEntriesIdByEntryPublishedAt(mergedEntries[view])
const sortEntries = useMemo(
() =>
isCollection
? sortEntriesIdByStarAt(mergedEntries[view])
: isList
? sortEntriesIdByEntryInsertedAt(mergedEntries[view])
: sortEntriesIdByEntryPublishedAt(mergedEntries[view]),
[isCollection, isList, mergedEntries, view],
)
const groupByDate = useGeneralSettingKey("groupByDate")
const groupedCounts: number[] | undefined = useMemo(() => {
@@ -22,8 +22,9 @@ export const EntryItemWrapper: FC<
view?: number
itemClassName?: string
overlay?: boolean
style?: React.CSSProperties
} & PropsWithChildren
> = ({ entry, view, overlay, children, itemClassName }) => {
> = ({ entry, view, overlay, children, itemClassName, style }) => {
const { items } = useEntryActions({
view,
entry,
@@ -111,7 +112,7 @@ export const EntryItemWrapper: FC<
)
return (
<div data-entry-id={entry.entries.id}>
<div data-entry-id={entry.entries.id} style={style}>
<div
className={cn(
"relative",
@@ -12,62 +12,78 @@ import { getPreferredTitle, useFeedById } from "~/store/feed"
import { StarIcon } from "../star-icon"
import type { UniversalItemProps } from "../types"
export function GridItem({
entryId,
entryPreview,
translation,
children,
wrapperClassName,
}: UniversalItemProps & {
interface GridItemProps extends UniversalItemProps {
children?: React.ReactNode
wrapperClassName?: string
}) {
}
export function GridItem(props: GridItemProps) {
const { entryId, entryPreview, wrapperClassName, children, translation } = props
const entry = useEntry(entryId) || entryPreview
const feeds = useFeedById(entry?.feedId)
const asRead = useAsRead(entry)
if (!entry) return <ReactVirtuosoItemPlaceholder />
return (
<div className={cn("p-1.5", wrapperClassName)}>
{children}
<div className={cn("relative px-2 py-1 text-sm")}>
<div className="flex items-center">
<div
className={cn(
"mr-1 size-1.5 shrink-0 self-center rounded-full bg-accent duration-200",
asRead && "mr-0 w-0",
)}
/>
<div
className={cn(
"relative mb-1 mt-1.5 flex w-full items-center gap-1 truncate font-medium leading-none",
!!entry.collections && "pr-5",
)}
>
<TitleMarquee className="min-w-0 grow">
<EntryTranslation source={entry.entries.title} target={translation?.title} />
</TitleMarquee>
{!!entry.collections && <StarIcon className="static shrink-0 self-end" />}
</div>
</div>
<div className="flex items-center gap-1 truncate text-[13px]">
<FeedIcon
fallback
className="mr-0.5 flex"
feed={feeds!}
entry={entry.entries}
size={18}
/>
<span className="min-w-0 truncate">{getPreferredTitle(feeds)}</span>
<span className="text-zinc-500">·</span>
<span className="text-zinc-500">
{dayjs
.duration(dayjs(entry.entries.publishedAt).diff(dayjs(), "minute"), "minute")
.humanize()}
</span>
<GridItemFooter entryId={entryId} entryPreview={entryPreview} translation={translation} />
</div>
)
}
export const GridItemFooter = ({
entryId,
entryPreview,
translation,
// classNames
titleClassName,
descriptionClassName,
timeClassName,
}: Pick<GridItemProps, "entryId" | "entryPreview" | "translation"> & {
titleClassName?: string
descriptionClassName?: string
timeClassName?: string
}) => {
const entry = useEntry(entryId) || entryPreview
const feeds = useFeedById(entry?.feedId)
const asRead = useAsRead(entry)
if (!entry) return null
return (
<div className={cn("relative px-2 py-1 text-sm")}>
<div className="flex items-center">
<div
className={cn(
"mr-1 size-1.5 shrink-0 self-center rounded-full bg-accent duration-200",
asRead && "mr-0 w-0",
)}
/>
<div
className={cn(
"relative mb-1 mt-1.5 flex w-full items-center gap-1 truncate font-medium leading-none",
!!entry.collections && "pr-5",
titleClassName,
)}
>
<TitleMarquee className="min-w-0 grow">
<EntryTranslation source={entry.entries.title} target={translation?.title} />
</TitleMarquee>
{!!entry.collections && <StarIcon className="static shrink-0 self-end" />}
</div>
</div>
<div className="flex items-center gap-1 truncate text-[13px]">
<FeedIcon fallback className="mr-0.5 flex" feed={feeds!} entry={entry.entries} size={18} />
<span className={cn("min-w-0 truncate", descriptionClassName)}>
{getPreferredTitle(feeds)}
</span>
<span className={cn("text-zinc-500", timeClassName)}>·</span>
<span className={cn("text-zinc-500", timeClassName)}>
{dayjs
.duration(dayjs(entry.entries.publishedAt).diff(dayjs(), "minute"), "minute")
.humanize()}
</span>
</div>
</div>
)
}
+125 -52
View File
@@ -318,9 +318,6 @@ importers:
apps/renderer:
dependencies:
'@egjs/react-infinitegrid':
specifier: 4.12.0
version: 4.12.0
'@egoist/tipc':
specifier: 0.3.2
version: 0.3.2(electron@32.1.2)(react@18.3.1)
@@ -507,6 +504,9 @@ importers:
lodash-es:
specifier: 4.17.21
version: 4.17.21
masonic:
specifier: 4.0.1
version: 4.0.1(react@18.3.1)
nanoid:
specifier: 5.0.7
version: 5.0.7
@@ -1310,12 +1310,6 @@ packages:
resolution: {integrity: sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==}
engines: {node: '>=6.9.0'}
'@cfcs/core@0.0.24':
resolution: {integrity: sha512-feB38qu+eDk0Pggh/yR7gjaNmvUYA2uCxHP3Pz2MLE4LZ/9jPdtu8bzCSI47yTEhWyZCF5Pk698hdz8IN2mTjA==}
'@cfcs/core@0.0.5':
resolution: {integrity: sha512-TZ/RXKV7MUrqFpiX+16uaaptv5jgChWNsuE6w8Rn3eJbO1PFd4Wpn25zeJbii7ch46ck8/ZIIYCcW3pHiYtm4Q==}
'@cfcs/core@0.0.6':
resolution: {integrity: sha512-FxfJMwoLB8MEMConeXUCqtMGqxdtePQxRBOiGip9ULcYYam3WfCgoY6xdnMaSkYvRvmosp5iuG+TiPofm65+Pw==}
@@ -1352,21 +1346,9 @@ packages:
'@egjs/component@3.0.5':
resolution: {integrity: sha512-cLcGizTrrUNA2EYE3MBmEDt2tQv1joVP1Q3oDisZ5nw0MZDx2kcgEXM+/kZpfa/PAkFvYVhRUZwytIQWoN3V/w==}
'@egjs/grid@1.16.0':
resolution: {integrity: sha512-w344hL2HNwmOHu379EG9I8ULkWF4A0cVf1XDn5nGlLXc+8c/rMvQadMBkGPOcdWMEKvFZpEiOPI7tWlXLOCloQ==}
'@egjs/imready@1.4.1':
resolution: {integrity: sha512-JIOBs4lB7FYdsKi5uvz2j3SObX8eShtZjtqlOH41tm185aJOQZwiKBK8+V4MxzG4X6DqVhpdN8UcuVwBbElfsg==}
'@egjs/infinitegrid@4.12.0':
resolution: {integrity: sha512-zoDz+mag7DAropcgmxW0Bx3JQ5ID19lk+AUN9rf9U7diwmO8IBfddX44jOVc9+ya5yZ+Goj95Fkm5S3GqCOrZQ==}
'@egjs/list-differ@1.0.1':
resolution: {integrity: sha512-OTFTDQcWS+1ZREOdCWuk5hCBgYO4OsD30lXcOCyVOAjXMhgL5rBRDnt/otb6Nz8CzU0L/igdcaQBDLWc4t9gvg==}
'@egjs/react-infinitegrid@4.12.0':
resolution: {integrity: sha512-V661KH1nka13wgy73N0IGBazZGe7LiECml1JDqB5DP6axTERUVCs8KRHadHu6oQihDeXwJIHe1YRhhMN9eAnUw==}
'@egoist/tailwindcss-icons@1.8.1':
resolution: {integrity: sha512-hqZeASrhT6BOeaBHYDPB0yBH/zgMKqmm7y2Rsq0c4iRnNVv1RWEiXMBMJB38JsDMTHME450FKa/wvdaIhED+Iw==}
peerDependencies:
@@ -1912,6 +1894,18 @@ packages:
resolution: {integrity: sha512-vH9PiIMMwvhCx31Af3HiGzsVNULDbyVkHXwlemn/B0TFj/00ho3y55efXrUZTfQipxoHC5u4xq6zblww1zm1Ig==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@essentials/memoize-one@1.1.0':
resolution: {integrity: sha512-HMkuIkKNe0EWSUpZhlaq9+5Yp47YhrMhxLMnXTRnEyE5N4xKLspAvMGjUFdi794VnEF1EcOZFS8rdROeujrgag==}
'@essentials/one-key-map@1.2.0':
resolution: {integrity: sha512-C2H7zHVcsoipDv4VKY5uUcv5ilsK+uEgEj+WeOdN5oz/Qj1/OZIzCdle90gDzj0xnGQrmZ9qDujwD7AkBb5k9A==}
'@essentials/raf@1.2.0':
resolution: {integrity: sha512-AWJvpprE2o7ATMb7HBYMVUVmPJBCt2wZp2rY7d+rAcNSMvzLbDepy9KFeqqrPZh+s9aIpbw1LgmuAW7kuRFgrQ==}
'@essentials/request-timeout@1.3.0':
resolution: {integrity: sha512-lKZPhKScNFnR1MBnk4+sxshk46fpvdN+Uh1LlKWFO5g1ocuz4EcknNIL7tm/rsCAs/+xMWiBTwbDUvm+pDNlXw==}
'@floating-ui/core@0.6.2':
resolution: {integrity: sha512-jktYRmZwmau63adUG3GKOAVCofBXkk55S/zQ94XOorAHhwqFIOFAy1rSp2N0Wp6/tGbe9V3u/ExlGZypyY17rg==}
@@ -3065,6 +3059,41 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0
'@react-hook/debounce@3.0.0':
resolution: {integrity: sha512-ir/kPrSfAzY12Gre0sOHkZ2rkEmM4fS5M5zFxCi4BnCeXh2nvx9Ujd+U4IGpKCuPA+EQD0pg1eK2NGLvfWejag==}
peerDependencies:
react: '>=16.8'
'@react-hook/event@1.2.6':
resolution: {integrity: sha512-JUL5IluaOdn5w5Afpe/puPa1rj8X6udMlQ9dt4hvMuKmTrBS1Ya6sb4sVgvfe2eU4yDuOfAhik8xhbcCekbg9Q==}
peerDependencies:
react: '>=16.8'
'@react-hook/latest@1.0.3':
resolution: {integrity: sha512-dy6duzl+JnAZcDbNTfmaP3xHiKtbXYOaz3G51MGVljh548Y8MWzTr+PHLOfvpypEVW9zwvl+VyKjbWKEVbV1Rg==}
peerDependencies:
react: '>=16.8'
'@react-hook/passive-layout-effect@1.2.1':
resolution: {integrity: sha512-IwEphTD75liO8g+6taS+4oqz+nnroocNfWVHWz7j+N+ZO2vYrc6PV1q7GQhuahL0IOR7JccFTsFKQ/mb6iZWAg==}
peerDependencies:
react: '>=16.8'
'@react-hook/throttle@2.2.0':
resolution: {integrity: sha512-LJ5eg+yMV8lXtqK3lR+OtOZ2WH/EfWvuiEEu0M3bhR7dZRfTyEJKxH1oK9uyBxiXPtWXiQggWbZirMCXam51tg==}
peerDependencies:
react: '>=16.8'
'@react-hook/window-scroll@1.3.0':
resolution: {integrity: sha512-LdYnCL22pFI+LTs85Fi2OQHSKWkzIuHFgv8lA+wwuaPxLOEhWR5bzJ21iygUH9X4meeLVRZKEbfpYi3OWWD4GQ==}
peerDependencies:
react: '>=16.8'
'@react-hook/window-size@3.1.1':
resolution: {integrity: sha512-yWnVS5LKnOUIrEsI44oz3bIIUYqflamPL27n+k/PC//PsX/YeWBky09oPeAoc9As6jSH16Wgo8plI+ECZaHk3g==}
peerDependencies:
react: '>=16.8'
'@react-stately/utils@3.10.3':
resolution: {integrity: sha512-moClv7MlVSHpbYtQIkm0Cx+on8Pgt1XqtPx6fy9rQFb2DNc9u1G3AUVnqA17buOkH1vLxAtX4MedlxMWyRCYYA==}
peerDependencies:
@@ -6236,6 +6265,11 @@ packages:
markdown-table@3.0.3:
resolution: {integrity: sha512-Z1NL3Tb1M9wH4XESsCDEksWoKTdlUafKc4pt0GRwjUyXaCFZ+dc3g2erqB6zm3szA2IUSi7VnPI+o/9jnxh9hw==}
masonic@4.0.1:
resolution: {integrity: sha512-gOj1B61NtrELoGigCy+E9SZpWSRGmAONMXrzYboBNbI0uvy7otinzGVGKDXLIZBYdNdcFySyON8qtu6IsFp6Sw==}
peerDependencies:
react: '>=16.8'
matcher@3.0.0:
resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}
engines: {node: '>=10'}
@@ -7315,6 +7349,9 @@ packages:
resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==}
engines: {node: '>=10'}
raf-schd@4.0.3:
resolution: {integrity: sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ==}
random-path@0.1.2:
resolution: {integrity: sha512-4jY0yoEaQ5v9StCl5kZbNIQlg1QheIDBrdkDn53EynpPb9FgO6//p3X/tgMnrC45XN6QZCzU1Xz/+pSSsJBpRw==}
@@ -8163,6 +8200,9 @@ packages:
resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}
hasBin: true
trie-memoize@1.2.0:
resolution: {integrity: sha512-hEDLVEP1FCgaRtt0oZDJdz2lK9uK7WlB7ASswt9U9cqruSNueVigtRGxI97hevKlViqhAcRgNgzuY/m8FCCMcg==}
trigram-utils@2.0.1:
resolution: {integrity: sha512-nfWIXHEaB+HdyslAfMxSqWKDdmqY9I32jS7GnqpdWQnLH89r6A5sdk3fDVYqGAZ0CrT8ovAFSAo6HRiWcWNIGQ==}
@@ -9517,14 +9557,6 @@ snapshots:
'@babel/helper-validator-identifier': 7.24.7
to-fast-properties: 2.0.0
'@cfcs/core@0.0.24':
dependencies:
'@egjs/component': 3.0.5
'@cfcs/core@0.0.5':
dependencies:
'@egjs/component': 3.0.5
'@cfcs/core@0.0.6':
dependencies:
'@egjs/component': 3.0.5
@@ -9561,31 +9593,8 @@ snapshots:
'@egjs/component@3.0.5': {}
'@egjs/grid@1.16.0':
dependencies:
'@egjs/children-differ': 1.0.1
'@egjs/component': 3.0.5
'@egjs/imready': 1.4.1
'@egjs/imready@1.4.1':
dependencies:
'@cfcs/core': 0.0.24
'@egjs/component': 3.0.5
'@egjs/infinitegrid@4.12.0':
dependencies:
'@cfcs/core': 0.0.5
'@egjs/children-differ': 1.0.1
'@egjs/component': 3.0.5
'@egjs/grid': 1.16.0
'@egjs/list-differ': 1.0.1
'@egjs/list-differ@1.0.1': {}
'@egjs/react-infinitegrid@4.12.0':
dependencies:
'@egjs/infinitegrid': 4.12.0
'@egoist/tailwindcss-icons@1.8.1(tailwindcss@3.4.12)':
dependencies:
'@iconify/utils': 2.1.32
@@ -10353,6 +10362,16 @@ snapshots:
dependencies:
levn: 0.4.1
'@essentials/memoize-one@1.1.0': {}
'@essentials/one-key-map@1.2.0': {}
'@essentials/raf@1.2.0': {}
'@essentials/request-timeout@1.3.0':
dependencies:
'@essentials/raf': 1.2.0
'@floating-ui/core@0.6.2': {}
'@floating-ui/core@1.6.7':
@@ -11687,6 +11706,41 @@ snapshots:
clsx: 2.1.1
react: 18.3.1
'@react-hook/debounce@3.0.0(react@18.3.1)':
dependencies:
'@react-hook/latest': 1.0.3(react@18.3.1)
react: 18.3.1
'@react-hook/event@1.2.6(react@18.3.1)':
dependencies:
react: 18.3.1
'@react-hook/latest@1.0.3(react@18.3.1)':
dependencies:
react: 18.3.1
'@react-hook/passive-layout-effect@1.2.1(react@18.3.1)':
dependencies:
react: 18.3.1
'@react-hook/throttle@2.2.0(react@18.3.1)':
dependencies:
'@react-hook/latest': 1.0.3(react@18.3.1)
react: 18.3.1
'@react-hook/window-scroll@1.3.0(react@18.3.1)':
dependencies:
'@react-hook/event': 1.2.6(react@18.3.1)
'@react-hook/throttle': 2.2.0(react@18.3.1)
react: 18.3.1
'@react-hook/window-size@3.1.1(react@18.3.1)':
dependencies:
'@react-hook/debounce': 3.0.0(react@18.3.1)
'@react-hook/event': 1.2.6(react@18.3.1)
'@react-hook/throttle': 2.2.0(react@18.3.1)
react: 18.3.1
'@react-stately/utils@3.10.3(react@18.3.1)':
dependencies:
'@swc/helpers': 0.5.13
@@ -15612,6 +15666,21 @@ snapshots:
markdown-table@3.0.3: {}
masonic@4.0.1(react@18.3.1):
dependencies:
'@essentials/memoize-one': 1.1.0
'@essentials/one-key-map': 1.2.0
'@essentials/request-timeout': 1.3.0
'@react-hook/event': 1.2.6(react@18.3.1)
'@react-hook/latest': 1.0.3(react@18.3.1)
'@react-hook/passive-layout-effect': 1.2.1(react@18.3.1)
'@react-hook/throttle': 2.2.0(react@18.3.1)
'@react-hook/window-scroll': 1.3.0(react@18.3.1)
'@react-hook/window-size': 3.1.1(react@18.3.1)
raf-schd: 4.0.3
react: 18.3.1
trie-memoize: 1.2.0
matcher@3.0.0:
dependencies:
escape-string-regexp: 4.0.0
@@ -16875,6 +16944,8 @@ snapshots:
quick-lru@5.1.1: {}
raf-schd@4.0.3: {}
random-path@0.1.2:
dependencies:
base32-encode: 1.2.0
@@ -17836,6 +17907,8 @@ snapshots:
tree-kill@1.2.2: {}
trie-memoize@1.2.0: {}
trigram-utils@2.0.1:
dependencies:
collapse-white-space: 2.1.0