LinkEditModal.tsx 13 KB

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