LinkEditModal.jsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import {
  4. Modal,
  5. ModalHeader,
  6. ModalBody,
  7. ModalFooter,
  8. } from 'reactstrap';
  9. import { debounce } from 'throttle-debounce';
  10. import path from 'path';
  11. import validator from 'validator';
  12. import Preview from './Preview';
  13. import PagePreviewIcon from '../Icons/PagePreviewIcon';
  14. import AppContainer from '../../services/AppContainer';
  15. import PageContainer from '../../services/PageContainer';
  16. import SearchTypeahead from '../SearchTypeahead';
  17. import Linker from '../../models/Linker';
  18. import { withUnstatedContainers } from '../UnstatedUtils';
  19. class LinkEditModal extends React.PureComponent {
  20. constructor(props) {
  21. super(props);
  22. this.state = {
  23. show: false,
  24. isUseRelativePath: false,
  25. isUsePermanentLink: false,
  26. linkInputValue: '',
  27. labelInputValue: '',
  28. linkerType: Linker.types.markdownLink,
  29. markdown: '',
  30. permalink: '',
  31. linkText: '',
  32. };
  33. this.isApplyPukiwikiLikeLinkerPlugin = window.growiRenderer.preProcessors.some(process => process.constructor.name === 'PukiwikiLikeLinker');
  34. this.show = this.show.bind(this);
  35. this.hide = this.hide.bind(this);
  36. this.cancel = this.cancel.bind(this);
  37. this.handleChangeTypeahead = this.handleChangeTypeahead.bind(this);
  38. this.handleChangeLabelInput = this.handleChangeLabelInput.bind(this);
  39. this.handleChangeLinkInput = this.handleChangeLinkInput.bind(this);
  40. this.handleSelecteLinkerType = this.handleSelecteLinkerType.bind(this);
  41. this.toggleIsUseRelativePath = this.toggleIsUseRelativePath.bind(this);
  42. this.toggleIsUsePamanentLink = this.toggleIsUsePamanentLink.bind(this);
  43. this.save = this.save.bind(this);
  44. this.generateLink = this.generateLink.bind(this);
  45. this.renderPreview = this.renderPreview.bind(this);
  46. this.getRootPath = this.getRootPath.bind(this);
  47. this.generateAndSetPreviewDebounced = debounce(200, this.generateAndSetPreview.bind(this));
  48. }
  49. componentDidUpdate(prevProps, prevState) {
  50. const { linkInputValue: prevLinkInputValue } = prevState;
  51. const { linkInputValue } = this.state;
  52. if (linkInputValue !== prevLinkInputValue) {
  53. this.generateAndSetPreviewDebounced(linkInputValue);
  54. }
  55. }
  56. // defaultMarkdownLink is an instance of Linker
  57. show(defaultMarkdownLink = null) {
  58. // if defaultMarkdownLink is null, set default value in inputs.
  59. const { label = '', link = '' } = defaultMarkdownLink;
  60. let { type = Linker.types.markdownLink } = defaultMarkdownLink;
  61. // if type of defaultMarkdownLink is pukiwikiLink when pukiwikiLikeLinker plugin is disable, change type(not change label and link)
  62. if (type === Linker.types.pukiwikiLink && !this.isApplyPukiwikiLikeLinkerPlugin) {
  63. type = Linker.types.markdownLink;
  64. }
  65. this.parseLinkAndSetState(link, type);
  66. this.setState({
  67. show: true,
  68. labelInputValue: label,
  69. isUsePermanentLink: false,
  70. permalink: '',
  71. linkerType: type,
  72. });
  73. }
  74. // parse link, link is ...
  75. // case-1. url of this growi's page (ex. 'http://localhost:3000/hoge/fuga')
  76. // case-2. absolute path of this growi's page (ex. '/hoge/fuga')
  77. // case-3. relative path of this growi's page (ex. '../fuga', 'hoge')
  78. // case-4. external link (ex. 'https://growi.org')
  79. // case-5. the others (ex. '')
  80. parseLinkAndSetState(link, type) {
  81. // create url from link, add dummy origin if link is not valid url.
  82. // ex-1. link = 'https://growi.org/' -> url = 'https://growi.org/' (case-1,4)
  83. // ex-2. link = 'hoge' -> url = 'http://example.com/hoge' (case-2,3,5)
  84. const url = new URL(link, 'http://example.com');
  85. const isUrl = url.origin !== 'http://example.com';
  86. let isUseRelativePath = false;
  87. let reshapedLink = link;
  88. // if case-1, reshapedLink becomes page path
  89. reshapedLink = this.convertUrlToPathIfPageUrl(reshapedLink, url);
  90. // case-3
  91. if (!isUrl && !reshapedLink.startsWith('/') && reshapedLink !== '') {
  92. isUseRelativePath = true;
  93. const rootPath = this.getRootPath(type);
  94. reshapedLink = path.resolve(rootPath, reshapedLink);
  95. }
  96. this.setState({
  97. linkInputValue: reshapedLink,
  98. isUseRelativePath,
  99. });
  100. }
  101. // return path name of link if link is this growi page url, else return original link.
  102. convertUrlToPathIfPageUrl(link, url) {
  103. // when link is this growi's page url, url.origin === window.location.origin and return path name
  104. return url.origin === window.location.origin ? decodeURI(url.pathname) : link;
  105. }
  106. cancel() {
  107. this.hide();
  108. }
  109. hide() {
  110. this.setState({
  111. show: false,
  112. });
  113. }
  114. toggleIsUseRelativePath() {
  115. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  116. return;
  117. }
  118. // User can't use both relativePath and permalink at the same time
  119. this.setState({ isUseRelativePath: !this.state.isUseRelativePath, isUsePermanentLink: false });
  120. }
  121. toggleIsUsePamanentLink() {
  122. if (this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink) {
  123. return;
  124. }
  125. // User can't use both relativePath and permalink at the same time
  126. this.setState({ isUsePermanentLink: !this.state.isUsePermanentLink, isUseRelativePath: false });
  127. }
  128. renderPreview() {
  129. return (
  130. <div className="linkedit-preview">
  131. <Preview markdown={this.state.markdown} />
  132. </div>
  133. );
  134. }
  135. async generateAndSetPreview(path) {
  136. let markdown = '';
  137. let permalink = '';
  138. if (path.startsWith('/')) {
  139. const pathWithoutFragment = new URL(path, 'http://dummy').pathname;
  140. const isPermanentLink = validator.isMongoId(pathWithoutFragment.slice(1));
  141. const pageId = isPermanentLink ? pathWithoutFragment.slice(1) : null;
  142. try {
  143. const { page } = await this.props.appContainer.apiGet('/pages.get', { path: pathWithoutFragment, page_id: pageId });
  144. markdown = page.revision.body;
  145. // create permanent link only if path isn't permanent link because checkbox for isUsePermanentLink is disabled when permalink is ''.
  146. permalink = !isPermanentLink ? `${window.location.origin}/${page.id}` : '';
  147. }
  148. catch (err) {
  149. markdown = `<div class="alert alert-warning" role="alert"><strong>${err.message}</strong></div>`;
  150. }
  151. }
  152. else {
  153. markdown = '<div class="alert alert-success" role="alert">Page preview here.</div>';
  154. }
  155. this.setState({ markdown, permalink });
  156. }
  157. renderLinkPreview() {
  158. const linker = this.generateLink();
  159. if (this.isUsePermanentLink && this.permalink != null) {
  160. linker.link = this.permalink;
  161. }
  162. if (linker.label === '') {
  163. linker.label = linker.link;
  164. }
  165. const linkText = linker.generateMarkdownText();
  166. return (
  167. <div>{linkText} &gt; <a href={linker.link}>{linker.label}</a></div>
  168. );
  169. }
  170. handleChangeTypeahead(selected) {
  171. const page = selected[0];
  172. if (page != null) {
  173. this.setState({ linkInputValue: page.path });
  174. }
  175. }
  176. handleChangeLabelInput(label) {
  177. this.setState({ labelInputValue: label });
  178. }
  179. handleChangeLinkInput(link) {
  180. let isUseRelativePath = this.state.isUseRelativePath;
  181. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  182. isUseRelativePath = false;
  183. }
  184. this.setState({ linkInputValue: link, isUseRelativePath, isUsePermanentLink: false });
  185. }
  186. handleSelecteLinkerType(linkerType) {
  187. let { isUseRelativePath, isUsePermanentLink } = this.state;
  188. if (linkerType === Linker.types.growiLink) {
  189. isUseRelativePath = false;
  190. isUsePermanentLink = false;
  191. }
  192. this.setState({ linkerType, isUseRelativePath, isUsePermanentLink });
  193. }
  194. save() {
  195. if (this.props.onSave != null) {
  196. this.props.onSave(this.state.linkText);
  197. }
  198. this.hide();
  199. }
  200. generateLink() {
  201. const {
  202. linkInputValue, labelInputValue, linkerType, isUseRelativePath, isUsePermanentLink, permalink,
  203. } = this.state;
  204. let reshapedLink = linkInputValue;
  205. if (isUseRelativePath) {
  206. const rootPath = this.getRootPath(linkerType);
  207. reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
  208. }
  209. if (isUsePermanentLink && permalink != null) {
  210. reshapedLink = permalink;
  211. }
  212. return new Linker(linkerType, labelInputValue, reshapedLink);
  213. }
  214. getRootPath(type) {
  215. const { pageContainer } = this.props;
  216. const pagePath = pageContainer.state.path;
  217. // rootPaths of md link and pukiwiki link are different
  218. return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
  219. }
  220. render() {
  221. return (
  222. <Modal isOpen={this.state.show} toggle={this.cancel} size="lg">
  223. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  224. Edit Links
  225. </ModalHeader>
  226. <ModalBody className="container">
  227. <div className="row">
  228. <div className="col-12">
  229. <form className="form-group">
  230. <div className="form-gorup my-3">
  231. <div className="input-group flex-nowrap">
  232. <div className="input-group-prepend">
  233. <span className="input-group-text">link</span>
  234. </div>
  235. <SearchTypeahead
  236. onChange={this.handleChangeTypeahead}
  237. onInputChange={this.handleChangeLinkInput}
  238. inputName="link"
  239. placeholder="Input page path or URL"
  240. keywordOnInit={this.state.linkInputValue}
  241. />
  242. <div className="input-group-append" onClick="">
  243. <button type="button" className="btn btn-info btn-page-preview"><PagePreviewIcon /></button>
  244. </div>
  245. </div>
  246. </div>
  247. <div className="form-gorup my-3">
  248. <div className="input-group flex-nowrap">
  249. <div className="input-group-prepend">
  250. <span className="input-group-text">label</span>
  251. </div>
  252. <input
  253. type="text"
  254. className="form-control"
  255. id="label"
  256. value={this.state.labelInputValue}
  257. onChange={e => this.handleChangeLabelInput(e.target.value)}
  258. disabled={this.state.linkerType === Linker.types.growiLink}
  259. />
  260. </div>
  261. </div>
  262. </form>
  263. <div className="card">
  264. <div className="card-body">
  265. <form className="form-group mb-0">
  266. <div className="form-group row">
  267. <label className="col-sm-3">Path format</label>
  268. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  269. <input
  270. className="custom-control-input"
  271. id="relativePath"
  272. type="checkbox"
  273. checked={this.state.isUseRelativePath}
  274. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  275. />
  276. <label className="custom-control-label" htmlFor="relativePath" onClick={this.toggleIsUseRelativePath}>
  277. Use relative path
  278. </label>
  279. </div>
  280. <div className="custom-control custom-checkbox custom-checkbox-info custom-control-inline">
  281. <input
  282. className="custom-control-input"
  283. id="permanentLink"
  284. type="checkbox"
  285. checked={this.state.isUsePermanentLink}
  286. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  287. />
  288. <label className="custom-control-label" htmlFor="permanentLink" onClick={this.toggleIsUsePamanentLink}>
  289. Use permanent link
  290. </label>
  291. </div>
  292. </div>
  293. <div className="form-group row mb-0">
  294. <label className="col-sm-3">Notation</label>
  295. <div className="custom-control custom-radio custom-control-inline">
  296. <input
  297. type="radio"
  298. className="custom-control-input"
  299. id="markdownType"
  300. name={Linker.types.markdownLink}
  301. checked={this.state.linkerType === Linker.types.markdownLink}
  302. />
  303. <label className="custom-control-label" htmlFor="markdownType" onClick={e => this.handleSelecteLinkerType(e.target.name)}>
  304. Markdown
  305. </label>
  306. </div>
  307. <div className="custom-control custom-radio custom-control-inline">
  308. <input
  309. type="radio"
  310. className="custom-control-input"
  311. id="growiType"
  312. name={Linker.types.growiLink}
  313. checked={this.state.linkerType === Linker.types.growiLink}
  314. />
  315. <label className="custom-control-label" htmlFor="growiType" onClick={e => this.handleSelecteLinkerType(e.target.name)}>
  316. Growi original
  317. </label>
  318. </div>
  319. <div className="custom-control custom-radio custom-control-inline">
  320. <input
  321. type="radio"
  322. className="custom-control-input"
  323. id="pukiwikiType"
  324. name={Linker.types.pukiwikiLink}
  325. checked={this.state.linkerType === Linker.types.pukiwikiLink}
  326. />
  327. <label className="custom-control-label" htmlFor="pukiwikiType" onClick={e => this.handleSelecteLinkerType(e.target.name)}>
  328. Pukiwiki
  329. </label>
  330. </div>
  331. </div>
  332. </form>
  333. </div>
  334. </div>
  335. {/* TODO GW-3448 fix layout */}
  336. {this.renderLinkPreview()}
  337. </div>
  338. <div className="col d-none d-lg-block pr-0 mr-3 overflow-auto">{this.renderPreview()}</div>
  339. </div>
  340. </ModalBody>
  341. <ModalFooter>
  342. <button type="button" className="btn btn-sm btn-outline-secondary" onClick={this.hide}>
  343. Cancel
  344. </button>
  345. <button type="submit" className="btn btn-sm btn-primary" onClick={this.save}>
  346. Done
  347. </button>
  348. </ModalFooter>
  349. </Modal>
  350. );
  351. }
  352. }
  353. LinkEditModal.propTypes = {
  354. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  355. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  356. onSave: PropTypes.func,
  357. };
  358. /**
  359. * Wrapper component for using unstated
  360. */
  361. const LinkEditModalWrapper = withUnstatedContainers(LinkEditModal, [AppContainer, PageContainer]);
  362. export default LinkEditModalWrapper;