Skip to content

Commit

Permalink
Fix length mismatch when copying code (slab#3028)
Browse files Browse the repository at this point in the history
  • Loading branch information
luin committed Apr 30, 2020
1 parent 676816a commit 125bc3c
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 6 deletions.
12 changes: 9 additions & 3 deletions formats/code.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<pre>${escapeText(text)}</pre>`;
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 `<pre>\n${this.code(index, length)}\n</pre>`;
}
}

Expand Down
12 changes: 12 additions & 0 deletions modules/syntax.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<pre data-language="${language}">\n${this.code(
index,
length,
)}\n</pre>`;
}

optimize(context) {
super.optimize(context);
if (
Expand Down
16 changes: 13 additions & 3 deletions test/unit/core/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -727,9 +727,19 @@ describe('Editor', function() {
});

it('multiline code', function() {
const editor = this.initialize(Editor, '<p>0123</p><p>4567</p>');
editor.formatLine(0, 9, { 'code-block': 'javascript' });
expect(editor.getHTML(0, 9)).toEqual('<pre>0123\n4567</pre>');
const editor = this.initialize(
Editor,
'<p><br></p><p>0123</p><p><br></p><p><br></p><p>4567</p><p><br></p>',
);
const length = editor.scroll.length();
editor.formatLine(0, length, { 'code-block': 'javascript' });

expect(editor.getHTML(0, length)).toEqual(
'<pre>\n\n0123\n\n\n4567\n\n</pre>',
);
expect(editor.getHTML(1, 7)).toEqual('<pre>\n0123\n\n\n\n</pre>');
expect(editor.getHTML(2, 7)).toEqual('<pre>\n123\n\n\n4\n</pre>');
expect(editor.getHTML(5, 7)).toEqual('<pre>\n\n\n\n4567\n</pre>');
});
});
});
8 changes: 8 additions & 0 deletions test/unit/modules/syntax.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,4 +294,12 @@ describe('Syntax', function() {
});
});
});

describe('html', function() {
it('code language', function() {
expect(this.quill.getSemanticHTML()).toContain(
'data-language="javascript"',
);
});
});
});

0 comments on commit 125bc3c

Please sign in to comment.