Skip to content
This repository has been archived by the owner on Feb 6, 2023. It is now read-only.

Avoid extra new line in Firefox when block ends with soft new line #3142

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
11 changes: 11 additions & 0 deletions src/component/handlers/edit/editOnBeforeInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const editOnInput = require('editOnInput');
const getEntityKeyForSelection = require('getEntityKeyForSelection');
const isEventHandled = require('isEventHandled');
const isSelectionAtLeafStart = require('isSelectionAtLeafStart');
const isSelectionAtBlockEndWithNewLine = require('isSelectionAtBlockEndWithNewLine');
const nullthrows = require('nullthrows');
const setImmediate = require('setImmediate');

Expand Down Expand Up @@ -162,6 +163,16 @@ function editOnBeforeInput(
editor._latestCommittedEditorState,
);
}

if (!mustPreventNative) {
// When there is \n at the end of the block, there is one extra \n added in DraftEditorLeaf for the content to render properly in browsers
// editOnInput takes care of it, but we must prevent the new char to land natively between the two
// as in that case the check in editOnInput wouldn't detect the situation properly
mustPreventNative = isSelectionAtBlockEndWithNewLine(
editor._latestCommittedEditorState,
);
}

if (!mustPreventNative) {
// Let's say we have a decorator that highlights hashtags. In many cases
// we need to prevent native behavior and rerender ourselves --
Expand Down
25 changes: 25 additions & 0 deletions src/component/selection/isSelectionAtBlockEndWithNewLine.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+draft_js
* @flow strict-local
* @format
*/
'use strict';

import type EditorState from 'EditorState';

function isSelectionAtBlockEndWithNewLine(editorState: EditorState): boolean {
const selection = editorState.getSelection();
const anchorKey = selection.getAnchorKey();
const offset = selection.getStartOffset();

const block = editorState.getCurrentContent().getBlockForKey(anchorKey);

return block.getLength() === offset && block.getText()[offset - 1] === '\n';
}

module.exports = isSelectionAtBlockEndWithNewLine;