LinkEditModal.jsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. import React from 'react';
  2. import path from 'path';
  3. import { useTranslation } from 'next-i18next';
  4. import PropTypes from 'prop-types';
  5. import {
  6. Modal,
  7. ModalHeader,
  8. ModalBody,
  9. ModalFooter,
  10. Popover,
  11. PopoverBody,
  12. } from 'reactstrap';
  13. import validator from 'validator';
  14. import Linker from '~/client/models/Linker';
  15. import { apiv3Get } from '~/client/util/apiv3-client';
  16. import { useCurrentPagePath } from '~/stores/page';
  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. class LinkEditModal extends React.PureComponent {
  24. constructor(props) {
  25. super(props);
  26. this.state = {
  27. show: false,
  28. isUseRelativePath: false,
  29. isUsePermanentLink: false,
  30. linkInputValue: '',
  31. labelInputValue: '',
  32. linkerType: Linker.types.markdownLink,
  33. markdown: null,
  34. pagePath: null,
  35. previewError: '',
  36. permalink: '',
  37. isPreviewOpen: false,
  38. };
  39. // this.isApplyPukiwikiLikeLinkerPlugin = window.growiRenderer.preProcessors.some(process => process.constructor.name === 'PukiwikiLikeLinker');
  40. this.show = this.show.bind(this);
  41. this.hide = this.hide.bind(this);
  42. this.cancel = this.cancel.bind(this);
  43. this.handleChangeTypeahead = this.handleChangeTypeahead.bind(this);
  44. this.handleChangeLabelInput = this.handleChangeLabelInput.bind(this);
  45. this.handleChangeLinkInput = this.handleChangeLinkInput.bind(this);
  46. this.handleSelecteLinkerType = this.handleSelecteLinkerType.bind(this);
  47. this.toggleIsUseRelativePath = this.toggleIsUseRelativePath.bind(this);
  48. this.toggleIsUsePamanentLink = this.toggleIsUsePamanentLink.bind(this);
  49. this.save = this.save.bind(this);
  50. this.generateLink = this.generateLink.bind(this);
  51. this.getRootPath = this.getRootPath.bind(this);
  52. this.toggleIsPreviewOpen = this.toggleIsPreviewOpen.bind(this);
  53. this.setMarkdown = this.setMarkdown.bind(this);
  54. }
  55. // defaultMarkdownLink is an instance of Linker
  56. show(defaultMarkdownLink = null) {
  57. // if defaultMarkdownLink is null, set default value in inputs.
  58. const { label = '', link = '' } = defaultMarkdownLink;
  59. let { type = Linker.types.markdownLink } = defaultMarkdownLink;
  60. // if type of defaultMarkdownLink is pukiwikiLink when pukiwikiLikeLinker plugin is disable, change type(not change label and link)
  61. if (type === Linker.types.pukiwikiLink && !this.isApplyPukiwikiLikeLinkerPlugin) {
  62. type = Linker.types.markdownLink;
  63. }
  64. this.parseLinkAndSetState(link, type);
  65. this.setState({
  66. show: true,
  67. labelInputValue: label,
  68. isUsePermanentLink: false,
  69. permalink: '',
  70. linkerType: type,
  71. });
  72. }
  73. // parse link, link is ...
  74. // case-1. url of this growi's page (ex. 'http://localhost:3000/hoge/fuga')
  75. // case-2. absolute path of this growi's page (ex. '/hoge/fuga')
  76. // case-3. relative path of this growi's page (ex. '../fuga', 'hoge')
  77. // case-4. external link (ex. 'https://growi.org')
  78. // case-5. the others (ex. '')
  79. parseLinkAndSetState(link, type) {
  80. // create url from link, add dummy origin if link is not valid url.
  81. // ex-1. link = 'https://growi.org/' -> url = 'https://growi.org/' (case-1,4)
  82. // ex-2. link = 'hoge' -> url = 'http://example.com/hoge' (case-2,3,5)
  83. let isFqcn = false;
  84. let isUseRelativePath = false;
  85. let url;
  86. try {
  87. const url = new URL(link, 'http://example.com');
  88. isFqcn = url.origin !== 'http://example.com';
  89. }
  90. catch (err) {
  91. logger.debug(err);
  92. }
  93. // case-1: when link is this growi's page url, return pathname only
  94. let reshapedLink = url != null && url.origin === window.location.origin
  95. ? decodeURIComponent(url.pathname)
  96. : link;
  97. // case-3
  98. if (!isFqcn && !reshapedLink.startsWith('/') && reshapedLink !== '') {
  99. isUseRelativePath = true;
  100. const rootPath = this.getRootPath(type);
  101. reshapedLink = path.resolve(rootPath, reshapedLink);
  102. }
  103. this.setState({
  104. linkInputValue: reshapedLink,
  105. isUseRelativePath,
  106. });
  107. }
  108. cancel() {
  109. this.hide();
  110. }
  111. hide() {
  112. this.setState({
  113. show: false,
  114. });
  115. }
  116. toggleIsUseRelativePath() {
  117. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  118. return;
  119. }
  120. // User can't use both relativePath and permalink at the same time
  121. this.setState({ isUseRelativePath: !this.state.isUseRelativePath, isUsePermanentLink: false });
  122. }
  123. toggleIsUsePamanentLink() {
  124. if (this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink) {
  125. return;
  126. }
  127. // User can't use both relativePath and permalink at the same time
  128. this.setState({ isUsePermanentLink: !this.state.isUsePermanentLink, isUseRelativePath: false });
  129. }
  130. async setMarkdown() {
  131. const { t } = this.props;
  132. const path = this.state.linkInputValue;
  133. let markdown = null;
  134. let pagePath = null;
  135. let permalink = '';
  136. let previewError = '';
  137. if (path.startsWith('/')) {
  138. try {
  139. const pathWithoutFragment = new URL(path, 'http://dummy').pathname;
  140. const isPermanentLink = validator.isMongoId(pathWithoutFragment.slice(1));
  141. const pageId = isPermanentLink ? pathWithoutFragment.slice(1) : null;
  142. const { data } = await apiv3Get('/page', { path: pathWithoutFragment, page_id: pageId });
  143. const { page } = data;
  144. markdown = page.revision.body;
  145. pagePath = page.path;
  146. permalink = page.id;
  147. }
  148. catch (err) {
  149. previewError = err.message;
  150. }
  151. }
  152. else {
  153. previewError = t('link_edit.page_not_found_in_preview', { path });
  154. }
  155. this.setState({
  156. markdown, pagePath, previewError, permalink,
  157. });
  158. }
  159. renderLinkPreview() {
  160. const linker = this.generateLink();
  161. return (
  162. <div className="d-flex justify-content-between mb-3 flex-column flex-sm-row">
  163. <div className="card card-disabled w-100 p-1 mb-0">
  164. <p className="text-left text-muted mb-1 small">Markdown</p>
  165. <p className="text-center text-truncate text-muted">{linker.generateMarkdownText()}</p>
  166. </div>
  167. <div className="d-flex align-items-center justify-content-center">
  168. <span className="lead mx-3">
  169. <i className="d-none d-sm-block fa fa-caret-right"></i>
  170. <i className="d-sm-none fa fa-caret-down"></i>
  171. </span>
  172. </div>
  173. <div className="card w-100 p-1 mb-0">
  174. <p className="text-left text-muted mb-1 small">HTML</p>
  175. <p className="text-center text-truncate">
  176. <a href={linker.link}>{linker.label}</a>
  177. </p>
  178. </div>
  179. </div>
  180. );
  181. }
  182. handleChangeTypeahead(selected) {
  183. const pageWithMeta = selected[0];
  184. if (pageWithMeta != null) {
  185. const page = pageWithMeta.data;
  186. const permalink = `${window.location.origin}/${page.id}`;
  187. this.setState({ linkInputValue: page.path, permalink });
  188. }
  189. }
  190. handleChangeLabelInput(label) {
  191. this.setState({ labelInputValue: label });
  192. }
  193. handleChangeLinkInput(link) {
  194. let isUseRelativePath = this.state.isUseRelativePath;
  195. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  196. isUseRelativePath = false;
  197. }
  198. this.setState({
  199. linkInputValue: link, isUseRelativePath, isUsePermanentLink: false, permalink: '',
  200. });
  201. }
  202. handleSelecteLinkerType(linkerType) {
  203. let { isUseRelativePath, isUsePermanentLink } = this.state;
  204. if (linkerType === Linker.types.growiLink) {
  205. isUseRelativePath = false;
  206. isUsePermanentLink = false;
  207. }
  208. this.setState({ linkerType, isUseRelativePath, isUsePermanentLink });
  209. }
  210. save() {
  211. const linker = this.generateLink();
  212. if (this.props.onSave != null) {
  213. this.props.onSave(linker.generateMarkdownText());
  214. }
  215. this.hide();
  216. }
  217. generateLink() {
  218. const {
  219. linkInputValue, labelInputValue, linkerType, isUseRelativePath, isUsePermanentLink, permalink,
  220. } = this.state;
  221. let reshapedLink = linkInputValue;
  222. if (isUseRelativePath) {
  223. const rootPath = this.getRootPath(linkerType);
  224. reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
  225. }
  226. if (isUsePermanentLink && permalink != null) {
  227. reshapedLink = permalink;
  228. }
  229. return new Linker(linkerType, labelInputValue, reshapedLink);
  230. }
  231. getRootPath(type) {
  232. const { pagePath } = this.props;
  233. // rootPaths of md link and pukiwiki link are different
  234. return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
  235. }
  236. async toggleIsPreviewOpen() {
  237. // open popover
  238. if (this.state.isPreviewOpen === false) {
  239. this.setMarkdown();
  240. }
  241. this.setState({ isPreviewOpen: !this.state.isPreviewOpen });
  242. }
  243. renderLinkAndLabelForm() {
  244. const { t } = this.props;
  245. const { pagePath } = this.state;
  246. return (
  247. <>
  248. <h3 className="grw-modal-head">{t('link_edit.set_link_and_label')}</h3>
  249. <form className="form-group">
  250. <div className="form-gorup my-3">
  251. <div className="input-group flex-nowrap">
  252. <div className="input-group-prepend">
  253. <span className="input-group-text">{t('link_edit.link')}</span>
  254. </div>
  255. <SearchTypeahead
  256. onChange={this.handleChangeTypeahead}
  257. onInputChange={this.handleChangeLinkInput}
  258. inputName="link"
  259. placeholder={t('link_edit.placeholder_of_link_input')}
  260. keywordOnInit={this.state.linkInputValue}
  261. autoFocus
  262. />
  263. <div className="d-none d-sm-block input-group-append">
  264. <button type="button" id="preview-btn" className={`btn btn-info btn-page-preview ${styles['btn-page-preview']}`}>
  265. <PagePreviewIcon />
  266. </button>
  267. <Popover trigger="focus" placement="right" isOpen={this.state.isPreviewOpen} target="preview-btn" toggle={this.toggleIsPreviewOpen}>
  268. <PopoverBody>
  269. {this.state.markdown != null && pagePath != null
  270. && <div className={`linkedit-preview ${styles['linkedit-preview']}`}>
  271. <Preview markdown={this.state.markdown} pagePath={pagePath} />
  272. </div>
  273. }
  274. </PopoverBody>
  275. </Popover>
  276. </div>
  277. </div>
  278. </div>
  279. <div className="form-gorup my-3">
  280. <div className="input-group flex-nowrap">
  281. <div className="input-group-prepend">
  282. <span className="input-group-text">{t('link_edit.label')}</span>
  283. </div>
  284. <input
  285. type="text"
  286. className="form-control"
  287. id="label"
  288. value={this.state.labelInputValue}
  289. onChange={e => this.handleChangeLabelInput(e.target.value)}
  290. disabled={this.state.linkerType === Linker.types.growiLink}
  291. placeholder={this.state.linkInputValue}
  292. />
  293. </div>
  294. </div>
  295. </form>
  296. </>
  297. );
  298. }
  299. renderPathFormatForm() {
  300. const { t } = this.props;
  301. return (
  302. <div className="card well pt-3">
  303. <form className="form-group mb-0">
  304. <div className="form-group mb-0 row">
  305. <label className="col-sm-3">{t('link_edit.path_format')}</label>
  306. <div className="col-sm-9">
  307. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  308. <input
  309. className="custom-control-input"
  310. id="relativePath"
  311. type="checkbox"
  312. checked={this.state.isUseRelativePath}
  313. onChange={this.toggleIsUseRelativePath}
  314. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  315. />
  316. <label className="custom-control-label" htmlFor="relativePath">
  317. {t('link_edit.use_relative_path')}
  318. </label>
  319. </div>
  320. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  321. <input
  322. className="custom-control-input"
  323. id="permanentLink"
  324. type="checkbox"
  325. checked={this.state.isUsePermanentLink}
  326. onChange={this.toggleIsUsePamanentLink}
  327. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  328. />
  329. <label className="custom-control-label" htmlFor="permanentLink">
  330. {t('link_edit.use_permanent_link')}
  331. </label>
  332. </div>
  333. </div>
  334. </div>
  335. {this.isApplyPukiwikiLikeLinkerPlugin && (
  336. <div className="form-group row mb-0 mt-1">
  337. <label className="col-sm-3">{t('link_edit.notation')}</label>
  338. <div className="col-sm-9">
  339. <div className="custom-control custom-radio custom-control-inline">
  340. <input
  341. type="radio"
  342. className="custom-control-input"
  343. id="markdownType"
  344. value={Linker.types.markdownLink}
  345. checked={this.state.linkerType === Linker.types.markdownLink}
  346. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  347. />
  348. <label className="custom-control-label" htmlFor="markdownType">
  349. {t('link_edit.markdown')}
  350. </label>
  351. </div>
  352. <div className="custom-control custom-radio custom-control-inline">
  353. <input
  354. type="radio"
  355. className="custom-control-input"
  356. id="pukiwikiType"
  357. value={Linker.types.pukiwikiLink}
  358. checked={this.state.linkerType === Linker.types.pukiwikiLink}
  359. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  360. />
  361. <label className="custom-control-label" htmlFor="pukiwikiType">
  362. {t('link_edit.pukiwiki')}
  363. </label>
  364. </div>
  365. </div>
  366. </div>
  367. )}
  368. </form>
  369. </div>
  370. );
  371. }
  372. render() {
  373. const { t } = this.props;
  374. return (
  375. <Modal className="link-edit-modal" isOpen={this.state.show} toggle={this.cancel} size="lg" autoFocus={false}>
  376. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  377. {t('link_edit.edit_link')}
  378. </ModalHeader>
  379. <ModalBody className="container">
  380. <div className="row">
  381. <div className="col-12">
  382. {this.renderLinkAndLabelForm()}
  383. {this.renderPathFormatForm()}
  384. </div>
  385. </div>
  386. <div className="row">
  387. <div className="col-12">
  388. <h3 className="grw-modal-head">{t('link_edit.preview')}</h3>
  389. {this.renderLinkPreview()}
  390. </div>
  391. </div>
  392. </ModalBody>
  393. <ModalFooter>
  394. <button type="button" className="btn btn-sm btn-outline-secondary mx-1" onClick={this.hide}>
  395. {t('Cancel')}
  396. </button>
  397. <button type="submit" className="btn btn-sm btn-primary mx-1" onClick={this.save}>
  398. {t('Done')}
  399. </button>
  400. </ModalFooter>
  401. </Modal>
  402. );
  403. }
  404. }
  405. const LinkEditModalFc = React.memo(React.forwardRef((props, ref) => {
  406. const { t } = useTranslation();
  407. const { data: currentPath } = useCurrentPagePath();
  408. return <LinkEditModal t={t} ref={ref} pagePath={currentPath} {...props} />;
  409. }));
  410. LinkEditModal.propTypes = {
  411. t: PropTypes.func.isRequired,
  412. pagePath: PropTypes.string,
  413. onSave: PropTypes.func,
  414. };
  415. export default LinkEditModalFc;