mirror of
https://github.com/amitwh/markdown-converter.git
synced 2026-08-02 18:10:18 +05:30
feat(renderer): useScrollSync hook (60fps throttling, ratio calc)
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import { useCallback, useRef } from 'react';
|
||||
|
||||
interface Options {
|
||||
onEditorScroll?: (ratio: number) => void;
|
||||
onPreviewScroll?: (ratio: number) => void;
|
||||
}
|
||||
|
||||
export function useScrollSync(opts: Options) {
|
||||
const FRAME_MS = 1000 / 60;
|
||||
const lastTick = useRef(-FRAME_MS);
|
||||
|
||||
const handleEditorScroll = useCallback((evt: React.UIEvent<HTMLElement>) => {
|
||||
const target = evt.currentTarget;
|
||||
const ratio = target.scrollTop / Math.max(target.scrollHeight - target.clientHeight, 1);
|
||||
const now = performance.now();
|
||||
if (now - lastTick.current < FRAME_MS) return;
|
||||
lastTick.current = now;
|
||||
opts.onEditorScroll?.(ratio);
|
||||
}, [opts]);
|
||||
|
||||
const handlePreviewScroll = useCallback((evt: React.UIEvent<HTMLElement>) => {
|
||||
const target = evt.currentTarget;
|
||||
const ratio = target.scrollTop / Math.max(target.scrollHeight - target.clientHeight, 1);
|
||||
opts.onPreviewScroll?.(ratio);
|
||||
}, [opts]);
|
||||
|
||||
return { handleEditorScroll, handlePreviewScroll };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useScrollSync } from '@/hooks/use-scroll-sync';
|
||||
|
||||
describe('useScrollSync', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
// Mock performance.now() to return 0 and not auto-advance
|
||||
let time = 0;
|
||||
vi.spyOn(performance, 'now').mockImplementation(() => time);
|
||||
});
|
||||
|
||||
it('throttles editor scroll events to 60fps', () => {
|
||||
const onScroll = vi.fn();
|
||||
const { result } = renderHook(() => useScrollSync({ onEditorScroll: onScroll }));
|
||||
const mockEvt = { currentTarget: { scrollTop: 100, scrollHeight: 1000, clientHeight: 200 } } as any;
|
||||
// All calls within the same act() - performance.now() stays at 0
|
||||
// First call passes, subsequent calls within FRAME_MS are throttled
|
||||
act(() => {
|
||||
result.current.handleEditorScroll(mockEvt);
|
||||
result.current.handleEditorScroll(mockEvt);
|
||||
result.current.handleEditorScroll(mockEvt);
|
||||
});
|
||||
expect(onScroll).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user