8
0

text.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * @license Copyright (c) 2003-2017, 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. export default class Text extends Node {
  21. /**
  22. * Creates a text node.
  23. *
  24. * @param {String} data Node's text.
  25. * @param {Object} [attrs] Node's attributes. See {@link module:utils/tomap~toMap} for a list of accepted values.
  26. */
  27. constructor( data, attrs ) {
  28. super( attrs );
  29. /**
  30. * Text data contained in this text node.
  31. *
  32. * @type {String}
  33. */
  34. this.data = data || '';
  35. }
  36. /**
  37. * @inheritDoc
  38. */
  39. get offsetSize() {
  40. return this.data.length;
  41. }
  42. /**
  43. * Creates a copy of this text node and returns it. Created text node has same text data and attributes as original text node.
  44. */
  45. clone() {
  46. return new Text( this.data, this.getAttributes() );
  47. }
  48. /**
  49. * Converts `Text` instance to plain object and returns it.
  50. *
  51. * @returns {Object} `Text` instance converted to plain object.
  52. */
  53. toJSON() {
  54. let json = super.toJSON();
  55. json.data = this.data;
  56. return json;
  57. }
  58. /**
  59. * Creates a `Text` instance from given plain object (i.e. parsed JSON string).
  60. *
  61. * @param {Object} json Plain object to be converted to `Text`.
  62. * @returns {module:engine/model/text~Text} `Text` instance created using given plain object.
  63. */
  64. static fromJSON( json ) {
  65. return new Text( json.data, json.attributes );
  66. }
  67. }