commons.ts 6.5 KB

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