Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retain active format for empty lines #1

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Changes from 3 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
52 changes: 52 additions & 0 deletions blots/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,21 @@ import {
import Break from './break';
import Inline from './inline';
import TextBlot from './text';
import Cursor from './cursor';

const NEWLINE_LENGTH = 1;
const TEXT_FORMAT_NODES = [
'SPAN',
'STRONG',
'B',
'EM',
'I',
'SUB',
'SUP',
'S',
'STRIKE',
'U',
];

class Block extends BlockBlot {
constructor(scroll, domNode) {
Expand Down Expand Up @@ -110,6 +123,25 @@ class Block extends BlockBlot {
split(index, force = false) {
if (force && (index === 0 || index >= this.length() - NEWLINE_LENGTH)) {
const clone = this.clone();
/**
* This part was added to retain the active format for the empty lines.
*/
if (
this.domNode.tagName === 'P' &&
this.children &&
this.children.head &&
this.children.head.domNode.nodeType === Node.ELEMENT_NODE
) {
const node = this.children.head.domNode.cloneNode(true);
this.retainFormats(node);
const cursor = node.querySelector(`.${Cursor.className}`);
if (cursor) {
const br = document.createElement('br');
cursor.parentNode.replaceChild(br, cursor);
const formatBlot = this.scroll.create(node);
clone.insertBefore(formatBlot, null);
}
}
if (index === 0) {
this.parent.insertBefore(clone, this);
return this;
Expand All @@ -121,6 +153,26 @@ class Block extends BlockBlot {
this.cache = {};
return next;
}

/**
* Retains the style nodes specified in TEXT_FORMAT_NODES
* and removes all other nodes for the given element
*/
retainFormats(element) {
const nodes = element.childNodes;
for (let i = 0; i < nodes.length; i += 1) {
const node = nodes[i];
if (
node.nodeType === Node.TEXT_NODE &&
!TEXT_FORMAT_NODES.includes(node.nodeName)
) {
node.parentNode.removeChild(node);
i -= 1;
} else if (node.nodeType === Node.ELEMENT_NODE) {
this.retainFormats(node);
}
}
}
}
Block.blotName = 'block';
Block.tagName = 'P';
Expand Down