text.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import AttributeList from './attributelist.js';
  7. import TextNode from './textnode.js';
  8. import langUtils from '../lib/lodash/lang.js';
  9. /**
  10. * Data structure for text with attributes. Note that the `Text` is not a {@link treeModel.Node}. This class is used
  11. * as an aggregator for multiple characters that have same attributes. Example usage:
  12. *
  13. * let attrFoo = new Attribute( 'foo', true );
  14. * let attrBar = new Attribute( 'bar', true );
  15. * let myElem = new Element( 'li', [], new Text( 'text with attributes', [ attrFoo, attrBar ] ) );
  16. *
  17. * @class treeModel.Text
  18. */
  19. export default class Text {
  20. /**
  21. * Creates a text with attributes.
  22. *
  23. * @param {String} text Described text.
  24. * @param {Iterable} attrs Iterable collection of {@link treeModel.Attribute attributes}.
  25. * @constructor
  26. */
  27. constructor( text, attrs ) {
  28. /**
  29. * Text.
  30. *
  31. * @readonly
  32. * @property {String}
  33. */
  34. this.text = text || '';
  35. /**
  36. * Iterable collection of {@link treeModel.Attribute attributes}.
  37. *
  38. * @property {Iterable}
  39. */
  40. this.attrs = new AttributeList( attrs );
  41. }
  42. /**
  43. * Creates and returns a text node that represents whole text contained in this text object.
  44. *
  45. * @returns {TextNode}
  46. */
  47. getTextNode( start, length ) {
  48. start = start && start >= 0 ? start : 0;
  49. length = length && length >= 0 ? length : this.text.length;
  50. return new TextNode( this, start, length );
  51. }
  52. /**
  53. * Custom toJSON method to solve child-parent circular dependencies.
  54. *
  55. * @returns {Object} Clone of this object with the parent property replaced with its name.
  56. */
  57. toJSON() {
  58. const json = langUtils.clone( this );
  59. // Due to circular references we need to remove parent reference.
  60. json.parent = this.parent ? this.parent.name : null;
  61. return json;
  62. }
  63. }