Last active
June 2, 2022 09:15
-
-
Save vbfox/577c581a986d0d6ffa7cbfc66c129501 to your computer and use it in GitHub Desktop.
split-grid as react hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useEffect, useCallback } from 'react'; | |
import Split, { SplitOptions, SplitInstance } from 'split-grid'; | |
export function useSplitGrid(options: SplitOptions): SplitInstance | undefined { | |
const splitInstance = useRef<SplitInstance>(); | |
useEffect(() => { | |
const split = Split(options); | |
splitInstance.current = split; | |
return () => split.destroy(); | |
}, [options]); | |
return splitInstance.current; | |
} | |
function makeUseSplitGridGutter( | |
addFn: (splitInstance: SplitInstance, element: HTMLElement, track: number) => void, | |
removeFn: (splitInstance: SplitInstance, track: number) => void, | |
) { | |
return (splitInstance: SplitInstance | undefined, track: number): React.Ref<any> => { | |
const gutterRef = useRef<HTMLElement>(); | |
const addOrReplace = useCallback(() => { | |
if (gutterRef.current && splitInstance) { | |
addFn(splitInstance, gutterRef.current, track); | |
} | |
}, [splitInstance, track]); | |
const remove = useCallback(() => { | |
if (splitInstance) { | |
removeFn(splitInstance, track); | |
} | |
}, [splitInstance, track]); | |
const onRefChanges = useCallback( | |
(value: HTMLElement | null) => { | |
const hadValue = !!gutterRef.current; | |
gutterRef.current = value || undefined; | |
if (value) { | |
addOrReplace(); | |
} else if (hadValue) { | |
remove(); | |
} | |
}, | |
[addOrReplace, remove], | |
); | |
useEffect(() => { | |
if (!splitInstance) { | |
return undefined; | |
} | |
addOrReplace(); | |
return () => remove(); | |
}, [addOrReplace, remove, splitInstance]); | |
return onRefChanges; | |
}; | |
} | |
export const useSplitGridGutterRow = makeUseSplitGridGutter( | |
(i, e, t) => i.addRowGutter(e, t), | |
(i, t) => i.removeRowGutter(t), | |
); | |
export const useSplitGridGutterColumn = makeUseSplitGridGutter( | |
(i, e, t) => i.addColumnGutter(e, t), | |
(i, t) => i.removeColumnGutter(t), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment