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

Merged
merged 5 commits into from
Jul 10, 2024

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 9c7363a
🔍 Latest deploy log https://app.netlify.com/sites/tiptap-embed/deploys/668e567d85ea7d000955dd31
😎 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
Contributor

@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
Contributor

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

🦋 Changeset detected

Latest commit: 9c7363a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 54 packages
Name Type
@tiptap/react Patch
@tiptap/core Patch
@tiptap/extension-blockquote Patch
@tiptap/extension-bold Patch
@tiptap/extension-bubble-menu Patch
@tiptap/extension-bullet-list Patch
@tiptap/extension-character-count Patch
@tiptap/extension-code-block-lowlight Patch
@tiptap/extension-code-block Patch
@tiptap/extension-code Patch
@tiptap/extension-collaboration-cursor Patch
@tiptap/extension-collaboration Patch
@tiptap/extension-color Patch
@tiptap/extension-document Patch
@tiptap/extension-dropcursor Patch
@tiptap/extension-floating-menu Patch
@tiptap/extension-focus Patch
@tiptap/extension-font-family Patch
@tiptap/extension-gapcursor Patch
@tiptap/extension-hard-break Patch
@tiptap/extension-heading Patch
@tiptap/extension-highlight Patch
@tiptap/extension-history Patch
@tiptap/extension-horizontal-rule Patch
@tiptap/extension-image Patch
@tiptap/extension-italic Patch
@tiptap/extension-link Patch
@tiptap/extension-list-item Patch
@tiptap/extension-list-keymap Patch
@tiptap/extension-mention Patch
@tiptap/extension-ordered-list Patch
@tiptap/extension-paragraph Patch
@tiptap/extension-placeholder Patch
@tiptap/extension-strike Patch
@tiptap/extension-subscript Patch
@tiptap/extension-superscript Patch
@tiptap/extension-table-cell Patch
@tiptap/extension-table-header Patch
@tiptap/extension-table-row Patch
@tiptap/extension-table Patch
@tiptap/extension-task-item Patch
@tiptap/extension-task-list Patch
@tiptap/extension-text-align Patch
@tiptap/extension-text-style Patch
@tiptap/extension-text Patch
@tiptap/extension-typography Patch
@tiptap/extension-underline Patch
@tiptap/extension-youtube Patch
@tiptap/html Patch
@tiptap/pm Patch
@tiptap/starter-kit Patch
@tiptap/suggestion Patch
@tiptap/vue-2 Patch
@tiptap/vue-3 Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another 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

@nperez0111 nperez0111 merged commit df5609c into develop Jul 10, 2024
14 checks passed
@nperez0111 nperez0111 deleted the fix/react-rerenders branch July 10, 2024 09:43
@alii
Copy link
Contributor

alii commented Jul 10, 2024

🎉Amazing work, thank you!!!🎉

@alii
Copy link
Contributor

alii commented Jul 10, 2024

Weirdly it seems that the overloads for useEditorState break in the published built declarations.

It seems to be fixed if the overload with Editor | null goes beneath, rather than above. e.g.:

CleanShot 2024-07-10 at 12 15 24@2x
(in the published version right now, the | null is above and so I assume typescript matches that first)

Otherwise the result from useEditorState is typed as T | null, even if the editor is always provided (which in my case, it is).

@nperez0111
Copy link
Contributor Author

Hm, I ran into this myself. I think you might need useEditor({...options} as const) because typescript by default interprets true to be a boolean. But I'm uncertain on that.

@alii

Comment on lines +97 to +102
export function useEditorState<TSelectorResult>(
options: UseEditorStateOptions<TSelectorResult, Editor | null>
): TSelectorResult | null;
export function useEditorState<TSelectorResult>(
options: UseEditorStateOptions<TSelectorResult, Editor>
): TSelectorResult;
Copy link
Contributor

Choose a reason for hiding this comment

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

Do you mean useEditor or useEditorState?

Because if I go into node_modules and just flip the order of these overloads (in the .d.ts file of useEditorState) it seems to be working all fine. I think this is because TypeScript will resolve the Editor overload first, and if it's null it will resolve the Editor | null second. But since Editor DOES extend Editor | null, it resolved the nullable one first. Sorry that's a bit of a mouthful to read😆

I'm wondering if just flipping the order of the overloads in the source code will fix it? Would it be possible to make another changeset & pre-release to test?

Happy to make a PR as well if I haven't explained it very well 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh I was talking useEditor, Hm interesting. I would happily take a PR for it!

Copy link
Contributor

Choose a reason for hiding this comment

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

Gotcha. will make a PR

Fwiw, typescript IS able to infer the boolean to true exactly, but only because it was explicitly written out in the overloads. Here's an example of that behaviour

@Nantris
Copy link
Contributor

Nantris commented Jul 11, 2024

Thank you for the tremendous work!

I wonder if anyone can provide insight into possible circumstances where immediatelyRender is not compatible out of the box? Unfortunately it causes nothing to render for us. No errors either. It's too late for me to start tonight, but I'm not sure where I'd even begin to look.

@nperez0111
Copy link
Contributor Author

Thank you for the tremendous work!

I wonder if anyone can provide insight into possible circumstances where immediatelyRender is not compatible out of the box? Unfortunately it causes nothing to render for us. No errors either. It's too late for me to start tonight, but I'm not sure where I'd even begin to look.

@Nantris Hm,

It causes nothing to render? That is strange, I mean I thought I tried all of the cases. If doing SSR it must be false, if doing CSR it can be true (for better typing). undefined will try to guess if you are doing CSR or SSR, better to be explicitly, this behavior was for backwards-compatibility.

Does the editor instance not get returned back to you? Are you on an older React version maybe?

@andrictham
Copy link

I’m using Next.js. Which version will this be rolling out in, and will there docs for this change?

@nperez0111
Copy link
Contributor Author

Currently released in the latest beta version (which you can try this out with)

Definitely will be writing docs for it, just isn't on the main release yet so haven't gotten around to it.

We've been working on our release structure (moving to changesets and CI pipelines) so we just haven't been confident to do a stable release just yet. Would very interested here how it is working for you though.

For Next.js would amount to immediatelyRender: false and separately if you want more control over your re-rendering behavior:
shouldRerenderOnTransaction: false and use the new useEditorState hook instead.

@alii
Copy link
Contributor

alii commented Jul 11, 2024

Chiming in as I'm also using Next.js, I've split the entire editor into a separate component, and then imported it dynamically, like this:

// components/editor.tsx
import {useEditor} from '@tiptap/react';

export function Editor() {
  const editor = useEditor({immediatelyRender: true, shouldRerenderOnTransaction: false});

  // ...
}
// pages/editor.tsx
import dynamic from 'next/dynamic';

const Editor = dynamic(
  () => import('../components/editor.tsx').then(mod => mod.Editor),
  {ssr: false},
);

<Editor />

I've had this setup from before the changes in this PR, however there were no issues once I upgraded.

Worth noting that this, of course, changes when/where the code for the Editor is bundled and this may not be your desired behaviour. Though one advantage is that the editor only mounts in the browser anyway, and now you don't ever have to deal with null checks as the editor will always exist by the time you're rendering.

@Nantris
Copy link
Contributor

Nantris commented Jul 11, 2024

Thanks for your reply @nperez0111!

After having some time to look into this, I think the issue must be internal to TipTap somehow.

It's quite curious. I see you tested in Vite and that's where I do my development. There's no SSR involed. The useEditor hook does return the editor, but it seems that the DOM element is never attached to the page.

When I enter editor.view.dom in console and press enter it returns this DOM node:

<div contenteditable="true" translate=​"no" class=​"tiptap ProseMirror" tabindex=​"0">​…​</div>

But curiously, when I right-click it and "Reveal in Elements Panel" it tells me, Node cannot be found in the current page. - and indeed it is not part of the page's DOM. The detached DOM node does contains the expected content though.

React is on 18.3.1 and I ran yarn upgrade after installing the latest version just to be sure nothing was inadvertently out of date.

I wonder if you have any theory what the issue could be? Thank you again for the stellar work!

@nperez0111
Copy link
Contributor Author

Hm, nothing off the top of my head should have been different, could you double check with the previous beta (maybe something changed in another beta?) So maybe check @tiptap/react@2.5.0-pre.13?

Other than that, I've heard from others that it is working properly so I am unsure why it'd be different, could you share your code? If not maybe a reproducible example? Maybe just delete features until you have it working?

@szymonchudy
Copy link

szymonchudy commented Jul 12, 2024

Thank you for the tremendous work!
I wonder if anyone can provide insight into possible circumstances where immediatelyRender is not compatible out of the box? Unfortunately it causes nothing to render for us. No errors either. It's too late for me to start tonight, but I'm not sure where I'd even begin to look.

@Nantris Hm,

It causes nothing to render? That is strange, I mean I thought I tried all of the cases. If doing SSR it must be false, if doing CSR it can be true (for better typing). undefined will try to guess if you are doing CSR or SSR, better to be explicitly, this behavior was for backwards-compatibility.

Does the editor instance not get returned back to you? Are you on an older React version maybe?

Hey! First, a big thank you for taking the time to prepare this PR, @nperez0111!

We observed similar behavior to that described by @Nantris while working in Strict Mode. Essentially, the editor displays an empty div. When Strict Mode is turned off, everything functions as expected.

@nperez0111
Copy link
Contributor Author

Thank you for the tremendous work!
I wonder if anyone can provide insight into possible circumstances where immediatelyRender is not compatible out of the box? Unfortunately it causes nothing to render for us. No errors either. It's too late for me to start tonight, but I'm not sure where I'd even begin to look.

@Nantris Hm,
It causes nothing to render? That is strange, I mean I thought I tried all of the cases. If doing SSR it must be false, if doing CSR it can be true (for better typing). undefined will try to guess if you are doing CSR or SSR, better to be explicitly, this behavior was for backwards-compatibility.
Does the editor instance not get returned back to you? Are you on an older React version maybe?

Hey! First, a big thank you for taking the time to prepare this PR, @nperez0111!

We observed similar behavior to that described by @Nantris while working in Strict Mode. Essentially, the editor displays an empty div. When Strict Mode is turned off, everything functions as expected.

Great hint, I put it in StrictMode and it is not working for me either. I will look into what is happening

@Nantris
Copy link
Contributor

Nantris commented Jul 12, 2024

I can confirm our issue is Strict Mode related as well. Great find!

nperez0111 added a commit that referenced this pull request Jul 13, 2024
…ounted

This forces the editor to re-use the editor instance that existed prior to an unmount and remount of the same component.
This fixes a bug in `React.StrictMode` introduced with the latest performance updates by PR #5161
@nperez0111
Copy link
Contributor Author

Great, I think I have a fix with: #5338

nperez0111 added a commit that referenced this pull request Jul 13, 2024
…5338)

This forces the editor to re-use the editor instance that existed prior to an unmount and remount of the same component.
This fixes a bug in `React.StrictMode` introduced with the latest performance updates by PR #5161
@nperez0111 nperez0111 mentioned this pull request Jul 13, 2024
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

6 participants