ui.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import {
  2. type RefObject, useCallback, useEffect,
  3. useLayoutEffect,
  4. } from 'react';
  5. import { PageGrant, type Nullable } from '@growi/core';
  6. import { type SWRResponseWithUtils, useSWRStatic, withUtils } from '@growi/core/dist/swr';
  7. import { pagePathUtils, isClient } from '@growi/core/dist/utils';
  8. import { Breakpoint } from '@growi/ui/dist/interfaces';
  9. import { addBreakpointListener, cleanupBreakpointListener } from '@growi/ui/dist/utils';
  10. import { useRouter } from 'next/router';
  11. import type { HtmlElementNode } from 'rehype-toc';
  12. import type { MutatorOptions } from 'swr';
  13. import {
  14. useSWRConfig, type SWRResponse, type Key,
  15. } from 'swr';
  16. import useSWRImmutable from 'swr/immutable';
  17. import { scheduleToPut } from '~/client/services/user-ui-settings';
  18. import type { IPageSelectedGrant } from '~/interfaces/page';
  19. import { SidebarContentsType, SidebarMode } from '~/interfaces/ui';
  20. import type { UpdateDescCountData } from '~/interfaces/websocket';
  21. import {
  22. useIsEditable, useIsReadOnlyUser,
  23. useIsSharedUser, useIsIdenticalPath, useCurrentUser, useShareLinkId,
  24. } from '~/stores-universal/context';
  25. import { EditorMode, useEditorMode } from '~/stores-universal/ui';
  26. import {
  27. useIsNotFound, useCurrentPagePath, useIsTrashPage, useCurrentPageId,
  28. } from '~/stores/page';
  29. import loggerFactory from '~/utils/logger';
  30. import { useStaticSWR } from './use-static-swr';
  31. const { isTrashTopPage, isUsersTopPage } = pagePathUtils;
  32. const logger = loggerFactory('growi:stores:ui');
  33. /** **********************************************************
  34. * Storing objects to ref
  35. *********************************************************** */
  36. export const useCurrentPageTocNode = (): SWRResponse<HtmlElementNode, any> => {
  37. const { data: currentPagePath } = useCurrentPagePath();
  38. return useStaticSWR(['currentPageTocNode', currentPagePath]);
  39. };
  40. /** **********************************************************
  41. * SWR Hooks
  42. * for switching UI
  43. *********************************************************** */
  44. export const useSidebarScrollerRef = (initialData?: RefObject<HTMLDivElement>): SWRResponse<RefObject<HTMLDivElement>, Error> => {
  45. return useSWRStatic<RefObject<HTMLDivElement>, Error>('sidebarScrollerRef', initialData);
  46. };
  47. export const useIsMobile = (): SWRResponse<boolean, Error> => {
  48. const key = isClient() ? 'isMobile' : null;
  49. let configuration;
  50. if (isClient()) {
  51. const userAgent = window.navigator.userAgent.toLowerCase();
  52. configuration = {
  53. fallbackData: /iphone|ipad|android/.test(userAgent),
  54. };
  55. }
  56. return useStaticSWR<boolean, Error>(key, undefined, configuration);
  57. };
  58. export const useIsDeviceLargerThanMd = (): SWRResponse<boolean, Error> => {
  59. const key: Key = isClient() ? 'isDeviceLargerThanMd' : null;
  60. const { cache, mutate } = useSWRConfig();
  61. useEffect(() => {
  62. if (key != null) {
  63. const mdOrAvobeHandler = function(this: MediaQueryList): void {
  64. // sm -> md: matches will be true
  65. // md -> sm: matches will be false
  66. mutate(key, this.matches);
  67. };
  68. const mql = addBreakpointListener(Breakpoint.MD, mdOrAvobeHandler);
  69. // initialize
  70. if (cache.get(key)?.data == null) {
  71. cache.set(key, { ...cache.get(key), data: mql.matches });
  72. }
  73. return () => {
  74. cleanupBreakpointListener(mql, mdOrAvobeHandler);
  75. };
  76. }
  77. }, [cache, key, mutate]);
  78. return useSWRStatic(key);
  79. };
  80. export const useIsDeviceLargerThanLg = (): SWRResponse<boolean, Error> => {
  81. const key: Key = isClient() ? 'isDeviceLargerThanLg' : null;
  82. const { cache, mutate } = useSWRConfig();
  83. useEffect(() => {
  84. if (key != null) {
  85. const lgOrAvobeHandler = function(this: MediaQueryList): void {
  86. // md -> lg: matches will be true
  87. // lg -> md: matches will be false
  88. mutate(key, this.matches);
  89. };
  90. const mql = addBreakpointListener(Breakpoint.LG, lgOrAvobeHandler);
  91. // initialize
  92. if (cache.get(key)?.data == null) {
  93. cache.set(key, { ...cache.get(key), data: mql.matches });
  94. }
  95. return () => {
  96. cleanupBreakpointListener(mql, lgOrAvobeHandler);
  97. };
  98. }
  99. }, [cache, key, mutate]);
  100. return useSWRStatic(key);
  101. };
  102. export const useIsDeviceLargerThanXl = (): SWRResponse<boolean, Error> => {
  103. const key: Key = isClient() ? 'isDeviceLargerThanXl' : null;
  104. const { cache, mutate } = useSWRConfig();
  105. useEffect(() => {
  106. if (key != null) {
  107. const xlOrAvobeHandler = function(this: MediaQueryList): void {
  108. // lg -> xl: matches will be true
  109. // xl -> lg: matches will be false
  110. mutate(key, this.matches);
  111. };
  112. const mql = addBreakpointListener(Breakpoint.XL, xlOrAvobeHandler);
  113. // initialize
  114. if (cache.get(key)?.data == null) {
  115. cache.set(key, { ...cache.get(key), data: mql.matches });
  116. }
  117. return () => {
  118. cleanupBreakpointListener(mql, xlOrAvobeHandler);
  119. };
  120. }
  121. }, [cache, key, mutate]);
  122. return useSWRStatic(key);
  123. };
  124. type MutateAndSaveUserUISettings<Data> = (data: Data, opts?: boolean | MutatorOptions<Data>) => Promise<Data | undefined>;
  125. type MutateAndSaveUserUISettingsUtils<Data> = {
  126. mutateAndSave: MutateAndSaveUserUISettings<Data>;
  127. }
  128. export const useCurrentSidebarContents = (
  129. initialData?: SidebarContentsType,
  130. ): SWRResponseWithUtils<MutateAndSaveUserUISettingsUtils<SidebarContentsType>, SidebarContentsType> => {
  131. const swrResponse = useSWRStatic('sidebarContents', initialData, { fallbackData: SidebarContentsType.TREE });
  132. const { mutate } = swrResponse;
  133. const mutateAndSave: MutateAndSaveUserUISettings<SidebarContentsType> = useCallback((data, opts?) => {
  134. scheduleToPut({ currentSidebarContents: data });
  135. return mutate(data, opts);
  136. }, [mutate]);
  137. return withUtils(swrResponse, { mutateAndSave });
  138. };
  139. export const usePageControlsX = (initialData?: number): SWRResponse<number> => {
  140. return useSWRStatic('pageControlsX', initialData);
  141. };
  142. export const useCurrentProductNavWidth = (initialData?: number): SWRResponseWithUtils<MutateAndSaveUserUISettingsUtils<number>, number> => {
  143. const swrResponse = useSWRStatic('productNavWidth', initialData, { fallbackData: 320 });
  144. const { mutate } = swrResponse;
  145. const mutateAndSave: MutateAndSaveUserUISettings<number> = useCallback((data, opts?) => {
  146. scheduleToPut({ currentProductNavWidth: data });
  147. return mutate(data, opts);
  148. }, [mutate]);
  149. return withUtils(swrResponse, { mutateAndSave });
  150. };
  151. export const usePreferCollapsedMode = (initialData?: boolean): SWRResponseWithUtils<MutateAndSaveUserUISettingsUtils<boolean>, boolean> => {
  152. const swrResponse = useSWRStatic('isPreferCollapsedMode', initialData, { fallbackData: false });
  153. const { mutate } = swrResponse;
  154. const mutateAndSave: MutateAndSaveUserUISettings<boolean> = useCallback((data, opts?) => {
  155. scheduleToPut({ preferCollapsedModeByUser: data });
  156. return mutate(data, opts);
  157. }, [mutate]);
  158. return withUtils(swrResponse, { mutateAndSave });
  159. };
  160. export const useCollapsedContentsOpened = (initialData?: boolean): SWRResponse<boolean> => {
  161. return useSWRStatic('isCollapsedContentsOpened', initialData, { fallbackData: false });
  162. };
  163. export const useDrawerOpened = (isOpened?: boolean): SWRResponse<boolean, Error> => {
  164. return useSWRStatic('isDrawerOpened', isOpened, { fallbackData: false });
  165. };
  166. type DetectSidebarModeUtils = {
  167. isDrawerMode(): boolean
  168. isCollapsedMode(): boolean
  169. isDockMode(): boolean
  170. }
  171. export const useSidebarMode = (): SWRResponseWithUtils<DetectSidebarModeUtils, SidebarMode> => {
  172. const { data: isDeviceLargerThanXl } = useIsDeviceLargerThanXl();
  173. const { data: editorMode } = useEditorMode();
  174. const { data: isCollapsedModeUnderDockMode } = usePreferCollapsedMode();
  175. const condition = isDeviceLargerThanXl != null && editorMode != null && isCollapsedModeUnderDockMode != null;
  176. const isEditorMode = editorMode === EditorMode.Editor;
  177. const fetcher = useCallback((
  178. [, isDeviceLargerThanXl, isEditorMode, isCollapsedModeUnderDockMode]: [Key, boolean|undefined, boolean|undefined, boolean|undefined],
  179. ) => {
  180. if (!isDeviceLargerThanXl) {
  181. return SidebarMode.DRAWER;
  182. }
  183. return isEditorMode || isCollapsedModeUnderDockMode ? SidebarMode.COLLAPSED : SidebarMode.DOCK;
  184. }, []);
  185. const swrResponse = useSWRImmutable(
  186. condition ? ['sidebarMode', isDeviceLargerThanXl, isEditorMode, isCollapsedModeUnderDockMode] : null,
  187. // calcDrawerMode,
  188. fetcher,
  189. { fallbackData: fetcher(['sidebarMode', isDeviceLargerThanXl, isEditorMode, isCollapsedModeUnderDockMode]) },
  190. );
  191. const _isDrawerMode = useCallback(() => swrResponse.data === SidebarMode.DRAWER, [swrResponse.data]);
  192. const _isCollapsedMode = useCallback(() => swrResponse.data === SidebarMode.COLLAPSED, [swrResponse.data]);
  193. const _isDockMode = useCallback(() => swrResponse.data === SidebarMode.DOCK, [swrResponse.data]);
  194. return {
  195. ...swrResponse,
  196. isDrawerMode: _isDrawerMode,
  197. isCollapsedMode: _isCollapsedMode,
  198. isDockMode: _isDockMode,
  199. };
  200. };
  201. export const useSelectedGrant = (initialData?: Nullable<IPageSelectedGrant>): SWRResponse<Nullable<IPageSelectedGrant>, Error> => {
  202. return useSWRStatic<Nullable<IPageSelectedGrant>, Error>('selectedGrant', initialData, { fallbackData: { grant: PageGrant.GRANT_PUBLIC } });
  203. };
  204. type PageTreeDescCountMapUtils = {
  205. update(newData?: UpdateDescCountData): Promise<UpdateDescCountData | undefined>
  206. getDescCount(pageId?: string): number | null | undefined
  207. }
  208. export const usePageTreeDescCountMap = (initialData?: UpdateDescCountData): SWRResponse<UpdateDescCountData, Error> & PageTreeDescCountMapUtils => {
  209. const key = 'pageTreeDescCountMap';
  210. const swrResponse = useStaticSWR<UpdateDescCountData, Error>(key, initialData, { fallbackData: new Map() });
  211. return {
  212. ...swrResponse,
  213. getDescCount: (pageId?: string) => (pageId != null ? swrResponse.data?.get(pageId) : null),
  214. update: (newData: UpdateDescCountData) => swrResponse.mutate(new Map([...(swrResponse.data || new Map()), ...newData])),
  215. };
  216. };
  217. type UseCommentEditorDirtyMapOperation = {
  218. evaluate(key: string, commentBody: string): Promise<number>,
  219. clean(key: string): Promise<number>,
  220. }
  221. export const useCommentEditorDirtyMap = (): SWRResponse<Map<string, boolean>, Error> & UseCommentEditorDirtyMapOperation => {
  222. const router = useRouter();
  223. const swrResponse = useSWRStatic<Map<string, boolean>, Error>('editingCommentsNum', undefined, { fallbackData: new Map() });
  224. const { mutate } = swrResponse;
  225. const evaluate = useCallback(async(key: string, commentBody: string) => {
  226. const newMap = await mutate((map) => {
  227. if (map == null) return new Map();
  228. if (commentBody.length === 0) {
  229. map.delete(key);
  230. }
  231. else {
  232. map.set(key, true);
  233. }
  234. return map;
  235. });
  236. return newMap?.size ?? 0;
  237. }, [mutate]);
  238. const clean = useCallback(async(key: string) => {
  239. const newMap = await mutate((map) => {
  240. if (map == null) return new Map();
  241. map.delete(key);
  242. return map;
  243. });
  244. return newMap?.size ?? 0;
  245. }, [mutate]);
  246. const reset = useCallback(() => mutate(new Map()), [mutate]);
  247. useLayoutEffect(() => {
  248. router.events.on('routeChangeComplete', reset);
  249. return () => {
  250. router.events.off('routeChangeComplete', reset);
  251. };
  252. }, [reset, router.events]);
  253. return {
  254. ...swrResponse,
  255. evaluate,
  256. clean,
  257. };
  258. };
  259. /** **********************************************************
  260. * SWR Hooks
  261. * Determined value by context
  262. *********************************************************** */
  263. export const useIsAbleToShowTrashPageManagementButtons = (): SWRResponse<boolean, Error> => {
  264. const key = 'isAbleToShowTrashPageManagementButtons';
  265. const { data: _currentUser } = useCurrentUser();
  266. const isCurrentUserExist = _currentUser != null;
  267. const { data: _currentPageId } = useCurrentPageId();
  268. const { data: _isNotFound } = useIsNotFound();
  269. const { data: _isTrashPage } = useIsTrashPage();
  270. const { data: _isReadOnlyUser } = useIsReadOnlyUser();
  271. const isPageExist = _currentPageId != null && _isNotFound === false;
  272. const isTrashPage = isPageExist && _isTrashPage === true;
  273. const isReadOnlyUser = isPageExist && _isReadOnlyUser === true;
  274. const includesUndefined = [_currentUser, _currentPageId, _isNotFound, _isReadOnlyUser, _isTrashPage].some(v => v === undefined);
  275. return useSWRImmutable(
  276. includesUndefined ? null : [key, isTrashPage, isCurrentUserExist, isReadOnlyUser],
  277. ([, isTrashPage, isCurrentUserExist, isReadOnlyUser]) => isTrashPage && isCurrentUserExist && !isReadOnlyUser,
  278. );
  279. };
  280. export const useIsAbleToShowPageManagement = (): SWRResponse<boolean, Error> => {
  281. const key = 'isAbleToShowPageManagement';
  282. const { data: currentPageId } = useCurrentPageId();
  283. const { data: _isTrashPage } = useIsTrashPage();
  284. const { data: _isSharedUser } = useIsSharedUser();
  285. const { data: isNotFound } = useIsNotFound();
  286. const pageId = currentPageId;
  287. const includesUndefined = [pageId, _isTrashPage, _isSharedUser, isNotFound].some(v => v === undefined);
  288. const isPageExist = (pageId != null) && isNotFound === false;
  289. const isEmptyPage = (pageId != null) && isNotFound === true;
  290. const isTrashPage = isPageExist && _isTrashPage === true;
  291. const isSharedUser = isPageExist && _isSharedUser === true;
  292. return useSWRImmutable(
  293. includesUndefined ? null : [key, pageId, isPageExist, isEmptyPage, isTrashPage, isSharedUser],
  294. ([, , isPageExist, isEmptyPage, isTrashPage, isSharedUser]) => (isPageExist && !isTrashPage && !isSharedUser) || isEmptyPage,
  295. );
  296. };
  297. export const useIsAbleToShowTagLabel = (): SWRResponse<boolean, Error> => {
  298. const key = 'isAbleToShowTagLabel';
  299. const { data: pageId } = useCurrentPageId();
  300. const { data: currentPagePath } = useCurrentPagePath();
  301. const { data: isIdenticalPath } = useIsIdenticalPath();
  302. const { data: isNotFound } = useIsNotFound();
  303. const { data: editorMode } = useEditorMode();
  304. const { data: shareLinkId } = useShareLinkId();
  305. const includesUndefined = [currentPagePath, isIdenticalPath, isNotFound, editorMode].some(v => v === undefined);
  306. const isViewMode = editorMode === EditorMode.View;
  307. return useSWRImmutable(
  308. includesUndefined ? null : [key, pageId, currentPagePath, isIdenticalPath, isNotFound, editorMode, shareLinkId],
  309. // "/trash" page does not exist on page collection and unable to add tags
  310. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  311. () => !isUsersTopPage(currentPagePath!) && !isTrashTopPage(currentPagePath!) && shareLinkId == null && !isIdenticalPath && !(isViewMode && isNotFound),
  312. );
  313. };
  314. export const useIsAbleToChangeEditorMode = (): SWRResponse<boolean, Error> => {
  315. const key = 'isAbleToChangeEditorMode';
  316. const { data: isEditable } = useIsEditable();
  317. const { data: isSharedUser } = useIsSharedUser();
  318. const includesUndefined = [isEditable, isSharedUser].some(v => v === undefined);
  319. return useSWRImmutable(
  320. includesUndefined ? null : [key, isEditable, isSharedUser],
  321. () => !!isEditable && !isSharedUser,
  322. );
  323. };
  324. export const useIsAbleToShowPageAuthors = (): SWRResponse<boolean, Error> => {
  325. const key = 'isAbleToShowPageAuthors';
  326. const { data: pageId } = useCurrentPageId();
  327. const { data: pagePath } = useCurrentPagePath();
  328. const { data: isNotFound } = useIsNotFound();
  329. const includesUndefined = [pageId, pagePath, isNotFound].some(v => v === undefined);
  330. const isPageExist = (pageId != null) && !isNotFound;
  331. const isUsersTopPagePath = pagePath != null && isUsersTopPage(pagePath);
  332. return useSWRImmutable(
  333. includesUndefined ? null : [key, pageId, pagePath, isNotFound],
  334. () => isPageExist && !isUsersTopPagePath,
  335. );
  336. };
  337. export const useIsUntitledPage = (): SWRResponse<boolean> => {
  338. const key = 'isUntitledPage';
  339. const { data: pageId } = useCurrentPageId();
  340. return useSWRStatic(
  341. pageId == null ? null : [key, pageId],
  342. undefined,
  343. { fallbackData: false },
  344. );
  345. };