Kaynağa Gözat

Changed: Added `view.Node#toJSON` method to prevent throwing error when stringifying.

Szymon Cofalik 8 yıl önce
ebeveyn
işleme
f13a875925

+ 10 - 0
packages/ckeditor5-engine/src/view/node.js

@@ -10,6 +10,7 @@
 import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
 import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
 import mix from '@ckeditor/ckeditor5-utils/src/mix';
+import clone from '@ckeditor/ckeditor5-utils/src/lib/lodash/clone';
 
 /**
  * Abstract tree view node class.
@@ -181,6 +182,15 @@ export default class Node {
 		}
 	}
 
+	toJSON() {
+		const json = clone( this );
+
+		// Due to circular references we need to remove parent reference.
+		delete json.parent;
+
+		return json;
+	}
+
 	/**
 	 * Clones this node.
 	 *

+ 15 - 0
packages/ckeditor5-engine/tests/view/node.js

@@ -279,6 +279,21 @@ describe( 'Node', () => {
 		} );
 	} );
 
+	describe( 'toJSON()', () => {
+		it( 'should prevent circular reference when stringifying a node', () => {
+			const char = new Text( 'a' );
+			const parent = new Element( 'p', null );
+			parent.appendChildren( char );
+
+			const json = JSON.stringify( char );
+			const parsed = JSON.parse( json );
+
+			expect( parsed ).to.deep.equal( {
+				_data: 'a'
+			} );
+		} );
+	} );
+
 	describe( 'change event', () => {
 		let root, text, img, rootChangeSpy;