LinkEditModal.jsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 Preview from './Preview';
  12. import AppContainer from '../../services/AppContainer';
  13. import PageContainer from '../../services/PageContainer';
  14. import SearchTypeahead from '../SearchTypeahead';
  15. import Linker from '../../models/Linker';
  16. import { withUnstatedContainers } from '../UnstatedUtils';
  17. class LinkEditModal extends React.PureComponent {
  18. constructor(props) {
  19. super(props);
  20. this.state = {
  21. show: false,
  22. isUseRelativePath: false,
  23. isUsePermanentLink: false,
  24. linkInputValue: '',
  25. labelInputValue: '',
  26. linkerType: Linker.types.markdownLink,
  27. markdown: '',
  28. permalink: '',
  29. linkText: '',
  30. };
  31. this.isApplyPukiwikiLikeLinkerPlugin = window.growiRenderer.preProcessors.some(process => process.constructor.name === 'PukiwikiLikeLinker');
  32. this.show = this.show.bind(this);
  33. this.hide = this.hide.bind(this);
  34. this.cancel = this.cancel.bind(this);
  35. this.handleChangeTypeahead = this.handleChangeTypeahead.bind(this);
  36. this.handleChangeLabelInput = this.handleChangeLabelInput.bind(this);
  37. this.handleChangeLinkInput = this.handleChangeLinkInput.bind(this);
  38. this.handleSelecteLinkerType = this.handleSelecteLinkerType.bind(this);
  39. this.toggleIsUseRelativePath = this.toggleIsUseRelativePath.bind(this);
  40. this.toggleIsUsePamanentLink = this.toggleIsUsePamanentLink.bind(this);
  41. this.save = this.save.bind(this);
  42. this.generateLink = this.generateLink.bind(this);
  43. this.renderPreview = this.renderPreview.bind(this);
  44. this.getRootPath = this.getRootPath.bind(this);
  45. this.getPreviewDebounced = debounce(200, this.getPreview.bind(this));
  46. this.getLinkTextPreviewDebounced = debounce(200, this.getLinkTextPreview.bind(this));
  47. }
  48. componentDidUpdate(prevProps, prevState) {
  49. const { linkInputValue: prevLinkInputValue } = prevState;
  50. const { linkInputValue } = this.state;
  51. if (linkInputValue !== prevLinkInputValue) {
  52. this.getPreviewDebounced(linkInputValue);
  53. }
  54. this.getLinkTextPreviewDebounced();
  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 getPreview(path) {
  136. let markdown = '';
  137. let permalink = '';
  138. try {
  139. const res = await this.props.appContainer.apiGet('/pages.get', { path });
  140. markdown = res.page.revision.body;
  141. permalink = `${window.location.origin}/${res.page.id}`;
  142. }
  143. catch (err) {
  144. markdown = `<div class="alert alert-warning" role="alert"><strong>${err.message}</strong></div>`;
  145. }
  146. this.setState({ markdown, permalink });
  147. }
  148. getLinkTextPreview() {
  149. const linker = this.generateLink();
  150. const linkText = linker.generateMarkdownText();
  151. this.setState({ linkText });
  152. }
  153. handleChangeTypeahead(selected) {
  154. const page = selected[0];
  155. if (page != null) {
  156. this.setState({ linkInputValue: page.path });
  157. }
  158. }
  159. handleChangeLabelInput(label) {
  160. this.setState({ labelInputValue: label });
  161. }
  162. handleChangeLinkInput(link) {
  163. let isUseRelativePath = this.state.isUseRelativePath;
  164. if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
  165. isUseRelativePath = false;
  166. }
  167. this.setState({ linkInputValue: link, isUseRelativePath, isUsePermanentLink: false });
  168. }
  169. handleSelecteLinkerType(linkerType) {
  170. let { isUseRelativePath, isUsePermanentLink } = this.state;
  171. if (linkerType === Linker.types.growiLink) {
  172. isUseRelativePath = false;
  173. isUsePermanentLink = false;
  174. }
  175. this.setState({ linkerType, isUseRelativePath, isUsePermanentLink });
  176. }
  177. save() {
  178. if (this.props.onSave != null) {
  179. this.props.onSave(this.state.linkText);
  180. }
  181. this.hide();
  182. }
  183. generateLink() {
  184. const {
  185. linkInputValue, labelInputValue, linkerType, isUseRelativePath, isUsePermanentLink, permalink,
  186. } = this.state;
  187. let reshapedLink = linkInputValue;
  188. if (isUseRelativePath) {
  189. const rootPath = this.getRootPath(linkerType);
  190. reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
  191. }
  192. return new Linker(linkerType, labelInputValue, reshapedLink, isUsePermanentLink, permalink);
  193. }
  194. getRootPath(type) {
  195. const { pageContainer } = this.props;
  196. const pagePath = pageContainer.state.path;
  197. // rootPaths of md link and pukiwiki link are different
  198. return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
  199. }
  200. render() {
  201. return (
  202. <Modal isOpen={this.state.show} toggle={this.cancel} size="lg">
  203. <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
  204. Edit Links
  205. </ModalHeader>
  206. <ModalBody className="container">
  207. <div className="row">
  208. <div className="col-12 col-lg-6">
  209. <form className="form-group">
  210. <div className="form-gorup my-3">
  211. <label htmlFor="linkInput">Link</label>
  212. <div className="input-group">
  213. <SearchTypeahead
  214. onChange={this.handleChangeTypeahead}
  215. onInputChange={this.handleChangeLinkInput}
  216. inputName="link"
  217. placeholder="Input page path or URL"
  218. keywordOnInit={this.state.linkInputValue}
  219. />
  220. </div>
  221. </div>
  222. </form>
  223. <div className="d-block d-lg-none mb-3 overflow-auto">{this.renderPreview()}</div>
  224. <div className="card">
  225. <div className="card-body">
  226. <form className="form-group">
  227. <div className="form-group btn-group d-flex" role="group" aria-label="type">
  228. <button
  229. type="button"
  230. name={Linker.types.markdownLink}
  231. className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.markdownLink && 'active'}`}
  232. onClick={e => this.handleSelecteLinkerType(e.target.name)}
  233. >
  234. Markdown
  235. </button>
  236. <button
  237. type="button"
  238. name={Linker.types.growiLink}
  239. className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.growiLink && 'active'}`}
  240. onClick={e => this.handleSelecteLinkerType(e.target.name)}
  241. >
  242. Growi Original
  243. </button>
  244. {this.isApplyPukiwikiLikeLinkerPlugin && (
  245. <button
  246. type="button"
  247. name={Linker.types.pukiwikiLink}
  248. className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.pukiwikiLink && 'active'}`}
  249. onClick={e => this.handleSelecteLinkerType(e.target.name)}
  250. >
  251. Pukiwiki
  252. </button>
  253. )}
  254. </div>
  255. <div className="form-group">
  256. <label htmlFor="label">Label</label>
  257. <input
  258. type="text"
  259. className="form-control"
  260. id="label"
  261. value={this.state.labelInputValue}
  262. onChange={e => this.handleChangeLabelInput(e.target.value)}
  263. disabled={this.state.linkerType === Linker.types.growiLink}
  264. />
  265. </div>
  266. <div className="form-inline">
  267. <div className="custom-control custom-checkbox custom-checkbox-info">
  268. <input
  269. className="custom-control-input"
  270. id="relativePath"
  271. type="checkbox"
  272. checked={this.state.isUseRelativePath}
  273. disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
  274. />
  275. <label className="custom-control-label" htmlFor="relativePath" onClick={this.toggleIsUseRelativePath}>
  276. Use relative path
  277. </label>
  278. </div>
  279. </div>
  280. <div className="form-inline">
  281. <div className="custom-control custom-checkbox custom-checkbox-info">
  282. <input
  283. className="custom-control-input"
  284. id="permanentLink"
  285. type="checkbox"
  286. checked={this.state.isUsePermanentLink}
  287. disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
  288. />
  289. <label className="custom-control-label" htmlFor="permanentLink" onClick={this.toggleIsUsePamanentLink}>
  290. Use permanent link
  291. </label>
  292. </div>
  293. </div>
  294. </form>
  295. </div>
  296. </div>
  297. </div>
  298. <div className="col d-none d-lg-block pr-0 mr-3 overflow-auto">{this.renderPreview()}</div>
  299. </div>
  300. </ModalBody>
  301. <ModalFooter>
  302. <button type="button" className="btn btn-sm btn-outline-secondary" onClick={this.hide}>
  303. Cancel
  304. </button>
  305. <button type="submit" className="btn btn-sm btn-primary" onClick={this.save}>
  306. Done
  307. </button>
  308. </ModalFooter>
  309. </Modal>
  310. );
  311. }
  312. }
  313. LinkEditModal.propTypes = {
  314. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  315. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  316. onSave: PropTypes.func,
  317. };
  318. /**
  319. * Wrapper component for using unstated
  320. */
  321. const LinkEditModalWrapper = withUnstatedContainers(LinkEditModal, [AppContainer, PageContainer]);
  322. export default LinkEditModalWrapper;