msgFormatter.js 20 KB

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