From 6e694c113ad65d5b458f39231b39daea12f4032b Mon Sep 17 00:00:00 2001 From: Bruno Windels Date: Wed, 4 Sep 2019 12:40:21 +0200 Subject: [PATCH] add support for inline/block code formatting --- .../views/rooms/BasicMessageComposer.js | 9 ++++++-- src/editor/operations.js | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/components/views/rooms/BasicMessageComposer.js b/src/components/views/rooms/BasicMessageComposer.js index 38cfff9b65..cd8589ee29 100644 --- a/src/components/views/rooms/BasicMessageComposer.js +++ b/src/components/views/rooms/BasicMessageComposer.js @@ -24,6 +24,7 @@ import {setCaretPosition} from '../../../editor/caret'; import { replaceRangeAndExpandSelection, formatRangeAsQuote, + formatRangeAsCode, formatInline, } from '../../../editor/operations'; import {getCaretOffsetAndText, getRangeForSelection} from '../../../editor/dom'; @@ -457,8 +458,12 @@ export default class BasicMessageEditor extends React.Component { formatRangeAsQuote(range); } - _formatCodeBlock = () => { - + _formatCode = () => { + const range = getRangeForSelection( + this._editorRef, + this.props.model, + document.getSelection()); + formatRangeAsCode(range); } render() { diff --git a/src/editor/operations.js b/src/editor/operations.js index be979c275a..df3047618b 100644 --- a/src/editor/operations.js +++ b/src/editor/operations.js @@ -67,6 +67,29 @@ export function formatRangeAsQuote(range) { replaceRangeAndExpandSelection(model, range, parts); } +export function formatRangeAsCode(range) { + const {model, parts} = range; + const {partCreator} = model; + const needsBlock = parts.some(p => p.type === "newline"); + if (needsBlock) { + parts.unshift(partCreator.plain("```"), partCreator.newline()); + if (!rangeStartsAtBeginningOfLine(range)) { + parts.unshift(partCreator.newline()); + } + parts.push( + partCreator.newline(), + partCreator.plain("```")); + if (rangeEndsAtEndOfLine(range)) { + parts.push(partCreator.newline()); + } + replaceRangeAndExpandSelection(model, range, parts); + } else { + parts.unshift(partCreator.plain("`")); + parts.push(partCreator.plain("`")); + replaceRangeAndExpandSelection(model, range, parts); + } +} + export function formatInline(range, prefix, suffix = prefix) { const {model, parts} = range; const {partCreator} = model;