LinkEditModal.tsx 14 KB

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