LinkEditModal.jsx 14 KB

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