mending3
mending3

Reputation: 712

tiptap: make isEmpty return true when the editor only contains whitespaces and new lines (LITERALLY empty)

this isEmpty still returns true when the editor contains only whitespace(s) (and alongside with new lines) :

import { EditorContent, Editor } from "@tiptap/vue-3";

const editor = new Editor({
  // ...
})

const isEmpty = () => !editor.state.doc.textContent.length;

https://codesandbox.io/s/tiptap-vue-forked-gpwrpn

P.S. I don't use editor.isEmpty because it's unreliable, views whitespaces and new lines as not empty

Upvotes: 0

Views: 2650

Answers (2)

Angad Sethi
Angad Sethi

Reputation: 1

This (editor.state.doc.textContent.trim().length) will work when your editor only has text nodes, but it will fail when the editor has atom nodes like images and mentions, as mentioned in this Github comment.

To check whether the editor is truly empty or not, you should implement a custom function that cycles through all the nodes and checks whether a node of that type is empty or not.

Here is a good starting point:

function isContentBlockEmpty(block) {
    if (!block || !block.type) {
        return true
    }

    if (block.type in SOME_CUSTOM_OBJECT) {
        return SOME_CUSTOM_OBJECT[block.type](block)
    }

    if ('text' in block) {
        return !block.text?.trim()
    }

    return block.content ? block.content.every((_block) => isContentBlockEmpty(_block)) : true
}

And you can call this function, like this: isContentBlockEmpty(editor.getJSON())

Upvotes: 0

Flow
Flow

Reputation: 791

You could use the trim method on your textContent :

const isEmpty = () => !editor.state.doc.textContent.trim().length;

Upvotes: 2

Related Questions