| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295 |
- import React from 'react';
- import PropTypes from 'prop-types';
- import * as toastr from 'toastr';
- import {debounce} from 'throttle-debounce';
- import Editor from './PageEditor/Editor';
- import Preview from './PageEditor/Preview';
- export default class PageEditor extends React.Component {
- constructor(props) {
- super(props);
- const config = this.props.crowi.getConfig();
- const isUploadable = config.upload.image || config.upload.file;
- this.state = {
- revisionId: this.props.revisionId,
- markdown: this.props.markdown,
- isUploadable,
- };
- this.setCaretLine = this.setCaretLine.bind(this);
- this.focusToEditor = this.focusToEditor.bind(this);
- this.onMarkdownChanged = this.onMarkdownChanged.bind(this);
- this.onSave = this.onSave.bind(this);
- this.onUpload = this.onUpload.bind(this);
- this.onEditorScroll = this.onEditorScroll.bind(this);
- this.getMaxScrollTop = this.getMaxScrollTop.bind(this);
- this.getScrollTop = this.getScrollTop.bind(this);
- this.saveDraft = this.saveDraft.bind(this);
- this.clearDraft = this.clearDraft.bind(this);
- this.pageSavedHandler = this.pageSavedHandler.bind(this);
- this.apiErrorHandler = this.apiErrorHandler.bind(this);
- // create debounced function
- this.saveDraftWithDebounce = debounce(300, this.saveDraft);
- }
- componentWillMount() {
- // restore draft
- this.restoreDraft();
- // initial preview
- this.renderPreview();
- }
- focusToEditor() {
- this.refs.editor.forceToFocus();
- }
- /**
- * set caret position of editor
- * @param {number} line
- */
- setCaretLine(line) {
- this.refs.editor.setCaretLine(line);
- }
- /**
- * the change event handler for `markdown` state
- * @param {string} value
- */
- onMarkdownChanged(value) {
- this.setState({
- markdown: value,
- });
- this.renderPreview();
- this.saveDraftWithDebounce()
- }
- /**
- * the save event handler
- */
- onSave() {
- let endpoint;
- let data;
- // update
- if (this.props.pageId != null) {
- endpoint = '/pages.update';
- data = {
- page_id: this.props.pageId,
- revision_id: this.state.revisionId,
- body: this.state.markdown,
- };
- }
- // create
- else {
- endpoint = '/pages.create';
- data = {
- path: this.props.pagePath,
- body: this.state.markdown,
- };
- }
- this.props.crowi.apiPost(endpoint, data)
- .then((res) => {
- // show toastr
- toastr.success(undefined, 'Saved successfully', {
- closeButton: true,
- progressBar: true,
- newestOnTop: false,
- showDuration: "100",
- hideDuration: "100",
- timeOut: "1200",
- extendedTimeOut: "150",
- });
- this.pageSavedHandler(res.page);
- })
- .catch(this.apiErrorHandler)
- }
- /**
- * the upload event handler
- * @param {any} files
- */
- onUpload(file) {
- const endpoint = '/attachments.add';
- // create a FromData instance
- const formData = new FormData();
- formData.append('_csrf', this.props.crowi.csrfToken);
- formData.append('file', file);
- formData.append('path', this.props.pagePath);
- formData.append('page_id', this.props.pageId || 0);
- // post
- this.props.crowi.apiPost(endpoint, formData)
- .then((res) => {
- const url = res.url;
- const attachment = res.attachment;
- const fileName = attachment.originalName;
- let insertText = `[${fileName}](${url})`;
- // when image
- if (attachment.fileFormat.startsWith('image/')) {
- // modify to "" syntax
- insertText = '!' + insertText;
- }
- this.refs.editor.insertText(insertText);
- // update page information if created
- if (res.pageCreated) {
- this.pageSavedHandler(res.page);
- }
- })
- .catch(this.apiErrorHandler);
- }
- /**
- * the scroll event handler from codemirror
- * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position, the size of the scrollable area, and the size of the visible area (minus scrollbars).
- * see https://codemirror.net/doc/manual.html#events
- */
- onEditorScroll(data) {
- const rate = data.top / (data.height - data.clientHeight)
- const top = this.getScrollTop(this.previewElement, rate);
- this.previewElement.scrollTop = top;
- }
- /**
- * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
- * @param {*} dom
- */
- getMaxScrollTop(dom) {
- var rect = dom.getBoundingClientRect();
- return dom.scrollHeight - rect.height;
- };
- /**
- * transplanted from crowi-form.js -- 2018.01.21 Yuki Takei
- * @param {*} dom
- */
- getScrollTop(dom, rate) {
- var maxScrollTop = this.getMaxScrollTop(dom);
- var top = maxScrollTop * rate;
- return top;
- };
- restoreDraft() {
- // restore draft when the first time to edit
- const draft = this.props.crowi.findDraft(this.props.pagePath);
- if (!this.props.revisionId && draft != null) {
- this.setState({markdown: draft});
- }
- }
- saveDraft() {
- // only when the first time to edit
- if (!this.state.revisionId) {
- this.props.crowi.saveDraft(this.props.pagePath, this.state.markdown);
- }
- }
- clearDraft() {
- this.props.crowi.clearDraft(this.props.pagePath);
- }
- pageSavedHandler(page) {
- // update states
- this.setState({
- revisionId: page.revision._id,
- markdown: page.revision.body
- })
- // clear draft
- this.clearDraft();
- // dispatch onSaveSuccess event
- if (this.props.onSaveSuccess != null) {
- this.props.onSaveSuccess(page);
- }
- }
- apiErrorHandler(error) {
- console.error(error);
- toastr.error(error.message, 'Error occured', {
- closeButton: true,
- progressBar: true,
- newestOnTop: false,
- showDuration: "100",
- hideDuration: "100",
- timeOut: "3000",
- });
- }
- renderPreview() {
- const config = this.props.crowi.config;
- // generate options obj
- const rendererOptions = {
- // see: https://www.npmjs.com/package/marked
- marked: {
- breaks: config.isEnabledLineBreaks,
- }
- };
- // render html
- var context = {
- markdown: this.state.markdown,
- dom: this.previewElement,
- currentPagePath: decodeURIComponent(location.pathname)
- };
- this.props.crowi.interceptorManager.process('preRenderPreview', context)
- .then(() => crowi.interceptorManager.process('prePreProcess', context))
- .then(() => {
- context.markdown = crowiRenderer.preProcess(context.markdown, context.dom);
- })
- .then(() => crowi.interceptorManager.process('postPreProcess', context))
- .then(() => {
- var parsedHTML = crowiRenderer.render(context.markdown, context.dom, rendererOptions);
- context['parsedHTML'] = parsedHTML;
- })
- .then(() => crowi.interceptorManager.process('postRenderPreview', context))
- .then(() => crowi.interceptorManager.process('preRenderPreviewHtml', context))
- .then(() => {
- this.setState({html: context.parsedHTML});
- // set html to the hidden input (for submitting to save)
- $('#form-body').val(this.state.markdown);
- })
- // process interceptors for post rendering
- .then(() => crowi.interceptorManager.process('postRenderPreviewHtml', context));
- }
- render() {
- return (
- <div className="row">
- <div className="col-md-6 col-sm-12 page-editor-editor-container">
- <Editor ref="editor" value={this.state.markdown}
- isUploadable={this.state.isUploadable}
- onScroll={this.onEditorScroll}
- onChange={this.onMarkdownChanged}
- onSave={this.onSave}
- onUpload={this.onUpload}
- />
- </div>
- <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
- <Preview html={this.state.html} inputRef={el => this.previewElement = el} />
- </div>
- </div>
- )
- }
- }
- PageEditor.propTypes = {
- crowi: PropTypes.object.isRequired,
- markdown: PropTypes.string.isRequired,
- pageId: PropTypes.string,
- revisionId: PropTypes.string,
- pagePath: PropTypes.string,
- onSaveSuccess: PropTypes.func,
- };
|