use-formatter.tsx 1.1 KB

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