LinkEditModal.tsx 13 KB

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