Template.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import dateFnsFormat from 'date-fns/format';
  2. export default class Template {
  3. constructor(crowi) {
  4. this.templatePattern = {
  5. 'year': this.getYear,
  6. 'month': this.getMonth,
  7. 'date': this.getDate,
  8. 'user': this.getUser,
  9. };
  10. }
  11. getYear() {
  12. return dateFnsFormat(new Date(), 'YYYY');
  13. }
  14. getMonth() {
  15. return dateFnsFormat(new Date(), 'YYYY/MM');
  16. }
  17. getDate() {
  18. return dateFnsFormat(new Date(), 'YYYY/MM/DD');
  19. }
  20. getUser() {
  21. // FIXME
  22. const username = window.crowi.me || null;
  23. if (!username) {
  24. return '';
  25. }
  26. return `/user/${username}`;
  27. }
  28. parseTemplateString(templateString) {
  29. let parsed = templateString;
  30. Object.keys(this.templatePattern).forEach(key => {
  31. const k = key .replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  32. const matcher = new RegExp(`{${k}}`, 'g');
  33. if (parsed.match(matcher)) {
  34. const replacer = this.templatePattern[key]();
  35. parsed = parsed.replace(matcher, replacer);
  36. }
  37. });
  38. return parsed;
  39. }
  40. process(code, lang) {
  41. const templateId = new Date().getTime().toString(16) + Math.floor(1000 * Math.random()).toString(16);
  42. let pageName = lang;
  43. if (lang.match(':')) {
  44. pageName = this.parseTemplateString(lang.split(':')[1]);
  45. }
  46. code = this.parseTemplateString(code);
  47. const content = `
  48. <div class="page-template-builder">
  49. <button class="template-create-button btn btn-default" data-template="${templateId}" data-path="${pageName}">
  50. <i class="fa fa-pencil"></i> ${pageName}
  51. </button>
  52. <pre><code id="${templateId}" class="lang-${lang}">${code}\n</code></pre>
  53. </div>`;
  54. // wrap with <pre-dummy>
  55. // to avoid to be wrapped with <pre><code> by markdown-it
  56. return `<pre-dummy>${content}<pre-dummy>\n`;
  57. }
  58. }