improved error handling for invalid content

This commit is contained in:
Philipp Kühn
2018-11-16 14:12:25 +01:00
parent 41a6fd54c5
commit abfc9d5331
3 changed files with 48 additions and 7 deletions

View File

@@ -32,6 +32,9 @@ module.exports = {
// required semicolons
'semi': ['error', 'never'],
// error handling
'no-console': ['error', { allow: ['warn', 'error'] }],
// indent
'no-tabs': 'off',
'indent': 'off',

View File

@@ -40,6 +40,12 @@ export default class Editor {
editable: true,
extensions: [],
content: '',
emptyDocument: {
type: 'doc',
content: [{
type: 'paragraph',
}],
},
onInit: () => {},
onUpdate: () => {},
onFocus: () => {},
@@ -125,7 +131,12 @@ export default class Editor {
createDocument(content) {
if (typeof content === 'object') {
try {
return this.schema.nodeFromJSON(content)
} catch (error) {
console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)
return this.schema.nodeFromJSON(this.options.emptyDocument)
}
}
if (typeof content === 'string') {
@@ -263,12 +274,7 @@ export default class Editor {
}
clearContent(emitUpdate = false) {
this.setContent({
type: 'doc',
content: [{
type: 'paragraph',
}],
}, emitUpdate)
this.setContent(this.options.emptyDocument, emitUpdate)
}
setActiveNodesAndMarks() {

View File

@@ -25,6 +25,38 @@ test('create editor', () => {
expect(editor).toBeDefined()
})
test('check invalid content (JSON)', () => {
const editor = new Editor({
content: { thisIsNotAValidDocument: true },
})
expect(editor.getHTML()).toEqual('<p></p>')
})
test('check invalid content (HTML)', () => {
const editor = new Editor({
content: '</>',
})
expect(editor.getHTML()).toEqual('<p></p>')
})
test('check invalid content (unsupported format: Function)', () => {
const editor = new Editor({
content: () => false,
})
expect(editor.getHTML()).toEqual('<p></p>')
})
test('check invalid content (unsupported format: Array)', () => {
const editor = new Editor({
content: [],
})
expect(editor.getHTML()).toEqual('<p></p>')
})
test('set HTML, get HTML', () => {
const content = '<p>Lorem <strong>ipsum</strong> dolor sit amet.</p>'