text.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/text
  7. */
  8. import Node from './node';
  9. /**
  10. * Model text node. Type of {@link module:engine/model/node~Node node} that contains {@link module:engine/model/text~Text#data text data}.
  11. *
  12. * **Important:** see {@link module:engine/model/node~Node} to read about restrictions using `Text` and `Node` API.
  13. *
  14. * **Note:** keep in mind that `Text` instances might indirectly got removed from model tree when model is changed.
  15. * This happens when {@link module:engine/model/writer~Writer model writer} is used to change model and the text node is merged with
  16. * another text node. Then, both text nodes are removed and a new text node is inserted into the model. Because of
  17. * this behavior, keeping references to `Text` is not recommended. Instead, consider creating
  18. * {@link module:engine/model/liveposition~LivePosition live position} placed before the text node.
  19. *
  20. * @extends {module:engine/model/node~Node}
  21. */
  22. export default class Text extends Node {
  23. /**
  24. * Creates a text node.
  25. *
  26. * @param {String} data Node's text.
  27. * @param {Object} [attrs] Node's attributes. See {@link module:utils/tomap~toMap} for a list of accepted values.
  28. */
  29. constructor( data, attrs ) {
  30. super( attrs );
  31. /**
  32. * Text data contained in this text node.
  33. *
  34. * @type {String}
  35. */
  36. this.data = data || '';
  37. }
  38. /**
  39. * @inheritDoc
  40. */
  41. get offsetSize() {
  42. return this.data.length;
  43. }
  44. /**
  45. * @inheritDoc
  46. */
  47. is( type ) {
  48. return type == 'text';
  49. }
  50. /**
  51. * Creates a copy of this text node and returns it. Created text node has same text data and attributes as original text node.
  52. */
  53. clone() {
  54. return new Text( this.data, this.getAttributes() );
  55. }
  56. /**
  57. * Converts `Text` instance to plain object and returns it.
  58. *
  59. * @returns {Object} `Text` instance converted to plain object.
  60. */
  61. toJSON() {
  62. const json = super.toJSON();
  63. json.data = this.data;
  64. return json;
  65. }
  66. /**
  67. * Creates a `Text` instance from given plain object (i.e. parsed JSON string).
  68. *
  69. * @param {Object} json Plain object to be converted to `Text`.
  70. * @returns {module:engine/model/text~Text} `Text` instance created using given plain object.
  71. */
  72. static fromJSON( json ) {
  73. return new Text( json.data, json.attributes );
  74. }
  75. }