msgFormatter.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // FIXME eol and quote ( > ) with quote level
  2. /** @type {function(string):string} */
  3. var formatText = (function() {
  4. /**
  5. * @param {string} c
  6. * @return {boolean}
  7. **/
  8. function isAlphadec(c) {
  9. return ((c >= 'A' && c <= 'Z') ||
  10. (c >= 'a' && c <= 'z') ||
  11. (c >= '0' && c <= '9') ||
  12. "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ".indexOf(c) !== -1);
  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|MsgTree} _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 === '>';
  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. /** @const @type {MsgBranch|MsgTree} */
  58. this._parent = _parent;
  59. /** @type {MsgBranch|null} */
  60. this.prevTwin = null;
  61. /** @type {boolean|number} */
  62. this.terminated = false;
  63. }
  64. /** @return {boolean} */
  65. MsgBranch.prototype.checkIsBold = function() {
  66. return (this.isBold && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsBold());
  67. };
  68. /** @return {boolean} */
  69. MsgBranch.prototype.checkIsItalic = function() {
  70. return (this.isItalic && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsItalic());
  71. };
  72. /** @return {boolean} */
  73. MsgBranch.prototype.checkIsStrike = function() {
  74. return (this.isStrike && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsStrike());
  75. };
  76. /** @return {boolean} */
  77. MsgBranch.prototype.checkIsQuote = function() {
  78. return (this.isQuote && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsQuote());
  79. };
  80. /** @return {boolean} */
  81. MsgBranch.prototype.checkIsEmoji = function() {
  82. return (this.isEmoji && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsEmoji());
  83. };
  84. /** @return {boolean} */
  85. MsgBranch.prototype.checkIsCode = function() {
  86. return (this.isCode && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsCode());
  87. };
  88. /** @return {boolean} */
  89. MsgBranch.prototype.checkIsCodeBlock = function() {
  90. return (this.isCodeBlock && !!this.terminated) || (this._parent instanceof MsgBranch && this._parent.checkIsCodeBlock());
  91. };
  92. MsgBranch.prototype.containsUnterminatedBranch = function() {
  93. for (var i =0, nbBranches = this.subNodes.length; i < nbBranches; i++) {
  94. if (this.subNodes[i] instanceof MsgBranch && (
  95. !this.subNodes[i].terminated || this.subNodes[i].containsUnterminatedBranch()))
  96. return true;
  97. }
  98. return false;
  99. };
  100. /**
  101. * Check if this token closes the branch
  102. * In this case, finishWith should return the new leave
  103. * Exemple: `_text *bold_ bold continue*` should be
  104. * + root
  105. * | italic
  106. * | "text"
  107. * | bold
  108. * | "bold"
  109. * | bold
  110. * | "bold continue"
  111. * and this function will return a "bold" branch
  112. *
  113. * @param {string} str
  114. * @param {number} i
  115. * @return {boolean|MsgBranch}
  116. **/
  117. MsgBranch.prototype.finishWith = function(str, i) {
  118. if (this.trigger === '<' && str[i] === '>')
  119. return true;
  120. if (str.substr(i, this.trigger.length) === this.trigger) {
  121. if (this.lastNode && this.containsUnterminatedBranch()) // sub nodes contains at least one branch wich should be replicated
  122. return this.lastNode.makeNewBranchFromThis();
  123. else if (this.hasContent()) // self or any prevTwin has Content
  124. return true;
  125. // else no content, should not be finished now
  126. }
  127. return false;
  128. };
  129. /**
  130. * @return {boolean}
  131. **/
  132. MsgBranch.prototype.hasContent = function() {
  133. var _this = this;
  134. while (_this) {
  135. for (var i = 0, nbNodes = _this.subNodes.length; i < nbNodes; i++)
  136. if (_this.subNodes[i] instanceof MsgBranch || _this.subNodes[i].text.length)
  137. return true;
  138. // self or any prevTwin has Content
  139. _this = _this.prevTwin;
  140. }
  141. return false;
  142. };
  143. /**
  144. * @return {MsgBranch}
  145. **/
  146. MsgBranch.prototype.makeNewBranchFromThis = function() {
  147. var other = new MsgBranch(this._parent, this.triggerIndex, this.trigger);
  148. other.prevTwin = this;
  149. if (this.lastNode && this.lastNode instanceof MsgBranch) {
  150. other.lastNode = this.lastNode.makeNewBranchFromThis();
  151. other.subNodes = [ other.lastNode ];
  152. }
  153. return other;
  154. };
  155. /**
  156. * Check if this token is compatible with this branch
  157. * @param {string} str
  158. * @param {number} i
  159. * @return {boolean}
  160. **/
  161. MsgBranch.prototype.isAcceptable = function(str, i) {
  162. if (this.isEmoji && (str[i] === ' ' || str[i] === '\t'))
  163. return false;
  164. if ((this.isEmoji || this.isLink || this.isBold || this.isItalic || this.isStrike || this.isCode) &&
  165. str[i] === '\n')
  166. return false;
  167. return true;
  168. };
  169. /**
  170. * Check if str[i] is a trigger for a new node
  171. * if true, return the trigger
  172. * @param {string} str
  173. * @param {number} i
  174. * @return {string|null}
  175. **/
  176. MsgBranch.prototype.isNewToken = function(str, i) {
  177. if (this.isCode || this.isCodeBlock || this.isEmoji)
  178. return null;
  179. if (!this.lastNode || this.lastNode instanceof MsgTextLeaf) {
  180. var nextIsAlphadec = isAlphadec(str[i +1]);
  181. if (str.substr(i, 3) === '```')
  182. return '```';
  183. if (['`', '\n'].indexOf(str[i]) !== -1)
  184. return str[i];
  185. if (['*', '~', '-', '_' ].indexOf(str[i]) !== -1 && (nextIsAlphadec || ['*', '`', '~', '-', '_', ':', '<'].indexOf(str[i+1]) !== -1))
  186. return str[i];
  187. if ([':', '<'].indexOf(str[i]) !== -1 && nextIsAlphadec)
  188. return str[i];
  189. }
  190. return null;
  191. };
  192. /** @return {number} */
  193. MsgTextLeaf.prototype.addChar = function(str, i) {
  194. this.text += str[i];
  195. return 1;
  196. };
  197. /**
  198. * Parse next char
  199. * @param {string} str
  200. * @param {number} i
  201. * @return {number}
  202. **/
  203. MsgBranch.prototype.addChar = function(str, i) {
  204. var isFinished = (this.lastNode && this.lastNode.finishWith) ? this.lastNode.finishWith(str, i) : null;
  205. if (isFinished) {
  206. var lastTriggerLen = this.lastNode.trigger.length;
  207. this.lastNode.terminate(this.lastNode.triggerIndex, i);
  208. if (isFinished instanceof MsgBranch) {
  209. this.lastNode = isFinished;
  210. this.subNodes.push(isFinished);
  211. }
  212. return lastTriggerLen;
  213. } else {
  214. if (!this.lastNode || this.lastNode.terminated || this.lastNode instanceof MsgTextLeaf || this.lastNode.isAcceptable(str, i)) {
  215. var isNewToken = this.isNewToken(str, i);
  216. if (isNewToken) {
  217. this.lastNode = new MsgBranch(this, i, isNewToken);
  218. this.subNodes.push(this.lastNode);
  219. return this.lastNode.trigger.length;
  220. } else {
  221. if (!this.lastNode || this.lastNode.terminated) {
  222. this.lastNode = new MsgTextLeaf(this);
  223. this.subNodes.push(this.lastNode);
  224. }
  225. return this.lastNode.addChar(str, i);
  226. }
  227. } else {
  228. // last branch child is not compatible with this token.
  229. // So, lastBranch is not a branch
  230. var revertTo = this.lastNode.triggerIndex +1;
  231. this.getRoot().cancelTerminate(this.lastNode.triggerIndex);
  232. // Add a new "escaped" node to replace trigger
  233. this.lastNode = new MsgTextLeaf(this);
  234. this.lastNode.addChar(str, revertTo -1); // Add "escaped" trigger
  235. this.subNodes.pop();
  236. this.subNodes.push(this.lastNode);
  237. // return negative value to start parsing again
  238. return revertTo -i;
  239. }
  240. }
  241. };
  242. MsgBranch.prototype.terminate = function(triggerIndex, terminateAtIndex) {
  243. var _this = this;
  244. while (_this) {
  245. _this.terminated = terminateAtIndex;
  246. _this = _this.prevTwin;
  247. }
  248. };
  249. MsgBranch.prototype.getRoot = function() {
  250. var branch = this;
  251. while (branch._parent && branch._parent instanceof MsgBranch)
  252. branch = branch._parent;
  253. return branch;
  254. };
  255. /**
  256. * @param {number} unTerminatedIndex
  257. **/
  258. MsgBranch.prototype.cancelTerminate = function(unTerminatedIndex) {
  259. if (this.terminated && this.terminated >= unTerminatedIndex)
  260. this.terminated = false;
  261. this.subNodes.forEach(function(node) {
  262. if (node instanceof MsgBranch) {
  263. node.cancelTerminate(unTerminatedIndex);
  264. }
  265. });
  266. };
  267. /**
  268. * @return {string}
  269. **/
  270. MsgTextLeaf.prototype.innerHTML = function() {
  271. return this._parent.checkIsEmoji() ? (':' +this.text +':') : (this.text);
  272. };
  273. /**
  274. * @return {string}
  275. **/
  276. MsgTextLeaf.prototype.outerHTML = function() {
  277. var tagName = 'span'
  278. ,classList = [];
  279. if (this._parent.checkIsCodeBlock()) {
  280. // TODO syntax highlight
  281. classList.push('codeblock');
  282. } else if (this._parent.checkIsCode()) {
  283. classList.push('code');
  284. } else {
  285. if (this.isLink)
  286. tagName = 'a';
  287. if (this._parent.checkIsBold())
  288. classList.push('bold');
  289. if (this._parent.checkIsItalic())
  290. classList.push('italic');
  291. if (this._parent.checkIsStrike())
  292. classList.push('strike');
  293. if (this._parent.checkIsEmoji())
  294. classList.push('emoji'); // FIXME emoji
  295. }
  296. return '<' +tagName +(classList.length ? ' class="' +classList.join(' ') +'"' : '') +'>' +this.innerHTML() +'</' +tagName +'>';
  297. };
  298. MsgBranch.prototype.outerHTML = function() {
  299. var html = "";
  300. if (this.isQuote) {
  301. html += '<span class="quote">';
  302. }
  303. this.subNodes.forEach(function(node) {
  304. html += node.outerHTML();
  305. });
  306. if (this.isQuote) {
  307. html += '</span>';
  308. }
  309. return html;
  310. };
  311. /**
  312. * @constructor
  313. * @param {string} text
  314. */
  315. function MsgTree(text) {
  316. /** @const @type {string} */
  317. this.text = text;
  318. /** @type {MsgBranch|null} */
  319. this.root = null;
  320. }
  321. MsgTree.prototype.parseFrom = function(i) {
  322. for (var textLen = this.text.length; i < textLen;)
  323. i += this.root.addChar(this.text, i);
  324. this.eof();
  325. };
  326. MsgTree.prototype.parse = function() {
  327. this.root = new MsgBranch(this, 0);
  328. this.parseFrom(0);
  329. };
  330. /** @param {MsgBranch} root */
  331. MsgTree.prototype.getFirstUnterminated = function(root) {
  332. for (var i =0, nbBranches = root.subNodes.length; i < nbBranches; i++) {
  333. var branch = root.subNodes[i];
  334. if (branch instanceof MsgBranch) {
  335. if (!branch.terminated) {
  336. return branch;
  337. } else {
  338. var unTerminatedChild = this.getFirstUnterminated(branch);
  339. if (unTerminatedChild)
  340. return unTerminatedChild;
  341. }
  342. }
  343. }
  344. return null;
  345. };
  346. /**
  347. * @param {MsgBranch} branch
  348. * @param {boolean} next kill this branch or all the next ones ?
  349. **/
  350. MsgTree.prototype.revertTree = function(branch, next) {
  351. if (branch._parent instanceof MsgBranch) {
  352. branch._parent.subNodes.splice(branch._parent.subNodes.indexOf(branch) +(next ? 1 : 0));
  353. branch._parent.lastNode = branch._parent.subNodes[branch._parent.subNodes.length -1];
  354. this.revertTree(branch._parent, true);
  355. }
  356. };
  357. MsgTree.prototype.eof = function() {
  358. var unterminated = this.getFirstUnterminated(this.root);
  359. if (unterminated) {
  360. // We have a first token, but never closed
  361. // kill that branch
  362. this.revertTree(unterminated, false);
  363. // "unterminate" all branch that will be closed in the future
  364. this.root.cancelTerminate(unterminated.triggerIndex);
  365. // Add a new text leaf containing trigger
  366. var textNode = new MsgTextLeaf(unterminated._parent);
  367. textNode.addChar(this.text, unterminated.triggerIndex);
  368. unterminated._parent.subNodes.push(textNode);
  369. unterminated._parent.lastNode = textNode;
  370. // Restart parsing
  371. this.parseFrom(unterminated.triggerIndex +1);
  372. }
  373. // Else no problem
  374. };
  375. /**
  376. * @return {string}
  377. **/
  378. MsgTree.prototype.toHTML = function() {
  379. return this.root ? this.root.outerHTML() : "";
  380. };
  381. return function(text) {
  382. var root = new MsgTree(text);
  383. root.parse();
  384. return (root.toHTML());
  385. };
  386. })();
  387. if (typeof module !== "undefined") module.exports.formatText = formatText;