use-formatter.tsx 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { format as dateFnsFormat } from 'date-fns/format';
  2. import mustache from 'mustache';
  3. import path from 'path';
  4. import { useCurrentPagePath } from '~/states/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 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. } catch (err) {
  30. logger.warn('An error occured while ejs processing.', err);
  31. return markdown;
  32. }
  33. };
  34. return { format };
  35. };