LinkEditModal.jsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 bg-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. <form className="form-group">
  250. <div className="form-gorup my-3">
  251. <div className="input-group flex-nowrap">
  252. <div className="input-group-prepend">
  253. <span className="input-group-text">link</span>
  254. </div>
  255. <SearchTypeahead
  256. onChange={this.handleChangeTypeahead}
  257. onInputChange={this.handleChangeLinkInput}
  258. inputName="link"
  259. placeholder="Input page path or URL"
  260. keywordOnInit={this.state.linkInputValue}
  261. />
  262. <div className="input-group-append">
  263. <button type="button" id="preview-btn" className="btn btn-info btn-page-preview">
  264. <PagePreviewIcon />
  265. </button>
  266. <Popover placement="right" isOpen={this.state.isPreviewOpen} target="preview-btn" toggle={this.toggleIsPreviewOpen}>
  267. <PopoverBody>
  268. {this.renderPreview()}
  269. </PopoverBody>
  270. </Popover>
  271. </div>
  272. </div>
  273. </div>
  274. <div className="form-gorup my-3">
  275. <div className="input-group flex-nowrap">
  276. <div className="input-group-prepend">
  277. <span className="input-group-text">label</span>
  278. </div>
  279. <input
  280. type="text"
  281. className="form-control"
  282. id="label"
  283. value={this.state.labelInputValue}
  284. onChange={e => this.handleChangeLabelInput(e.target.value)}
  285. disabled={this.state.linkerType === Linker.types.growiLink}
  286. />
  287. </div>
  288. </div>
  289. </form>
  290. );
  291. }
  292. renderPathFormatForm() {
  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">Path format</label>
  298. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  299. <input
  300. className="custom-control-input"
  301. id="relativePath"
  302. type="checkbox"
  303. checked={this.state.isUseRelativePath}
  304. onChange={this.toggleIsUseRelativePath}
  305. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  306. />
  307. <label className="custom-control-label" htmlFor="relativePath">
  308. Use relative path
  309. </label>
  310. </div>
  311. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  312. <input
  313. className="custom-control-input"
  314. id="permanentLink"
  315. type="checkbox"
  316. checked={this.state.isUsePermanentLink}
  317. onChange={this.toggleIsUsePamanentLink}
  318. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  319. />
  320. <label className="custom-control-label" htmlFor="permanentLink">
  321. Use permanent link
  322. </label>
  323. </div>
  324. </div>
  325. <div className="form-group row mb-0">
  326. <label className="col-sm-3">Notation</label>
  327. <div className="custom-control custom-radio custom-control-inline">
  328. <input
  329. type="radio"
  330. className="custom-control-input"
  331. id="markdownType"
  332. value={Linker.types.markdownLink}
  333. checked={this.state.linkerType === Linker.types.markdownLink}
  334. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  335. />
  336. <label className="custom-control-label" htmlFor="markdownType">
  337. Markdown
  338. </label>
  339. </div>
  340. <div className="custom-control custom-radio custom-control-inline">
  341. <input
  342. type="radio"
  343. className="custom-control-input"
  344. id="growiType"
  345. value={Linker.types.growiLink}
  346. checked={this.state.linkerType === Linker.types.growiLink}
  347. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  348. />
  349. <label className="custom-control-label" htmlFor="growiType">
  350. Growi original
  351. </label>
  352. </div>
  353. <div className="custom-control custom-radio custom-control-inline">
  354. <input
  355. type="radio"
  356. className="custom-control-input"
  357. id="pukiwikiType"
  358. value={Linker.types.pukiwikiLink}
  359. checked={this.state.linkerType === Linker.types.pukiwikiLink}
  360. onChange={e => this.handleSelecteLinkerType(e.target.value)}
  361. />
  362. <label className="custom-control-label" htmlFor="pukiwikiType">
  363. Pukiwiki
  364. </label>
  365. </div>
  366. </div>
  367. </form>
  368. </div>
  369. );
  370. }
  371. render() {
  372. return (
  373. <Modal className="link-edit-modal" isOpen={this.state.show} toggle={this.cancel} size="lg">
  374. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  375. Edit Links
  376. </ModalHeader>
  377. <ModalBody className="container">
  378. <div className="row">
  379. <div className="col-12">
  380. <h3 className="grw-modal-head">Set link and label</h3>
  381. {this.renderPathFormatForm()}
  382. </div>
  383. </div>
  384. <div className="row">
  385. <div className="col-12">
  386. <h3 className="grw-modal-head">Preview</h3>
  387. {this.renderLinkPreview()}
  388. </div>
  389. </div>
  390. <div className="row">
  391. <div className="col-12 text-center">
  392. <button type="button" className="btn btn-sm btn-outline-secondary mx-1" onClick={this.hide}>
  393. Cancel
  394. </button>
  395. <button type="submit" className="btn btn-sm btn-primary mx-1" onClick={this.save}>
  396. Done
  397. </button>
  398. </div>
  399. </div>
  400. </ModalBody>
  401. </Modal>
  402. );
  403. }
  404. }
  405. LinkEditModal.propTypes = {
  406. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  407. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  408. onSave: PropTypes.func,
  409. };
  410. /**
  411. * Wrapper component for using unstated
  412. */
  413. const LinkEditModalWrapper = withUnstatedContainers(LinkEditModal, [AppContainer, PageContainer]);
  414. export default LinkEditModalWrapper;