Skip to content

Commit

Permalink
fix: placeholders now check for empty content compared to their "true…
Browse files Browse the repository at this point in the history
…" empty state (#5278)

* fix: placeholders now check for empty content compared to their "true" empty state

* chore: add changeset
  • Loading branch information
nperez0111 authored Jun 28, 2024
1 parent c2e4ad9 commit 89fefab
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 23 deletions.
5 changes: 5 additions & 0 deletions .changeset/mean-cooks-cheer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tiptap/extension-placeholder": patch
---

Placeholders can now handle more complex default content
26 changes: 3 additions & 23 deletions packages/extension-placeholder/src/placeholder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Editor, Extension } from '@tiptap/core'
import { Editor, Extension, isNodeEmpty } from '@tiptap/core'
import { Node as ProsemirrorNode } from '@tiptap/pm/model'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
Expand Down Expand Up @@ -31,15 +31,6 @@ export interface PlaceholderOptions {
}) => string)
| string

/**
* **Used for empty check on the document.**
*
* If true, any node that is not a leaf or atom will be considered for empty check.
* If false, only default nodes (paragraphs) will be considered for empty check.
* @default false
*/
considerAnyAsEmpty: boolean

/**
* **Checks if the placeholder should be only shown when the editor is editable.**
*
Expand Down Expand Up @@ -82,7 +73,6 @@ export const Placeholder = Extension.create<PlaceholderOptions>({
emptyNodeClass: 'is-empty',
placeholder: 'Write something …',
showOnlyWhenEditable: true,
considerAnyAsEmpty: false,
showOnlyCurrent: true,
includeChildren: false,
}
Expand All @@ -102,21 +92,11 @@ export const Placeholder = Extension.create<PlaceholderOptions>({
return null
}

// only calculate isEmpty once due to its performance impacts (see issue #3360)
const { firstChild } = doc.content
const isLeaf = firstChild && firstChild.type.isLeaf
const isAtom = firstChild && firstChild.isAtom
const isValidNode = this.options.considerAnyAsEmpty
? true
: firstChild && firstChild.type.name === doc.type.contentMatch.defaultType?.name
const isEmptyDoc = doc.content.childCount <= 1
&& firstChild
&& isValidNode
&& (firstChild.nodeSize <= 2 && (!isLeaf || !isAtom))
const isEmptyDoc = this.editor.isEmpty

doc.descendants((node, pos) => {
const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize
const isEmpty = !node.isLeaf && !node.childCount
const isEmpty = !node.isLeaf && isNodeEmpty(node)

if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
const classes = [this.options.emptyNodeClass]
Expand Down

0 comments on commit 89fefab

Please sign in to comment.