LinkEditModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import React, { useEffect, useState, useCallback } from 'react';
  2. import path from 'path';
  3. import Linker from '@growi/editor/src/services/link-util/Linker';
  4. import { useLinkEditModal } from '@growi/editor/src/stores/use-link-edit-modal';
  5. import { useTranslation } from 'next-i18next';
  6. import {
  7. Modal,
  8. ModalHeader,
  9. ModalBody,
  10. ModalFooter,
  11. Popover,
  12. PopoverBody,
  13. } from 'reactstrap';
  14. import validator from 'validator';
  15. import { apiv3Get } from '~/client/util/apiv3-client';
  16. import { useCurrentPagePath } from '~/stores/page';
  17. import { usePreviewOptions } from '~/stores/renderer';
  18. import loggerFactory from '~/utils/logger';
  19. import PagePreviewIcon from '../Icons/PagePreviewIcon';
  20. import SearchTypeahead from '../SearchTypeahead';
  21. import Preview from './Preview';
  22. import styles from './LinkEditPreview.module.scss';
  23. const logger = loggerFactory('growi:components:LinkEditModal');
  24. export const LinkEditModal = (): JSX.Element => {
  25. const { t } = useTranslation();
  26. const { data: currentPath } = useCurrentPagePath();
  27. const { data: rendererOptions } = usePreviewOptions();
  28. const { data: linkEditModalStatus, close } = useLinkEditModal();
  29. const [isUseRelativePath, setIsUseRelativePath] = useState<boolean>(false);
  30. const [isUsePermanentLink, setIsUsePermanentLink] = useState<boolean>(false);
  31. const [linkInputValue, setLinkInputValue] = useState<string>('');
  32. const [labelInputValue, setLabelInputValue] = useState<string>('');
  33. const [linkerType, setLinkerType] = useState<string>('');
  34. const [markdown, setMarkdown] = useState<string>('');
  35. const [pagePath, setPagePath] = useState<string>('');
  36. const [previewError, setPreviewError] = useState<string>();
  37. const [permalink, setPermalink] = useState<string>('');
  38. const [isPreviewOpen, setIsPreviewOpen] = useState<boolean>(false);
  39. const getRootPath = useCallback((type: string) => {
  40. // rootPaths of md link and pukiwiki link are different
  41. if (currentPath == null) return '';
  42. return type === Linker.types.markdownLink ? path.dirname(currentPath) : currentPath;
  43. }, [currentPath]);
  44. // parse link, link is ...
  45. // case-1. url of this growi's page (ex. 'http://localhost:3000/hoge/fuga')
  46. // case-2. absolute path of this growi's page (ex. '/hoge/fuga')
  47. // case-3. relative path of this growi's page (ex. '../fuga', 'hoge')
  48. // case-4. external link (ex. 'https://growi.org')
  49. // case-5. the others (ex. '')
  50. const parseLinkAndSetState = useCallback((link: string, type: string) => {
  51. // create url from link, add dummy origin if link is not valid url.
  52. // ex-1. link = 'https://growi.org/' -> url = 'https://growi.org/' (case-1,4)
  53. // ex-2. link = 'hoge' -> url = 'http://example.com/hoge' (case-2,3,5)
  54. let isFqcn = false;
  55. let isUseRelativePath = false;
  56. let url;
  57. try {
  58. const url = new URL(link, 'http://example.com');
  59. isFqcn = url.origin !== 'http://example.com';
  60. }
  61. catch (err) {
  62. logger.debug(err);
  63. }
  64. // case-1: when link is this growi's page url, return pathname only
  65. let reshapedLink = url != null && url.origin === window.location.origin
  66. ? decodeURIComponent(url.pathname)
  67. : link;
  68. // case-3
  69. if (!isFqcn && !reshapedLink.startsWith('/') && reshapedLink !== '') {
  70. isUseRelativePath = true;
  71. const rootPath = getRootPath(type);
  72. reshapedLink = path.resolve(rootPath, reshapedLink);
  73. }
  74. setLinkInputValue(reshapedLink);
  75. setIsUseRelativePath(isUseRelativePath);
  76. }, [getRootPath]);
  77. useEffect(() => {
  78. if (linkEditModalStatus == null) { return }
  79. const { label = '', link = '' } = linkEditModalStatus.defaultMarkdownLink ?? {};
  80. const { type = Linker.types.markdownLink } = linkEditModalStatus.defaultMarkdownLink ?? {};
  81. parseLinkAndSetState(link, type);
  82. setLabelInputValue(label);
  83. setIsUsePermanentLink(false);
  84. setPermalink('');
  85. setLinkerType(type);
  86. }, [linkEditModalStatus, parseLinkAndSetState]);
  87. const toggleIsUseRelativePath = () => {
  88. if (!linkInputValue.startsWith('/') || linkerType === Linker.types.growiLink) {
  89. return;
  90. }
  91. // User can't use both relativePath and permalink at the same time
  92. setIsUseRelativePath(!isUseRelativePath);
  93. setIsUsePermanentLink(false);
  94. };
  95. const toggleIsUsePamanentLink = () => {
  96. if (permalink === '' || linkerType === Linker.types.growiLink) {
  97. return;
  98. }
  99. // User can't use both relativePath and permalink at the same time
  100. setIsUsePermanentLink(!isUsePermanentLink);
  101. setIsUseRelativePath(false);
  102. };
  103. const setMarkdownHandler = async() => {
  104. const path = linkInputValue;
  105. let markdown = '';
  106. let pagePath = '';
  107. let permalink = '';
  108. if (path.startsWith('/')) {
  109. try {
  110. const pathWithoutFragment = new URL(path, 'http://dummy').pathname;
  111. const isPermanentLink = validator.isMongoId(pathWithoutFragment.slice(1));
  112. const pageId = isPermanentLink ? pathWithoutFragment.slice(1) : null;
  113. const { data } = await apiv3Get('/page', { path: pathWithoutFragment, page_id: pageId });
  114. const { page } = data;
  115. markdown = page.revision.body;
  116. pagePath = page.path;
  117. permalink = page.id;
  118. }
  119. catch (err) {
  120. setPreviewError(err.message);
  121. }
  122. }
  123. else {
  124. setPreviewError(t('link_edit.page_not_found_in_preview', { path }));
  125. }
  126. setMarkdown(markdown);
  127. setPagePath(pagePath);
  128. setPermalink(permalink);
  129. };
  130. const generateLink = () => {
  131. let reshapedLink = linkInputValue;
  132. if (isUseRelativePath) {
  133. const rootPath = getRootPath(linkerType);
  134. reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
  135. }
  136. if (isUsePermanentLink && permalink != null) {
  137. reshapedLink = permalink;
  138. }
  139. return new Linker(linkerType, labelInputValue, reshapedLink);
  140. };
  141. const renderLinkPreview = (): JSX.Element => {
  142. const linker = generateLink();
  143. return (
  144. <div className="d-flex justify-content-between mb-3 flex-column flex-sm-row">
  145. <div className="card card-disabled w-100 p-1 mb-0">
  146. <p className="text-start text-muted mb-1 small">Markdown</p>
  147. <p className="text-center text-truncate text-muted">{linker.generateMarkdownText()}</p>
  148. </div>
  149. <div className="d-flex align-items-center justify-content-center">
  150. <span className="lead mx-3">
  151. <i className="d-none d-sm-block fa fa-caret-right"></i>
  152. <i className="d-sm-none fa fa-caret-down"></i>
  153. </span>
  154. </div>
  155. <div className="card w-100 p-1 mb-0">
  156. <p className="text-start text-muted mb-1 small">HTML</p>
  157. <p className="text-center text-truncate">
  158. <a href={linker.link}>{linker.label}</a>
  159. </p>
  160. </div>
  161. </div>
  162. );
  163. };
  164. const handleChangeTypeahead = (selected) => {
  165. const pageWithMeta = selected[0];
  166. if (pageWithMeta != null) {
  167. const page = pageWithMeta.data;
  168. const permalink = `${window.location.origin}/${page.id}`;
  169. setLinkInputValue(page.path);
  170. setPermalink(permalink);
  171. }
  172. };
  173. const handleChangeLabelInput = (label: string) => {
  174. setLabelInputValue(label);
  175. };
  176. const handleChangeLinkInput = (link) => {
  177. let useRelativePath = isUseRelativePath;
  178. if (!linkInputValue.startsWith('/') || linkerType === Linker.types.growiLink) {
  179. useRelativePath = false;
  180. }
  181. setLinkInputValue(link);
  182. setIsUseRelativePath(useRelativePath);
  183. setIsUsePermanentLink(false);
  184. setPermalink('');
  185. };
  186. const save = () => {
  187. const linker = generateLink();
  188. if (linkEditModalStatus?.onSave != null) {
  189. linkEditModalStatus.onSave(linker.generateMarkdownText() ?? '');
  190. }
  191. close();
  192. };
  193. const toggleIsPreviewOpen = async() => {
  194. // open popover
  195. if (!isPreviewOpen) {
  196. setMarkdownHandler();
  197. }
  198. setIsPreviewOpen(!isPreviewOpen);
  199. };
  200. const renderLinkAndLabelForm = (): JSX.Element => {
  201. return (
  202. <>
  203. <h3 className="grw-modal-head">{t('link_edit.set_link_and_label')}</h3>
  204. <form>
  205. <div className="form-gorup my-3">
  206. <div className="input-group flex-nowrap">
  207. <div>
  208. <span className="input-group-text">{t('link_edit.link')}</span>
  209. </div>
  210. <SearchTypeahead
  211. onChange={handleChangeTypeahead}
  212. onInputChange={handleChangeLinkInput}
  213. placeholder={t('link_edit.placeholder_of_link_input')}
  214. keywordOnInit={linkInputValue}
  215. autoFocus
  216. />
  217. <div className="d-none d-sm-block">
  218. <button type="button" id="preview-btn" className={`btn btn-info btn-page-preview ${styles['btn-page-preview']}`}>
  219. <PagePreviewIcon />
  220. </button>
  221. <Popover trigger="focus" placement="right" isOpen={isPreviewOpen} target="preview-btn" toggle={toggleIsPreviewOpen}>
  222. <PopoverBody>
  223. {markdown != null && pagePath != null && rendererOptions != null
  224. && (
  225. <div className={`linkedit-preview ${styles['linkedit-preview']}`}>
  226. <Preview markdown={markdown} pagePath={pagePath} rendererOptions={rendererOptions} />
  227. </div>
  228. )
  229. }
  230. </PopoverBody>
  231. </Popover>
  232. </div>
  233. </div>
  234. </div>
  235. <div className="form-gorup my-3">
  236. <div className="input-group flex-nowrap">
  237. <div>
  238. <span className="input-group-text">{t('link_edit.label')}</span>
  239. </div>
  240. <input
  241. type="text"
  242. className="form-control"
  243. id="label"
  244. value={labelInputValue}
  245. onChange={e => handleChangeLabelInput(e.target.value)}
  246. disabled={linkerType === Linker.types.growiLink}
  247. placeholder={linkInputValue}
  248. />
  249. </div>
  250. </div>
  251. </form>
  252. </>
  253. );
  254. };
  255. const renderPathFormatForm = (): JSX.Element => {
  256. return (
  257. <div className="card custom-card pt-3">
  258. <form className="mb-0">
  259. <div className="mb-0 row">
  260. <label className="form-label col-sm-3">{t('link_edit.path_format')}</label>
  261. <div className="col-sm-9">
  262. <div className="form-check form-check-info form-check-inline">
  263. <input
  264. className="form-check-input"
  265. id="relativePath"
  266. type="checkbox"
  267. checked={isUseRelativePath}
  268. onChange={toggleIsUseRelativePath}
  269. disabled={!linkInputValue.startsWith('/') || linkerType === Linker.types.growiLink}
  270. />
  271. <label className="form-label form-check-label" htmlFor="relativePath">
  272. {t('link_edit.use_relative_path')}
  273. </label>
  274. </div>
  275. <div className="form-check form-check-info form-check-inline">
  276. <input
  277. className="form-check-input"
  278. id="permanentLink"
  279. type="checkbox"
  280. checked={isUsePermanentLink}
  281. onChange={toggleIsUsePamanentLink}
  282. disabled={permalink === '' || linkerType === Linker.types.growiLink}
  283. />
  284. <label className="form-label form-check-label" htmlFor="permanentLink">
  285. {t('link_edit.use_permanent_link')}
  286. </label>
  287. </div>
  288. </div>
  289. </div>
  290. </form>
  291. </div>
  292. );
  293. };
  294. if (linkEditModalStatus == null) {
  295. return <></>;
  296. }
  297. return (
  298. <Modal className="link-edit-modal" isOpen={linkEditModalStatus.isOpened} toggle={close} size="lg" autoFocus={false}>
  299. <ModalHeader tag="h4" toggle={close} className="bg-primary text-light">
  300. {t('link_edit.edit_link')}
  301. </ModalHeader>
  302. <ModalBody className="container">
  303. <div className="row">
  304. <div className="col-12">
  305. {renderLinkAndLabelForm()}
  306. {renderPathFormatForm()}
  307. </div>
  308. </div>
  309. <div className="row">
  310. <div className="col-12">
  311. <h3 className="grw-modal-head">{t('link_edit.preview')}</h3>
  312. {renderLinkPreview()}
  313. </div>
  314. </div>
  315. </ModalBody>
  316. <ModalFooter>
  317. { previewError && <span className="text-danger">{previewError}</span>}
  318. <button type="button" className="btn btn-sm btn-outline-secondary mx-1" onClick={close}>
  319. {t('Cancel')}
  320. </button>
  321. <button type="submit" className="btn btn-sm btn-primary mx-1" onClick={save}>
  322. {t('Done')}
  323. </button>
  324. </ModalFooter>
  325. </Modal>
  326. );
  327. };
  328. LinkEditModal.displayName = 'LinkEditModal';