Skip to content

Commit

Permalink
feat: Address feedback for CharacterCountPlugin
Browse files Browse the repository at this point in the history
  • Loading branch information
h1un committed Jan 22, 2025
1 parent f715bd3 commit 539bc41
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 17 deletions.
17 changes: 13 additions & 4 deletions packages/lexical-react/src/LexicalCharacterCountPlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,30 @@ function utf8Length(text: string) {

export function CharacterCountPlugin({
charset = 'UTF-16',
render = DefaultRenderer,
}: {
charset?: 'UTF-16' | 'UTF-8';
render?: (characterCount: number) => JSX.Element;
}): JSX.Element {
const [editor] = useLexicalComposerContext();
const characterCount = useCharacterCount(editor, {
strlen: (text: string) => {

const strlen = React.useMemo(() => {
return (text: string) => {
if (charset === 'UTF-8') {
return utf8Length(text);
} else if (charset === 'UTF-16') {
return text.length;
} else {
throw new Error('Unrecognized charset');
}
},
});
};
}, [charset]);

const characterCount = useCharacterCount(editor, {strlen});

return render(characterCount);
}

function DefaultRenderer(characterCount: number) {
return <span className="characters-count">{characterCount}</span>;
}
13 changes: 0 additions & 13 deletions packages/lexical-react/src/shared/useCharacterCount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
*/
import type {LexicalEditor} from 'lexical';

import {OverflowNode} from '@lexical/overflow';
import {useEffect, useState} from 'react';
import invariant from 'shared/invariant';

type OptionalProps = {
strlen?: (input: string) => number;
Expand All @@ -23,17 +21,6 @@ export function useCharacterCount(
const [characterCount, setCharacterCount] = useState(0);

useEffect(() => {
// Check if OverflowNode is registered
if (!editor.hasNodes([OverflowNode])) {
invariant(
false,
'useCharacterCount: OverflowNode not registered on editor',
);
}
}, [editor]);

useEffect(() => {
// Update character count whenever the text content changes
const unregisterTextContentListener = editor.registerTextContentListener(
(currentText: string) => {
setCharacterCount(strlen(currentText));
Expand Down

0 comments on commit 539bc41

Please sign in to comment.