LinkEditModal.jsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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: 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 this.props.appContainer.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 { pageContainer } = this.props;
  228. const pagePath = pageContainer.state.path;
  229. // rootPaths of md link and pukiwiki link are different
  230. return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
  231. }
  232. async toggleIsPreviewOpen() {
  233. // open popover
  234. if (this.state.isPreviewOpen === false) {
  235. this.setMarkdown();
  236. }
  237. this.setState({ isPreviewOpen: !this.state.isPreviewOpen });
  238. }
  239. renderLinkAndLabelForm() {
  240. const { t } = this.props;
  241. const { pagePath } = this.state;
  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. autoFocus
  258. />
  259. <div className="d-none d-sm-block input-group-append">
  260. <button type="button" id="preview-btn" className="btn btn-info btn-page-preview">
  261. <PagePreviewIcon />
  262. </button>
  263. <Popover trigger="focus" placement="right" isOpen={this.state.isPreviewOpen} target="preview-btn" toggle={this.toggleIsPreviewOpen}>
  264. <PopoverBody>
  265. <PreviewWithSuspense setMarkdown={this.setMarkdown} markdown={this.state.markdown} pagePath={pagePath} error={this.state.previewError} />
  266. </PopoverBody>
  267. </Popover>
  268. </div>
  269. </div>
  270. </div>
  271. <div className="form-gorup my-3">
  272. <div className="input-group flex-nowrap">
  273. <div className="input-group-prepend">
  274. <span className="input-group-text">{t('link_edit.label')}</span>
  275. </div>
  276. <input
  277. type="text"
  278. className="form-control"
  279. id="label"
  280. value={this.state.labelInputValue}
  281. onChange={e => this.handleChangeLabelInput(e.target.value)}
  282. disabled={this.state.linkerType === Linker.types.growiLink}
  283. placeholder={this.state.linkInputValue}
  284. />
  285. </div>
  286. </div>
  287. </form>
  288. </>
  289. );
  290. }
  291. renderPathFormatForm() {
  292. const { t } = this.props;
  293. return (
  294. <div className="card well pt-3">
  295. <form className="form-group mb-0">
  296. <div className="form-group row">
  297. <label className="col-sm-3">{t('link_edit.path_format')}</label>
  298. <div className="col-sm-9">
  299. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  300. <input
  301. className="custom-control-input"
  302. id="relativePath"
  303. type="checkbox"
  304. checked={this.state.isUseRelativePath}
  305. onChange={this.toggleIsUseRelativePath}
  306. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  307. />
  308. <label className="custom-control-label" htmlFor="relativePath">
  309. {t('link_edit.use_relative_path')}
  310. </label>
  311. </div>
  312. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  313. <input
  314. className="custom-control-input"
  315. id="permanentLink"
  316. type="checkbox"
  317. checked={this.state.isUsePermanentLink}
  318. onChange={this.toggleIsUsePamanentLink}
  319. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  320. />
  321. <label className="custom-control-label" htmlFor="permanentLink">
  322. {t('link_edit.use_permanent_link')}
  323. </label>
  324. </div>
  325. </div>
  326. </div>
  327. <div className="form-group row mb-0">
  328. <label className="col-sm-3">{t('link_edit.notation')}</label>
  329. <div className="col-sm-9">
  330. <div className="custom-control custom-radio custom-control-inline">
  331. <input
  332. type="radio"
  333. className="custom-control-input"
  334. id="markdownType"
  335. value={Linker.types.markdownLink}
  336. checked={this.state.linkerType === Linker.types.markdownLink}
  337. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  338. />
  339. <label className="custom-control-label" htmlFor="markdownType">
  340. {t('link_edit.markdown')}
  341. </label>
  342. </div>
  343. <div className="custom-control custom-radio custom-control-inline">
  344. <input
  345. type="radio"
  346. className="custom-control-input"
  347. id="growiType"
  348. value={Linker.types.growiLink}
  349. checked={this.state.linkerType === Linker.types.growiLink}
  350. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  351. />
  352. <label className="custom-control-label" htmlFor="growiType">
  353. {t('link_edit.GROWI_original')}
  354. </label>
  355. </div>
  356. {this.isApplyPukiwikiLikeLinkerPlugin && (
  357. <div className="custom-control custom-radio custom-control-inline">
  358. <input
  359. type="radio"
  360. className="custom-control-input"
  361. id="pukiwikiType"
  362. value={Linker.types.pukiwikiLink}
  363. checked={this.state.linkerType === Linker.types.pukiwikiLink}
  364. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  365. />
  366. <label className="custom-control-label" htmlFor="pukiwikiType">
  367. {t('link_edit.pukiwiki')}
  368. </label>
  369. </div>
  370. )}
  371. </div>
  372. </div>
  373. </form>
  374. </div>
  375. );
  376. }
  377. render() {
  378. const { t } = this.props;
  379. return (
  380. <Modal className="link-edit-modal" isOpen={this.state.show} toggle={this.cancel} size="lg" autoFocus={false}>
  381. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  382. {t('link_edit.edit_link')}
  383. </ModalHeader>
  384. <ModalBody className="container">
  385. <div className="row">
  386. <div className="col-12">
  387. {this.renderLinkAndLabelForm()}
  388. {this.renderPathFormatForm()}
  389. </div>
  390. </div>
  391. <div className="row">
  392. <div className="col-12">
  393. <h3 className="grw-modal-head">{t('link_edit.preview')}</h3>
  394. {this.renderLinkPreview()}
  395. </div>
  396. </div>
  397. </ModalBody>
  398. <ModalFooter>
  399. <button type="button" className="btn btn-sm btn-outline-secondary mx-1" onClick={this.hide}>
  400. {t('Cancel')}
  401. </button>
  402. <button type="submit" className="btn btn-sm btn-primary mx-1" onClick={this.save}>
  403. {t('Done')}
  404. </button>
  405. </ModalFooter>
  406. </Modal>
  407. );
  408. }
  409. }
  410. LinkEditModal.propTypes = {
  411. t: PropTypes.func.isRequired,
  412. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  413. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  414. onSave: PropTypes.func,
  415. };
  416. /**
  417. * Wrapper component for using unstated
  418. */
  419. const LinkEditModalWrapper = withUnstatedContainers(LinkEditModal, [AppContainer, PageContainer]);
  420. export default withTranslation('translation', { withRef: true })(LinkEditModalWrapper);