convert method
Converts an HTML string into Delta operations.
Converts the HTML string htmlText
into Delta operations using QuillJS-compatible attributes.
Custom blocks can be applied based on registered customBlocks.
Parameters:
htmlText
: The HTML string to convert into Delta operations.
Returns: A Delta object representing the formatted content from HTML.
Example:
final delta = converter.convert('<p>Hello <strong>world</strong></p>');
print(delta.toJson()); // Output: [{"insert":"Hello "},{"insert":"world","attributes":{"bold":true}},{"insert":"\n"}]
Implementation
Delta convert(String htmlText) {
final Delta delta = Delta();
final dom.Document $document = dparser.parse(
replaceNormalNewLinesToBr ? htmlText.replaceAll('\n', '<br>') : htmlText,
);
final dom.Element? $body = $document.body;
final dom.Element? $html = $document.documentElement;
// Determine nodes to process: <body>, <html>, or document nodes if neither is present
final List<dom.Node> nodesToProcess =
$body?.nodes ?? $html?.nodes ?? $document.nodes;
for (var node in nodesToProcess) {
//first just verify if the customBlocks aren't empty and then store on them to
//validate if one of them make match with the current Node
if (customBlocks != null &&
customBlocks!.isNotEmpty &&
node is dom.Element) {
for (var customBlock in customBlocks!) {
if (customBlock.matches(node)) {
final operations = customBlock.convert(node);
operations.forEach((Operation op) {
delta.insert(op.data, op.attributes);
});
continue;
}
}
}
final List<Operation> operations = nodeToOperation(node, htmlToOp);
if (operations.isNotEmpty) {
for (final op in operations) {
delta.insert(op.data, op.attributes);
}
}
}
//ensure insert a new line at the final to avoid any conflict with assertions
final lastOpdata = delta.last;
final bool lastDataIsNotNewLine = lastOpdata.data.toString() != '\n';
final bool hasAttributes = lastOpdata.attributes != null;
if (lastDataIsNotNewLine && hasAttributes ||
lastDataIsNotNewLine ||
!lastDataIsNotNewLine && hasAttributes) {
delta.insert('\n');
}
return delta;
}