text.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. * @inheritDoc
  44. */
  45. is( type ) {
  46. return type == 'text';
  47. }
  48. /**
  49. * Creates a copy of this text node and returns it. Created text node has same text data and attributes as original text node.
  50. */
  51. clone() {
  52. return new Text( this.data, this.getAttributes() );
  53. }
  54. /**
  55. * Converts `Text` instance to plain object and returns it.
  56. *
  57. * @returns {Object} `Text` instance converted to plain object.
  58. */
  59. toJSON() {
  60. let json = super.toJSON();
  61. json.data = this.data;
  62. return json;
  63. }
  64. /**
  65. * Creates a `Text` instance from given plain object (i.e. parsed JSON string).
  66. *
  67. * @param {Object} json Plain object to be converted to `Text`.
  68. * @returns {module:engine/model/text~Text} `Text` instance created using given plain object.
  69. */
  70. static fromJSON( json ) {
  71. return new Text( json.data, json.attributes );
  72. }
  73. }