Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

draftjs-to-html.js 18 KiB

há 3 anos
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.draftjsToHtml = factory());
  5. }(this, (function () { 'use strict';
  6. /**
  7. * Utility function to execute callback for eack key->value pair.
  8. */
  9. function forEach(obj, callback) {
  10. if (obj) {
  11. for (var key in obj) {
  12. // eslint-disable-line no-restricted-syntax
  13. if ({}.hasOwnProperty.call(obj, key)) {
  14. callback(key, obj[key]);
  15. }
  16. }
  17. }
  18. }
  19. /**
  20. * The function returns true if the string passed to it has no content.
  21. */
  22. function isEmptyString(str) {
  23. if (str === undefined || str === null || str.length === 0 || str.trim().length === 0) {
  24. return true;
  25. }
  26. return false;
  27. }
  28. /**
  29. * Mapping block-type to corresponding html tag.
  30. */
  31. var blockTypesMapping = {
  32. unstyled: 'p',
  33. 'header-one': 'h1',
  34. 'header-two': 'h2',
  35. 'header-three': 'h3',
  36. 'header-four': 'h4',
  37. 'header-five': 'h5',
  38. 'header-six': 'h6',
  39. 'unordered-list-item': 'ul',
  40. 'ordered-list-item': 'ol',
  41. blockquote: 'blockquote',
  42. code: 'pre'
  43. };
  44. /**
  45. * Function will return HTML tag for a block.
  46. */
  47. function getBlockTag(type) {
  48. return type && blockTypesMapping[type];
  49. }
  50. /**
  51. * Function will return style string for a block.
  52. */
  53. function getBlockStyle(data) {
  54. var styles = '';
  55. forEach(data, function (key, value) {
  56. if (value) {
  57. styles += key + ':' + value + ';';
  58. }
  59. });
  60. return styles;
  61. }
  62. /**
  63. * The function returns an array of hashtag-sections in blocks.
  64. * These will be areas in block which have hashtags applicable to them.
  65. */
  66. function getHashtagRanges(blockText, hashtagConfig) {
  67. var sections = [];
  68. if (hashtagConfig) {
  69. var counter = 0;
  70. var startIndex = 0;
  71. var text = blockText;
  72. var trigger = hashtagConfig.trigger || '#';
  73. var separator = hashtagConfig.separator || ' ';
  74. for (; text.length > 0 && startIndex >= 0;) {
  75. if (text[0] === trigger) {
  76. startIndex = 0;
  77. counter = 0;
  78. text = text.substr(trigger.length);
  79. } else {
  80. startIndex = text.indexOf(separator + trigger);
  81. if (startIndex >= 0) {
  82. text = text.substr(startIndex + (separator + trigger).length);
  83. counter += startIndex + separator.length;
  84. }
  85. }
  86. if (startIndex >= 0) {
  87. var endIndex = text.indexOf(separator) >= 0 ? text.indexOf(separator) : text.length;
  88. var hashtag = text.substr(0, endIndex);
  89. if (hashtag && hashtag.length > 0) {
  90. sections.push({
  91. offset: counter,
  92. length: hashtag.length + trigger.length,
  93. type: 'HASHTAG'
  94. });
  95. }
  96. counter += trigger.length;
  97. }
  98. }
  99. }
  100. return sections;
  101. }
  102. /**
  103. * The function returns an array of entity-sections in blocks.
  104. * These will be areas in block which have same entity or no entity applicable to them.
  105. */
  106. function getSections(block, hashtagConfig) {
  107. var sections = [];
  108. var lastOffset = 0;
  109. var sectionRanges = block.entityRanges.map(function (range) {
  110. var offset = range.offset,
  111. length = range.length,
  112. key = range.key;
  113. return {
  114. offset: offset,
  115. length: length,
  116. key: key,
  117. type: 'ENTITY'
  118. };
  119. });
  120. sectionRanges = sectionRanges.concat(getHashtagRanges(block.text, hashtagConfig));
  121. sectionRanges = sectionRanges.sort(function (s1, s2) {
  122. return s1.offset - s2.offset;
  123. });
  124. sectionRanges.forEach(function (r) {
  125. if (r.offset > lastOffset) {
  126. sections.push({
  127. start: lastOffset,
  128. end: r.offset
  129. });
  130. }
  131. sections.push({
  132. start: r.offset,
  133. end: r.offset + r.length,
  134. entityKey: r.key,
  135. type: r.type
  136. });
  137. lastOffset = r.offset + r.length;
  138. });
  139. if (lastOffset < block.text.length) {
  140. sections.push({
  141. start: lastOffset,
  142. end: block.text.length
  143. });
  144. }
  145. return sections;
  146. }
  147. /**
  148. * Function to check if the block is an atomic entity block.
  149. */
  150. function isAtomicEntityBlock(block) {
  151. if (block.entityRanges.length > 0 && (isEmptyString(block.text) || block.type === 'atomic')) {
  152. return true;
  153. }
  154. return false;
  155. }
  156. /**
  157. * The function will return array of inline styles applicable to the block.
  158. */
  159. function getStyleArrayForBlock(block) {
  160. var text = block.text,
  161. inlineStyleRanges = block.inlineStyleRanges;
  162. var inlineStyles = {
  163. BOLD: new Array(text.length),
  164. ITALIC: new Array(text.length),
  165. UNDERLINE: new Array(text.length),
  166. STRIKETHROUGH: new Array(text.length),
  167. CODE: new Array(text.length),
  168. SUPERSCRIPT: new Array(text.length),
  169. SUBSCRIPT: new Array(text.length),
  170. COLOR: new Array(text.length),
  171. BGCOLOR: new Array(text.length),
  172. FONTSIZE: new Array(text.length),
  173. FONTFAMILY: new Array(text.length),
  174. length: text.length
  175. };
  176. if (inlineStyleRanges && inlineStyleRanges.length > 0) {
  177. inlineStyleRanges.forEach(function (range) {
  178. var offset = range.offset;
  179. var length = offset + range.length;
  180. for (var i = offset; i < length; i += 1) {
  181. if (range.style.indexOf('color-') === 0) {
  182. inlineStyles.COLOR[i] = range.style.substring(6);
  183. } else if (range.style.indexOf('bgcolor-') === 0) {
  184. inlineStyles.BGCOLOR[i] = range.style.substring(8);
  185. } else if (range.style.indexOf('fontsize-') === 0) {
  186. inlineStyles.FONTSIZE[i] = range.style.substring(9);
  187. } else if (range.style.indexOf('fontfamily-') === 0) {
  188. inlineStyles.FONTFAMILY[i] = range.style.substring(11);
  189. } else if (inlineStyles[range.style]) {
  190. inlineStyles[range.style][i] = true;
  191. }
  192. }
  193. });
  194. }
  195. return inlineStyles;
  196. }
  197. /**
  198. * The function will return inline style applicable at some offset within a block.
  199. */
  200. function getStylesAtOffset(inlineStyles, offset) {
  201. var styles = {};
  202. if (inlineStyles.COLOR[offset]) {
  203. styles.COLOR = inlineStyles.COLOR[offset];
  204. }
  205. if (inlineStyles.BGCOLOR[offset]) {
  206. styles.BGCOLOR = inlineStyles.BGCOLOR[offset];
  207. }
  208. if (inlineStyles.FONTSIZE[offset]) {
  209. styles.FONTSIZE = inlineStyles.FONTSIZE[offset];
  210. }
  211. if (inlineStyles.FONTFAMILY[offset]) {
  212. styles.FONTFAMILY = inlineStyles.FONTFAMILY[offset];
  213. }
  214. if (inlineStyles.UNDERLINE[offset]) {
  215. styles.UNDERLINE = true;
  216. }
  217. if (inlineStyles.ITALIC[offset]) {
  218. styles.ITALIC = true;
  219. }
  220. if (inlineStyles.BOLD[offset]) {
  221. styles.BOLD = true;
  222. }
  223. if (inlineStyles.STRIKETHROUGH[offset]) {
  224. styles.STRIKETHROUGH = true;
  225. }
  226. if (inlineStyles.CODE[offset]) {
  227. styles.CODE = true;
  228. }
  229. if (inlineStyles.SUBSCRIPT[offset]) {
  230. styles.SUBSCRIPT = true;
  231. }
  232. if (inlineStyles.SUPERSCRIPT[offset]) {
  233. styles.SUPERSCRIPT = true;
  234. }
  235. return styles;
  236. }
  237. /**
  238. * Function returns true for a set of styles if the value of these styles at an offset
  239. * are same as that on the previous offset.
  240. */
  241. function sameStyleAsPrevious(inlineStyles, styles, index) {
  242. var sameStyled = true;
  243. if (index > 0 && index < inlineStyles.length) {
  244. styles.forEach(function (style) {
  245. sameStyled = sameStyled && inlineStyles[style][index] === inlineStyles[style][index - 1];
  246. });
  247. } else {
  248. sameStyled = false;
  249. }
  250. return sameStyled;
  251. }
  252. /**
  253. * Function returns html for text depending on inline style tags applicable to it.
  254. */
  255. function addInlineStyleMarkup(style, content) {
  256. if (style === 'BOLD') {
  257. return '<strong>' + content + '</strong>';
  258. } else if (style === 'ITALIC') {
  259. return '<em>' + content + '</em>';
  260. } else if (style === 'UNDERLINE') {
  261. return '<ins>' + content + '</ins>';
  262. } else if (style === 'STRIKETHROUGH') {
  263. return '<del>' + content + '</del>';
  264. } else if (style === 'CODE') {
  265. return '<code>' + content + '</code>';
  266. } else if (style === 'SUPERSCRIPT') {
  267. return '<sup>' + content + '</sup>';
  268. } else if (style === 'SUBSCRIPT') {
  269. return '<sub>' + content + '</sub>';
  270. }
  271. return content;
  272. }
  273. /**
  274. * The function returns text for given section of block after doing required character replacements.
  275. */
  276. function getSectionText(text) {
  277. if (text && text.length > 0) {
  278. var chars = text.map(function (ch) {
  279. switch (ch) {
  280. case '\n':
  281. return '<br>';
  282. case '&':
  283. return '&amp;';
  284. case '<':
  285. return '&lt;';
  286. case '>':
  287. return '&gt;';
  288. default:
  289. return ch;
  290. }
  291. });
  292. return chars.join('');
  293. }
  294. return '';
  295. }
  296. /**
  297. * Function returns html for text depending on inline style tags applicable to it.
  298. */
  299. function addStylePropertyMarkup(styles, text) {
  300. if (styles && (styles.COLOR || styles.BGCOLOR || styles.FONTSIZE || styles.FONTFAMILY)) {
  301. var styleString = 'style="';
  302. if (styles.COLOR) {
  303. styleString += 'color: ' + styles.COLOR + ';';
  304. }
  305. if (styles.BGCOLOR) {
  306. styleString += 'background-color: ' + styles.BGCOLOR + ';';
  307. }
  308. if (styles.FONTSIZE) {
  309. styleString += 'font-size: ' + styles.FONTSIZE + (/^\d+$/.test(styles.FONTSIZE) ? 'px' : '') + ';';
  310. }
  311. if (styles.FONTFAMILY) {
  312. styleString += 'font-family: ' + styles.FONTFAMILY + ';';
  313. }
  314. styleString += '"';
  315. return '<span ' + styleString + '>' + text + '</span>';
  316. }
  317. return text;
  318. }
  319. /**
  320. * Function will return markup for Entity.
  321. */
  322. function getEntityMarkup(entityMap, entityKey, text, customEntityTransform) {
  323. var entity = entityMap[entityKey];
  324. if (typeof customEntityTransform === 'function') {
  325. var html = customEntityTransform(entity, text);
  326. if (html) {
  327. return html;
  328. }
  329. }
  330. if (entity.type === 'MENTION') {
  331. return '<a href="' + entity.data.url + '" class="wysiwyg-mention" data-mention data-value="' + entity.data.value + '">' + text + '</a>';
  332. }
  333. if (entity.type === 'LINK') {
  334. var targetOption = entity.data.targetOption || '_self';
  335. return '<a href="' + entity.data.url + '" target="' + targetOption + '">' + text + '</a>';
  336. }
  337. if (entity.type === 'IMAGE') {
  338. return '<img src="' + entity.data.src + '" alt="' + entity.data.alt + '" style="float:' + (entity.data.alignment || 'none') + ';height: ' + entity.data.height + ';width: ' + entity.data.width + '"/>';
  339. }
  340. if (entity.type === 'EMBEDDED_LINK') {
  341. return '<iframe width="' + entity.data.width + '" height="' + entity.data.height + '" src="' + entity.data.src + '" frameBorder="0"></iframe>';
  342. }
  343. return text;
  344. }
  345. /**
  346. * For a given section in a block the function will return a further list of sections,
  347. * with similar inline styles applicable to them.
  348. */
  349. function getInlineStyleSections(block, styles, start, end) {
  350. var styleSections = [];
  351. var text = block.text;
  352. if (text.length > 0) {
  353. var inlineStyles = getStyleArrayForBlock(block);
  354. var section = void 0;
  355. for (var i = start; i < end; i += 1) {
  356. if (i !== start && sameStyleAsPrevious(inlineStyles, styles, i)) {
  357. section.text.push(text[i]);
  358. section.end = i + 1;
  359. } else {
  360. section = {
  361. styles: getStylesAtOffset(inlineStyles, i),
  362. text: [text[i]],
  363. start: i,
  364. end: i + 1
  365. };
  366. styleSections.push(section);
  367. }
  368. }
  369. }
  370. return styleSections;
  371. }
  372. /**
  373. * Replace leading blank spaces by &nbsp;
  374. */
  375. function trimLeadingZeros(sectionText) {
  376. if (sectionText) {
  377. var replacedText = sectionText;
  378. for (var i = 0; i < replacedText.length; i += 1) {
  379. if (sectionText[i] === ' ') {
  380. replacedText = replacedText.replace(' ', '&nbsp;');
  381. } else {
  382. break;
  383. }
  384. }
  385. return replacedText;
  386. }
  387. return sectionText;
  388. }
  389. /**
  390. * Replace trailing blank spaces by &nbsp;
  391. */
  392. function trimTrailingZeros(sectionText) {
  393. if (sectionText) {
  394. var replacedText = sectionText;
  395. for (var i = replacedText.length - 1; i >= 0; i -= 1) {
  396. if (replacedText[i] === ' ') {
  397. replacedText = replacedText.substring(0, i) + '&nbsp;' + replacedText.substring(i + 1);
  398. } else {
  399. break;
  400. }
  401. }
  402. return replacedText;
  403. }
  404. return sectionText;
  405. }
  406. /**
  407. * The method returns markup for section to which inline styles
  408. * like BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, CODE, SUPERSCRIPT, SUBSCRIPT are applicable.
  409. */
  410. function getStyleTagSectionMarkup(styleSection) {
  411. var styles = styleSection.styles,
  412. text = styleSection.text;
  413. var content = getSectionText(text);
  414. forEach(styles, function (style, value) {
  415. content = addInlineStyleMarkup(style, content, value);
  416. });
  417. return content;
  418. }
  419. /**
  420. * The method returns markup for section to which inline styles
  421. like color, background-color, font-size are applicable.
  422. */
  423. function getInlineStyleSectionMarkup(block, styleSection) {
  424. var styleTagSections = getInlineStyleSections(block, ['BOLD', 'ITALIC', 'UNDERLINE', 'STRIKETHROUGH', 'CODE', 'SUPERSCRIPT', 'SUBSCRIPT'], styleSection.start, styleSection.end);
  425. var styleSectionText = '';
  426. styleTagSections.forEach(function (stylePropertySection) {
  427. styleSectionText += getStyleTagSectionMarkup(stylePropertySection);
  428. });
  429. styleSectionText = addStylePropertyMarkup(styleSection.styles, styleSectionText);
  430. return styleSectionText;
  431. }
  432. /*
  433. * The method returns markup for an entity section.
  434. * An entity section is a continuous section in a block
  435. * to which same entity or no entity is applicable.
  436. */
  437. function getSectionMarkup(block, entityMap, section, customEntityTransform) {
  438. var entityInlineMarkup = [];
  439. var inlineStyleSections = getInlineStyleSections(block, ['COLOR', 'BGCOLOR', 'FONTSIZE', 'FONTFAMILY'], section.start, section.end);
  440. inlineStyleSections.forEach(function (styleSection) {
  441. entityInlineMarkup.push(getInlineStyleSectionMarkup(block, styleSection));
  442. });
  443. var sectionText = entityInlineMarkup.join('');
  444. if (section.type === 'ENTITY') {
  445. if (section.entityKey !== undefined && section.entityKey !== null) {
  446. sectionText = getEntityMarkup(entityMap, section.entityKey, sectionText, customEntityTransform); // eslint-disable-line max-len
  447. }
  448. } else if (section.type === 'HASHTAG') {
  449. sectionText = '<a href="' + sectionText + '" class="wysiwyg-hashtag">' + sectionText + '</a>';
  450. }
  451. return sectionText;
  452. }
  453. /**
  454. * Function will return the markup for block preserving the inline styles and
  455. * special characters like newlines or blank spaces.
  456. */
  457. function getBlockInnerMarkup(block, entityMap, hashtagConfig, customEntityTransform) {
  458. var blockMarkup = [];
  459. var sections = getSections(block, hashtagConfig);
  460. sections.forEach(function (section, index) {
  461. var sectionText = getSectionMarkup(block, entityMap, section, customEntityTransform);
  462. if (index === 0) {
  463. sectionText = trimLeadingZeros(sectionText);
  464. }
  465. if (index === sections.length - 1) {
  466. sectionText = trimTrailingZeros(sectionText);
  467. }
  468. blockMarkup.push(sectionText);
  469. });
  470. return blockMarkup.join('');
  471. }
  472. /**
  473. * Function will return html for the block.
  474. */
  475. function getBlockMarkup(block, entityMap, hashtagConfig, directional, customEntityTransform) {
  476. var blockHtml = [];
  477. if (isAtomicEntityBlock(block)) {
  478. blockHtml.push(getEntityMarkup(entityMap, block.entityRanges[0].key, undefined, customEntityTransform));
  479. } else {
  480. var blockTag = getBlockTag(block.type);
  481. if (blockTag) {
  482. blockHtml.push('<' + blockTag);
  483. var blockStyle = getBlockStyle(block.data);
  484. if (blockStyle) {
  485. blockHtml.push(' style="' + blockStyle + '"');
  486. }
  487. if (directional) {
  488. blockHtml.push(' dir = "auto"');
  489. }
  490. blockHtml.push('>');
  491. blockHtml.push(getBlockInnerMarkup(block, entityMap, hashtagConfig, customEntityTransform));
  492. blockHtml.push('</' + blockTag + '>');
  493. }
  494. }
  495. blockHtml.push('\n');
  496. return blockHtml.join('');
  497. }
  498. /**
  499. * Function to check if a block is of type list.
  500. */
  501. function isList(blockType) {
  502. return blockType === 'unordered-list-item' || blockType === 'ordered-list-item';
  503. }
  504. /**
  505. * Function will return html markup for a list block.
  506. */
  507. function getListMarkup(listBlocks, entityMap, hashtagConfig, directional, customEntityTransform) {
  508. var listHtml = [];
  509. var nestedListBlock = [];
  510. var previousBlock = void 0;
  511. listBlocks.forEach(function (block) {
  512. var nestedBlock = false;
  513. if (!previousBlock) {
  514. listHtml.push('<' + getBlockTag(block.type) + '>\n');
  515. } else if (previousBlock.type !== block.type) {
  516. listHtml.push('</' + getBlockTag(previousBlock.type) + '>\n');
  517. listHtml.push('<' + getBlockTag(block.type) + '>\n');
  518. } else if (previousBlock.depth === block.depth) {
  519. if (nestedListBlock && nestedListBlock.length > 0) {
  520. listHtml.push(getListMarkup(nestedListBlock, entityMap, hashtagConfig, directional, customEntityTransform));
  521. nestedListBlock = [];
  522. }
  523. } else {
  524. nestedBlock = true;
  525. nestedListBlock.push(block);
  526. }
  527. if (!nestedBlock) {
  528. listHtml.push('<li');
  529. var blockStyle = getBlockStyle(block.data);
  530. if (blockStyle) {
  531. listHtml.push(' style="' + blockStyle + '"');
  532. }
  533. if (directional) {
  534. listHtml.push(' dir = "auto"');
  535. }
  536. listHtml.push('>');
  537. listHtml.push(getBlockInnerMarkup(block, entityMap, hashtagConfig, customEntityTransform));
  538. listHtml.push('</li>\n');
  539. previousBlock = block;
  540. }
  541. });
  542. if (nestedListBlock && nestedListBlock.length > 0) {
  543. listHtml.push(getListMarkup(nestedListBlock, entityMap, hashtagConfig, directional, customEntityTransform));
  544. }
  545. listHtml.push('</' + getBlockTag(previousBlock.type) + '>\n');
  546. return listHtml.join('');
  547. }
  548. /**
  549. * The function will generate html markup for given draftjs editorContent.
  550. */
  551. function draftToHtml(editorContent, hashtagConfig, directional, customEntityTransform) {
  552. var html = [];
  553. if (editorContent) {
  554. var blocks = editorContent.blocks,
  555. entityMap = editorContent.entityMap;
  556. if (blocks && blocks.length > 0) {
  557. var listBlocks = [];
  558. blocks.forEach(function (block) {
  559. if (isList(block.type)) {
  560. listBlocks.push(block);
  561. } else {
  562. if (listBlocks.length > 0) {
  563. var listHtml = getListMarkup(listBlocks, entityMap, hashtagConfig, customEntityTransform); // eslint-disable-line max-len
  564. html.push(listHtml);
  565. listBlocks = [];
  566. }
  567. var blockHtml = getBlockMarkup(block, entityMap, hashtagConfig, directional, customEntityTransform);
  568. html.push(blockHtml);
  569. }
  570. });
  571. if (listBlocks.length > 0) {
  572. var listHtml = getListMarkup(listBlocks, entityMap, hashtagConfig, directional, customEntityTransform); // eslint-disable-line max-len
  573. html.push(listHtml);
  574. listBlocks = [];
  575. }
  576. }
  577. }
  578. return html.join('');
  579. }
  580. return draftToHtml;
  581. })));