commons.ts 7.1 KB

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