commons.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import type { ColorScheme, IUserHasId } from '@growi/core';
  2. import {
  3. DevidedPagePath, Lang, AllLang,
  4. } from '@growi/core';
  5. import type { GetServerSideProps, GetServerSidePropsContext } from 'next';
  6. import type { SSRConfig, UserConfig } from 'next-i18next';
  7. import * as nextI18NextConfig from '^/config/next-i18next.config';
  8. import { detectLocaleFromBrowserAcceptLanguage } from '~/client/util/locale-utils';
  9. import type { CrowiRequest } from '~/interfaces/crowi-request';
  10. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  11. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  12. import {
  13. useCurrentProductNavWidth, useCurrentSidebarContents, usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed,
  14. } from '~/stores/ui';
  15. export type CommonProps = {
  16. namespacesRequired: string[], // i18next
  17. currentPathname: string,
  18. appTitle: string,
  19. siteUrl: string,
  20. confidential: string,
  21. customTitleTemplate: string,
  22. csrfToken: string,
  23. isContainerFluid: boolean,
  24. growiVersion: string,
  25. isMaintenanceMode: boolean,
  26. redirectDestination: string | null,
  27. isDefaultLogo: boolean,
  28. currentUser?: IUserHasId,
  29. forcedColorScheme?: ColorScheme,
  30. } & Partial<SSRConfig>;
  31. // eslint-disable-next-line max-len
  32. export const getServerSideCommonProps: GetServerSideProps<CommonProps> = async(context: GetServerSidePropsContext) => {
  33. const req = context.req as CrowiRequest<IUserHasId & any>;
  34. const { crowi, user } = req;
  35. const {
  36. appService, configManager, customizeService, attachmentService,
  37. } = crowi;
  38. const url = new URL(context.resolvedUrl, 'http://example.com');
  39. const currentPathname = decodeURIComponent(url.pathname);
  40. const isMaintenanceMode = appService.isMaintenanceMode();
  41. let currentUser;
  42. if (user != null) {
  43. currentUser = user.toObject();
  44. }
  45. // Redirect destination for page transition by next/link
  46. let redirectDestination: string | null = null;
  47. if (!crowi.aclService.isGuestAllowedToRead() && currentUser == null) {
  48. redirectDestination = '/login';
  49. }
  50. else if (!isMaintenanceMode && currentPathname === '/maintenance') {
  51. redirectDestination = '/';
  52. }
  53. else if (isMaintenanceMode && !currentPathname.match('/admin/*') && !(currentPathname === '/maintenance')) {
  54. redirectDestination = '/maintenance';
  55. }
  56. else {
  57. redirectDestination = null;
  58. }
  59. const isCustomizedLogoUploaded = await attachmentService.isBrandLogoExist();
  60. const isDefaultLogo = crowi.configManager.getConfig('crowi', 'customize:isDefaultLogo') || !isCustomizedLogoUploaded;
  61. const forcedColorScheme = crowi.customizeService.forcedColorScheme;
  62. const props: CommonProps = {
  63. namespacesRequired: ['translation'],
  64. currentPathname,
  65. appTitle: appService.getAppTitle(),
  66. siteUrl: configManager.getConfig('crowi', 'app:siteUrl'), // DON'T USE appService.getSiteUrl()
  67. confidential: appService.getAppConfidential() || '',
  68. customTitleTemplate: customizeService.customTitleTemplate,
  69. csrfToken: req.csrfToken(),
  70. isContainerFluid: configManager.getConfig('crowi', 'customize:isContainerFluid') ?? false,
  71. growiVersion: crowi.version,
  72. isMaintenanceMode,
  73. redirectDestination,
  74. currentUser,
  75. isDefaultLogo,
  76. forcedColorScheme,
  77. };
  78. return { props };
  79. };
  80. export const getNextI18NextConfig = async(
  81. // 'serverSideTranslations' method should be given from Next.js Page
  82. // because importing it in this file causes https://github.com/isaachinman/next-i18next/issues/1545
  83. serverSideTranslations: (
  84. initialLocale: string, namespacesRequired?: string[] | undefined, configOverride?: UserConfig | null, extraLocales?: string[] | false
  85. ) => Promise<SSRConfig>,
  86. context: GetServerSidePropsContext, namespacesRequired?: string[] | undefined, preloadAllLang = false,
  87. ): Promise<SSRConfig> => {
  88. const req: CrowiRequest = context.req as CrowiRequest;
  89. const { crowi, user, headers } = req;
  90. const { configManager } = crowi;
  91. // determine language
  92. const locale = user == null ? detectLocaleFromBrowserAcceptLanguage(headers)
  93. : (user.lang ?? configManager.getConfig('crowi', 'app:globalLang') as Lang ?? Lang.en_US);
  94. const namespaces = ['commons'];
  95. if (namespacesRequired != null) {
  96. namespaces.push(...namespacesRequired);
  97. }
  98. // TODO: deprecate 'translation.json' in the future
  99. else {
  100. namespaces.push('translation');
  101. }
  102. return serverSideTranslations(locale, namespaces, nextI18NextConfig, preloadAllLang ? AllLang : false);
  103. };
  104. /**
  105. * Generate whole title string for the specified title
  106. * @param props
  107. * @param title
  108. */
  109. export const generateCustomTitle = (props: CommonProps, title: string): string => {
  110. return props.customTitleTemplate
  111. .replace('{{sitename}}', props.appTitle)
  112. .replace('{{pagepath}}', title)
  113. .replace('{{pagename}}', title);
  114. };
  115. /**
  116. * Generate whole title string for the specified page path
  117. * @param props
  118. * @param pagePath
  119. */
  120. export const generateCustomTitleForPage = (props: CommonProps, pagePath: string): string => {
  121. const dPagePath = new DevidedPagePath(pagePath, true, true);
  122. return props.customTitleTemplate
  123. .replace('{{sitename}}', props.appTitle)
  124. .replace('{{pagepath}}', pagePath)
  125. .replace('{{pagename}}', dPagePath.latter);
  126. };
  127. export const useInitSidebarConfig = (sidebarConfig: ISidebarConfig, userUISettings?: IUserUISettings): void => {
  128. // UserUISettings
  129. usePreferDrawerModeByUser(userUISettings?.preferDrawerModeByUser ?? sidebarConfig.isSidebarDrawerMode);
  130. usePreferDrawerModeOnEditByUser(userUISettings?.preferDrawerModeOnEditByUser);
  131. useSidebarCollapsed(userUISettings?.isSidebarCollapsed ?? sidebarConfig.isSidebarClosedAtDockMode);
  132. useCurrentSidebarContents(userUISettings?.currentSidebarContents);
  133. useCurrentProductNavWidth(userUISettings?.currentProductNavWidth);
  134. };