@terrible-lexical/react
Version:
This package provides Lexical components and hooks for React applications.
50 lines (42 loc) • 1.46 kB
text/typescript
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type {LexicalEditor} from 'terrible-lexical';
import {$canShowPlaceholderCurry} from '@terrible-lexical/text/src';
import {mergeRegister} from '@terrible-lexical/utils/src';
import {useState} from 'react';
import useLayoutEffect from '@terrible-lexical/shared/src/useLayoutEffect';
function canShowPlaceholderFromCurrentEditorState(
editor: LexicalEditor,
): boolean {
const currentCanShowPlaceholder = editor
.getEditorState()
.read($canShowPlaceholderCurry(editor.isComposing()));
return currentCanShowPlaceholder;
}
export function useCanShowPlaceholder(editor: LexicalEditor): boolean {
const [canShowPlaceholder, setCanShowPlaceholder] = useState(() =>
canShowPlaceholderFromCurrentEditorState(editor),
);
useLayoutEffect(() => {
function resetCanShowPlaceholder() {
const currentCanShowPlaceholder =
canShowPlaceholderFromCurrentEditorState(editor);
setCanShowPlaceholder(currentCanShowPlaceholder);
}
resetCanShowPlaceholder();
return mergeRegister(
editor.registerUpdateListener(() => {
resetCanShowPlaceholder();
}),
editor.registerEditableListener(() => {
resetCanShowPlaceholder();
}),
);
}, [editor]);
return canShowPlaceholder;
}