msgFormatter.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /* jshint sub: true */
  2. var formatText = (function() {
  3. /** @type {string} */
  4. var text;
  5. /** @type {MsgBranch} */
  6. var root;
  7. var opts = {
  8. /** @type {Array<string>} */
  9. highlights: [],
  10. /** @type {function(string):string} */
  11. emojiFormatFunction: identity,
  12. /** @type {function(string):string} */
  13. textFilter: identity,
  14. /** @type {function(string):{link: string, text: string}} */
  15. linkFilter: linkidentity
  16. };
  17. /**
  18. * @constructor
  19. * @param {MsgBranch!} _parent
  20. **/
  21. function MsgTextLeaf(_parent) {
  22. /** @type {string} */
  23. this.text = "";
  24. /** @const @type {MsgBranch} */
  25. this._parent = _parent;
  26. }
  27. /**
  28. * @constructor
  29. * @param {MsgBranch} _parent
  30. * @param {number} triggerIndex
  31. * @param {string=} trigger
  32. */
  33. function MsgBranch(_parent, triggerIndex, trigger) {
  34. /** @const @type {number} */
  35. this.triggerIndex = triggerIndex;
  36. /** @type {MsgBranch|MsgTextLeaf|null} */
  37. this.lastNode = null;
  38. /** @type {Array<MsgBranch|MsgTextLeaf>} */
  39. this.subNodes = [ ];
  40. /** @const @type {string} */
  41. this.trigger = trigger || '';
  42. /** @type {boolean} */
  43. this.isLink = this.trigger === '<';
  44. /** @type {boolean} */
  45. this.isBold = this.trigger === '*';
  46. /** @type {boolean} */
  47. this.isItalic = this.trigger === '_';
  48. /** @type {boolean} */
  49. this.isStrike = this.trigger === '~' || this.trigger === '-';
  50. /** @type {boolean} */
  51. this.isQuote = this.trigger === '>' || this.trigger === "&gt;";
  52. /** @type {boolean} */
  53. this.isEmoji = this.trigger === ':';
  54. /** @type {boolean} */
  55. this.isCode = this.trigger === '`';
  56. /** @type {boolean} */
  57. this.isCodeBlock = this.trigger === '```';
  58. /** @type {boolean} */
  59. this.isEol = this.trigger === '\n';
  60. /** @type {boolean} */
  61. this.isHighlight = trigger !== undefined && opts.highlights.indexOf(trigger) !== -1;
  62. /** @const @type {MsgBranch} */
  63. this._parent = _parent;
  64. /** @type {MsgBranch|null} */
  65. this.prevTwin = null;
  66. /** @type {boolean|number} */
  67. this.terminated = this.isEol || this.isHighlight ? (triggerIndex +trigger.length -1) : false;
  68. if (this.isHighlight) {
  69. this.lastNode = new MsgTextLeaf(this);
  70. this.subNodes.push(this.lastNode);
  71. this.lastNode.text = /** @type {string} */ (trigger);
  72. }
  73. }
  74. /** @return {boolean} */
  75. MsgBranch.prototype.checkIsBold = function() {
  76. return (this.isBold && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsBold());
  77. };
  78. /** @return {boolean} */
  79. MsgBranch.prototype.checkIsItalic = function() {
  80. return (this.isItalic && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsItalic());
  81. };
  82. /** @return {boolean} */
  83. MsgBranch.prototype.checkIsStrike = function() {
  84. return (this.isStrike && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsStrike());
  85. };
  86. /** @return {boolean} */
  87. MsgBranch.prototype.checkIsQuote = function() {
  88. return (this.isQuote && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsQuote());
  89. };
  90. /** @return {boolean} */
  91. MsgBranch.prototype.checkIsEmoji = function() {
  92. return (this.isEmoji && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsEmoji());
  93. };
  94. /** @return {boolean} */
  95. MsgBranch.prototype.checkIsHighlight = function() {
  96. return (this.isHighlight && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsHighlight());
  97. };
  98. /** @return {boolean} */
  99. MsgBranch.prototype.checkIsCode = function() {
  100. return (this.isCode && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsCode());
  101. };
  102. /** @return {boolean} */
  103. MsgBranch.prototype.checkIsCodeBlock = function() {
  104. return (this.isCodeBlock && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsCodeBlock());
  105. };
  106. MsgBranch.prototype.containsUnterminatedBranch = function() {
  107. for (var i =0, nbBranches = this.subNodes.length; i < nbBranches; i++) {
  108. if (this.subNodes[i] instanceof MsgBranch && (
  109. !this.subNodes[i].terminated || this.subNodes[i].containsUnterminatedBranch()))
  110. return true;
  111. }
  112. return false;
  113. };
  114. /**
  115. * Check if this token closes the branch
  116. * In this case, finishWith should return the new leave
  117. * Exemple: `_text *bold_ bold continue*` should be
  118. * + root
  119. * | italic
  120. * | "text"
  121. * | bold
  122. * | "bold"
  123. * | bold
  124. * | "bold continue"
  125. * and this function will return a "bold" branch
  126. *
  127. * @param {number} i
  128. * @return {boolean|MsgBranch}
  129. **/
  130. MsgBranch.prototype.finishWith = function(i) {
  131. if (this.trigger === '<' && text[i] === '>')
  132. return true;
  133. var prevIsAlphadec = isAlphadec(text[i -1]);
  134. if (!this.isQuote && text.substr(i, this.trigger.length) === this.trigger) {
  135. if (!prevIsAlphadec && (this.isBold || this.isItalic || this.isStrike)) {
  136. // previous char is not compatible with finishing now
  137. return false;
  138. }
  139. if (this.lastNode && this.containsUnterminatedBranch()) // sub nodes contains at least one branch wich should be replicated
  140. return this.lastNode.makeNewBranchFromThis();
  141. else if (this.hasContent()) // self or any prevTwin has Content
  142. return true;
  143. // else no content, should not be finished now
  144. }
  145. if (text[i] === '\n' && this.isQuote)
  146. return true;
  147. return false;
  148. };
  149. /**
  150. * @return {boolean}
  151. **/
  152. MsgBranch.prototype.hasContent = function() {
  153. var _this = this;
  154. while (_this) {
  155. for (var i = 0, nbNodes = _this.subNodes.length; i < nbNodes; i++)
  156. if (_this.subNodes[i] instanceof MsgBranch || _this.subNodes[i].text.length)
  157. return true;
  158. // self or any prevTwin has Content
  159. _this = _this.prevTwin;
  160. }
  161. return false;
  162. };
  163. /**
  164. * @return {MsgBranch}
  165. **/
  166. MsgBranch.prototype.makeNewBranchFromThis = function() {
  167. var other = new MsgBranch(this._parent, this.triggerIndex, this.trigger);
  168. other.prevTwin = this;
  169. if (this.lastNode && this.lastNode instanceof MsgBranch) {
  170. other.lastNode = this.lastNode.makeNewBranchFromThis();
  171. other.subNodes = [ other.lastNode ];
  172. }
  173. return other;
  174. };
  175. /**
  176. * Check if this token is compatible with this branch
  177. * @param {number} i
  178. * @return {boolean}
  179. **/
  180. MsgBranch.prototype.isAcceptable = function(i) {
  181. if (this.isEmoji && (text[i] === ' ' || text[i] === '\t'))
  182. return false;
  183. if ((this.isEmoji || this.isLink || this.isBold || this.isItalic || this.isStrike || this.isCode) && text[i] === '\n')
  184. return false;
  185. return true;
  186. };
  187. /**
  188. * Check if str[i] is a trigger for a new node
  189. * if true, return the trigger
  190. * @param {number} i
  191. * @return {string|null}
  192. **/
  193. MsgBranch.prototype.isNewToken = function(i) {
  194. if (this.isCode || this.isEmoji || this.isCodeBlock || this.isLink)
  195. return null;
  196. if (!this.lastNode || this.lastNode.terminated || this.lastNode instanceof MsgTextLeaf) {
  197. var prevIsAlphadec = isAlphadec(text[i -1]),
  198. nextIsAlphadec = isAlphadec(text[i +1]);
  199. if (text.substr(i, 3) === '```')
  200. return '```';
  201. if (isBeginingOfLine()) {
  202. if (text.substr(i, 4) === "&gt;")
  203. return "&gt;";
  204. if (text[i] === '>')
  205. return text[i];
  206. }
  207. if ('`' === text[i] && !prevIsAlphadec)
  208. return text[i];
  209. if ('\n' === text[i])
  210. return text[i];
  211. if (['*', '~', '-', '_' ].indexOf(text[i]) !== -1 &&
  212. (nextIsAlphadec || text[i +1] === undefined || ['*', '~', '-', '_', '<', '&'].indexOf(text[i+1]) !== -1) &&
  213. (!prevIsAlphadec || text[i -1] === undefined || ['*', '~', '-', '_', '<', '&'].indexOf(text[i-1]) !== -1))
  214. return text[i];
  215. if ([':'].indexOf(text[i]) !== -1 && nextIsAlphadec)
  216. return text[i];
  217. if (['<'].indexOf(text[i]) !== -1)
  218. return text[i];
  219. for (var highlightIndex =0, nbHighlight =opts.highlights.length; highlightIndex < nbHighlight; highlightIndex++) {
  220. var highlight = opts.highlights[highlightIndex];
  221. if (text.substr(i, highlight.length) === highlight)
  222. return highlight;
  223. }
  224. }
  225. return null;
  226. };
  227. /** @return {boolean|undefined} */
  228. MsgTextLeaf.prototype.isBeginingOfLine = function() {
  229. if (this.text.trim() !== '')
  230. return false;
  231. return undefined;
  232. };
  233. /** @return {boolean|undefined} */
  234. MsgBranch.prototype.isBeginingOfLine = function() {
  235. for (var i = this.subNodes.length -1; i >= 0; i--) {
  236. var isNewLine = this.subNodes[i].isBeginingOfLine();
  237. if (isNewLine !== undefined)
  238. return isNewLine;
  239. }
  240. if (this.isEol || this.isQuote)
  241. return true;
  242. return undefined;
  243. };
  244. /**
  245. * @param {string} c
  246. * @return {boolean}
  247. **/
  248. function isAlphadec(c) {
  249. return (/[A-Za-z0-9àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ+]/).test(c);
  250. /*
  251. return ((c >= 'A' && c <= 'Z') ||
  252. (c >= 'a' && c <= 'z') ||
  253. (c >= '0' && c <= '9') ||
  254. "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ+".indexOf(c) !== -1);
  255. */
  256. }
  257. /** @return {boolean} */
  258. function isBeginingOfLine() {
  259. var isNewLine = root.isBeginingOfLine();
  260. return isNewLine === undefined ? true : isNewLine;
  261. }
  262. /** @return {number} */
  263. MsgTextLeaf.prototype.addChar = function(i) {
  264. this.text += text[i];
  265. return 1;
  266. };
  267. /**
  268. * Parse next char
  269. * @param {number} i
  270. * @return {number}
  271. **/
  272. MsgBranch.prototype.addChar = function(i) {
  273. var isFinished = (this.lastNode && !this.lastNode.terminated && this.lastNode.finishWith) ? this.lastNode.finishWith(i) : null;
  274. if (isFinished) {
  275. var lastTriggerLen = this.lastNode.trigger.length;
  276. this.lastNode.terminate(i);
  277. if (isFinished instanceof MsgBranch) {
  278. this.lastNode = isFinished;
  279. this.subNodes.push(isFinished);
  280. }
  281. return lastTriggerLen;
  282. } else {
  283. if (!this.lastNode || this.lastNode.terminated || this.lastNode instanceof MsgTextLeaf || this.lastNode.isAcceptable(i)) {
  284. var isNewToken = this.isNewToken(i);
  285. if (isNewToken) {
  286. // FIXME if this is a quote and newToken is also a quote, trim lastnode (and remove it if necessary)
  287. this.lastNode = new MsgBranch(this, i, isNewToken);
  288. this.subNodes.push(this.lastNode);
  289. return this.lastNode.trigger.length;
  290. } else {
  291. if (!this.lastNode || this.lastNode.terminated) {
  292. this.lastNode = new MsgTextLeaf(this);
  293. this.subNodes.push(this.lastNode);
  294. }
  295. return this.lastNode.addChar(i);
  296. }
  297. } else {
  298. // last branch child is not compatible with this token.
  299. // So, lastBranch is not a branch
  300. var revertTo = this.lastNode.triggerIndex +1;
  301. root.cancelTerminate(this.lastNode.triggerIndex);
  302. // Add a new "escaped" node to replace trigger
  303. this.lastNode = new MsgTextLeaf(this);
  304. this.lastNode.addChar(revertTo -1); // Add "escaped" trigger
  305. this.subNodes.pop();
  306. this.subNodes.push(this.lastNode);
  307. // return negative value to start parsing again
  308. return revertTo -i;
  309. }
  310. }
  311. };
  312. MsgBranch.prototype.terminate = function(terminateAtIndex) {
  313. var _this = this;
  314. while (_this) {
  315. _this.terminated = terminateAtIndex;
  316. _this = _this.prevTwin;
  317. }
  318. };
  319. /**
  320. * @param {number} unTerminatedIndex
  321. **/
  322. MsgBranch.prototype.cancelTerminate = function(unTerminatedIndex) {
  323. if (this.terminated && this.terminated >= unTerminatedIndex)
  324. this.terminated = false;
  325. this.subNodes.forEach(function(node) {
  326. if (node instanceof MsgBranch) {
  327. node.cancelTerminate(unTerminatedIndex);
  328. }
  329. });
  330. };
  331. /**
  332. * @return {string}
  333. **/
  334. MsgTextLeaf.prototype.innerHTML = function() {
  335. if (this._parent.checkIsEmoji()) {
  336. var _parent = this._parent;
  337. while (_parent && !_parent.isEmoji)
  338. _parent = _parent._parent;
  339. if (_parent) {
  340. var fallback = _parent.trigger +this.text +_parent.trigger;
  341. var formatted = opts.emojiFormatFunction(fallback);
  342. return formatted ? formatted : fallback;
  343. }
  344. var _formatted = opts.emojiFormatFunction(this.text);
  345. return _formatted ? _formatted : this.text;
  346. }
  347. if (this._parent.checkIsCodeBlock()) {
  348. if (typeof hljs !== "undefined") {
  349. try {
  350. var lang = this.text.match(/^\w+/);
  351. hljs.configure({
  352. "useBR": true,
  353. "tabReplace": "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",
  354. });
  355. if (lang && hljs.getLanguage(lang[0]))
  356. return hljs.fixMarkup(hljs.highlight(lang[0], this.text.substr(lang[0].length)).value);
  357. return hljs.fixMarkup(hljs.highlightAuto(this.text).value);
  358. } catch (e) {
  359. console.error(e);
  360. }
  361. }
  362. return this.text.replace(/\n/g, '<br/>');
  363. }
  364. return opts.textFilter(this.text);
  365. };
  366. /**
  367. * @return {string}
  368. **/
  369. MsgTextLeaf.prototype.outerHTML = function() {
  370. var tagName = 'span',
  371. classList = [],
  372. innerHTML,
  373. params = '';
  374. if (this._parent.checkIsCodeBlock()) {
  375. tagName = "pre";
  376. classList.push('codeblock');
  377. innerHTML = this.innerHTML();
  378. } else if (this._parent.checkIsCode()) {
  379. classList.push('code');
  380. innerHTML = this.innerHTML();
  381. } else {
  382. var link;
  383. if (this._parent.isLink && (link = opts.linkFilter(this.text))) {
  384. tagName = 'a';
  385. params = ' href="' +link.link +'"';
  386. if (link.style)
  387. params += ' style="' +link.style +'"';
  388. if (!link.isInternal)
  389. params += ' target="_blank"';
  390. if (link.classes)
  391. link.classes.forEach(function(i) {
  392. classList.push(i);
  393. });
  394. innerHTML = opts.textFilter(link.text);
  395. } else {
  396. innerHTML = this.innerHTML();
  397. }
  398. if (this._parent.checkIsBold())
  399. classList.push('bold');
  400. if (this._parent.checkIsItalic())
  401. classList.push('italic');
  402. if (this._parent.checkIsStrike())
  403. classList.push('strike');
  404. if (this._parent.checkIsEmoji())
  405. classList.push('emoji');
  406. if (this._parent.checkIsHighlight())
  407. classList.push('highlight');
  408. }
  409. return '<' +tagName +params +(classList.length ? ' class="' +classList.join(' ') +'"' : '') +'>' +innerHTML +'</' +tagName +'>';
  410. };
  411. MsgBranch.prototype.outerHTML = function() {
  412. var html = "";
  413. if (this.isQuote)
  414. html += '<span class="quote">';
  415. if (this.isEol)
  416. html += '<br/>';
  417. this.subNodes.forEach(function(node) {
  418. html += node.outerHTML();
  419. });
  420. if (this.isQuote)
  421. html += '</span>';
  422. return html;
  423. };
  424. /** @param {MsgBranch=} _root */
  425. function getFirstUnterminated(_root) {
  426. _root = _root || root;
  427. for (var i =0, nbBranches = _root.subNodes.length; i < nbBranches; i++) {
  428. var branch = _root.subNodes[i];
  429. if (branch instanceof MsgBranch) {
  430. if (!branch.terminated) {
  431. return branch;
  432. } else {
  433. var unTerminatedChild = getFirstUnterminated(branch);
  434. if (unTerminatedChild)
  435. return unTerminatedChild;
  436. }
  437. }
  438. }
  439. return null;
  440. }
  441. /**
  442. * @param {MsgBranch} branch
  443. * @param {boolean} next kill this branch or all the next ones ?
  444. **/
  445. function revertTree(branch, next) {
  446. if (branch._parent instanceof MsgBranch) {
  447. branch._parent.subNodes.splice(branch._parent.subNodes.indexOf(branch) +(next ? 1 : 0));
  448. branch._parent.lastNode = branch._parent.subNodes[branch._parent.subNodes.length -1];
  449. revertTree(branch._parent, true);
  450. }
  451. }
  452. MsgBranch.prototype.implicitClose = function(i) {
  453. if (this.isQuote && !this.terminated) {
  454. this.terminate(i);
  455. }
  456. this.subNodes.forEach(function(node) {
  457. if (node instanceof MsgBranch)
  458. node.implicitClose(i);
  459. });
  460. };
  461. /**
  462. * Try to close the tree.
  463. * If a problem is found, return its index after reverting tree at this position
  464. * @return {number|undefined}
  465. **/
  466. function eof() {
  467. root.implicitClose(text.length);
  468. var unterminated = getFirstUnterminated();
  469. if (unterminated) {
  470. // We have a first token, but never closed
  471. // kill that branch
  472. revertTree(unterminated, false);
  473. // "unterminate" all branch that will be closed in the future
  474. root.cancelTerminate(unterminated.triggerIndex);
  475. // Add a new text leaf containing trigger
  476. var textNode = new MsgTextLeaf(unterminated._parent);
  477. textNode.addChar(unterminated.triggerIndex);
  478. unterminated._parent.subNodes.push(textNode);
  479. unterminated._parent.lastNode = textNode;
  480. // Restart parsing
  481. return unterminated.triggerIndex +1;
  482. } else {
  483. // FIXME merge of same block-branches (opti)
  484. }
  485. }
  486. function htmlEntities(str) { return str.replace('<', "&lt;"); }
  487. function identity(a) { return a; }
  488. function linkidentity(str) {
  489. return {
  490. link: str,
  491. text: str,
  492. isInternal: false
  493. };
  494. }
  495. /**
  496. * @param {string} _text
  497. * @param {({
  498. * highlights: (Array<string>|undefined),
  499. * emojiFormatFunction: (function(string):string|undefined),
  500. * textFilter: (function(string):string|undefined)
  501. * })=} _opts
  502. * @return {string}
  503. **/
  504. function _parse(_text, _opts) {
  505. if (!_opts)
  506. _opts = {};
  507. opts.highlights = _opts.highlights || [];
  508. opts.emojiFormatFunction = _opts.emojiFormatFunction || identity;
  509. opts.textFilter = _opts.textFilter || htmlEntities;
  510. opts.linkFilter = _opts.linkFilter || linkidentity;
  511. text = _text;
  512. root = new MsgBranch(this, 0);
  513. var i =0,
  514. textLen = text.length;
  515. do {
  516. while (i < textLen)
  517. i += root.addChar(i);
  518. i = eof();
  519. } while (i !== undefined);
  520. return root.outerHTML();
  521. }
  522. return _parse;
  523. })();
  524. if (typeof module !== "undefined") module.exports.formatText = formatText;