fix(editor): should preserve format in <p> when importing html (#12275)

Closes: [BS-3485](https://linear.app/affine-design/issue/BS-3485/粘贴-html-格式的内容时,紧邻着-bold-text-的普通文本会丢失空格)

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **Bug Fixes**
  - Improved handling of spaces and whitespace in paragraphs when converting HTML with inline formatting, ensuring spaces are preserved as in the original content.

- **Tests**
  - Added a new test to verify that spaces are correctly preserved in paragraphs containing bold and italic formatting during HTML conversion.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
donteatfriedrice
2025-05-15 00:50:10 +00:00
parent 278aa8f7a0
commit d56d46d8d6
2 changed files with 82 additions and 1 deletions
@@ -5,6 +5,24 @@ import {
import { collapseWhiteSpace } from 'collapse-white-space';
import type { Element } from 'hast';
/**
* Handle empty text nodes created by HTML parser for styling purposes.
* These nodes typically contain only whitespace/newlines, for example:
* ```json
* {
* "type": "text",
* "value": "\n\n \n \n "
* }
* ```
* We collapse and trim the whitespace to check if the node is truly empty,
* and return an empty array in that case.
*/
const isEmptyText = (ast: HtmlAST): boolean => {
return (
ast.type === 'text' && collapseWhiteSpace(ast.value, { trim: true }) === ''
);
};
const isElement = (ast: HtmlAST): ast is Element => {
return ast.type === 'element';
};
@@ -22,12 +40,16 @@ export const htmlTextToDeltaMatcher = HtmlASTToDeltaExtension({
return [];
}
const { options } = context;
options.trim ??= true;
options.trim ??= false;
if (options.pre) {
return [{ insert: ast.value }];
}
if (isEmptyText(ast)) {
return [];
}
const value = options.trim
? collapseWhiteSpace(ast.value, { trim: options.trim })
: collapseWhiteSpace(ast.value);