Skip to content

Commit

Permalink
HTML codec : <hr> & <img> special treatment (#346)
Browse files Browse the repository at this point in the history
  • Loading branch information
amantoux authored May 9, 2024
1 parent eb7b3ca commit 6a9fcd2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/parchment/lib/src/codecs/html.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class ParchmentHtmlCodec extends Codec<ParchmentDocument, String> {
// Mutable record for the state of the encoder
class _EncoderState {
StringBuffer buffer = StringBuffer();

// Stack on inline tags
final List<_HtmlInlineTag> openInlineTags = [];

Expand Down Expand Up @@ -887,12 +888,22 @@ class _ParchmentHtmlDecoder extends Converter<String, ParchmentDocument> {
}
if (node is html.Element) {
if (node.localName == 'hr') {
// <hr> is a block element and cannot be enclosed in <p>
delta.insert(BlockEmbed.horizontalRule.toJson());
delta.insert('\n');
return delta;
}
if (node.localName == 'img') {
final src = node.attributes['src'] ?? '';
delta.insert(BlockEmbed.image(src).toJson());
// <img> can be enclosed in a <p> element, but
// we only want to support <p> with only one node (<img>)
if (node.parent is html.Element &&
node.parent!.localName == 'p' &&
node.parent!.children.length == 1) {
return delta;
}
delta.insert('\n');
return delta;
}
inlineStyle = _updateInlineStyle(node, inlineStyle);
Expand Down
13 changes: 13 additions & 0 deletions packages/parchment/test/codecs/html_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1702,6 +1702,19 @@ void main() {
});

group('Embeds', () {
test('Block embeds special treatment', () {
String html = '<p><hr><p><img src="http://fake.link/image.png"></p>'
'<img src="http://another.fake.link/image.png"></p><p>a</p>';
final doc = ParchmentDocument.fromJson([
{'insert': '\n'}
]);
doc.insert(0, 'a');
doc.insert(0, BlockEmbed.image('http://another.fake.link/image.png'));
doc.insert(0, BlockEmbed.image('http://fake.link/image.png'));
doc.insert(0, BlockEmbed.horizontalRule);
expect(codec.decode(html).toDelta(), doc.toDelta());
});

test('Image', () {
final html = '<img src="http://fake.link/image.png">';
final doc = ParchmentDocument.fromJson([
Expand Down

0 comments on commit 6a9fcd2

Please sign in to comment.