LinkEditModal.jsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 pathWithoutFragment = new URL(path, 'http://dummy').pathname;
  141. const isPermanentLink = validator.isMongoId(pathWithoutFragment.slice(1));
  142. const pageId = isPermanentLink ? pathWithoutFragment.slice(1) : null;
  143. try {
  144. const { page } = await this.props.appContainer.apiGet('/pages.get', { path: pathWithoutFragment, page_id: pageId });
  145. markdown = page.revision.body;
  146. // create permanent link only if path isn't permanent link because checkbox for isUsePermanentLink is disabled when permalink is ''.
  147. permalink = !isPermanentLink ? `${window.location.origin}/${page.id}` : '';
  148. }
  149. catch (err) {
  150. markdown = `<div class="alert alert-warning" role="alert"><strong>${err.message}</strong></div>`;
  151. }
  152. }
  153. else {
  154. markdown = '<div class="alert alert-success" role="alert">Page preview here.</div>';
  155. }
  156. this.setState({ markdown, permalink });
  157. }
  158. generateAndSetLinkTextPreview() {
  159. const linker = this.generateLink();
  160. const linkText = linker.generateMarkdownText();
  161. this.setState({ linkText });
  162. }
  163. handleChangeTypeahead(selected) {
  164. const page = selected[0];
  165. if (page != null) {
  166. this.setState({ linkInputValue: page.path });
  167. }
  168. }
  169. handleChangeLabelInput(label) {
  170. this.setState({ labelInputValue: label });
  171. }
  172. handleChangeLinkInput(link) {
  173. let isUseRelativePath = this.state.isUseRelativePath;
  174. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  175. isUseRelativePath = false;
  176. }
  177. this.setState({ linkInputValue: link, isUseRelativePath, isUsePermanentLink: false });
  178. }
  179. handleSelecteLinkerType(linkerType) {
  180. let { isUseRelativePath, isUsePermanentLink } = this.state;
  181. if (linkerType === Linker.types.growiLink) {
  182. isUseRelativePath = false;
  183. isUsePermanentLink = false;
  184. }
  185. this.setState({ linkerType, isUseRelativePath, isUsePermanentLink });
  186. }
  187. save() {
  188. if (this.props.onSave != null) {
  189. this.props.onSave(this.state.linkText);
  190. }
  191. this.hide();
  192. }
  193. generateLink() {
  194. const {
  195. linkInputValue, labelInputValue, linkerType, isUseRelativePath, isUsePermanentLink, permalink,
  196. } = this.state;
  197. let reshapedLink = linkInputValue;
  198. if (isUseRelativePath) {
  199. const rootPath = this.getRootPath(linkerType);
  200. reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
  201. }
  202. if (isUsePermanentLink && permalink != null) {
  203. reshapedLink = permalink;
  204. }
  205. return new Linker(linkerType, labelInputValue, reshapedLink);
  206. }
  207. getRootPath(type) {
  208. const { pageContainer } = this.props;
  209. const pagePath = pageContainer.state.path;
  210. // rootPaths of md link and pukiwiki link are different
  211. return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
  212. }
  213. render() {
  214. return (
  215. <Modal isOpen={this.state.show} toggle={this.cancel} size="lg">
  216. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  217. Edit Links
  218. </ModalHeader>
  219. <ModalBody className="container">
  220. <div className="row">
  221. <div className="col-12 col-lg-6">
  222. <form className="form-group">
  223. <div className="form-gorup my-3">
  224. <label htmlFor="linkInput">Link</label>
  225. <div className="input-group">
  226. <SearchTypeahead
  227. onChange={this.handleChangeTypeahead}
  228. onInputChange={this.handleChangeLinkInput}
  229. inputName="link"
  230. placeholder="Input page path or URL"
  231. keywordOnInit={this.state.linkInputValue}
  232. />
  233. </div>
  234. </div>
  235. </form>
  236. <div className="d-block d-lg-none mb-3 overflow-auto">{this.renderPreview()}</div>
  237. <div className="card">
  238. <div className="card-body">
  239. <form className="form-group">
  240. <div className="form-group btn-group d-flex" role="group" aria-label="type">
  241. <button
  242. type="button"
  243. name={Linker.types.markdownLink}
  244. className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.markdownLink && 'active'}`}
  245. onClick={e => this.handleSelecteLinkerType(e.target.name)}
  246. >
  247. Markdown
  248. </button>
  249. <button
  250. type="button"
  251. name={Linker.types.growiLink}
  252. className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.growiLink && 'active'}`}
  253. onClick={e => this.handleSelecteLinkerType(e.target.name)}
  254. >
  255. Growi Original
  256. </button>
  257. {this.isApplyPukiwikiLikeLinkerPlugin && (
  258. <button
  259. type="button"
  260. name={Linker.types.pukiwikiLink}
  261. className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.pukiwikiLink && 'active'}`}
  262. onClick={e => this.handleSelecteLinkerType(e.target.name)}
  263. >
  264. Pukiwiki
  265. </button>
  266. )}
  267. </div>
  268. <div className="form-group">
  269. <label htmlFor="label">Label</label>
  270. <input
  271. type="text"
  272. className="form-control"
  273. id="label"
  274. value={this.state.labelInputValue}
  275. onChange={e => this.handleChangeLabelInput(e.target.value)}
  276. disabled={this.state.linkerType === Linker.types.growiLink}
  277. />
  278. </div>
  279. <div className="form-inline">
  280. <div className="custom-control custom-checkbox custom-checkbox-info">
  281. <input
  282. className="custom-control-input"
  283. id="relativePath"
  284. type="checkbox"
  285. checked={this.state.isUseRelativePath}
  286. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  287. />
  288. <label className="custom-control-label" htmlFor="relativePath" onClick={this.toggleIsUseRelativePath}>
  289. Use relative path
  290. </label>
  291. </div>
  292. </div>
  293. <div className="form-inline">
  294. <div className="custom-control custom-checkbox custom-checkbox-info">
  295. <input
  296. className="custom-control-input"
  297. id="permanentLink"
  298. type="checkbox"
  299. checked={this.state.isUsePermanentLink}
  300. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  301. />
  302. <label className="custom-control-label" htmlFor="permanentLink" onClick={this.toggleIsUsePamanentLink}>
  303. Use permanent link
  304. </label>
  305. </div>
  306. </div>
  307. </form>
  308. </div>
  309. </div>
  310. </div>
  311. <div className="col d-none d-lg-block pr-0 mr-3 overflow-auto">{this.renderPreview()}</div>
  312. </div>
  313. </ModalBody>
  314. <ModalFooter>
  315. <button type="button" className="btn btn-sm btn-outline-secondary" onClick={this.hide}>
  316. Cancel
  317. </button>
  318. <button type="submit" className="btn btn-sm btn-primary" onClick={this.save}>
  319. Done
  320. </button>
  321. </ModalFooter>
  322. </Modal>
  323. );
  324. }
  325. }
  326. LinkEditModal.propTypes = {
  327. t: PropTypes.func.isRequired, // i18next
  328. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  329. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  330. onSave: PropTypes.func,
  331. };
  332. /**
  333. * Wrapper component for using unstated
  334. */
  335. const LinkEditModalWrapper = withUnstatedContainers(LinkEditModal, [AppContainer, PageContainer]);
  336. export default LinkEditModalWrapper;