LinkEditModal.jsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 PreviewWithSuspense from './PreviewWithSuspense';
  15. import PagePreviewIcon from '../Icons/PagePreviewIcon';
  16. import AppContainer from '../../services/AppContainer';
  17. import PageContainer from '../../services/PageContainer';
  18. import SearchTypeahead from '../SearchTypeahead';
  19. import Linker from '../../models/Linker';
  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 previewError = '';
  129. let permalink = '';
  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 { page } = await this.props.appContainer.apiGet('/pages.get', { path: pathWithoutFragment, page_id: pageId });
  136. markdown = page.revision.body;
  137. // create permanent link only if path isn't permanent link because checkbox for isUsePermanentLink is disabled when permalink is ''.
  138. permalink = !isPermanentLink ? `${window.location.origin}/${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. getLinkForPreview() {
  150. const linker = this.generateLink();
  151. if (this.isUsePermanentLink && this.permalink != null) {
  152. linker.link = this.permalink;
  153. }
  154. if (linker.label === '') {
  155. linker.label = linker.link;
  156. }
  157. return linker;
  158. }
  159. renderLinkPreview() {
  160. const linker = this.getLinkForPreview();
  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 page = selected[0];
  184. if (page != null) {
  185. this.setState({ linkInputValue: page.path });
  186. }
  187. }
  188. handleChangeLabelInput(label) {
  189. this.setState({ labelInputValue: label });
  190. }
  191. handleChangeLinkInput(link) {
  192. let isUseRelativePath = this.state.isUseRelativePath;
  193. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  194. isUseRelativePath = false;
  195. }
  196. this.setState({ linkInputValue: link, isUseRelativePath, isUsePermanentLink: false });
  197. }
  198. handleSelecteLinkerType(linkerType) {
  199. let { isUseRelativePath, isUsePermanentLink } = this.state;
  200. if (linkerType === Linker.types.growiLink) {
  201. isUseRelativePath = false;
  202. isUsePermanentLink = false;
  203. }
  204. this.setState({ linkerType, isUseRelativePath, isUsePermanentLink });
  205. }
  206. save() {
  207. const linker = this.getLinkForPreview();
  208. if (this.props.onSave != null) {
  209. this.props.onSave(linker.generateMarkdownText());
  210. }
  211. this.hide();
  212. }
  213. generateLink() {
  214. const {
  215. linkInputValue, labelInputValue, linkerType, isUseRelativePath, isUsePermanentLink, permalink,
  216. } = this.state;
  217. let reshapedLink = linkInputValue;
  218. if (isUseRelativePath) {
  219. const rootPath = this.getRootPath(linkerType);
  220. reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
  221. }
  222. if (isUsePermanentLink && permalink != null) {
  223. reshapedLink = permalink;
  224. }
  225. return new Linker(linkerType, labelInputValue, reshapedLink);
  226. }
  227. getRootPath(type) {
  228. const { pageContainer } = this.props;
  229. const pagePath = pageContainer.state.path;
  230. // rootPaths of md link and pukiwiki link are different
  231. return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
  232. }
  233. async toggleIsPreviewOpen() {
  234. // open popover
  235. if (this.state.isPreviewOpen === false) {
  236. this.setMarkdown();
  237. }
  238. this.setState({ isPreviewOpen: !this.state.isPreviewOpen });
  239. }
  240. renderLinkAndLabelForm() {
  241. const { t } = this.props;
  242. return (
  243. <>
  244. <h3 className="grw-modal-head">{t('link_edit.set_link_and_label')}</h3>
  245. <form className="form-group">
  246. <div className="form-gorup my-3">
  247. <div className="input-group flex-nowrap">
  248. <div className="input-group-prepend">
  249. <span className="input-group-text">{t('link_edit.link')}</span>
  250. </div>
  251. <SearchTypeahead
  252. onChange={this.handleChangeTypeahead}
  253. onInputChange={this.handleChangeLinkInput}
  254. inputName="link"
  255. placeholder={t('link_edit.placeholder_of_link_input')}
  256. keywordOnInit={this.state.linkInputValue}
  257. behaviorOfResetBtn="clear"
  258. autoFocus
  259. />
  260. <div className="d-none d-sm-block input-group-append">
  261. <button type="button" id="preview-btn" className="btn btn-info btn-page-preview">
  262. <PagePreviewIcon />
  263. </button>
  264. <Popover trigger="focus" placement="right" isOpen={this.state.isPreviewOpen} target="preview-btn" toggle={this.toggleIsPreviewOpen}>
  265. <PopoverBody>
  266. <PreviewWithSuspense setMarkdown={this.setMarkdown} markdown={this.state.markdown} error={this.state.previewError} />
  267. </PopoverBody>
  268. </Popover>
  269. </div>
  270. </div>
  271. </div>
  272. <div className="form-gorup my-3">
  273. <div className="input-group flex-nowrap">
  274. <div className="input-group-prepend">
  275. <span className="input-group-text">{t('link_edit.label')}</span>
  276. </div>
  277. <input
  278. type="text"
  279. className="form-control"
  280. id="label"
  281. value={this.state.labelInputValue}
  282. onChange={e => this.handleChangeLabelInput(e.target.value)}
  283. disabled={this.state.linkerType === Linker.types.growiLink}
  284. placeholder={this.state.linkInputValue}
  285. />
  286. </div>
  287. </div>
  288. </form>
  289. </>
  290. );
  291. }
  292. renderPathFormatForm() {
  293. const { t } = this.props;
  294. return (
  295. <div className="card well pt-3">
  296. <form className="form-group mb-0">
  297. <div className="form-group row">
  298. <label className="col-sm-3">{t('link_edit.path_format')}</label>
  299. <div className="col-sm-9">
  300. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  301. <input
  302. className="custom-control-input"
  303. id="relativePath"
  304. type="checkbox"
  305. checked={this.state.isUseRelativePath}
  306. onChange={this.toggleIsUseRelativePath}
  307. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  308. />
  309. <label className="custom-control-label" htmlFor="relativePath">
  310. {t('link_edit.use_relative_path')}
  311. </label>
  312. </div>
  313. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  314. <input
  315. className="custom-control-input"
  316. id="permanentLink"
  317. type="checkbox"
  318. checked={this.state.isUsePermanentLink}
  319. onChange={this.toggleIsUsePamanentLink}
  320. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  321. />
  322. <label className="custom-control-label" htmlFor="permanentLink">
  323. {t('link_edit.use_permanent_link')}
  324. </label>
  325. </div>
  326. </div>
  327. </div>
  328. <div className="form-group row mb-0">
  329. <label className="col-sm-3">{t('link_edit.notation')}</label>
  330. <div className="col-sm-9">
  331. <div className="custom-control custom-radio custom-control-inline">
  332. <input
  333. type="radio"
  334. className="custom-control-input"
  335. id="markdownType"
  336. value={Linker.types.markdownLink}
  337. checked={this.state.linkerType === Linker.types.markdownLink}
  338. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  339. />
  340. <label className="custom-control-label" htmlFor="markdownType">
  341. {t('link_edit.markdown')}
  342. </label>
  343. </div>
  344. <div className="custom-control custom-radio custom-control-inline">
  345. <input
  346. type="radio"
  347. className="custom-control-input"
  348. id="growiType"
  349. value={Linker.types.growiLink}
  350. checked={this.state.linkerType === Linker.types.growiLink}
  351. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  352. />
  353. <label className="custom-control-label" htmlFor="growiType">
  354. {t('link_edit.GROWI_original')}
  355. </label>
  356. </div>
  357. {this.isApplyPukiwikiLikeLinkerPlugin && (
  358. <div className="custom-control custom-radio custom-control-inline">
  359. <input
  360. type="radio"
  361. className="custom-control-input"
  362. id="pukiwikiType"
  363. value={Linker.types.pukiwikiLink}
  364. checked={this.state.linkerType === Linker.types.pukiwikiLink}
  365. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  366. />
  367. <label className="custom-control-label" htmlFor="pukiwikiType">
  368. {t('link_edit.pukiwiki')}
  369. </label>
  370. </div>
  371. )}
  372. </div>
  373. </div>
  374. </form>
  375. </div>
  376. );
  377. }
  378. render() {
  379. const { t } = this.props;
  380. return (
  381. <Modal className="link-edit-modal" isOpen={this.state.show} toggle={this.cancel} size="lg" autoFocus={false}>
  382. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  383. {t('link_edit.edit_link')}
  384. </ModalHeader>
  385. <ModalBody className="container">
  386. <div className="row">
  387. <div className="col-12">
  388. {this.renderLinkAndLabelForm()}
  389. {this.renderPathFormatForm()}
  390. </div>
  391. </div>
  392. <div className="row">
  393. <div className="col-12">
  394. <h3 className="grw-modal-head">{t('link_edit.preview')}</h3>
  395. {this.renderLinkPreview()}
  396. </div>
  397. </div>
  398. </ModalBody>
  399. <ModalFooter>
  400. <button type="button" className="btn btn-sm btn-outline-secondary mx-1" onClick={this.hide}>
  401. {t('Cancel')}
  402. </button>
  403. <button type="submit" className="btn btn-sm btn-primary mx-1" onClick={this.save}>
  404. {t('Done')}
  405. </button>
  406. </ModalFooter>
  407. </Modal>
  408. );
  409. }
  410. }
  411. LinkEditModal.propTypes = {
  412. t: PropTypes.func.isRequired,
  413. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  414. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  415. onSave: PropTypes.func,
  416. };
  417. /**
  418. * Wrapper component for using unstated
  419. */
  420. const LinkEditModalWrapper = withUnstatedContainers(LinkEditModal, [AppContainer, PageContainer]);
  421. export default withTranslation('translation', { withRef: true })(LinkEditModalWrapper);