LinkEditModal.jsx 16 KB

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