msgFormatter.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 nextIsAlphadec = isAlphadec(text[i +1]);
  197. if (text.substr(i, 3) === '```')
  198. return '```';
  199. if (isBeginingOfLine()) {
  200. if (text.substr(i, 4) === "&gt;")
  201. return "&gt;";
  202. if (text[i] === '>')
  203. return text[i];
  204. }
  205. if (['`', '\n'].indexOf(text[i]) !== -1)
  206. return text[i];
  207. if (['*', '~', '-', '_' ].indexOf(text[i]) !== -1 && (nextIsAlphadec || ['*', '~', '-', '_', '<', '&'].indexOf(text[i+1]) !== -1))
  208. return text[i];
  209. if ([':'].indexOf(text[i]) !== -1 && nextIsAlphadec)
  210. return text[i];
  211. if (['<'].indexOf(text[i]) !== -1)
  212. return text[i];
  213. for (var highlightIndex =0, nbHighlight =opts.highlights.length; highlightIndex < nbHighlight; highlightIndex++) {
  214. var highlight = opts.highlights[highlightIndex];
  215. // TODO compare with collators
  216. if (text.substr(i, highlight.length) === highlight)
  217. return highlight;
  218. }
  219. }
  220. return null;
  221. };
  222. /** @return {boolean|undefined} */
  223. MsgTextLeaf.prototype.isBeginingOfLine = function() {
  224. if (this.text.trim() !== '')
  225. return false;
  226. return undefined;
  227. };
  228. /** @return {boolean|undefined} */
  229. MsgBranch.prototype.isBeginingOfLine = function() {
  230. for (var i = this.subNodes.length -1; i >= 0; i--) {
  231. var isNewLine = this.subNodes[i].isBeginingOfLine();
  232. if (isNewLine !== undefined)
  233. return isNewLine;
  234. }
  235. if (this.isEol || this.isQuote)
  236. return true;
  237. return undefined;
  238. };
  239. /**
  240. * @param {string} c
  241. * @return {boolean}
  242. **/
  243. function isAlphadec(c) {
  244. return ((c >= 'A' && c <= 'Z') ||
  245. (c >= 'a' && c <= 'z') ||
  246. (c >= '0' && c <= '9') ||
  247. "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ".indexOf(c) !== -1);
  248. }
  249. /** @return {boolean} */
  250. function isBeginingOfLine() {
  251. var isNewLine = root.isBeginingOfLine();
  252. return isNewLine === undefined ? true : isNewLine;
  253. };
  254. /** @return {number} */
  255. MsgTextLeaf.prototype.addChar = function(i) {
  256. this.text += text[i];
  257. return 1;
  258. };
  259. /**
  260. * Parse next char
  261. * @param {number} i
  262. * @return {number}
  263. **/
  264. MsgBranch.prototype.addChar = function(i) {
  265. var isFinished = (this.lastNode && !this.lastNode.terminated && this.lastNode.finishWith) ? this.lastNode.finishWith(i) : null;
  266. if (isFinished) {
  267. var lastTriggerLen = this.lastNode.trigger.length;
  268. this.lastNode.terminate(i);
  269. if (isFinished instanceof MsgBranch) {
  270. this.lastNode = isFinished;
  271. this.subNodes.push(isFinished);
  272. }
  273. return lastTriggerLen;
  274. } else {
  275. if (!this.lastNode || this.lastNode.terminated || this.lastNode instanceof MsgTextLeaf || this.lastNode.isAcceptable(i)) {
  276. var isNewToken = this.isNewToken(i);
  277. if (isNewToken) {
  278. // FIXME if this is a quote and newToken is also a quote, trim lastnode (and remove it if necessary)
  279. this.lastNode = new MsgBranch(this, i, isNewToken);
  280. this.subNodes.push(this.lastNode);
  281. return this.lastNode.trigger.length;
  282. } else {
  283. if (!this.lastNode || this.lastNode.terminated) {
  284. this.lastNode = new MsgTextLeaf(this);
  285. this.subNodes.push(this.lastNode);
  286. }
  287. return this.lastNode.addChar(i);
  288. }
  289. } else {
  290. // last branch child is not compatible with this token.
  291. // So, lastBranch is not a branch
  292. var revertTo = this.lastNode.triggerIndex +1;
  293. root.cancelTerminate(this.lastNode.triggerIndex);
  294. // Add a new "escaped" node to replace trigger
  295. this.lastNode = new MsgTextLeaf(this);
  296. this.lastNode.addChar(revertTo -1); // Add "escaped" trigger
  297. this.subNodes.pop();
  298. this.subNodes.push(this.lastNode);
  299. // return negative value to start parsing again
  300. return revertTo -i;
  301. }
  302. }
  303. };
  304. MsgBranch.prototype.terminate = function(terminateAtIndex) {
  305. var _this = this;
  306. while (_this) {
  307. _this.terminated = terminateAtIndex;
  308. _this = _this.prevTwin;
  309. }
  310. };
  311. /**
  312. * @param {number} unTerminatedIndex
  313. **/
  314. MsgBranch.prototype.cancelTerminate = function(unTerminatedIndex) {
  315. if (this.terminated && this.terminated >= unTerminatedIndex)
  316. this.terminated = false;
  317. this.subNodes.forEach(function(node) {
  318. if (node instanceof MsgBranch) {
  319. node.cancelTerminate(unTerminatedIndex);
  320. }
  321. });
  322. };
  323. /**
  324. * @return {string}
  325. **/
  326. MsgTextLeaf.prototype.innerHTML = function() {
  327. if (this._parent.checkIsEmoji()) {
  328. var _parent = this._parent;
  329. while (_parent && !_parent.isEmoji)
  330. _parent = _parent._parent;
  331. if (_parent)
  332. return opts.emojiFormatFunction(_parent.trigger +this.text +_parent.trigger);
  333. return opts.emojiFormatFunction(this.text);
  334. }
  335. if (this._parent.checkIsCodeBlock())
  336. return this.text.replace(/\n/g, '<br/>'); // TODO syntax highlight
  337. return opts.textFilter(this.text);
  338. };
  339. /**
  340. * @return {string}
  341. **/
  342. MsgTextLeaf.prototype.outerHTML = function() {
  343. var tagName = 'span'
  344. ,classList = []
  345. ,innerHTML
  346. ,params = '';
  347. if (this._parent.checkIsCodeBlock()) {
  348. classList.push('codeblock');
  349. innerHTML = this.innerHTML();
  350. } else if (this._parent.checkIsCode()) {
  351. classList.push('code');
  352. innerHTML = this.innerHTML();
  353. } else {
  354. if (this._parent.isLink) {
  355. var link = opts.linkFilter(this.text);
  356. tagName = 'a';
  357. params = ' href="' +link.link +'"';
  358. if (link.isExternal) {
  359. params += ' target="_blank"';
  360. }
  361. innerHTML = opts.textFilter(link.text);
  362. } else {
  363. innerHTML = this.innerHTML();
  364. }
  365. if (this._parent.checkIsBold())
  366. classList.push('bold');
  367. if (this._parent.checkIsItalic())
  368. classList.push('italic');
  369. if (this._parent.checkIsStrike())
  370. classList.push('strike');
  371. if (this._parent.checkIsEmoji())
  372. classList.push('emoji');
  373. if (this._parent.checkIsHighlight())
  374. classList.push('highlight');
  375. }
  376. return '<' +tagName +params +(classList.length ? ' class="' +classList.join(' ') +'"' : '') +'>' +innerHTML +'</' +tagName +'>';
  377. };
  378. MsgBranch.prototype.outerHTML = function() {
  379. var html = "";
  380. if (this.isQuote)
  381. html += '<span class="quote">';
  382. if (this.isEol)
  383. html += '<br/>';
  384. this.subNodes.forEach(function(node) {
  385. html += node.outerHTML();
  386. });
  387. if (this.isQuote)
  388. html += '</span>';
  389. return html;
  390. };
  391. /** @param {MsgBranch=} _root */
  392. function getFirstUnterminated(_root) {
  393. _root = _root || root;
  394. for (var i =0, nbBranches = _root.subNodes.length; i < nbBranches; i++) {
  395. var branch = _root.subNodes[i];
  396. if (branch instanceof MsgBranch) {
  397. if (!branch.terminated) {
  398. return branch;
  399. } else {
  400. var unTerminatedChild = getFirstUnterminated(branch);
  401. if (unTerminatedChild)
  402. return unTerminatedChild;
  403. }
  404. }
  405. }
  406. return null;
  407. };
  408. /**
  409. * @param {MsgBranch} branch
  410. * @param {boolean} next kill this branch or all the next ones ?
  411. **/
  412. function revertTree(branch, next) {
  413. if (branch._parent instanceof MsgBranch) {
  414. branch._parent.subNodes.splice(branch._parent.subNodes.indexOf(branch) +(next ? 1 : 0));
  415. branch._parent.lastNode = branch._parent.subNodes[branch._parent.subNodes.length -1];
  416. revertTree(branch._parent, true);
  417. }
  418. };
  419. MsgBranch.prototype.implicitClose = function(i) {
  420. if (this.isQuote && !this.terminated) {
  421. this.terminate(i);
  422. }
  423. this.subNodes.forEach(function(node) {
  424. if (node instanceof MsgBranch)
  425. node.implicitClose(i);
  426. });
  427. };
  428. /**
  429. * Try to close the tree.
  430. * If a problem is found, return its index after reverting tree at this position
  431. * @return {number|undefined}
  432. **/
  433. function eof() {
  434. root.implicitClose(text.length);
  435. var unterminated = getFirstUnterminated();
  436. if (unterminated) {
  437. // We have a first token, but never closed
  438. // kill that branch
  439. revertTree(unterminated, false);
  440. // "unterminate" all branch that will be closed in the future
  441. root.cancelTerminate(unterminated.triggerIndex);
  442. // Add a new text leaf containing trigger
  443. var textNode = new MsgTextLeaf(unterminated._parent);
  444. textNode.addChar(unterminated.triggerIndex);
  445. unterminated._parent.subNodes.push(textNode);
  446. unterminated._parent.lastNode = textNode;
  447. // Restart parsing
  448. return unterminated.triggerIndex +1;
  449. } else {
  450. // FIXME merge of same block-branches (opti)
  451. }
  452. };
  453. function identity(a) { return a; }
  454. function linkidentity(str) {
  455. return {
  456. link: str,
  457. text: str,
  458. isInternal: false
  459. };
  460. };
  461. /**
  462. * @param {string} _text
  463. * @param {({
  464. * highlights: (Array<string>|undefined),
  465. * emojiFormatFunction: (function(string):string|undefined),
  466. * textFilter: (function(string):string|undefined)
  467. * })=} _opts
  468. * @return {string}
  469. **/
  470. function _parse(_text, _opts) {
  471. if (!_opts)
  472. _opts = {};
  473. opts.highlights = _opts.highlights || [];
  474. opts.emojiFormatFunction = _opts.emojiFormatFunction || identity;
  475. opts.textFilter = _opts.textFilter || identity;
  476. opts.linkFilter = _opts.linkFilter || linkidentity;
  477. text = _text;
  478. root = new MsgBranch(this, 0);
  479. var i =0,
  480. textLen = text.length;
  481. do {
  482. while (i < textLen)
  483. i += root.addChar(i);
  484. i = eof();
  485. } while (i !== undefined);
  486. return root.outerHTML();
  487. };
  488. return _parse;
  489. })();
  490. window['_formatText'] = function(str, opts) {
  491. return formatText(str, {
  492. highlights: opts ? opts["highlights"] : undefined
  493. });
  494. }
  495. if (typeof module !== "undefined") module.exports.formatText = formatText;