-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(Editor): support external editor instances #6678
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
Open
sandros94
wants to merge
4
commits into
v4
Choose a base branch
from
feat/custom-editor-instance
base: v4
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ab2a472
feat(Editor): support external editor instances
sandros94 27618a7
docs(Editor): clarify v-model management for external editor instances
sandros94 2067be3
feat(Editor): add `prose` prop and stop mutating external editor instβ¦
sandros94 d09668d
refactor(Editor): scope prose classes to external editors only
sandros94 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| <script lang="ts"> | ||
| import type { VNode } from 'vue' | ||
| import type { ComputedRef, MaybeRef, VNode } from 'vue' | ||
| import type { AppConfig } from '@nuxt/schema' | ||
| import type { Editor as TiptapEditor, EditorOptions, Content } from '@tiptap/vue-3' | ||
| import type { StarterKitOptions } from '@tiptap/starter-kit' | ||
|
|
@@ -21,6 +21,16 @@ export interface EditorProps<T extends Content = Content, H extends EditorCustom | |
| * @defaultValue 'div' | ||
| */ | ||
| as?: any | ||
| /** | ||
| * An external TipTap editor instance to use instead of the built-in one. | ||
| * The component renders and styles it and wires it to the child components (toolbar, menus, β¦), | ||
| * while the instance keeps ownership of its content, schema and lifecycle: `v-model` and the | ||
| * TipTap options props (`starterKit`, `extensions`, `editorProps`, β¦) are ignored. | ||
| * Bind the prop from the first render (even while still `undefined`, e.g. an editor created | ||
| * asynchronously) β it is detected by presence, not value. | ||
| * @see https://tiptap.dev/docs/editor/getting-started/install/vue3 | ||
| */ | ||
| editor?: MaybeRef<TiptapEditor | undefined> | ComputedRef<TiptapEditor | undefined> | ||
| modelValue?: T | ||
| /** | ||
| * The content type the content is provided as. | ||
|
|
@@ -66,6 +76,14 @@ export interface EditorProps<T extends Content = Content, H extends EditorCustom | |
| * @see https://tiptap.dev/docs/editor/extensions/nodes/mention | ||
| */ | ||
| mention?: boolean | Partial<Omit<MentionOptions, 'suggestion' | 'suggestions'>> | ||
| /** | ||
| * Apply the theme's typography to the editor content wrapper, so external editors are styled too. | ||
| * Uses `:where()` selectors, so your own (or an extension's) styling always takes precedence. | ||
| * Set to `false` when the editor brings its own content styling. | ||
| * The built-in editor is always styled through the `base` slot (override `ui.base` to change it). | ||
| * @defaultValue true | ||
| */ | ||
| prose?: boolean | ||
| /** | ||
| * Custom item handlers to override or extend the default handlers. | ||
| * These handlers are provided to all child components (toolbar, suggestion menu, etc.). | ||
|
|
@@ -80,12 +98,17 @@ export interface EditorEmits<T extends Content = Content> { | |
| } | ||
|
|
||
| export interface EditorSlots<H extends EditorCustomHandlers = EditorCustomHandlers> { | ||
| default?(props: { editor: TiptapEditor, handlers: EditorHandlers<H> }): VNode[] | ||
| default?(props: { editor: TiptapEditor, handlers: EditorHandlers<H>, ui: Editor['ui'] }): VNode[] | ||
| /** | ||
| * Rendered while the editor is not yet available: during SSR and before mount, | ||
| * or while an asynchronously created external `editor` is still `undefined`. | ||
| */ | ||
| fallback?(props: Record<string, never>): VNode[] | ||
| } | ||
| </script> | ||
|
|
||
| <script setup lang="ts" generic="T extends Content, H extends EditorCustomHandlers"> | ||
| import { computed, provide, useAttrs, watch } from 'vue' | ||
| import { computed, provide, unref, useAttrs, watch } from 'vue' | ||
| import { defu } from 'defu' | ||
| import { Primitive } from 'reka-ui' | ||
| import { mergeAttributes } from '@tiptap/core' | ||
|
|
@@ -99,7 +122,7 @@ import StarterKit from '@tiptap/starter-kit' | |
| import { useEditor, EditorContent } from '@tiptap/vue-3' | ||
| import { reactiveOmit } from '@vueuse/core' | ||
| import { useAppConfig } from '#imports' | ||
| import { useComponentProps } from '../composables/useComponentProps' | ||
| import { isPropBound, useComponentProps } from '../composables/useComponentProps' | ||
| import { useForwardProps } from '../composables/useForwardProps' | ||
| import { createHandlers } from '../utils/editor' | ||
| import { tv } from '../utils/tv' | ||
|
|
@@ -120,12 +143,19 @@ const attrs = useAttrs() | |
|
|
||
| const appConfig = useAppConfig() as Editor['AppConfig'] | ||
|
|
||
| // External mode is detected from the presence of the `editor` prop, not its value, | ||
| // so an editor created asynchronously (`undefined` on first render) is still recognized. | ||
| const isExternalEditor = isPropBound('editor') | ||
|
|
||
| // eslint-disable-next-line vue/no-dupe-keys | ||
| const ui = computed(() => tv({ extend: theme, ...(appConfig.ui?.editor || {}) })({ | ||
| // Built-in editors are styled via `editorProps` on the editable element; only external editors | ||
| // need the content-wrapper copy, so the variant is disabled otherwise. | ||
| prose: isExternalEditor ? props.prose : false, | ||
| placeholderMode: typeof props.placeholder === 'object' ? props.placeholder.mode : undefined | ||
| })) | ||
|
|
||
| const rootProps = useForwardProps(reactiveOmit(props, 'starterKit', 'extensions', 'editorProps', 'contentType', 'class', 'placeholder', 'markdown', 'image', 'mention', 'handlers')) | ||
| const rootProps = useForwardProps(reactiveOmit(props, 'editor', 'starterKit', 'extensions', 'editorProps', 'contentType', 'class', 'placeholder', 'markdown', 'image', 'mention', 'prose', 'handlers')) | ||
|
|
||
| const editorProps = computed(() => defu(props.editorProps, { | ||
| attributes: { | ||
|
|
@@ -206,68 +236,98 @@ const extensions = computed(() => [ | |
| ...(props.extensions || []) | ||
| ].filter(extension => !!extension)) | ||
|
|
||
| const editor = useEditor({ | ||
| ...rootProps.value, | ||
| content: props.modelValue, | ||
| contentType: contentType.value, | ||
| extensions: extensions.value, | ||
| editorProps: editorProps.value, | ||
| onCreate: ({ editor }) => { | ||
| // Force placeholder decorations to render immediately without needing focus | ||
| if (props.placeholder) { | ||
| editor.view.dispatch(editor.state.tr) | ||
| const externalEditor = computed(() => unref(props.editor) as TiptapEditor | undefined) | ||
|
|
||
| if (import.meta.dev) { | ||
| if (isExternalEditor) { | ||
| // Every prop not listed here only configures the built-in editor. | ||
| const shellProps = ['editor', 'as', 'class', 'ui', 'handlers', 'prose'] | ||
| const inertProps = Object.keys(_props).filter(name => !shellProps.includes(name) && isPropBound(name)) | ||
| if (inertProps.length) { | ||
| console.warn(`[@nuxt/ui] <UEditor> ignores [${inertProps.join(', ')}] when the \`editor\` prop is provided; the external editor owns its content, schema and lifecycle.`) | ||
| } | ||
| }, | ||
| onUpdate: ({ editor }) => { | ||
| let value | ||
| try { | ||
| if (contentType.value === 'html') { | ||
| value = editor.getHTML() | ||
| } else if (contentType.value === 'json') { | ||
| value = editor.getJSON() | ||
| } else if (contentType.value === 'markdown') { | ||
| value = editor.getMarkdown() | ||
| } else { | ||
| // The mode is fixed at setup, so an `editor` bound after the first render is inert. | ||
| const stop = watch(() => unref(props.editor), (value) => { | ||
| if (value) { | ||
| console.warn('[@nuxt/ui] <UEditor> received an `editor` after its first render and will keep using the built-in editor; bind the `editor` prop from the start (even while `undefined`) to use an external editor.') | ||
| stop() | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // No `useEditor` in external mode: it creates its own instance and destroys it on unmount. | ||
| const internalEditor = isExternalEditor | ||
| ? undefined | ||
| : useEditor({ | ||
| ...rootProps.value, | ||
| content: props.modelValue, | ||
| contentType: contentType.value, | ||
| extensions: extensions.value, | ||
| editorProps: editorProps.value, | ||
| onCreate: ({ editor }) => { | ||
| // Force placeholder decorations to render immediately without needing focus | ||
| if (props.placeholder) { | ||
| editor.view.dispatch(editor.state.tr) | ||
| } | ||
| }, | ||
| onUpdate: ({ editor }) => { | ||
| let value | ||
| try { | ||
| if (contentType.value === 'html') { | ||
| value = editor.getHTML() | ||
| } else if (contentType.value === 'json') { | ||
| value = editor.getJSON() | ||
| } else if (contentType.value === 'markdown') { | ||
| value = editor.getMarkdown() | ||
| } | ||
| } catch (error) { | ||
| value = editor.getText() | ||
| } | ||
|
|
||
| emits('update:modelValue', value as T) | ||
| } | ||
| } catch (error) { | ||
| value = editor.getText() | ||
| }) | ||
|
|
||
| // eslint-disable-next-line vue/no-dupe-keys | ||
| const editor = computed(() => isExternalEditor ? externalEditor.value : internalEditor?.value) | ||
|
|
||
| // `v-model` only syncs the built-in editor; an external editor owns its content. | ||
| if (!isExternalEditor) { | ||
| watch(() => props.modelValue, (newVal) => { | ||
| if (!editor.value || newVal == null) { | ||
| return | ||
| } | ||
|
|
||
| emits('update:modelValue', value as T) | ||
| } | ||
| }) | ||
| const currentContent = contentType.value === 'html' | ||
| ? editor.value.getHTML() | ||
| : contentType.value === 'json' | ||
| ? JSON.stringify(editor.value.getJSON()) | ||
| : contentType.value === 'markdown' | ||
| ? editor.value.getMarkdown() | ||
| : editor.value.getText() | ||
|
|
||
| watch(() => props.modelValue, (newVal) => { | ||
| if (!editor.value || newVal == null) { | ||
| return | ||
| } | ||
| const newContent = contentType.value === 'json' && typeof newVal === 'object' | ||
| ? JSON.stringify(newVal) | ||
| : String(newVal) | ||
|
|
||
| if (currentContent !== newContent) { | ||
| // Store current cursor position | ||
| const currentSelection = editor.value.state.selection | ||
| const currentPos = currentSelection.from | ||
|
|
||
| const currentContent = contentType.value === 'html' | ||
| ? editor.value.getHTML() | ||
| : contentType.value === 'json' | ||
| ? JSON.stringify(editor.value.getJSON()) | ||
| : contentType.value === 'markdown' | ||
| ? editor.value.getMarkdown() | ||
| : editor.value.getText() | ||
|
|
||
| const newContent = contentType.value === 'json' && typeof newVal === 'object' | ||
| ? JSON.stringify(newVal) | ||
| : String(newVal) | ||
|
|
||
| if (currentContent !== newContent) { | ||
| // Store current cursor position | ||
| const currentSelection = editor.value.state.selection | ||
| const currentPos = currentSelection.from | ||
|
|
||
| // Set the new content | ||
| editor.value.commands.setContent(newVal, { contentType: contentType.value }) | ||
|
|
||
| // Restore cursor position if the position is still valid in the new content | ||
| const newDoc = editor.value.state.doc | ||
| if (currentPos <= newDoc.content.size) { | ||
| editor.value.commands.setTextSelection(currentPos) | ||
| // Set the new content | ||
| editor.value.commands.setContent(newVal, { contentType: contentType.value }) | ||
|
|
||
| // Restore cursor position if the position is still valid in the new content | ||
| const newDoc = editor.value.state.doc | ||
| if (currentPos <= newDoc.content.size) { | ||
| editor.value.commands.setTextSelection(currentPos) | ||
| } | ||
| } | ||
| } | ||
| }) | ||
| }) | ||
| } | ||
|
|
||
| // eslint-disable-next-line vue/no-dupe-keys | ||
| const handlers = computed(() => ({ | ||
|
|
@@ -285,14 +345,17 @@ defineExpose({ | |
| <template> | ||
| <Primitive :as="props.as" data-slot="root" :class="ui.root({ class: [props.ui?.root, props.class] })"> | ||
| <template v-if="editor"> | ||
| <slot :editor="editor" :handlers="handlers" /> | ||
| <slot :editor="editor" :handlers="handlers" :ui="ui" /> | ||
|
|
||
| <EditorContent | ||
| role="presentation" | ||
| :editor="editor" | ||
| data-slot="content" | ||
| :class="ui.content({ class: props.ui?.content })" | ||
| v-bind="isExternalEditor ? $attrs : undefined" | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is the only thing I'm not fully sure about. I added it because I do tend to use it when in a pinch, but feel free to change @benjamincanac (the |
||
| /> | ||
| </template> | ||
|
|
||
| <slot v-else name="fallback" /> | ||
| </Primitive> | ||
| </template> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.