Skip to content

Instantly share code, notes, and snippets.

@heyitsaamir
Created May 23, 2020 18:11
Show Gist options
  • Save heyitsaamir/6089165fe6789eee170b46809cb61fc6 to your computer and use it in GitHub Desktop.
Save heyitsaamir/6089165fe6789eee170b46809cb61fc6 to your computer and use it in GitHub Desktop.
Simple HOC to maintain current selection of the editor (slatejs)
import React, { useContext, useRef } from 'react';
import { isEqual } from 'lodash';
import { Range } from 'slate';
import { ReactEditor, useSlate } from 'slate-react';
export const CurrentSelectionContext = React.createContext<{
current: Range | null;
}>({ current: null });
export function withCurrentSelection<OriginalProps>(WrappedComponent: React.ComponentType<OriginalProps>) {
return React.forwardRef((props: OriginalProps, ref) => {
const editor = useSlate();
const currentSelection = useRef<Range | null>(editor.selection);
if (ReactEditor.isFocused(editor)) {
if (!isEqual(currentSelection.current, editor.selection)) {
currentSelection.current = editor.selection;
}
}
return (
<CurrentSelectionContext.Provider
value={{
current: currentSelection.current,
}}
>
<WrappedComponent {...props} ref={ref} />
</CurrentSelectionContext.Provider>
);
});
}
export const useCurrentSelection = () => useContext(CurrentSelectionContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment