LinkEditModal.jsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. class LinkEditModal extends React.PureComponent {
  21. constructor(props) {
  22. super(props);
  23. this.state = {
  24. show: false,
  25. isUseRelativePath: false,
  26. isUsePermanentLink: false,
  27. linkInputValue: '',
  28. labelInputValue: '',
  29. linkerType: Linker.types.markdownLink,
  30. markdown: null,
  31. pagePath: null,
  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 = null;
  128. let pagePath = null;
  129. let permalink = '';
  130. let previewError = '';
  131. if (path.startsWith('/')) {
  132. const pathWithoutFragment = new URL(path, 'http://dummy').pathname;
  133. const isPermanentLink = validator.isMongoId(pathWithoutFragment.slice(1));
  134. const pageId = isPermanentLink ? pathWithoutFragment.slice(1) : null;
  135. try {
  136. const { data } = await apiv3Get('/page', { path: pathWithoutFragment, page_id: pageId });
  137. const { page } = data;
  138. markdown = page.revision.body;
  139. pagePath = page.path;
  140. permalink = page.id;
  141. }
  142. catch (err) {
  143. previewError = err.message;
  144. }
  145. }
  146. else {
  147. previewError = t('link_edit.page_not_found_in_preview', { path });
  148. }
  149. this.setState({
  150. markdown, pagePath, previewError, permalink,
  151. });
  152. }
  153. renderLinkPreview() {
  154. const linker = this.generateLink();
  155. return (
  156. <div className="d-flex justify-content-between mb-3 flex-column flex-sm-row">
  157. <div className="card card-disabled w-100 p-1 mb-0">
  158. <p className="text-left text-muted mb-1 small">Markdown</p>
  159. <p className="text-center text-truncate text-muted">{linker.generateMarkdownText()}</p>
  160. </div>
  161. <div className="d-flex align-items-center justify-content-center">
  162. <span className="lead mx-3">
  163. <i className="d-none d-sm-block fa fa-caret-right"></i>
  164. <i className="d-sm-none fa fa-caret-down"></i>
  165. </span>
  166. </div>
  167. <div className="card w-100 p-1 mb-0">
  168. <p className="text-left text-muted mb-1 small">HTML</p>
  169. <p className="text-center text-truncate">
  170. <a href={linker.link}>{linker.label}</a>
  171. </p>
  172. </div>
  173. </div>
  174. );
  175. }
  176. handleChangeTypeahead(selected) {
  177. const pageWithMeta = selected[0];
  178. if (pageWithMeta != null) {
  179. const page = pageWithMeta.data;
  180. const permalink = `${window.location.origin}/${page.id}`;
  181. this.setState({ linkInputValue: page.path, permalink });
  182. }
  183. }
  184. handleChangeLabelInput(label) {
  185. this.setState({ labelInputValue: label });
  186. }
  187. handleChangeLinkInput(link) {
  188. let isUseRelativePath = this.state.isUseRelativePath;
  189. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  190. isUseRelativePath = false;
  191. }
  192. this.setState({
  193. linkInputValue: link, isUseRelativePath, isUsePermanentLink: false, permalink: '',
  194. });
  195. }
  196. handleSelecteLinkerType(linkerType) {
  197. let { isUseRelativePath, isUsePermanentLink } = this.state;
  198. if (linkerType === Linker.types.growiLink) {
  199. isUseRelativePath = false;
  200. isUsePermanentLink = false;
  201. }
  202. this.setState({ linkerType, isUseRelativePath, isUsePermanentLink });
  203. }
  204. save() {
  205. const linker = this.generateLink();
  206. if (this.props.onSave != null) {
  207. this.props.onSave(linker.generateMarkdownText());
  208. }
  209. this.hide();
  210. }
  211. generateLink() {
  212. const {
  213. linkInputValue, labelInputValue, linkerType, isUseRelativePath, isUsePermanentLink, permalink,
  214. } = this.state;
  215. let reshapedLink = linkInputValue;
  216. if (isUseRelativePath) {
  217. const rootPath = this.getRootPath(linkerType);
  218. reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
  219. }
  220. if (isUsePermanentLink && permalink != null) {
  221. reshapedLink = permalink;
  222. }
  223. return new Linker(linkerType, labelInputValue, reshapedLink);
  224. }
  225. getRootPath(type) {
  226. const { pagePath } = this.props;
  227. // rootPaths of md link and pukiwiki link are different
  228. return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
  229. }
  230. async toggleIsPreviewOpen() {
  231. // open popover
  232. if (this.state.isPreviewOpen === false) {
  233. this.setMarkdown();
  234. }
  235. this.setState({ isPreviewOpen: !this.state.isPreviewOpen });
  236. }
  237. renderLinkAndLabelForm() {
  238. const { t } = this.props;
  239. const { pagePath } = this.state;
  240. return (
  241. <>
  242. <h3 className="grw-modal-head">{t('link_edit.set_link_and_label')}</h3>
  243. <form className="form-group">
  244. <div className="form-gorup my-3">
  245. <div className="input-group flex-nowrap">
  246. <div className="input-group-prepend">
  247. <span className="input-group-text">{t('link_edit.link')}</span>
  248. </div>
  249. <SearchTypeahead
  250. onChange={this.handleChangeTypeahead}
  251. onInputChange={this.handleChangeLinkInput}
  252. inputName="link"
  253. placeholder={t('link_edit.placeholder_of_link_input')}
  254. keywordOnInit={this.state.linkInputValue}
  255. autoFocus
  256. />
  257. <div className="d-none d-sm-block input-group-append">
  258. <button type="button" id="preview-btn" className="btn btn-info btn-page-preview">
  259. <PagePreviewIcon />
  260. </button>
  261. <Popover trigger="focus" placement="right" isOpen={this.state.isPreviewOpen} target="preview-btn" toggle={this.toggleIsPreviewOpen}>
  262. <PopoverBody>
  263. {this.state.markdown != null && pagePath != null
  264. && <div className="linkedit-preview">
  265. <Preview markdown={this.state.markdown} pagePath={pagePath} />
  266. </div>
  267. }
  268. </PopoverBody>
  269. </Popover>
  270. </div>
  271. </div>
  272. </div>
  273. <div className="form-gorup my-3">
  274. <div className="input-group flex-nowrap">
  275. <div className="input-group-prepend">
  276. <span className="input-group-text">{t('link_edit.label')}</span>
  277. </div>
  278. <input
  279. type="text"
  280. className="form-control"
  281. id="label"
  282. value={this.state.labelInputValue}
  283. onChange={e => this.handleChangeLabelInput(e.target.value)}
  284. disabled={this.state.linkerType === Linker.types.growiLink}
  285. placeholder={this.state.linkInputValue}
  286. />
  287. </div>
  288. </div>
  289. </form>
  290. </>
  291. );
  292. }
  293. renderPathFormatForm() {
  294. const { t } = this.props;
  295. return (
  296. <div className="card well pt-3">
  297. <form className="form-group mb-0">
  298. <div className="form-group row">
  299. <label className="col-sm-3">{t('link_edit.path_format')}</label>
  300. <div className="col-sm-9">
  301. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  302. <input
  303. className="custom-control-input"
  304. id="relativePath"
  305. type="checkbox"
  306. checked={this.state.isUseRelativePath}
  307. onChange={this.toggleIsUseRelativePath}
  308. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  309. />
  310. <label className="custom-control-label" htmlFor="relativePath">
  311. {t('link_edit.use_relative_path')}
  312. </label>
  313. </div>
  314. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  315. <input
  316. className="custom-control-input"
  317. id="permanentLink"
  318. type="checkbox"
  319. checked={this.state.isUsePermanentLink}
  320. onChange={this.toggleIsUsePamanentLink}
  321. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  322. />
  323. <label className="custom-control-label" htmlFor="permanentLink">
  324. {t('link_edit.use_permanent_link')}
  325. </label>
  326. </div>
  327. </div>
  328. </div>
  329. <div className="form-group row mb-0">
  330. <label className="col-sm-3">{t('link_edit.notation')}</label>
  331. <div className="col-sm-9">
  332. <div className="custom-control custom-radio custom-control-inline">
  333. <input
  334. type="radio"
  335. className="custom-control-input"
  336. id="markdownType"
  337. value={Linker.types.markdownLink}
  338. checked={this.state.linkerType === Linker.types.markdownLink}
  339. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  340. />
  341. <label className="custom-control-label" htmlFor="markdownType">
  342. {t('link_edit.markdown')}
  343. </label>
  344. </div>
  345. <div className="custom-control custom-radio custom-control-inline">
  346. <input
  347. type="radio"
  348. className="custom-control-input"
  349. id="growiType"
  350. value={Linker.types.growiLink}
  351. checked={this.state.linkerType === Linker.types.growiLink}
  352. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  353. />
  354. <label className="custom-control-label" htmlFor="growiType">
  355. {t('link_edit.GROWI_original')}
  356. </label>
  357. </div>
  358. {this.isApplyPukiwikiLikeLinkerPlugin && (
  359. <div className="custom-control custom-radio custom-control-inline">
  360. <input
  361. type="radio"
  362. className="custom-control-input"
  363. id="pukiwikiType"
  364. value={Linker.types.pukiwikiLink}
  365. checked={this.state.linkerType === Linker.types.pukiwikiLink}
  366. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  367. />
  368. <label className="custom-control-label" htmlFor="pukiwikiType">
  369. {t('link_edit.pukiwiki')}
  370. </label>
  371. </div>
  372. )}
  373. </div>
  374. </div>
  375. </form>
  376. </div>
  377. );
  378. }
  379. render() {
  380. const { t } = this.props;
  381. return (
  382. <Modal className="link-edit-modal" isOpen={this.state.show} toggle={this.cancel} size="lg" autoFocus={false}>
  383. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  384. {t('link_edit.edit_link')}
  385. </ModalHeader>
  386. <ModalBody className="container">
  387. <div className="row">
  388. <div className="col-12">
  389. {this.renderLinkAndLabelForm()}
  390. {this.renderPathFormatForm()}
  391. </div>
  392. </div>
  393. <div className="row">
  394. <div className="col-12">
  395. <h3 className="grw-modal-head">{t('link_edit.preview')}</h3>
  396. {this.renderLinkPreview()}
  397. </div>
  398. </div>
  399. </ModalBody>
  400. <ModalFooter>
  401. <button type="button" className="btn btn-sm btn-outline-secondary mx-1" onClick={this.hide}>
  402. {t('Cancel')}
  403. </button>
  404. <button type="submit" className="btn btn-sm btn-primary mx-1" onClick={this.save}>
  405. {t('Done')}
  406. </button>
  407. </ModalFooter>
  408. </Modal>
  409. );
  410. }
  411. }
  412. const LinkEditModalFc = React.forwardRef((props, ref) => {
  413. const { t } = useTranslation();
  414. const { data: currentPath } = useCurrentPagePath();
  415. return <LinkEditModal t={t} ref={ref} pagePath={currentPath} {...props} />;
  416. });
  417. LinkEditModal.propTypes = {
  418. t: PropTypes.func.isRequired,
  419. pagePath: PropTypes.string,
  420. onSave: PropTypes.func,
  421. };
  422. export default LinkEditModalFc;