LinkEditModal.jsx 17 KB

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