msgFormatter.js 18 KB

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