Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@
"@silvermine/videojs-chromecast": "^1.3.3",
"@stripe/react-stripe-js": "^1.10.0",
"@stripe/stripe-js": "^1.35.0",
"@tiptap/extension-character-count": "^2.0.0-beta.207",
"@tiptap/extension-code-block-lowlight": "^2.0.0-beta.207",
"@tiptap/extension-link": "^2.0.0-beta.207",
"@tiptap/extension-placeholder": "^2.0.0-beta.207",
"@tiptap/react": "^2.0.0-beta.207",
"@tiptap/starter-kit": "^2.0.0-beta.207",
"@ungap/from-entries": "^0.2.1",
"auto-launch": "^5.0.5",
"core-js-pure": "^3.19.3",
Expand All @@ -67,9 +73,19 @@
"express": "^4.17.1",
"humanize-duration": "^3.27.0",
"if-env": "^1.0.4",
"lowlight": "^2.8.0",
"markdown-it": "^13.0.1",
"match-sorter": "^6.3.0",
"parse-duration": "^1.0.0",
"player.js": "^0.1.0",
"prosemirror-dropcursor": "1.5.0",
"prosemirror-gapcursor": "^1.3.1",
"prosemirror-history": "^1.3.0",
"prosemirror-markdown": "1.6.2",
"prosemirror-model": "1.16.0",
"prosemirror-state": "1.4.1",
"prosemirror-transform": "1.1.0",
"prosemirror-view": "1.28.2",
"proxy-polyfill": "0.1.6",
"re-reselect": "^4.0.0",
"react-balance-text": "^2.0.1",
Expand All @@ -91,6 +107,12 @@
"videojs-logo": "^2.1.4",
"videojs-vtt-thumbnails": "https://github.com/OdyseeTeam/videojs-vtt-thumbnails"
},
"resolutions": {
"prosemirror-model": "1.16.0",
"prosemirror-state": "1.4.1",
"prosemirror-transform": "1.1.0",
"prosemirror-view": "1.28.2"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
Expand Down
102 changes: 4 additions & 98 deletions ui/component/common/form-components/form-field.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,17 @@ import 'easymde/dist/easymde.min.css';

import './plugins/inline-attachment/inline-attachment';
import './plugins/inline-attachment/codemirror-4.inline-attachment';
import { IMG_CDN_PUBLISH_URL, JSON_RESPONSE_KEYS, UPLOAD_CONFIG } from 'constants/cdn_urls';
import { FF_MAX_CHARS_DEFAULT } from 'constants/form-field';
import { openEditorMenu, stopContextMenu } from 'util/context-menu';
import { lazyImport } from 'util/lazyImport';
import MarkdownPreview from 'component/common/markdown-preview';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import SimpleMDE from 'react-simplemde-editor';
import type { ElementRef } from 'react';
import { InputSimple, BlockWrapWrapper } from './input-simple';
import { InputSelect } from './input-select';
import { CountInfo, QuickAction, Label } from './common';
import { TextareaWrapper } from './slim-input-field';

import Tiptap from './markdownEditor';

// prettier-ignore
const TextareaWithSuggestions = lazyImport(() => import('component/textareaWithSuggestions' /* webpackChunkName: "suggestions" */));

Expand Down Expand Up @@ -179,76 +176,10 @@ export class FormField extends React.PureComponent<Props, State> {
</FormFieldWrapper>
);
case 'markdown':
const handleEvents = { contextmenu: openEditorMenu };

const getInstance = (editor) => {
// SimpleMDE max char check
editor.codemirror.on('beforeChange', (instance, changes) => {
if (textAreaMaxLength && changes.update) {
let str = changes.text.join('\n');
let delta = str.length - (instance.indexFromPos(changes.to) - instance.indexFromPos(changes.from));

if (delta <= 0) return;

delta = instance.getValue().length + delta - textAreaMaxLength;
if (delta > 0) {
str = str.substr(0, str.length - delta);
changes.update(changes.from, changes.to, str.split('\n'));
}
}
});

// "Create Link (Ctrl-K)": highlight URL instead of label:
editor.codemirror.on('changes', (instance, changes) => {
try {
// Grab the last change from the buffered list. I assume the
// buffered one ('changes', instead of 'change') is more efficient,
// and that "Create Link" will always end up last in the list.
const lastChange = changes[changes.length - 1];
if (lastChange.origin === '+input') {
// https://github.com/Ionaru/easy-markdown-editor/blob/8fa54c496f98621d5f45f57577ce630bee8c41ee/src/js/easymde.js#L765
const EASYMDE_URL_PLACEHOLDER = '(https://)';

// The URL placeholder is always placed last, so just look at the
// last text in the array to also cover the multi-line case:
const urlLineText = lastChange.text[lastChange.text.length - 1];

if (urlLineText.endsWith(EASYMDE_URL_PLACEHOLDER) && urlLineText !== '[]' + EASYMDE_URL_PLACEHOLDER) {
const from = lastChange.from;
const to = lastChange.to;
const isSelectionMultiline = lastChange.text.length > 1;
const baseIndex = isSelectionMultiline ? 0 : from.ch;

// Everything works fine for the [Ctrl-K] case, but for the
// [Button] case, this handler happens before the original
// code, thus our change got wiped out.
// Add a small delay to handle that case.
setTimeout(() => {
instance.setSelection(
{ line: to.line, ch: baseIndex + urlLineText.lastIndexOf('(') + 1 },
{ line: to.line, ch: baseIndex + urlLineText.lastIndexOf(')') }
);
}, 25);
}
}
} catch (e) {} // Do nothing (revert to original behavior)
});

// Add ability to upload pasted/dragged image (https://github.com/sparksuite/simplemde-markdown-editor/issues/328#issuecomment-227075500)
window.inlineAttachment.editors.codemirror4.attach(editor.codemirror, {
uploadUrl: IMG_CDN_PUBLISH_URL,
uploadFieldName: UPLOAD_CONFIG.BLOB_KEY,
extraParams: { [UPLOAD_CONFIG.ACTION_KEY]: UPLOAD_CONFIG.ACTION_VAL },
filenameTag: '{filename}',
urlText: '![image]({filename})',
jsonFieldName: JSON_RESPONSE_KEYS.UPLOADED_URL,
errorText: '![image]("failed to upload file")',
});
};

return (
<FormFieldWrapper {...wrapperProps}>
<div className="form-field--SimpleMDE" onContextMenu={stopContextMenu}>
<div className="form-field--SimpleMDE">
<fieldset-section>
<div className="form-field__two-column">
<div>
Expand All @@ -258,32 +189,7 @@ export class FormField extends React.PureComponent<Props, State> {
<QuickAction {...quickActionProps} />
</div>

<SimpleMDE
{...inputProps}
id={name}
type="textarea"
events={handleEvents}
getMdeInstance={getInstance}
options={{
spellChecker: false,
hideIcons: ['heading', 'image', 'fullscreen', 'side-by-side'],
status: [
{
className: 'editor-statusbar__upload-hint',
defaultValue: (el) => {
el.innerHTML = __('Attach images by pasting or drag-and-drop.');
},
},
'lines',
'words',
'cursor',
],
previewRender(plainText) {
const preview = <MarkdownPreview content={plainText} noDataStore />;
return ReactDOMServer.renderToString(preview);
},
}}
/>
<Tiptap {...inputProps} textAreaMaxLength={textAreaMaxLength} />

<CountInfo {...countInfoProps} />
</fieldset-section>
Expand Down
121 changes: 121 additions & 0 deletions ui/component/common/form-components/markdownEditor/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// @flow
import React from 'react';
import { lowlight } from 'lowlight';

import './styles.scss';

import * as TipTap from '@tiptap/react';

import { getMarkdownOutput } from './internal/util/markdown';

// -- Plugins --
import StarterKit from '@tiptap/starter-kit';
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
import Link from '@tiptap/extension-link';
import CharacterCount from '@tiptap/extension-character-count';
import Placeholder from '@tiptap/extension-placeholder';

import MarkdownPasteHandler from './internal/customPlugins/markdown-paste-handler';

// -- End Plugins --

import Button from 'component/button';
import MarkdownPreview from 'component/common/markdown-preview';
import MenuBar from './internal/menuBar';

type Props = {
value: string,
disabled: boolean,
placeholder: string,
textAreaMaxLength?: number,
onChange?: (value: string) => void,
};

const MarkdownEditor = (props: Props) => {
const { value, placeholder, textAreaMaxLength, onChange } = props;

const [cursor, setCursor] = React.useState({ line: 0, ch: 0 });
const [markdownOutput, setMarkdownOutput] = React.useState('');
const [viewMode, setViewMode] = React.useState(1);

function handleUpdate({ editor }) {
const markdownTxt = getMarkdownOutput(editor);
setMarkdownOutput(markdownTxt);

if (onChange) {
onChange(markdownTxt);
}
}

const editor = TipTap.useEditor({
extensions: [
StarterKit.configure({ codeBlock: false }),
CodeBlockLowlight.configure({ lowlight }),
Placeholder.configure({ placeholder }),
CharacterCount.configure({ limit: textAreaMaxLength }),
Link.configure({ protocols: ['ftp', 'mailto', 'lbry'], openOnClick: false }),
MarkdownPasteHandler,
],
onCreate: ({ editor }) => setMarkdownOutput(getMarkdownOutput(editor)),
onUpdate: handleUpdate,
onSelectionUpdate: ({ editor }) => {
const { anchor: cursorAnchor } = editor.state.selection;
const editorText = editor.getText();
const textBeforeAnchor = editorText.substring(0, cursorAnchor - 1);
const linesToAnchor = textBeforeAnchor.split('\n\n');
const currentLine = linesToAnchor.length;
const currentLineCh = linesToAnchor[linesToAnchor.length - 1].length;

setCursor({ line: currentLine, ch: currentLineCh });
},
editorProps: {},
content: value,
parseOptions: { to: 10 },
});

React.useEffect(() => {
if (markdownOutput && onChange) {
onChange(markdownOutput);
}
}, [markdownOutput, onChange]);

if (!editor) return null;

return (
<div id="content_post-wrapper">
<div className="EasyMDEContainer">
<div className="toolbar-editor">
<MenuBar editor={editor} />
</div>

<div style={{ display: viewMode === 0 && 'flex' }}>
<div style={{ width: viewMode === 0 && '50%' }} className="CodeMirror cm-s-easymde CodeMirror-wrap">
<TipTap.EditorContent editor={editor} />
</div>

{viewMode === 0 && (
<div style={{ width: '50%' }} className="CodeMirror cm-s-easymde CodeMirror-wrap">
<MarkdownPreview content={markdownOutput} />
</div>
)}
</div>

<div className="tiptap-editor__actions">
<Button className={viewMode === 0 && 'is-active'} label={__('Markdown')} onClick={() => setViewMode(0)} />
<Button className={viewMode === 1 && 'is-active'} label={__('WYSIWYG')} onClick={() => setViewMode(1)} />
</div>

<div className="editor-statusbar">
<span className="editor-statusbar__upload-hint">{__('Attach images by pasting or drag-and-drop.')}</span>
<span className="lines">{editor.getJSON().content.length}</span>
<span className="words">{editor.storage.characterCount.words()}</span>
<span className="cursor">
{cursor.line}:{cursor.ch}
</span>
</div>
</div>
</div>
);
};

export default MarkdownEditor;
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// @flow
// https://github.com/ueberdosis/tiptap/issues/2874#issuecomment-1153479930
import MarkdownIt from 'markdown-it';

import { Plugin, PluginKey } from 'prosemirror-state';
import { Extension, generateJSON } from '@tiptap/core';

import StarterKit from '@tiptap/starter-kit';
import Link from '@tiptap/extension-link';

const MarkdownPasteHandler = Extension.create({
name: 'eventHandler',

addProseMirrorPlugins() {
const { editor } = this;

return [
new Plugin({
key: new PluginKey('eventHandler'),
props: {
handlePaste(view, event, slice) {
const md = new MarkdownIt();

const mdContents = event.clipboardData.getData('text/plain');
const jsonContent = generateJSON(md.render(mdContents), [
MarkdownPasteHandler,
StarterKit,
Link.configure({ openOnClick: false }),
]);

editor.commands.insertContent(jsonContent.content.length > 1 ? jsonContent : mdContents, {
parseOptions: { preserveWhitespace: false },
});

return true;
},
},
}),
];
},
});

export default MarkdownPasteHandler;
Loading