text.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import NodeType from './type';
  2. import Node from './node';
  3. /**
  4. * TextNode to contain a text element in DOM tree.
  5. * @param {string} value [description]
  6. */
  7. export default class TextNode extends Node {
  8. constructor(rawText, parentNode) {
  9. super(parentNode);
  10. this.rawText = rawText;
  11. /**
  12. * Node Type declaration.
  13. * @type {Number}
  14. */
  15. this.nodeType = NodeType.TEXT_NODE;
  16. }
  17. /**
  18. * Returns text with all whitespace trimmed except single leading/trailing non-breaking space
  19. */
  20. get trimmedText() {
  21. if (this._trimmedText !== undefined)
  22. return this._trimmedText;
  23. const text = this.rawText;
  24. let i = 0;
  25. let startPos;
  26. let endPos;
  27. while (i >= 0 && i < text.length) {
  28. if (/\S/.test(text[i])) {
  29. if (startPos === undefined) {
  30. startPos = i;
  31. i = text.length;
  32. }
  33. else {
  34. endPos = i;
  35. i = void 0;
  36. }
  37. }
  38. if (startPos === undefined)
  39. i++;
  40. else
  41. i--;
  42. }
  43. if (startPos === undefined)
  44. startPos = 0;
  45. if (endPos === undefined)
  46. endPos = text.length - 1;
  47. const hasLeadingSpace = startPos > 0 && /[^\S\r\n]/.test(text[startPos - 1]);
  48. const hasTrailingSpace = endPos < (text.length - 1) && /[^\S\r\n]/.test(text[endPos + 1]);
  49. this._trimmedText = (hasLeadingSpace ? ' ' : '') + text.slice(startPos, endPos + 1) + (hasTrailingSpace ? ' ' : '');
  50. return this._trimmedText;
  51. }
  52. /**
  53. * Get unescaped text value of current node and its children.
  54. * @return {string} text content
  55. */
  56. get text() {
  57. return this.rawText;
  58. }
  59. /**
  60. * Detect if the node contains only white space.
  61. * @return {bool}
  62. */
  63. get isWhitespace() {
  64. return /^(\s|&nbsp;)*$/.test(this.rawText);
  65. }
  66. toString() {
  67. return this.text;
  68. }
  69. }