PageCreateModal.jsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. import React, {
  2. useEffect, useState, useMemo, useCallback,
  3. } from 'react';
  4. import { pagePathUtils, pathUtils } from '@growi/core';
  5. import { format } from 'date-fns';
  6. import PropTypes from 'prop-types';
  7. import { withTranslation } from 'react-i18next';
  8. import { Modal, ModalHeader, ModalBody } from 'reactstrap';
  9. import { debounce } from 'throttle-debounce';
  10. import AppContainer from '~/client/services/AppContainer';
  11. import { toastError } from '~/client/util/apiNotification';
  12. import { useCurrentUser } from '~/stores/context';
  13. import { usePageCreateModal } from '~/stores/modal';
  14. import PagePathAutoComplete from './PagePathAutoComplete';
  15. import { withUnstatedContainers } from './UnstatedUtils';
  16. const {
  17. userPageRoot, isCreatablePage, generateEditorPath, isUsersHomePage,
  18. } = pagePathUtils;
  19. const PageCreateModal = (props) => {
  20. const { t, appContainer } = props;
  21. const { data: currentUser } = useCurrentUser();
  22. const { data: pageCreateModalData, close: closeCreateModal } = usePageCreateModal();
  23. const { isOpened, path } = pageCreateModalData;
  24. const config = appContainer.getConfig();
  25. const isReachable = config.isSearchServiceReachable;
  26. const pathname = path || '';
  27. const userPageRootPath = userPageRoot(currentUser);
  28. const isCreatable = isCreatablePage(pathname) || isUsersHomePage(pathname);
  29. const pageNameInputInitialValue = isCreatable ? pathUtils.addTrailingSlash(pathname) : '/';
  30. const now = format(new Date(), 'yyyy/MM/dd');
  31. const [todayInput1, setTodayInput1] = useState(t('Memo'));
  32. const [todayInput2, setTodayInput2] = useState('');
  33. const [pageNameInput, setPageNameInput] = useState(pageNameInputInitialValue);
  34. const [template, setTemplate] = useState(null);
  35. const [isMatchedWithUserHomePagePath, setIsMatchedWithUserHomePagePath] = useState(false);
  36. // ensure pageNameInput is synced with selectedPagePath || currentPagePath
  37. useEffect(() => {
  38. setPageNameInput(isCreatable ? pathUtils.addTrailingSlash(pathname) : '/');
  39. }, [pathname, isCreatable]);
  40. const checkIsUsersHomePageDebounce = useMemo(() => {
  41. const checkIsUsersHomePage = () => {
  42. setIsMatchedWithUserHomePagePath(isUsersHomePage(pageNameInput));
  43. };
  44. return debounce(1000, checkIsUsersHomePage);
  45. }, [pageNameInput]);
  46. useEffect(() => {
  47. checkIsUsersHomePageDebounce(pageNameInput);
  48. }, [checkIsUsersHomePageDebounce, pageNameInput]);
  49. function transitBySubmitEvent(e, transitHandler) {
  50. // prevent page transition by submit
  51. e.preventDefault();
  52. transitHandler();
  53. }
  54. /**
  55. * change todayInput1
  56. * @param {string} value
  57. */
  58. function onChangeTodayInput1Handler(value) {
  59. setTodayInput1(value);
  60. }
  61. /**
  62. * change todayInput2
  63. * @param {string} value
  64. */
  65. function onChangeTodayInput2Handler(value) {
  66. setTodayInput2(value);
  67. }
  68. /**
  69. * change template
  70. * @param {string} value
  71. */
  72. function onChangeTemplateHandler(value) {
  73. setTemplate(value);
  74. }
  75. /**
  76. * join path, check if creatable, then redirect
  77. * @param {string} paths
  78. */
  79. async function redirectToEditor(...paths) {
  80. try {
  81. const editorPath = await generateEditorPath(...paths);
  82. window.location.href = editorPath;
  83. }
  84. catch (err) {
  85. toastError(err);
  86. }
  87. }
  88. /**
  89. * access today page
  90. */
  91. function createTodayPage() {
  92. let tmpTodayInput1 = todayInput1;
  93. if (tmpTodayInput1 === '') {
  94. tmpTodayInput1 = t('Memo');
  95. }
  96. redirectToEditor(userPageRootPath, tmpTodayInput1, now, todayInput2);
  97. }
  98. /**
  99. * access input page
  100. */
  101. function createInputPage() {
  102. redirectToEditor(pageNameInput);
  103. }
  104. function ppacSubmitHandler(input) {
  105. redirectToEditor(input);
  106. }
  107. /**
  108. * access template page
  109. */
  110. function createTemplatePage(e) {
  111. const pageName = (template === 'children') ? '_template' : '__template';
  112. redirectToEditor(pathname, pageName);
  113. }
  114. function renderCreateTodayForm() {
  115. return (
  116. <div className="row">
  117. <fieldset className="col-12 mb-4">
  118. <h3 className="grw-modal-head pb-2">{t("Create today's")}</h3>
  119. <div className="d-sm-flex align-items-center justify-items-between">
  120. <div className="d-flex align-items-center flex-fill flex-wrap flex-lg-nowrap">
  121. <div className="d-flex align-items-center">
  122. <span>{userPageRootPath}/</span>
  123. <form onSubmit={e => transitBySubmitEvent(e, createTodayPage)}>
  124. <input
  125. type="text"
  126. className="page-today-input1 form-control text-center mx-2"
  127. value={todayInput1}
  128. onChange={e => onChangeTodayInput1Handler(e.target.value)}
  129. />
  130. </form>
  131. <span className="page-today-suffix">/{now}/</span>
  132. </div>
  133. <form className="mt-1 mt-lg-0 ml-lg-2 w-100" onSubmit={e => transitBySubmitEvent(e, createTodayPage)}>
  134. <input
  135. type="text"
  136. className="page-today-input2 form-control w-100"
  137. id="page-today-input2"
  138. placeholder={t('Input page name (optional)')}
  139. value={todayInput2}
  140. onChange={e => onChangeTodayInput2Handler(e.target.value)}
  141. />
  142. </form>
  143. </div>
  144. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  145. <button
  146. type="button"
  147. data-testid="btn-create-memo"
  148. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ml-3"
  149. onClick={createTodayPage}
  150. >
  151. <i className="icon-fw icon-doc"></i>{t('Create')}
  152. </button>
  153. </div>
  154. </div>
  155. </fieldset>
  156. </div>
  157. );
  158. }
  159. function renderInputPageForm() {
  160. return (
  161. <div className="row" data-testid="row-create-page-under-below">
  162. <fieldset className="col-12 mb-4">
  163. <h3 className="grw-modal-head pb-2">{t('Create under')}</h3>
  164. <div className="d-sm-flex align-items-center justify-items-between">
  165. <div className="flex-fill">
  166. {isReachable
  167. ? (
  168. <PagePathAutoComplete
  169. initializedPath={pageNameInput}
  170. addTrailingSlash
  171. onSubmit={ppacSubmitHandler}
  172. onInputChange={value => setPageNameInput(value)}
  173. autoFocus
  174. />
  175. )
  176. : (
  177. <form onSubmit={e => transitBySubmitEvent(e, createInputPage)}>
  178. <input
  179. type="text"
  180. value={pageNameInput}
  181. className="form-control flex-fill"
  182. placeholder={t('Input page name')}
  183. onChange={e => setPageNameInput(e.target.value)}
  184. required
  185. />
  186. </form>
  187. )}
  188. </div>
  189. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  190. <button
  191. type="button"
  192. data-testid="btn-create-page-under-below"
  193. className="grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ml-3"
  194. onClick={createInputPage}
  195. disabled={isMatchedWithUserHomePagePath}
  196. >
  197. <i className="icon-fw icon-doc"></i>{t('Create')}
  198. </button>
  199. </div>
  200. </div>
  201. { isMatchedWithUserHomePagePath && (
  202. <p className="text-danger mt-2">Error: Cannot create page under /user page directory.</p>
  203. ) }
  204. </fieldset>
  205. </div>
  206. );
  207. }
  208. function renderTemplatePageForm() {
  209. return (
  210. <div className="row">
  211. <fieldset className="col-12">
  212. <h3 className="grw-modal-head pb-2">
  213. {t('template.modal_label.Create template under')}<br />
  214. <code className="h6">{pathname}</code>
  215. </h3>
  216. <div className="d-sm-flex align-items-center justify-items-between">
  217. <div id="dd-template-type" className="dropdown flex-fill">
  218. <button id="template-type" type="button" className="btn btn-secondary btn dropdown-toggle w-100" data-toggle="dropdown">
  219. {template == null && t('template.option_label.select')}
  220. {template === 'children' && t('template.children.label')}
  221. {template === 'decendants' && t('template.decendants.label')}
  222. </button>
  223. <div className="dropdown-menu" aria-labelledby="userMenu">
  224. <button className="dropdown-item" type="button" onClick={() => onChangeTemplateHandler('children')}>
  225. {t('template.children.label')} (_template)<br className="d-block d-md-none" />
  226. <small className="text-muted text-wrap">- {t('template.children.desc')}</small>
  227. </button>
  228. <button className="dropdown-item" type="button" onClick={() => onChangeTemplateHandler('decendants')}>
  229. {t('template.decendants.label')} (__template) <br className="d-block d-md-none" />
  230. <small className="text-muted">- {t('template.decendants.desc')}</small>
  231. </button>
  232. </div>
  233. </div>
  234. <div className="d-flex justify-content-end mt-1 mt-sm-0">
  235. <button
  236. type="button"
  237. className={`grw-btn-create-page btn btn-outline-primary rounded-pill text-nowrap ml-3 ${template == null && 'disabled'}`}
  238. onClick={createTemplatePage}
  239. >
  240. <i className="icon-fw icon-doc"></i>{t('Edit')}
  241. </button>
  242. </div>
  243. </div>
  244. </fieldset>
  245. </div>
  246. );
  247. }
  248. return (
  249. <Modal
  250. size="lg"
  251. isOpen={isOpened}
  252. toggle={() => closeCreateModal()}
  253. data-testid="page-create-modal"
  254. className="grw-create-page"
  255. autoFocus={false}
  256. >
  257. <ModalHeader tag="h4" toggle={() => closeCreateModal()} className="bg-primary text-light">
  258. {t('New Page')}
  259. </ModalHeader>
  260. <ModalBody>
  261. {renderCreateTodayForm()}
  262. {renderInputPageForm()}
  263. {renderTemplatePageForm()}
  264. </ModalBody>
  265. </Modal>
  266. );
  267. };
  268. /**
  269. * Wrapper component for using unstated
  270. */
  271. const ModalControlWrapper = withUnstatedContainers(PageCreateModal, [AppContainer]);
  272. PageCreateModal.propTypes = {
  273. t: PropTypes.func.isRequired, // i18next
  274. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  275. };
  276. export default withTranslation()(ModalControlWrapper);