PageCreateModal.tsx 10 KB

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