1
0
Fork 0

Maybe fixed contenteditable

This commit is contained in:
Pabloader 2026-04-13 06:39:17 +00:00
parent f81d8674c0
commit 0413c6a10a
1 changed files with 16 additions and 5 deletions

View File

@ -12,12 +12,19 @@ type Props = Omit<JSX.HTMLAttributes<HTMLDivElement>, 'value' | 'onInput'> & {
onInput?: JSX.EventHandler<JSX.TargetedInputEvent<HTMLDivElement>>;
};
const parseLines = (html: string): string => (
html
const parseLines = (html: string, keepSpan: boolean = false): string => {
html = html
.replace(/\n?<div><br\/?><\/div>/g, '\n\n')
.replace(/\n?<div[^>]*>/, '\n')
.replace(/<[^>]+>/g, '')
);
.replace(/<\/?div[^>]*>/g, '')
.replace(/<br[^>]*>/g, '');
if (!keepSpan) {
html = html.replace(/<[^>]+>/g, '');
}
return html;
};
function getCaretOffset(el: HTMLElement): number {
const sel = window.getSelection();
@ -86,8 +93,12 @@ export const ContentEditable = ({
const el = ref.current;
if (!el) return;
const offset = document.activeElement === el ? getCaretOffset(el) : null;
const newValue = enableHighlight ? highlight(value) : value;
const oldValue = parseLines(el.innerHTML, true);
if (oldValue === newValue) return;
const offset = document.activeElement === el ? getCaretOffset(el) : null;
el.innerHTML = newValue;
(el as any).value = value;
if (offset !== null) setCaretOffset(el, offset);