use-formatter.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import path from 'path';
  2. import type { ITemplate } from '@growi/core/dist/interfaces/template';
  3. import dateFnsFormat from 'date-fns/format';
  4. import mustache from 'mustache';
  5. import { useCurrentPagePath } from '~/stores/page';
  6. import loggerFactory from '~/utils/logger';
  7. const logger = loggerFactory('growi:components:TemplateModal:use-formatter');
  8. type FormatMethod = (selectedTemplate?: ITemplate) => string;
  9. type FormatterData = {
  10. format: FormatMethod,
  11. }
  12. export const useFormatter = (): FormatterData => {
  13. const { data: currentPagePath } = useCurrentPagePath();
  14. const format: FormatMethod = (selectedTemplate) => {
  15. if (selectedTemplate == null) {
  16. return '';
  17. }
  18. // replace placeholder
  19. let markdown = selectedTemplate.markdown;
  20. const now = new Date();
  21. try {
  22. markdown = mustache.render(selectedTemplate.markdown, {
  23. title: path.basename(currentPagePath ?? '/'),
  24. path: currentPagePath ?? '/',
  25. yyyy: dateFnsFormat(now, 'yyyy'),
  26. MM: dateFnsFormat(now, 'MM'),
  27. dd: dateFnsFormat(now, 'dd'),
  28. HH: dateFnsFormat(now, 'HH'),
  29. mm: dateFnsFormat(now, 'mm'),
  30. });
  31. }
  32. catch (err) {
  33. logger.warn('An error occured while ejs processing.', err);
  34. }
  35. return markdown;
  36. };
  37. return { format };
  38. };