LinkEditModal.jsx 16 KB

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