Skip to content

Commit

Permalink
fix: add delay for preloading that matches tooltips
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan authored and bjoerge committed Dec 20, 2024
1 parent e2fc335 commit 7d9c5e6
Showing 1 changed file with 13 additions and 23 deletions.
36 changes: 13 additions & 23 deletions packages/sanity/src/structure/components/paneItem/PaneItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import {Box, type CardProps, Text} from '@sanity/ui'
import {
type ComponentType,
type MouseEvent,
type ReactNode,
startTransition,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import {
Expand Down Expand Up @@ -139,10 +139,15 @@ export function PaneItem(props: PaneItemProps) {
useEffect(() => setClicked(false), [selected])

// Preloads the edit state on hover, using concurrent rendering with `startTransition` so preloads can be interrupted and not block rendering
const [handleMouseEnter, handleMouseLeave, preload] = usePreloadEditState(
id,
value && isSanityDocument(value) ? schemaType?.name : undefined,
)
const [preloading, setPreload] = useState(false)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const handleMouseEnter = useCallback(() => {
timeoutRef.current = setTimeout(() => startTransition(() => setPreload(true)), 400)
}, [])
const handleMouseLeave = useCallback(() => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
startTransition(() => setPreload(false))
}, [])

return (
<PreviewCard
Expand All @@ -166,28 +171,13 @@ export function PaneItem(props: PaneItemProps) {
tone="inherit"
>
{preview}
{preload}
{preloading && schemaType?.name && value && isSanityDocument(value) && (
<PreloadDocumentPane documentId={id} documentType={schemaType.name} />
)}
</PreviewCard>
)
}

function usePreloadEditState(
documentId: string,
documentType: string | undefined,
): [() => void, () => void, ReactNode] {
const [preloading, setPreload] = useState(false)
const handleMouseEnter = useCallback(() => startTransition(() => setPreload(true)), [])
const handleMouseLeave = useCallback(() => startTransition(() => setPreload(false)), [])

return [
handleMouseEnter,
handleMouseLeave,
preloading && documentType && (
<PreloadDocumentPane documentId={documentId} documentType={documentType} />
),
] as const
}

function PreloadDocumentPane(props: {documentId: string; documentType: string}) {
const {documentId, documentType} = props
// Preload the edit state for the document, and keep it alive until mouse leave
Expand Down

0 comments on commit 7d9c5e6

Please sign in to comment.