PageCreateModal.tsx 10 KB

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