msgFormatter.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. var fallback = _parent.trigger +this.text +_parent.trigger;
  333. var formatted = opts.emojiFormatFunction(fallback);
  334. return formatted ? formatted : fallback;
  335. }
  336. var formatted = opts.emojiFormatFunction(this.text);
  337. return formatted ? formatted : this.text;
  338. }
  339. if (this._parent.checkIsCodeBlock())
  340. return this.text.replace(/\n/g, '<br/>'); // TODO syntax highlight
  341. return opts.textFilter(this.text);
  342. };
  343. /**
  344. * @return {string}
  345. **/
  346. MsgTextLeaf.prototype.outerHTML = function() {
  347. var tagName = 'span'
  348. ,classList = []
  349. ,innerHTML
  350. ,params = '';
  351. if (this._parent.checkIsCodeBlock()) {
  352. classList.push('codeblock');
  353. innerHTML = this.innerHTML();
  354. } else if (this._parent.checkIsCode()) {
  355. classList.push('code');
  356. innerHTML = this.innerHTML();
  357. } else {
  358. if (this._parent.isLink) {
  359. var link = opts.linkFilter(this.text);
  360. tagName = 'a';
  361. params = ' href="' +link.link +'"';
  362. if (link.isExternal) {
  363. params += ' target="_blank"';
  364. }
  365. innerHTML = opts.textFilter(link.text);
  366. } else {
  367. innerHTML = this.innerHTML();
  368. }
  369. if (this._parent.checkIsBold())
  370. classList.push('bold');
  371. if (this._parent.checkIsItalic())
  372. classList.push('italic');
  373. if (this._parent.checkIsStrike())
  374. classList.push('strike');
  375. if (this._parent.checkIsEmoji())
  376. classList.push('emoji');
  377. if (this._parent.checkIsHighlight())
  378. classList.push('highlight');
  379. }
  380. return '<' +tagName +params +(classList.length ? ' class="' +classList.join(' ') +'"' : '') +'>' +innerHTML +'</' +tagName +'>';
  381. };
  382. MsgBranch.prototype.outerHTML = function() {
  383. var html = "";
  384. if (this.isQuote)
  385. html += '<span class="quote">';
  386. if (this.isEol)
  387. html += '<br/>';
  388. this.subNodes.forEach(function(node) {
  389. html += node.outerHTML();
  390. });
  391. if (this.isQuote)
  392. html += '</span>';
  393. return html;
  394. };
  395. /** @param {MsgBranch=} _root */
  396. function getFirstUnterminated(_root) {
  397. _root = _root || root;
  398. for (var i =0, nbBranches = _root.subNodes.length; i < nbBranches; i++) {
  399. var branch = _root.subNodes[i];
  400. if (branch instanceof MsgBranch) {
  401. if (!branch.terminated) {
  402. return branch;
  403. } else {
  404. var unTerminatedChild = getFirstUnterminated(branch);
  405. if (unTerminatedChild)
  406. return unTerminatedChild;
  407. }
  408. }
  409. }
  410. return null;
  411. };
  412. /**
  413. * @param {MsgBranch} branch
  414. * @param {boolean} next kill this branch or all the next ones ?
  415. **/
  416. function revertTree(branch, next) {
  417. if (branch._parent instanceof MsgBranch) {
  418. branch._parent.subNodes.splice(branch._parent.subNodes.indexOf(branch) +(next ? 1 : 0));
  419. branch._parent.lastNode = branch._parent.subNodes[branch._parent.subNodes.length -1];
  420. revertTree(branch._parent, true);
  421. }
  422. };
  423. MsgBranch.prototype.implicitClose = function(i) {
  424. if (this.isQuote && !this.terminated) {
  425. this.terminate(i);
  426. }
  427. this.subNodes.forEach(function(node) {
  428. if (node instanceof MsgBranch)
  429. node.implicitClose(i);
  430. });
  431. };
  432. /**
  433. * Try to close the tree.
  434. * If a problem is found, return its index after reverting tree at this position
  435. * @return {number|undefined}
  436. **/
  437. function eof() {
  438. root.implicitClose(text.length);
  439. var unterminated = getFirstUnterminated();
  440. if (unterminated) {
  441. // We have a first token, but never closed
  442. // kill that branch
  443. revertTree(unterminated, false);
  444. // "unterminate" all branch that will be closed in the future
  445. root.cancelTerminate(unterminated.triggerIndex);
  446. // Add a new text leaf containing trigger
  447. var textNode = new MsgTextLeaf(unterminated._parent);
  448. textNode.addChar(unterminated.triggerIndex);
  449. unterminated._parent.subNodes.push(textNode);
  450. unterminated._parent.lastNode = textNode;
  451. // Restart parsing
  452. return unterminated.triggerIndex +1;
  453. } else {
  454. // FIXME merge of same block-branches (opti)
  455. }
  456. };
  457. function identity(a) { return a; }
  458. function linkidentity(str) {
  459. return {
  460. link: str,
  461. text: str,
  462. isInternal: false
  463. };
  464. };
  465. /**
  466. * @param {string} _text
  467. * @param {({
  468. * highlights: (Array<string>|undefined),
  469. * emojiFormatFunction: (function(string):string|undefined),
  470. * textFilter: (function(string):string|undefined)
  471. * })=} _opts
  472. * @return {string}
  473. **/
  474. function _parse(_text, _opts) {
  475. if (!_opts)
  476. _opts = {};
  477. opts.highlights = _opts.highlights || [];
  478. opts.emojiFormatFunction = _opts.emojiFormatFunction || identity;
  479. opts.textFilter = _opts.textFilter || identity;
  480. opts.linkFilter = _opts.linkFilter || linkidentity;
  481. text = _text;
  482. root = new MsgBranch(this, 0);
  483. var i =0,
  484. textLen = text.length;
  485. do {
  486. while (i < textLen)
  487. i += root.addChar(i);
  488. i = eof();
  489. } while (i !== undefined);
  490. return root.outerHTML();
  491. };
  492. return _parse;
  493. })();
  494. window['_formatText'] = function(str, opts) {
  495. return formatText(str, {
  496. highlights: opts ? opts["highlights"] : undefined
  497. });
  498. }
  499. if (typeof module !== "undefined") module.exports.formatText = formatText;