commons.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { DevidedPagePath } from '@growi/core';
  2. import { GetServerSideProps, GetServerSidePropsContext } from 'next';
  3. import { CrowiRequest } from '~/interfaces/crowi-request';
  4. export type CommonProps = {
  5. namespacesRequired: string[], // i18next
  6. currentPagePath: string,
  7. appTitle: string,
  8. confidential: string,
  9. customTitleTemplate: string,
  10. growiVersion: string,
  11. }
  12. // eslint-disable-next-line max-len
  13. export const getServerSideCommonProps: GetServerSideProps<CommonProps> = async(context: GetServerSidePropsContext) => {
  14. const req: CrowiRequest = context.req as CrowiRequest;
  15. const { crowi } = req;
  16. const {
  17. appService, customizeService,
  18. } = crowi;
  19. const url = new URL(context.resolvedUrl, 'http://example.com');
  20. const currentPagePath = decodeURI(url.pathname);
  21. const props: CommonProps = {
  22. namespacesRequired: ['translation'],
  23. currentPagePath,
  24. appTitle: appService.getAppTitle(),
  25. confidential: appService.getAppConfidential() || '',
  26. customTitleTemplate: customizeService.customTitleTemplate,
  27. growiVersion: crowi.version,
  28. };
  29. return { props };
  30. };
  31. /**
  32. * Generate whole title string for the specified title
  33. * @param props
  34. * @param title
  35. */
  36. export const useCustomTitle = (props: CommonProps, title: string): string => {
  37. return props.customTitleTemplate
  38. .replace('{{sitename}}', props.appTitle)
  39. .replace('{{page}}', title)
  40. .replace('{{pagepath}}', title)
  41. .replace('{{pagename}}', title);
  42. };
  43. /**
  44. * Generate whole title string for the specified page path
  45. * @param props
  46. * @param pagePath
  47. */
  48. export const useCustomTitleForPage = (props: CommonProps, pagePath: string): string => {
  49. const dPagePath = new DevidedPagePath(pagePath, true, true);
  50. return props.customTitleTemplate
  51. .replace('{{sitename}}', props.appTitle)
  52. .replace('{{pagepath}}', pagePath)
  53. .replace('{{page}}', dPagePath.latter) // for backward compatibility
  54. .replace('{{pagename}}', dPagePath.latter);
  55. };