This repository has been archived on 2022-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
outline/app/components/Editor/Editor.js

97 lines
2.2 KiB
JavaScript
Raw Normal View History

// @flow
import * as React from 'react';
2019-01-19 08:23:39 +00:00
import { Redirect } from 'react-router-dom';
import { observable } from 'mobx';
import { observer } from 'mobx-react';
2019-03-13 04:35:35 +00:00
import { withTheme } from 'styled-components';
2018-11-19 02:28:22 +00:00
import RichMarkdownEditor from 'rich-markdown-editor';
2018-11-18 19:14:26 +00:00
import { uploadFile } from 'utils/uploadFile';
import isInternalUrl from 'utils/isInternalUrl';
import Embed from './Embed';
import embeds from '../../embeds';
type Props = {
2018-08-26 22:27:32 +00:00
defaultValue?: string,
2018-11-18 19:14:26 +00:00
readOnly?: boolean,
disableEmbeds?: boolean,
forwardedRef: *,
2018-11-18 19:14:26 +00:00
ui: *,
};
2019-01-19 08:23:39 +00:00
@observer
class Editor extends React.Component<Props> {
2019-01-19 08:23:39 +00:00
@observable redirectTo: ?string;
2018-11-18 19:14:26 +00:00
onUploadImage = async (file: File) => {
const result = await uploadFile(file);
return result.url;
};
onClickLink = (href: string) => {
// on page hash
if (href[0] === '#') {
window.location.href = href;
return;
}
if (isInternalUrl(href)) {
// relative
let navigateTo = href;
// probably absolute
if (href[0] !== '/') {
try {
const url = new URL(href);
navigateTo = url.pathname + url.hash;
} catch (err) {
navigateTo = href;
}
}
2019-01-19 08:23:39 +00:00
this.redirectTo = navigateTo;
2018-11-18 19:14:26 +00:00
} else {
window.open(href, '_blank');
}
};
onShowToast = (message: string) => {
this.props.ui.showToast(message);
2018-11-18 19:14:26 +00:00
};
getLinkComponent = node => {
if (this.props.disableEmbeds) return;
const url = node.data.get('href');
const keys = Object.keys(embeds);
for (const key of keys) {
const component = embeds[key];
for (const host of component.ENABLED) {
const matches = url.match(host);
if (matches) return Embed;
}
}
};
render() {
if (this.redirectTo) return <Redirect to={this.redirectTo} push />;
2019-01-19 08:23:39 +00:00
return (
2018-11-19 02:28:22 +00:00
<RichMarkdownEditor
ref={this.props.forwardedRef}
2018-11-19 02:28:22 +00:00
uploadImage={this.onUploadImage}
onClickLink={this.onClickLink}
onShowToast={this.onShowToast}
getLinkComponent={this.getLinkComponent}
2018-11-19 02:28:22 +00:00
{...this.props}
/>
);
}
}
2019-03-13 04:35:35 +00:00
export default withTheme(
// $FlowIssue - https://github.com/facebook/flow/issues/6103
React.forwardRef((props, ref) => <Editor {...props} forwardedRef={ref} />)
);