commons.ts 6.4 KB

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