1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-13 10:44:02 +02:00

fix trailing newline collapsing logic, closes #430

This commit is contained in:
Ian Storm Taylor
2016-11-17 13:15:14 -08:00
parent 85c6282d72
commit a2be745bed
2 changed files with 15 additions and 7 deletions

View File

@@ -441,23 +441,26 @@ class Content extends React.Component {
const schema = editor.getSchema()
const decorators = document.getDescendantDecorators(key, schema)
const node = document.getDescendant(key)
const block = document.getClosestBlock(node.key)
const ranges = node.getRanges(decorators)
const range = ranges.get(index)
const lastText = block.getLastText()
// Get the text information.
const isLast = index == ranges.size - 1
const { text, marks } = range
let { textContent } = anchorNode
const lastChar = textContent.charAt(textContent.length - 1)
const isLastText = node == lastText
const isLastRange = index == ranges.size - 1
// If we're dealing with the last leaf, and the DOM text ends in a new line,
// we will have added another new line in <Leaf>'s render method to account
// for browsers collapsing a single trailing new lines, so remove it.
if (isLast && lastChar == '\n') {
if (isLastText && isLastRange && lastChar == '\n') {
textContent = textContent.slice(0, -1)
}
// If the text is no different, abort.
const range = ranges.get(index)
const { text, marks } = range
if (textContent == text) return
// Determine what the selection should be after changing the text.

View File

@@ -257,7 +257,9 @@ class Leaf extends React.Component {
* @return {Element}
*/
renderText({ parent, text, index, ranges }) {
renderText(props) {
const { node, state, parent, text, index, ranges } = props
// COMPAT: If the text is empty and it's the only child, we need to render a
// <br/> to get the block to have the proper height.
if (text == '' && parent.kind == 'block' && parent.text == '') return <br />
@@ -269,9 +271,12 @@ class Leaf extends React.Component {
// COMPAT: Browsers will collapse trailing new lines at the end of blocks,
// so we need to add an extra trailing new lines to prevent that.
const block = state.document.getClosestBlock(node.key)
const lastText = block.getLastText()
const lastChar = text.charAt(text.length - 1)
const isLast = index == ranges.size - 1
if (isLast && lastChar == '\n') return `${text}\n`
const isLastText = node == lastText
const isLastRange = index == ranges.size - 1
if (isLastText && isLastRange && lastChar == '\n') return `${text}\n`
// Otherwise, just return the text.
return text