functions.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * Make wikitext formatting usage.
  3. * @param {String} [text] - The text to modify.
  4. * @param {Boolean} [showEmbed] - If the text is used in an embed.
  5. * @param {import('./wiki.js')|String} [args] - The text contains markdown links.
  6. * @returns {String}
  7. */
  8. function toFormatting(text = '', showEmbed = false, ...args) {
  9. if ( showEmbed ) return toMarkdown(text, ...args);
  10. else return toPlaintext(text);
  11. };
  12. /**
  13. * Turns wikitext formatting into markdown.
  14. * @param {String} [text] - The text to modify.
  15. * @param {import('./wiki.js')} [wiki] - The wiki.
  16. * @param {String} [title] - The page title.
  17. * @returns {String}
  18. */
  19. function toMarkdown(text = '', wiki, title = '') {
  20. text = text.replace( /[()\\]/g, '\\$&' );
  21. var link = null;
  22. var regex = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g;
  23. while ( ( link = regex.exec(text) ) !== null ) {
  24. var pagetitle = ( link[1] || link[2] );
  25. var page = wiki.toLink(( /^[#\/]/.test(pagetitle) ? title + ( pagetitle.startsWith( '/' ) ? pagetitle : '' ) : pagetitle ), '', ( pagetitle.startsWith( '#' ) ? pagetitle.substring(1) : '' ), true);
  26. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + page + ')' );
  27. }
  28. regex = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g;
  29. while ( title !== '' && ( link = regex.exec(text) ) !== null ) {
  30. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink(title, '', link[1], true) + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  31. }
  32. return escapeFormatting(text, true);
  33. };
  34. /**
  35. * Removes wikitext formatting.
  36. * @param {String} [text] - The text to modify.
  37. * @returns {String}
  38. */
  39. function toPlaintext(text = '') {
  40. return escapeFormatting(text.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ));
  41. };
  42. /**
  43. * Escapes formatting.
  44. * @param {String} [text] - The text to modify.
  45. * @param {Boolean} [isMarkdown] - The text contains markdown links.
  46. * @returns {String}
  47. */
  48. function escapeFormatting(text = '', isMarkdown = false) {
  49. if ( !isMarkdown ) text = text.replace( /[()\\]/g, '\\$&' );
  50. return text.replace( /[`_*~:<>{}@|]|\/\//g, '\\$&' );
  51. };
  52. module.exports = {
  53. toFormatting,
  54. toMarkdown,
  55. toPlaintext,
  56. escapeFormatting
  57. };