Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: default to rendering the editor immediately, while staying backward compatible #5161

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

nperez0111
Copy link
Contributor

@nperez0111 nperez0111 commented May 16, 2024

Changes Overview

A third PR for performance of the useEditor hook 😅.

What I've done here is combine a few of the different approaches and added a bit of my own spin to it:

Prior art:

What I've done here is to take a spin on #4579 and base it on a useSyncExternalStore instead (for efficient re-rendering handled by react).
While adding the performance optimization made by #4453 (re-using existing editor instances, and just updating their options if they change).
It is backward-compatible to people who use SSR (printing a warning and telling them they should set the new flag explicitly for forward-compatible but only in dev mode).
It is forward-compatible, where if you don't specify the new flag, people will automatically have the editor on first render.
If the flag is specified, you get better TS types since it is now guaranteed that you get an editor instance.
If you include the select function, you can effectively choose when the component should re-render by returning something different than selected before (inspired by useSelector in react-redux)
If you include the equalityFn function, you can choose how to compare your select function's return value (again inspired by useSelector in react-redux)

Implementation Approach

I've introduced 3 new options to the useEditor hook (and subsequently the editor provider).

  • immediatelyRender which is to control the new vs. the old behavior
  • select which is to give the consumer fine-grained control over rendering by selecting the values they care about in re-rendering the editor
  • equalityFn which defines how to compare the values that the consumer generates with the select function

When not specifying the immediateRender value, if it is detected to be in SSR mode (i.e. no window object) it will be assumed to be false to not break Next.js users (but printing a message that they should be explicit about this), otherwise it will be assumed to be true reducing flicker in existing applications.

Eventually, when we have confidence to do so (i.e. the next major version) we can throw an error instead and have Next.js users (and other ssr frameworks) have to explicitly opt out for their use case (or perhaps a new hook).

Testing Done

I tested in the demos using all possible options and in a next application here is a table for reference:

env immediatelyRender result error message
vite false useEditor returns null on first render, an editor instance afterwards none
vite true useEditor returns an editor instance consistently none
vite missing AKA undefined useEditor returns an editor instance consistently, since not in SSR mode none
next false useEditor returns null on first render (client & server), an editor instance afterwards (client only, since server renders only once) none
next true Error next can't use DOM APIs on the server & will fail to rehydrate An error is thrown stating this is an invalid configuration in dev mode
next missing AKA undefined Warning in the console. useEditor returns null on first render (client & server), an editor instance afterwards (client only, since server renders only once) A warning is printed to the console stating that the use should explicitly set the flag in dev mode

Testing this sort of thing in react can be a little complicated (since you need to control when react re-renders) but if someone knows of a way to test this I'm happy to add tests for it.

Verification Steps

Run the demos and set different values for immediatelyRender and in a Next.js app.

Additional Notes

I'm unsure what version tiptap claims to be compatible with, and I know older versions do not have useSyncExternalStore but I also know that react-redux uses a shim to make it compatible with older versions.

Checklist

  • I have renamed my PR according to the naming conventions. (e.g. feat: Implement new feature or chore(deps): Update dependencies)
  • My changes do not break the library.
  • I have added tests where applicable.
  • I have followed the project guidelines.
  • I have fixed any lint issues.

Related Issues

#5001

Copy link

netlify bot commented May 16, 2024

Deploy Preview for tiptap-embed ready!

Name Link
🔨 Latest commit fc0d1cb
🔍 Latest deploy log https://app.netlify.com/sites/tiptap-embed/deploys/668bcf9dd091f200077f4efb
😎 Deploy Preview https://deploy-preview-5161--tiptap-embed.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

} from 'react'

import { Editor } from './Editor.js'

const isDev = process.env.NODE_ENV !== 'production'
const isSSR = typeof window === 'undefined'
const isNext = isSSR || Boolean(typeof window !== 'undefined' && (window as any).next)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was the closest thing I could find to detecting that you are running Next.js (SSR or CSR)

Copy link

@alii alii left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, and would definitely be useful in our usage of tiptap.

However, just out of curiosity, what might be a use-case of the selector? Was it added in this PR as a requirement you had, or just as a potentially-nice-to-have?

@nperez0111
Copy link
Contributor Author

LGTM, and would definitely be useful in our usage of tiptap.

However, just out of curiosity, what might be a use-case of the selector? Was it added in this PR as a requirement you had, or just as a potentially-nice-to-have?

The use case of a selector would be two-fold. For preventing re-renders by allowing you to only re-render when that selected state changes (e.g. not on every transaction like it is by default), and to give a more convenient API for tiptap state.

I haven't updated the PR yet, but I envision an additional API like:

function MyComponent() {
  const { editor, state } = useEditorWithState({
    selector: (currentEditor) => {
      return { isBold: !currentEditor.can().setBold() };
    },
	equalityFn: deepEqual
  });

  return (
    <>
      <Toolbar>
        <button>{state.isBold ? "Bold" : "Not Bold"}</button>
      </Toolbar>
      <Editor editor={editor} />
    </>
  );
}

With the code above, the component only has to re-render when the editor switches from being able to bold the current selection and not being able to. Which drastically will reduce re-renders.
It also gives you a standard way to select state from the editor instead of relying on the instance at runtime which has been confusing to some users.

@alii
Copy link

alii commented Jun 25, 2024

Understood, that is super! I think it would make sense to have a selector API on the useCurrentEditor hook as well, or another hook (perhaps "useEditorState" that would accept the editor and allow you to select state from it. e.g.

function MyBubbleMenu() {
  const isBold = useCurrentEditor({
    selector: editor => !editor.can().setBold(),
  });
}

<EditorProvider>
  <MyBubbleMenu />
</EditorProvider>

Or, with a "useEditorState" hook

function MyBubbleMenu({editor}: {editor: Editor}) {
  const isBold = useEditorState(editor, {
    selector: editor => !editor.can().setBold(),
  });
}

function App() {
  const editor = useEditor();
  
  return (
    <>
      <MyBubbleMenu editor={editor} />
      <EditorContent editor={editor} />
    </>
  );
}

@nperez0111
Copy link
Contributor Author

Understood, that is super! I think it would make sense to have a selector API on the useCurrentEditor hook as well, or another hook (perhaps "useEditorState" that would accept the editor and allow you to select state from it. e.g.

function MyBubbleMenu() {
  const isBold = useCurrentEditor({
    selector: editor => !editor.can().setBold(),
  });
}

<EditorProvider>
  <MyBubbleMenu />
</EditorProvider>

Or, with a "useEditorState" hook

function MyBubbleMenu({editor}: {editor: Editor}) {
  const isBold = useEditorState(editor, {
    selector: editor => !editor.can().setBold(),
  });
}

function App() {
  const editor = useEditor();
  
  return (
    <>
      <MyBubbleMenu editor={editor} />
      <EditorContent editor={editor} />
    </>
  );
}

Yep, will be adding something like that to it. Just haven't gotten around to updating this PR yet

@nperez0111 nperez0111 force-pushed the fix/react-rerenders branch 4 times, most recently from a26ed74 to b65ac57 Compare June 26, 2024 20:50
Copy link

changeset-bot bot commented Jul 6, 2024

⚠️ No Changeset found

Latest commit: fc0d1cb

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@nperez0111 nperez0111 changed the base branch from main to develop July 6, 2024 20:27
@nperez0111
Copy link
Contributor Author

This example proves the difference between the default behavior & the new behavior enabled by the new shouldRerenderOnTransaction field:
https://deploy-preview-5161--tiptap-embed.netlify.app/preview/Examples/Performance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Triage open
Development

Successfully merging this pull request may close these issues.

None yet

2 participants