From 6c90c928bbccaaca7c5bb46978d10ea3167e25a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petri=20=C3=84mm=C3=A4l=C3=A4?= Date: Thu, 26 Sep 2024 16:31:51 +0300 Subject: [PATCH] Prevent triggering onContentChange if nothing changed --- packages/core/__tests__/editor/nbsp.test.tsx | 2 +- .../EditableGradingInstruction.tsx | 29 +++++++++++-------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/packages/core/__tests__/editor/nbsp.test.tsx b/packages/core/__tests__/editor/nbsp.test.tsx index 0626b1e52..5b65a6fd8 100644 --- a/packages/core/__tests__/editor/nbsp.test.tsx +++ b/packages/core/__tests__/editor/nbsp.test.tsx @@ -50,7 +50,7 @@ describe('Editor - NBSP', () => { await act(async () => { await userEvent.click(await result.findByText('NBSP')) }) - expect(onContentChangeMock).toHaveBeenCalledTimes(2) // focus causes another call + expect(onContentChangeMock).toHaveBeenCalledTimes(1) expect(onContentChangeMock).toHaveBeenLastCalledWith(expectedOutput, '') }) }) diff --git a/packages/core/src/components/grading-instructions/EditableGradingInstruction.tsx b/packages/core/src/components/grading-instructions/EditableGradingInstruction.tsx index 16e4a7460..cb463554b 100644 --- a/packages/core/src/components/grading-instructions/EditableGradingInstruction.tsx +++ b/packages/core/src/components/grading-instructions/EditableGradingInstruction.tsx @@ -64,18 +64,23 @@ function EditableGradingInstruction({ element }: { element: Element }) { mount={mount} state={state} dispatchTransaction={tr => { - setState(s => s.apply(tr)) - const fragment = DOMSerializer.fromSchema(outputSchema).serializeFragment(tr.doc.content) - const div = document.createElement('div') - div.appendChild(fragment) - const path = element.getAttribute('path') ?? '' - if (onContentChange) { - const nbspFixed = div.innerHTML - .replace(/ /g, ' ') - .replace(/
/g, '
') - .replace(/
/g, '
') - onContentChange(nbspFixed, path) - } + setState(s => { + const newContent = s.apply(tr) + if (tr.docChanged) { + const fragment = DOMSerializer.fromSchema(outputSchema).serializeFragment(tr.doc.content) + const div = document.createElement('div') + div.appendChild(fragment) + const path = element.getAttribute('path') ?? '' + if (onContentChange) { + const nbspFixed = div.innerHTML + .replace(/ /g, ' ') + .replace(/
/g, '
') + .replace(/
/g, '
') + onContentChange(nbspFixed, path) + } + } + return newContent + }) }} >