PageCreateModal.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import React, {
  2. useEffect, useState, useMemo, useCallback,
  3. } from 'react';
  4. import path from 'path';
  5. import { Origin } from '@growi/core';
  6. import { pagePathUtils, pathUtils } from '@growi/core/dist/utils';
  7. import { normalizePath } from '@growi/core/dist/utils/path-utils';
  8. import { format } from 'date-fns/format';
  9. import { useAtomValue } from 'jotai';
  10. import { useTranslation } from 'next-i18next';
  11. import {
  12. Modal, ModalHeader, ModalBody, UncontrolledButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem,
  13. } from 'reactstrap';
  14. import { debounce } from 'throttle-debounce';
  15. import { useCreateTemplatePage } from '~/client/services/create-page';
  16. import { useCreatePage } from '~/client/services/create-page/use-create-page';
  17. import { useToastrOnError } from '~/client/services/use-toastr-on-error';
  18. import { useCurrentUser } from '~/states/global';
  19. import { isSearchServiceReachableAtom } from '~/states/server-configurations';
  20. import { usePageCreateModalStatus, usePageCreateModalActions } from '~/states/ui/modal/page-create';
  21. import PagePathAutoComplete from './PagePathAutoComplete';
  22. import styles from './PageCreateModal.module.scss';
  23. const {
  24. isCreatablePage, isUsersHomepage,
  25. } = pagePathUtils;
  26. const PageCreateModal: React.FC = () => {
  27. const { t } = useTranslation();
  28. const currentUser = useCurrentUser();
  29. const { isOpened, path: pathname = '' } = usePageCreateModalStatus();
  30. const { close: closeCreateModal } = usePageCreateModalActions();
  31. const { create } = useCreatePage();
  32. const { createTemplate } = useCreateTemplatePage();
  33. const isReachable = useAtomValue(isSearchServiceReachableAtom);
  34. // Memoize computed values
  35. const userHomepagePath = useMemo(() => pagePathUtils.userHomepagePath(currentUser), [currentUser]);
  36. const isCreatable = useMemo(() => isCreatablePage(pathname) || isUsersHomepage(pathname), [pathname]);
  37. const pageNameInputInitialValue = useMemo(() => (isCreatable ? pathUtils.addTrailingSlash(pathname) : '/'), [isCreatable, pathname]);
  38. const now = useMemo(() => format(new Date(), 'yyyy/MM/dd'), []);
  39. const todaysParentPath = useMemo(
  40. () => [userHomepagePath, t('create_page_dropdown.todays.memo', { ns: 'commons' }), now].join('/'),
  41. [userHomepagePath, t, now],
  42. );
  43. const [todayInput, setTodayInput] = useState('');
  44. const [pageNameInput, setPageNameInput] = useState(pageNameInputInitialValue);
  45. const [template, setTemplate] = useState(null);
  46. const [isMatchedWithUserHomepagePath, setIsMatchedWithUserHomepagePath] = useState(false);
  47. const checkIsUsersHomepageDebounce = useMemo(() => {
  48. return debounce(1000, (input: string) => {
  49. setIsMatchedWithUserHomepagePath(isUsersHomepage(input));
  50. });
  51. }, []);
  52. useEffect(() => {
  53. if (isOpened) {
  54. checkIsUsersHomepageDebounce(pageNameInput);
  55. }
  56. }, [isOpened, checkIsUsersHomepageDebounce, pageNameInput]);
  57. const transitBySubmitEvent = useCallback((e, transitHandler) => {
  58. // prevent page transition by submit
  59. e.preventDefault();
  60. transitHandler();
  61. }, []);
  62. /**
  63. * change todayInput
  64. * @param {string} value
  65. */
  66. const onChangeTodayInputHandler = useCallback((value) => {
  67. setTodayInput(value);
  68. }, []);
  69. /**
  70. * change template
  71. * @param {string} value
  72. */
  73. const onChangeTemplateHandler = useCallback((value) => {
  74. setTemplate(value);
  75. }, []);
  76. /**
  77. * access today page
  78. */
  79. const createTodayPage = useCallback(async() => {
  80. const joinedPath = [todaysParentPath, todayInput].join('/');
  81. return create(
  82. {
  83. path: joinedPath, parentPath: todaysParentPath, wip: true, origin: Origin.View,
  84. },
  85. { onTerminated: closeCreateModal },
  86. );
  87. }, [closeCreateModal, create, todayInput, todaysParentPath]);
  88. /**
  89. * access input page
  90. */
  91. const createInputPage = useCallback(async() => {
  92. const targetPath = normalizePath(pageNameInput);
  93. const parentPath = path.dirname(targetPath);
  94. return create(
  95. {
  96. path: targetPath,
  97. parentPath,
  98. wip: true,
  99. origin: Origin.View,
  100. },
  101. { onTerminated: closeCreateModal },
  102. );
  103. }, [closeCreateModal, create, pageNameInput]);
  104. /**
  105. * access template page
  106. */
  107. const createTemplatePage = useCallback(async() => {
  108. const label = (template === 'children') ? '_template' : '__template';
  109. await createTemplate?.(label);
  110. closeCreateModal();
  111. }, [closeCreateModal, createTemplate, template]);
  112. const createTodaysMemoWithToastr = useToastrOnError(createTodayPage);
  113. const createInputPageWithToastr = useToastrOnError(createInputPage);
  114. const createTemplateWithToastr = useToastrOnError(createTemplatePage);
  115. const renderCreateTodayForm = useMemo(() => {
  116. if (!isOpened) {
  117. return <></>;
  118. }
  119. return (
  120. <div className="row">
  121. <fieldset className="col-12 mb-4">
  122. <h3 className="pb-2">{t('create_page_dropdown.todays.desc', { ns: 'commons' })}</h3>
  123. <div className="d-sm-flex align-items-center justify-items-between">
  124. <div className="d-flex align-items-center flex-fill flex-wrap flex-lg-nowrap">
  125. <div className="d-flex align-items-center text-nowrap">
  126. <span>{todaysParentPath}/</span>
  127. </div>
  128. <form className="mt-1 mt-lg-0 ms-lg-2 w-100" onSubmit={(e) => { transitBySubmitEvent(e, createTodaysMemoWithToastr) }}>
  129. <input
  130. type="text"
  131. className="page-today-input2 form-control w-100"
  132. id="page-today-input2"
  133. placeholder={t('Input page name (optional)')}
  134. value={todayInput}
  135. onChange={e => onChangeTodayInputHandler(e.target.value)}
  136. />
  137. </form>
  138. </div>
  139. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  140. <button
  141. type="button"
  142. data-testid="btn-create-memo"
  143. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ms-3"
  144. onClick={createTodaysMemoWithToastr}
  145. >
  146. <span className="material-symbols-outlined">description</span>{t('Create')}
  147. </button>
  148. </div>
  149. </div>
  150. </fieldset>
  151. </div>
  152. );
  153. }, [isOpened, todaysParentPath, todayInput, t, onChangeTodayInputHandler, transitBySubmitEvent, createTodaysMemoWithToastr]);
  154. const renderInputPageForm = useMemo(() => {
  155. if (!isOpened) {
  156. return <></>;
  157. }
  158. return (
  159. <div className="row" data-testid="row-create-page-under-below">
  160. <fieldset className="col-12 mb-4">
  161. <h3 className="pb-2">{t('Create under')}</h3>
  162. <div className="d-sm-flex align-items-center justify-items-between">
  163. <div className="flex-fill">
  164. {isReachable
  165. ? (
  166. <PagePathAutoComplete
  167. initializedPath={pageNameInputInitialValue}
  168. addTrailingSlash
  169. onSubmit={createInputPageWithToastr}
  170. onInputChange={value => setPageNameInput(value)}
  171. autoFocus
  172. />
  173. )
  174. : (
  175. <form onSubmit={(e) => { transitBySubmitEvent(e, createInputPageWithToastr) }}>
  176. <input
  177. type="text"
  178. value={pageNameInput}
  179. className="form-control flex-fill"
  180. placeholder={t('Input page name')}
  181. onChange={e => setPageNameInput(e.target.value)}
  182. required
  183. />
  184. </form>
  185. )}
  186. </div>
  187. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  188. <button
  189. type="button"
  190. data-testid="btn-create-page-under-below"
  191. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ms-3"
  192. onClick={createInputPageWithToastr}
  193. disabled={isMatchedWithUserHomepagePath}
  194. >
  195. <span className="material-symbols-outlined">description</span>{t('Create')}
  196. </button>
  197. </div>
  198. </div>
  199. { isMatchedWithUserHomepagePath && (
  200. <p className="text-danger mt-2">Error: Cannot create page under /user page directory.</p>
  201. ) }
  202. </fieldset>
  203. </div>
  204. );
  205. }, [isOpened, isReachable, pageNameInputInitialValue, createInputPageWithToastr, pageNameInput, isMatchedWithUserHomepagePath, t, transitBySubmitEvent]);
  206. const renderTemplatePageForm = useMemo(() => {
  207. if (!isOpened) {
  208. return <></>;
  209. }
  210. return (
  211. <div className="row">
  212. <fieldset className="col-12">
  213. <h3 className="pb-2">
  214. {t('template.modal_label.Create template under')}<br />
  215. <code className="h6" data-testid="grw-page-create-modal-path-name">{pathname}</code>
  216. </h3>
  217. <div className="d-sm-flex align-items-center justify-items-between">
  218. <UncontrolledButtonDropdown id="dd-template-type" className="flex-fill text-center">
  219. <DropdownToggle id="template-type" caret>
  220. {template == null && t('template.option_label.select')}
  221. {template === 'children' && t('template.children.label')}
  222. {template === 'descendants' && t('template.descendants.label')}
  223. </DropdownToggle>
  224. <DropdownMenu>
  225. <DropdownItem onClick={() => onChangeTemplateHandler('children')}>
  226. {t('template.children.label')} (_template)<br className="d-block d-md-none" />
  227. <small className="text-muted text-wrap">- {t('template.children.desc')}</small>
  228. </DropdownItem>
  229. <DropdownItem onClick={() => onChangeTemplateHandler('descendants')}>
  230. {t('template.descendants.label')} (__template) <br className="d-block d-md-none" />
  231. <small className="text-muted">- {t('template.descendants.desc')}</small>
  232. </DropdownItem>
  233. </DropdownMenu>
  234. </UncontrolledButtonDropdown>
  235. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  236. <button
  237. data-testid="grw-btn-edit-page"
  238. type="button"
  239. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ms-3"
  240. onClick={createTemplateWithToastr}
  241. disabled={template == null}
  242. >
  243. <span className="material-symbols-outlined">description</span>{t('Edit')}
  244. </button>
  245. </div>
  246. </div>
  247. </fieldset>
  248. </div>
  249. );
  250. }, [isOpened, pathname, template, onChangeTemplateHandler, createTemplateWithToastr, t]);
  251. return (
  252. <Modal
  253. size="lg"
  254. isOpen={isOpened}
  255. toggle={() => closeCreateModal()}
  256. data-testid="page-create-modal"
  257. className={`grw-create-page ${styles['grw-create-page']}`}
  258. autoFocus={false}
  259. >
  260. <ModalHeader tag="h4" toggle={() => closeCreateModal()}>
  261. {t('New Page')}
  262. </ModalHeader>
  263. <ModalBody>
  264. {renderCreateTodayForm}
  265. {renderInputPageForm}
  266. {renderTemplatePageForm}
  267. </ModalBody>
  268. </Modal>
  269. );
  270. };
  271. export default PageCreateModal;