BiblioNexus-Foundation / scripture-editors

Monorepo for various Scripture editors
MIT License
1 stars 1 forks source link

`onChange` fired when loading new text (`editorRef.current.setUsj(...)`) #135

Open tjcouch-sil opened 1 month ago

tjcouch-sil commented 1 month ago

Describe the bug The onChange callback editor prop is called when loading new text when someone runs the editor imperative handle's setUsj function.

onChange on an input element triggers when the input detects that the user wants to change the value. It does not trigger on programmatic updates from above. This is the same for controlled and uncontrolled. Demo at https://stackblitz.com/edit/vitejs-vite-va6b7p?file=src%2FApp.tsx

I suggest this is unexpected functionality to trigger onChange for programmatic updates because of the way it works on the input element (and other built-in elements).

To Reproduce Steps to reproduce the behavior:

  1. (Optional) In the current revision of the platform editor, you need to comment out the line in handleChange that runs setUsj to make this easier to see clearly (having setUsj in there makes what I would expect would be an infinite loop. But it only loops three times for some reason. Anyway removing this makes it just fire once as to be expected).
const handleChange = useCallback((usj: Usj, comments: Comments | undefined) => {
  console.log({ usj, comments });
  // marginalRef.current?.setUsj(usj); <-- COMMENT OUT TO SEE THIS PROBLEM MORE CLEARLY
}, []);
  1. Reload the editor preview page (just the preview page thing; not the whole CodeSandbox page)
  2. After everything loads, you will see {usj: Object, comments: Array(3)} in the console log because handleChange was fired when the delayed setUsj ran

Note: I also seem to see this two times on load and every time you make a change when you set up #134 to happen. I wonder if onChange is also being run every time the editor rerenders in general. Or maybe these are the same thing. Just wanted to mention it in hopes that it is the same issue.

Expected Behavior onChange only runs when something causes a change within the editor, not when the editor's state is programmatically set from the outside.

Tested on platform editor.