This repository has been archived by the owner on Sep 11, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 828
Rich Text Editor #292
Merged
Merged
Rich Text Editor #292
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
001011d
Initial version of rich text editor
aviraldg fe76eb9
minor improvements
aviraldg 96526c2
Merge branch 'develop' into feature-rte
aviraldg 29cdd1f
user and room decorators, history & typing notifs
aviraldg 4e0720d
Fix MessageComposerInput.setLastTextEntry
aviraldg bf8e56e
Merge branch 'develop' of github.com:matrix-org/matrix-react-sdk into…
aviraldg e4217c3
rte improvements, markdown mode
aviraldg b960d22
cleanup, better comments, markdown hotkeys
aviraldg c0d7629
get /commands working again
aviraldg a5a3e4e
Basic Markdown highlighting
pferreir 8f45f16
Fix highlighting behaviour on switch
pferreir 294a8ef
Fix behaviour of modifyText
pferreir e75a28b
Minimal house cleaning
pferreir df69d1d
Add basic Markdown highlighting
aviraldg 74527a4
Merge branch 'develop' into feature-rte
aviraldg 34be17c
use rte labs setting
aviraldg 2606ea9
fixes and improvements in RichText
aviraldg 8cb086e
use constants for keycodes in RTE
aviraldg ba69e43
more RTE fixes
aviraldg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
import { | ||
Editor, | ||
Modifier, | ||
ContentState, | ||
convertFromHTML, | ||
DefaultDraftBlockRenderMap, | ||
DefaultDraftInlineStyle, | ||
CompositeDecorator | ||
} from 'draft-js'; | ||
import * as sdk from './index'; | ||
|
||
const BLOCK_RENDER_MAP = DefaultDraftBlockRenderMap.set('unstyled', { | ||
element: 'p' // draft uses <div> by default which we don't really like, so we're using <p> | ||
}); | ||
|
||
const STYLES = { | ||
BOLD: 'strong', | ||
CODE: 'code', | ||
ITALIC: 'em', | ||
STRIKETHROUGH: 's', | ||
UNDERLINE: 'u' | ||
}; | ||
|
||
const MARKDOWN_REGEX = { | ||
LINK: /(?:\[([^\]]+)\]\(([^\)]+)\))|\<(\w+:\/\/[^\>]+)\>/g, | ||
ITALIC: /([\*_])([\w\s]+?)\1/g, | ||
BOLD: /([\*_])\1([\w\s]+?)\1\1/g | ||
}; | ||
|
||
const USERNAME_REGEX = /@\S+:\S+/g; | ||
const ROOM_REGEX = /#\S+:\S+/g; | ||
|
||
export function contentStateToHTML(contentState: ContentState): string { | ||
return contentState.getBlockMap().map((block) => { | ||
let elem = BLOCK_RENDER_MAP.get(block.getType()).element; | ||
let content = []; | ||
block.findStyleRanges( | ||
() => true, // always return true => don't filter any ranges out | ||
(start, end) => { | ||
// map style names to elements | ||
let tags = block.getInlineStyleAt(start).map(style => STYLES[style]).filter(style => !!style); | ||
// combine them to get well-nested HTML | ||
let open = tags.map(tag => `<${tag}>`).join(''); | ||
let close = tags.map(tag => `</${tag}>`).reverse().join(''); | ||
// and get the HTML representation of this styled range (this .substring() should never fail) | ||
content.push(`${open}${block.getText().substring(start, end)}${close}`); | ||
} | ||
); | ||
|
||
return (`<${elem}>${content.join('')}</${elem}>`); | ||
}).join(''); | ||
} | ||
|
||
export function HTMLtoContentState(html: string): ContentState { | ||
return ContentState.createFromBlockArray(convertFromHTML(html)); | ||
} | ||
|
||
/** | ||
* Returns a composite decorator which has access to provided scope. | ||
*/ | ||
export function getScopedRTDecorators(scope: any): CompositeDecorator { | ||
let MemberAvatar = sdk.getComponent('avatars.MemberAvatar'); | ||
|
||
let usernameDecorator = { | ||
strategy: (contentBlock, callback) => { | ||
findWithRegex(USERNAME_REGEX, contentBlock, callback); | ||
}, | ||
component: (props) => { | ||
let member = scope.room.getMember(props.children[0].props.text); | ||
// unused until we make these decorators immutable (autocomplete needed) | ||
let name = member ? member.name : null; | ||
let avatar = member ? <MemberAvatar member={member} width={16} height={16}/> : null; | ||
return <span className="mx_UserPill">{avatar} {props.children}</span>; | ||
} | ||
}; | ||
let roomDecorator = { | ||
strategy: (contentBlock, callback) => { | ||
findWithRegex(ROOM_REGEX, contentBlock, callback); | ||
}, | ||
component: (props) => { | ||
return <span className="mx_RoomPill">{props.children}</span>; | ||
} | ||
}; | ||
|
||
return [usernameDecorator, roomDecorator]; | ||
} | ||
|
||
export function getScopedMDDecorators(scope: any): CompositeDecorator { | ||
let markdownDecorators = ['BOLD', 'ITALIC'].map( | ||
(style) => ({ | ||
strategy: (contentBlock, callback) => { | ||
return findWithRegex(MARKDOWN_REGEX[style], contentBlock, callback); | ||
}, | ||
component: (props) => ( | ||
<span className={"mx_MarkdownElement mx_Markdown_" + style}> | ||
{props.children} | ||
</span> | ||
) | ||
})); | ||
|
||
markdownDecorators.push({ | ||
strategy: (contentBlock, callback) => { | ||
return findWithRegex(MARKDOWN_REGEX.LINK, contentBlock, callback); | ||
}, | ||
component: (props) => ( | ||
<a href="#" className="mx_MarkdownElement mx_Markdown_LINK"> | ||
{props.children} | ||
</a> | ||
) | ||
}); | ||
|
||
return markdownDecorators; | ||
} | ||
|
||
/** | ||
* Utility function that looks for regex matches within a ContentBlock and invokes {callback} with (start, end) | ||
* From https://facebook.github.io/draft-js/docs/advanced-topics-decorators.html | ||
*/ | ||
function findWithRegex(regex, contentBlock: ContentBlock, callback: (start: number, end: number) => any) { | ||
const text = contentBlock.getText(); | ||
let matchArr, start; | ||
while ((matchArr = regex.exec(text)) !== null) { | ||
start = matchArr.index; | ||
callback(start, start + matchArr[0].length); | ||
} | ||
} | ||
|
||
/** | ||
* Passes rangeToReplace to modifyFn and replaces it in contentState with the result. | ||
*/ | ||
export function modifyText(contentState: ContentState, rangeToReplace: SelectionState, | ||
modifyFn: (text: string) => string, inlineStyle, entityKey): ContentState { | ||
let getText = (key) => contentState.getBlockForKey(key).getText(), | ||
startKey = rangeToReplace.getStartKey(), | ||
startOffset = rangeToReplace.getStartOffset(), | ||
endKey = rangeToReplace.getEndKey(), | ||
endOffset = rangeToReplace.getEndOffset(), | ||
text = ""; | ||
|
||
|
||
for(let currentKey = startKey; | ||
currentKey && currentKey !== endKey; | ||
currentKey = contentState.getKeyAfter(currentKey)) { | ||
let blockText = getText(currentKey); | ||
text += blockText.substring(startOffset, blockText.length); | ||
|
||
// from now on, we'll take whole blocks | ||
startOffset = 0; | ||
} | ||
|
||
// add remaining part of last block | ||
text += getText(endKey).substring(startOffset, endOffset); | ||
|
||
return Modifier.replaceText(contentState, rangeToReplace, modifyFn(text), inlineStyle, entityKey); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess we've done this to fit into the same model as richtext, but doing this manually with regexes rather than using the markd library feels like a major step back here. There must be lots of markdown syntax we don't support?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So this *only *handles the preview that's rendered in the composer (which
for obvious reasons can't be a proper rendering) -- the sent message still
uses the markdown library.
On Mon, Jun 13, 2016 at 11:29 PM David Baker notifications@github.com
wrote:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah right, I see. Still doesn't feel great to have two different types of parsing for the markdown, but if it's not on the critical message path then probably ok.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I know, I was complaining about it on #vector-dev too, but there's very
little that can be done here.
On Tue, Jun 14, 2016 at 12:13 AM David Baker notifications@github.com
wrote:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why can't you parse it to markdown then render that markdown as the preview?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because at the end of the day, it still needs to be Markdown: using rendered Markdown will strip formatting characters and mangle tables, code blocks, etc. such that it becomes more like a rich text editor than a markdown one.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see how you can sensibly display these things "as-you-type" Markdown. If we can't do all of markdown, we'll end up with a mix of some stuff that is easy to render as markdown and some stuff which is too difficult to render sensibly so we don't bother. I'm not sure I see the value in this.
If we do have a way of representing all of Markdown as you type which doesn't make me want to stab the input box, then surely we should be using the actual hooks given to us in the
marked
library to implement customRenderer
s for things likestrong
,em
,codespan
, etc. This would make things a lot cleaner and doesn't introduce subtle formatting differences between our hand-crafted regex and themarked
parser. See https://github.com/chjj/marked/blob/88ce4df47c4d994dc1b1df1477a21fb893e11ddc/lib/marked.js#L857