CrowiTemplate.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import dateFnsFormat from 'date-fns/format';
  2. export default class CrowiTemplate {
  3. constructor(crowi) {
  4. this.crowi = crowi;
  5. this.getUser = this.getUser.bind(this);
  6. this.templatePattern = {
  7. year: this.getYear,
  8. month: this.getMonth,
  9. date: this.getDate,
  10. user: this.getUser,
  11. };
  12. }
  13. process(markdown) {
  14. // see: https://regex101.com/r/WR6IvX/3
  15. return markdown.replace(/:::\s*(\S+)[\r\n]((.|[\r\n])*?)[\r\n]:::/gm, (all, group1, group2) => {
  16. const lang = group1;
  17. let code = group2;
  18. if (!lang.match(/^template/)) {
  19. return all;
  20. }
  21. const templateId = new Date().getTime().toString(16) + Math.floor(1000 * Math.random()).toString(16);
  22. let pageName = lang;
  23. if (lang.match(':')) {
  24. pageName = this.parseTemplateString(lang.split(':')[1]);
  25. }
  26. code = this.parseTemplateString(code);
  27. return (
  28. /* eslint-disable quotes */
  29. `<div class="page-template-builder">`
  30. + `<button class="template-create-button btn btn-default" data-template="${templateId}" data-path="${pageName}">`
  31. + `<i class="fa fa-pencil"></i> ${pageName}`
  32. + `</button>`
  33. + `<pre><code id="${templateId}" class="lang-${lang}">${code}\n</code></pre>`
  34. + `</div>`
  35. /* eslint-enable quotes */
  36. );
  37. });
  38. }
  39. getYear() {
  40. return dateFnsFormat(new Date(), 'YYYY');
  41. }
  42. getMonth() {
  43. return dateFnsFormat(new Date(), 'YYYY/MM');
  44. }
  45. getDate() {
  46. return dateFnsFormat(new Date(), 'YYYY/MM/DD');
  47. }
  48. getUser() {
  49. const username = this.crowi.me || null;
  50. if (!username) {
  51. return '';
  52. }
  53. return `/user/${username}`;
  54. }
  55. parseTemplateString(templateString) {
  56. let parsed = templateString;
  57. Object.keys(this.templatePattern).forEach((key) => {
  58. const k = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  59. const matcher = new RegExp(`{${k}}`, 'g');
  60. if (parsed.match(matcher)) {
  61. const replacer = this.templatePattern[key]();
  62. parsed = parsed.replace(matcher, replacer);
  63. }
  64. });
  65. return parsed;
  66. }
  67. }