({
file,
theme,
shouldLoadHighlight,
}: {
file: DiffFile | undefined;
theme: AppTheme;
shouldLoadHighlight?: boolean;
})
| 163 | |
| 164 | /** Resolve highlighted diff content with shared caching and background prefetch support. */ |
| 165 | export function useHighlightedDiff({ |
| 166 | file, |
| 167 | theme, |
| 168 | shouldLoadHighlight, |
| 169 | }: { |
| 170 | file: DiffFile | undefined; |
| 171 | theme: AppTheme; |
| 172 | shouldLoadHighlight?: boolean; |
| 173 | }) { |
| 174 | const [highlighted, setHighlighted] = useState<HighlightedDiffCode | null>(null); |
| 175 | const [highlightedCacheKey, setHighlightedCacheKey] = useState<string | null>(null); |
| 176 | const appearanceCacheKey = file ? buildCacheKey(theme, file) : null; |
| 177 | |
| 178 | // Use a layout effect so a newly available cached result can replace the plain-text fallback |
| 179 | // before the next diff paint whenever possible. That reduces flash/stutter as files enter view. |
| 180 | useLayoutEffect(() => { |
| 181 | if (!file || !appearanceCacheKey) { |
| 182 | setHighlighted(null); |
| 183 | setHighlightedCacheKey(null); |
| 184 | return; |
| 185 | } |
| 186 | |
| 187 | if (highlightedCacheKey === appearanceCacheKey) { |
| 188 | return; |
| 189 | } |
| 190 | |
| 191 | const cached = SHARED_HIGHLIGHTED_DIFF_CACHE.get(appearanceCacheKey); |
| 192 | if (cached) { |
| 193 | setHighlighted(cached); |
| 194 | setHighlightedCacheKey(appearanceCacheKey); |
| 195 | return; |
| 196 | } |
| 197 | |
| 198 | if (!shouldLoadHighlight) { |
| 199 | return; |
| 200 | } |
| 201 | |
| 202 | let cancelled = false; |
| 203 | setHighlighted(null); |
| 204 | |
| 205 | ensureHighlightedDiffLoaded(file, theme, appearanceCacheKey).then((nextHighlighted) => { |
| 206 | if (cancelled) { |
| 207 | return; |
| 208 | } |
| 209 | |
| 210 | setHighlighted(nextHighlighted); |
| 211 | setHighlightedCacheKey(appearanceCacheKey); |
| 212 | }); |
| 213 | |
| 214 | return () => { |
| 215 | cancelled = true; |
| 216 | }; |
| 217 | }, [appearanceCacheKey, file, highlightedCacheKey, shouldLoadHighlight]); |
| 218 | |
| 219 | // Prefer cached highlights during render so revisiting a file can paint immediately. |
| 220 | return resolveHighlightedSnapshot({ |
| 221 | appearanceCacheKey, |
| 222 | highlighted, |
no test coverage detected