Skip to content

Commit

Permalink
Merge pull request #280 from CaritasDeutschland/COBH-4055
Browse files Browse the repository at this point in the history
feat: [COBH-4055] allow escaping in markdownToDraft
  • Loading branch information
mebo4b authored Dec 7, 2021
2 parents df9fb5a + 0727891 commit 799bddc
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ import {
emojiPickerCustomClasses,
toolbarCustomClasses,
handleEditorBeforeInput,
handleEditorPastedText
handleEditorPastedText,
escapeMarkdownChars
} from './richtextHelpers';
import { ReactComponent as EmojiIcon } from '../../resources/img/icons/smiley-positive.svg';
import { ReactComponent as FileDocIcon } from '../../resources/img/icons/file-doc.svg';
Expand Down Expand Up @@ -457,8 +458,10 @@ export const MessageSubmitInterfaceComponent = (
const contentState = currentEditorState
? currentEditorState.getCurrentContent()
: editorState.getCurrentContent();
const rawObject = convertToRaw(contentState);
const markdownString = draftToMarkdown(rawObject);
const rawObject = convertToRaw(escapeMarkdownChars(contentState));
const markdownString = draftToMarkdown(rawObject, {
escapeMarkdownCharacters: false
});
return markdownString.trim();
};

Expand Down
38 changes: 36 additions & 2 deletions src/components/messageSubmitInterface/richtextHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { DraftHandleValue } from 'draft-js';
import {
ContentState,
convertToRaw,
DraftHandleValue,
Modifier,
SelectionState
} from 'draft-js';
import sanitizeHtml from 'sanitize-html';

export const emojiPickerCustomClasses = {
Expand Down Expand Up @@ -96,7 +102,6 @@ export const markdownToDraftDefaultOptions = {
inline: [
'autolink',
'backticks',
'escape',
'htmltag',
'links',
'newline',
Expand All @@ -122,3 +127,32 @@ export const sanitizeHtmlDefaultOptions = {
],
allowedAttributes: sanitizeHtml.defaults.allowedAttributes
};

/**
* Escape markdown characters typed by the user
* @param contentState
*/
export const escapeMarkdownChars = (contentState: ContentState) => {
let newContentState = contentState;
const rawDraftObject = convertToRaw(contentState);

rawDraftObject.blocks.forEach((block) => {
const selectionState = SelectionState.createEmpty(block.key);
let counter = 0;
newContentState = [...block.text].reduce(
(contentState, char, charIndex) => {
if (['*', '_', '~', '`'].indexOf(char) < 0) return contentState;

const selection = selectionState.merge({
focusOffset: charIndex + counter,
anchorOffset: charIndex + counter
});
counter++;
return Modifier.insertText(contentState, selection, '\\');
},
newContentState
);
});

return newContentState;
};

0 comments on commit 799bddc

Please sign in to comment.