LinkEditModal.tsx 13 KB

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