PageCreateModal.tsx 12 KB

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