LinkEditModal.jsx 13 KB

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