From 125bc3c31d983611ad28f350c889bd2783f44830 Mon Sep 17 00:00:00 2001
From: Zihua Li
Date: Thu, 30 Apr 2020 08:52:45 +0800
Subject: [PATCH] Fix length mismatch when copying code (#3028)
---
formats/code.js | 12 +++++++++---
modules/syntax.js | 12 ++++++++++++
test/unit/core/editor.js | 16 +++++++++++++---
test/unit/modules/syntax.js | 8 ++++++++
4 files changed, 42 insertions(+), 6 deletions(-)
diff --git a/formats/code.js b/formats/code.js
index 25719b4f2f..edb653eca2 100644
--- a/formats/code.js
+++ b/formats/code.js
@@ -13,12 +13,18 @@ class CodeBlockContainer extends Container {
return domNode;
}
- html(index, length) {
+ code(index, length) {
const text = this.children
- .map(child => child.domNode.innerText)
+ .map(child => (child.length() <= 1 ? '' : child.domNode.innerText))
.join('\n')
.slice(index, index + length);
- return `${escapeText(text)}
`;
+ return escapeText(text);
+ }
+
+ html(index, length) {
+ // `\n`s are needed in order to support empty lines at the beginning and the end.
+ // https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
+ return `\n${this.code(index, length)}\n
`;
}
}
diff --git a/modules/syntax.js b/modules/syntax.js
index f62882bdcf..70e135423a 100644
--- a/modules/syntax.js
+++ b/modules/syntax.js
@@ -135,6 +135,18 @@ class SyntaxCodeBlockContainer extends CodeBlockContainer {
}
}
+ html(index, length) {
+ const [codeBlock] = this.children.find(index);
+ const language = codeBlock
+ ? SyntaxCodeBlock.formats(codeBlock.domNode)
+ : 'plain';
+
+ return `\n${this.code(
+ index,
+ length,
+ )}\n
`;
+ }
+
optimize(context) {
super.optimize(context);
if (
diff --git a/test/unit/core/editor.js b/test/unit/core/editor.js
index 2f2f099e35..5224624d5f 100644
--- a/test/unit/core/editor.js
+++ b/test/unit/core/editor.js
@@ -727,9 +727,19 @@ describe('Editor', function() {
});
it('multiline code', function() {
- const editor = this.initialize(Editor, '
0123
4567
'); - editor.formatLine(0, 9, { 'code-block': 'javascript' }); - expect(editor.getHTML(0, 9)).toEqual('0123\n4567'); + const editor = this.initialize( + Editor, + '
0123
4567
\n\n0123\n\n\n4567\n\n', + ); + expect(editor.getHTML(1, 7)).toEqual('
\n0123\n\n\n\n'); + expect(editor.getHTML(2, 7)).toEqual('
\n123\n\n\n4\n'); + expect(editor.getHTML(5, 7)).toEqual('
\n\n\n\n4567\n'); }); }); }); diff --git a/test/unit/modules/syntax.js b/test/unit/modules/syntax.js index 89420ae2f9..828e955989 100644 --- a/test/unit/modules/syntax.js +++ b/test/unit/modules/syntax.js @@ -294,4 +294,12 @@ describe('Syntax', function() { }); }); }); + + describe('html', function() { + it('code language', function() { + expect(this.quill.getSemanticHTML()).toContain( + 'data-language="javascript"', + ); + }); + }); });