PageCreateModal.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 { useCreatePageAndTransit } from '~/client/services/create-page/use-create-page-and-transit';
  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 { createAndTransit } = useCreatePageAndTransit();
  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 createAndTransit(
  77. { path: joinedPath, wip: true, origin: Origin.View },
  78. { shouldCheckPageExists: true, onTerminated: closeCreateModal },
  79. );
  80. }, [closeCreateModal, createAndTransit, todayInput, todaysParentPath]);
  81. /**
  82. * access input page
  83. */
  84. const createInputPage = useCallback(async() => {
  85. return createAndTransit(
  86. {
  87. path: pageNameInput,
  88. wip: true,
  89. origin: Origin.View,
  90. },
  91. { shouldCheckPageExists: true, onTerminated: closeCreateModal },
  92. );
  93. }, [closeCreateModal, createAndTransit, pageNameInput]);
  94. /**
  95. * access template page
  96. */
  97. const createTemplatePage = useCallback(async() => {
  98. const label = (template === 'children') ? '_template' : '__template';
  99. await createTemplate?.(label);
  100. closeCreateModal();
  101. }, [closeCreateModal, createTemplate, template]);
  102. const createTodaysMemoWithToastr = useToastrOnError(createTodayPage);
  103. const createInputPageWithToastr = useToastrOnError(createInputPage);
  104. const createTemplateWithToastr = useToastrOnError(createTemplatePage);
  105. function renderCreateTodayForm() {
  106. if (!isOpened) {
  107. return <></>;
  108. }
  109. return (
  110. <div className="row">
  111. <fieldset className="col-12 mb-4">
  112. <h3 className="pb-2">{t('create_page_dropdown.todays.desc', { ns: 'commons' })}</h3>
  113. <div className="d-sm-flex align-items-center justify-items-between">
  114. <div className="d-flex align-items-center flex-fill flex-wrap flex-lg-nowrap">
  115. <div className="d-flex align-items-center text-nowrap">
  116. <span>{todaysParentPath}/</span>
  117. </div>
  118. <form className="mt-1 mt-lg-0 ms-lg-2 w-100" onSubmit={(e) => { transitBySubmitEvent(e, createTodaysMemoWithToastr) }}>
  119. <input
  120. type="text"
  121. className="page-today-input2 form-control w-100"
  122. id="page-today-input2"
  123. placeholder={t('Input page name (optional)')}
  124. value={todayInput}
  125. onChange={e => onChangeTodayInputHandler(e.target.value)}
  126. />
  127. </form>
  128. </div>
  129. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  130. <button
  131. type="button"
  132. data-testid="btn-create-memo"
  133. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ms-3"
  134. onClick={createTodaysMemoWithToastr}
  135. >
  136. <span className="material-symbols-outlined">description</span>{t('Create')}
  137. </button>
  138. </div>
  139. </div>
  140. </fieldset>
  141. </div>
  142. );
  143. }
  144. function renderInputPageForm() {
  145. if (!isOpened) {
  146. return <></>;
  147. }
  148. return (
  149. <div className="row" data-testid="row-create-page-under-below">
  150. <fieldset className="col-12 mb-4">
  151. <h3 className="pb-2">{t('Create under')}</h3>
  152. <div className="d-sm-flex align-items-center justify-items-between">
  153. <div className="flex-fill">
  154. {isReachable
  155. ? (
  156. <PagePathAutoComplete
  157. initializedPath={pageNameInputInitialValue}
  158. addTrailingSlash
  159. onSubmit={createInputPageWithToastr}
  160. onInputChange={value => setPageNameInput(value)}
  161. autoFocus
  162. />
  163. )
  164. : (
  165. <form onSubmit={(e) => { transitBySubmitEvent(e, createInputPageWithToastr) }}>
  166. <input
  167. type="text"
  168. value={pageNameInput}
  169. className="form-control flex-fill"
  170. placeholder={t('Input page name')}
  171. onChange={e => setPageNameInput(e.target.value)}
  172. required
  173. />
  174. </form>
  175. )}
  176. </div>
  177. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  178. <button
  179. type="button"
  180. data-testid="btn-create-page-under-below"
  181. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ms-3"
  182. onClick={createInputPageWithToastr}
  183. disabled={isMatchedWithUserHomepagePath}
  184. >
  185. <span className="material-symbols-outlined">description</span>{t('Create')}
  186. </button>
  187. </div>
  188. </div>
  189. { isMatchedWithUserHomepagePath && (
  190. <p className="text-danger mt-2">Error: Cannot create page under /user page directory.</p>
  191. ) }
  192. </fieldset>
  193. </div>
  194. );
  195. }
  196. function renderTemplatePageForm() {
  197. if (!isOpened) {
  198. return <></>;
  199. }
  200. return (
  201. <div className="row">
  202. <fieldset className="col-12">
  203. <h3 className="pb-2">
  204. {t('template.modal_label.Create template under')}<br />
  205. <code className="h6" data-testid="grw-page-create-modal-path-name">{pathname}</code>
  206. </h3>
  207. <div className="d-sm-flex align-items-center justify-items-between">
  208. <UncontrolledButtonDropdown id="dd-template-type" className="flex-fill text-center">
  209. <DropdownToggle id="template-type" caret>
  210. {template == null && t('template.option_label.select')}
  211. {template === 'children' && t('template.children.label')}
  212. {template === 'descendants' && t('template.descendants.label')}
  213. </DropdownToggle>
  214. <DropdownMenu>
  215. <DropdownItem onClick={() => onChangeTemplateHandler('children')}>
  216. {t('template.children.label')} (_template)<br className="d-block d-md-none" />
  217. <small className="text-muted text-wrap">- {t('template.children.desc')}</small>
  218. </DropdownItem>
  219. <DropdownItem onClick={() => onChangeTemplateHandler('descendants')}>
  220. {t('template.descendants.label')} (__template) <br className="d-block d-md-none" />
  221. <small className="text-muted">- {t('template.descendants.desc')}</small>
  222. </DropdownItem>
  223. </DropdownMenu>
  224. </UncontrolledButtonDropdown>
  225. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  226. <button
  227. data-testid="grw-btn-edit-page"
  228. type="button"
  229. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ms-3"
  230. onClick={createTemplateWithToastr}
  231. disabled={template == null}
  232. >
  233. <span className="material-symbols-outlined">description</span>{t('Edit')}
  234. </button>
  235. </div>
  236. </div>
  237. </fieldset>
  238. </div>
  239. );
  240. }
  241. return (
  242. <Modal
  243. size="lg"
  244. isOpen={isOpened}
  245. toggle={() => closeCreateModal()}
  246. data-testid="page-create-modal"
  247. className={`grw-create-page ${styles['grw-create-page']}`}
  248. autoFocus={false}
  249. >
  250. <ModalHeader tag="h4" toggle={() => closeCreateModal()}>
  251. {t('New Page')}
  252. </ModalHeader>
  253. <ModalBody>
  254. {renderCreateTodayForm()}
  255. {renderInputPageForm()}
  256. {renderTemplatePageForm()}
  257. </ModalBody>
  258. </Modal>
  259. );
  260. };
  261. export default PageCreateModal;