msgFormatter.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 === '>' || 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. /** @const @type {MsgBranch|MsgTree} */
  58. this._parent = _parent;
  59. /** @type {MsgBranch|null} */
  60. this.prevTwin = null;
  61. /** @type {boolean|number} */
  62. this.terminated = this.isEol ? triggerIndex : 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. if (str[i] === '\n' && this.isEol)
  128. return true;
  129. return false;
  130. };
  131. /**
  132. * @return {boolean}
  133. **/
  134. MsgBranch.prototype.hasContent = function() {
  135. var _this = this;
  136. while (_this) {
  137. for (var i = 0, nbNodes = _this.subNodes.length; i < nbNodes; i++)
  138. if (_this.subNodes[i] instanceof MsgBranch || _this.subNodes[i].text.length)
  139. return true;
  140. // self or any prevTwin has Content
  141. _this = _this.prevTwin;
  142. }
  143. return false;
  144. };
  145. /**
  146. * @return {MsgBranch}
  147. **/
  148. MsgBranch.prototype.makeNewBranchFromThis = function() {
  149. var other = new MsgBranch(this._parent, this.triggerIndex, this.trigger);
  150. other.prevTwin = this;
  151. if (this.lastNode && this.lastNode instanceof MsgBranch) {
  152. other.lastNode = this.lastNode.makeNewBranchFromThis();
  153. other.subNodes = [ other.lastNode ];
  154. }
  155. return other;
  156. };
  157. /**
  158. * Check if this token is compatible with this branch
  159. * @param {string} str
  160. * @param {number} i
  161. * @return {boolean}
  162. **/
  163. MsgBranch.prototype.isAcceptable = function(str, i) {
  164. if (this.isEmoji && (str[i] === ' ' || str[i] === '\t'))
  165. return false;
  166. if ((this.isEmoji || this.isLink || this.isBold || this.isItalic || this.isStrike || this.isCode) &&
  167. str[i] === '\n')
  168. return false;
  169. return true;
  170. };
  171. /**
  172. * Check if str[i] is a trigger for a new node
  173. * if true, return the trigger
  174. * @param {string} str
  175. * @param {number} i
  176. * @return {string|null}
  177. **/
  178. MsgBranch.prototype.isNewToken = function(str, i) {
  179. if (this.isCode || this.isEmoji || this.isCodeBlock)
  180. return null;
  181. if (!this.lastNode || this.lastNode.terminated || this.lastNode instanceof MsgTextLeaf) {
  182. var nextIsAlphadec = isAlphadec(str[i +1])
  183. ,prevIsAlphadec = isAlphadec(str[i -1]);
  184. if (str.substr(i, 3) === '```')
  185. return '```';
  186. if (str.substr(i, 4) === "&gt;") // FIXME AND begining of line OR begining of QUOTED
  187. return "&gt;";
  188. if (str[i] === '>') // FIXME AND begining of line OR begining of QUOTED
  189. return str[i];
  190. if (['`', '\n'].indexOf(str[i]) !== -1)
  191. return str[i];
  192. if (['*', '~', '-', '_' ].indexOf(str[i]) !== -1 && (nextIsAlphadec || ['*', '~', '-', '_', '<', '&'].indexOf(str[i+1]) !== -1))
  193. return str[i];
  194. if ([':', '<'].indexOf(str[i]) !== -1 && nextIsAlphadec)
  195. return str[i];
  196. }
  197. return null;
  198. };
  199. /** @return {number} */
  200. MsgTextLeaf.prototype.addChar = function(str, i) {
  201. this.text += str[i];
  202. return 1;
  203. };
  204. /**
  205. * Parse next char
  206. * @param {string} str
  207. * @param {number} i
  208. * @return {number}
  209. **/
  210. MsgBranch.prototype.addChar = function(str, i) {
  211. var isFinished = (this.lastNode && this.lastNode.finishWith) ? this.lastNode.finishWith(str, i) : null;
  212. if (isFinished) {
  213. var lastTriggerLen = this.lastNode.trigger.length;
  214. this.lastNode.terminate(this.lastNode.triggerIndex, i);
  215. if (isFinished instanceof MsgBranch) {
  216. this.lastNode = isFinished;
  217. this.subNodes.push(isFinished);
  218. }
  219. return lastTriggerLen;
  220. } else {
  221. if (!this.lastNode || this.lastNode.terminated || this.lastNode instanceof MsgTextLeaf || this.lastNode.isAcceptable(str, i)) {
  222. var isNewToken = this.isNewToken(str, i);
  223. if (isNewToken) {
  224. this.lastNode = new MsgBranch(this, i, isNewToken);
  225. this.subNodes.push(this.lastNode);
  226. return this.lastNode.trigger.length;
  227. } else {
  228. if (!this.lastNode || this.lastNode.terminated) {
  229. this.lastNode = new MsgTextLeaf(this);
  230. this.subNodes.push(this.lastNode);
  231. }
  232. return this.lastNode.addChar(str, i);
  233. }
  234. } else {
  235. // last branch child is not compatible with this token.
  236. // So, lastBranch is not a branch
  237. var revertTo = this.lastNode.triggerIndex +1;
  238. this.getRoot().cancelTerminate(this.lastNode.triggerIndex);
  239. // Add a new "escaped" node to replace trigger
  240. this.lastNode = new MsgTextLeaf(this);
  241. this.lastNode.addChar(str, revertTo -1); // Add "escaped" trigger
  242. this.subNodes.pop();
  243. this.subNodes.push(this.lastNode);
  244. // return negative value to start parsing again
  245. return revertTo -i;
  246. }
  247. }
  248. };
  249. MsgBranch.prototype.terminate = function(triggerIndex, terminateAtIndex) {
  250. var _this = this;
  251. while (_this) {
  252. _this.terminated = terminateAtIndex;
  253. _this = _this.prevTwin;
  254. }
  255. };
  256. MsgBranch.prototype.getRoot = function() {
  257. var branch = this;
  258. while (branch._parent && branch._parent instanceof MsgBranch)
  259. branch = branch._parent;
  260. return branch;
  261. };
  262. /**
  263. * @param {number} unTerminatedIndex
  264. **/
  265. MsgBranch.prototype.cancelTerminate = function(unTerminatedIndex) {
  266. if (this.terminated && this.terminated >= unTerminatedIndex)
  267. this.terminated = false;
  268. this.subNodes.forEach(function(node) {
  269. if (node instanceof MsgBranch) {
  270. node.cancelTerminate(unTerminatedIndex);
  271. }
  272. });
  273. };
  274. /**
  275. * @return {string}
  276. **/
  277. MsgTextLeaf.prototype.innerHTML = function() {
  278. return this._parent.checkIsEmoji() ? (':' +this.text +':') : (this.text);
  279. };
  280. /**
  281. * @return {string}
  282. **/
  283. MsgTextLeaf.prototype.outerHTML = function() {
  284. var tagName = 'span'
  285. ,classList = [];
  286. if (this._parent.checkIsCodeBlock()) {
  287. // TODO syntax highlight
  288. // TODO line breaks
  289. classList.push('codeblock');
  290. } else if (this._parent.checkIsCode()) {
  291. classList.push('code');
  292. } else {
  293. if (this.isLink)
  294. tagName = 'a';
  295. if (this._parent.checkIsBold())
  296. classList.push('bold');
  297. if (this._parent.checkIsItalic())
  298. classList.push('italic');
  299. if (this._parent.checkIsStrike())
  300. classList.push('strike');
  301. if (this._parent.checkIsEmoji())
  302. classList.push('emoji'); // FIXME emoji
  303. }
  304. return '<' +tagName +(classList.length ? ' class="' +classList.join(' ') +'"' : '') +'>' +this.innerHTML() +'</' +tagName +'>';
  305. };
  306. MsgBranch.prototype.outerHTML = function() {
  307. var html = "";
  308. if (this.isQuote)
  309. html += '<span class="quote">';
  310. if (this.isEol)
  311. html += '<br/>';
  312. this.subNodes.forEach(function(node) {
  313. html += node.outerHTML();
  314. });
  315. if (this.isQuote)
  316. html += '</span>';
  317. return html;
  318. };
  319. /**
  320. * @constructor
  321. * @param {string} text
  322. */
  323. function MsgTree(text) {
  324. /** @const @type {string} */
  325. this.text = text;
  326. /** @type {MsgBranch|null} */
  327. this.root = null;
  328. }
  329. MsgTree.prototype.parseFrom = function(i) {
  330. for (var textLen = this.text.length; i < textLen;)
  331. i += this.root.addChar(this.text, i);
  332. this.eof();
  333. };
  334. MsgTree.prototype.parse = function() {
  335. this.root = new MsgBranch(this, 0);
  336. this.parseFrom(0);
  337. };
  338. /** @param {MsgBranch} root */
  339. MsgTree.prototype.getFirstUnterminated = function(root) {
  340. for (var i =0, nbBranches = root.subNodes.length; i < nbBranches; i++) {
  341. var branch = root.subNodes[i];
  342. if (branch instanceof MsgBranch) {
  343. if (!branch.terminated) {
  344. return branch;
  345. } else {
  346. var unTerminatedChild = this.getFirstUnterminated(branch);
  347. if (unTerminatedChild)
  348. return unTerminatedChild;
  349. }
  350. }
  351. }
  352. return null;
  353. };
  354. /**
  355. * @param {MsgBranch} branch
  356. * @param {boolean} next kill this branch or all the next ones ?
  357. **/
  358. MsgTree.prototype.revertTree = function(branch, next) {
  359. if (branch._parent instanceof MsgBranch) {
  360. branch._parent.subNodes.splice(branch._parent.subNodes.indexOf(branch) +(next ? 1 : 0));
  361. branch._parent.lastNode = branch._parent.subNodes[branch._parent.subNodes.length -1];
  362. this.revertTree(branch._parent, true);
  363. }
  364. };
  365. MsgTree.prototype.eof = function() {
  366. // FIXME merge of same block-branches (opti + quoted)
  367. var unterminated = this.getFirstUnterminated(this.root);
  368. if (unterminated) {
  369. // We have a first token, but never closed
  370. // kill that branch
  371. this.revertTree(unterminated, false);
  372. // "unterminate" all branch that will be closed in the future
  373. this.root.cancelTerminate(unterminated.triggerIndex);
  374. // Add a new text leaf containing trigger
  375. var textNode = new MsgTextLeaf(unterminated._parent);
  376. textNode.addChar(this.text, unterminated.triggerIndex);
  377. unterminated._parent.subNodes.push(textNode);
  378. unterminated._parent.lastNode = textNode;
  379. // Restart parsing
  380. this.parseFrom(unterminated.triggerIndex +1);
  381. }
  382. // Else no problem
  383. };
  384. /**
  385. * @return {string}
  386. **/
  387. MsgTree.prototype.toHTML = function() {
  388. return this.root ? this.root.outerHTML() : "";
  389. };
  390. return function(text) {
  391. var root = new MsgTree(text);
  392. root.parse();
  393. return (root.toHTML());
  394. };
  395. })();
  396. if (typeof module !== "undefined") module.exports.formatText = formatText;