diff --git a/docs/docs/api-reference/enriched-text-input.md b/docs/docs/api-reference/enriched-text-input.md index a2802ab41..f7109ef10 100644 --- a/docs/docs/api-reference/enriched-text-input.md +++ b/docs/docs/api-reference/enriched-text-input.md @@ -814,6 +814,9 @@ If `true`, external HTML pasted or inserted into the input (for example from Google Docs, Word, or web pages) is normalized into the canonical tag subset that the enriched parser understands. See [Normalization](/fundamentals/core-concepts#normalization). +If `false`, only the editor's own HTML (wrapped in ``) is parsed; any +other value is inserted as plain text, and pasted external HTML is replaced +with the clipboard's plain text. | Type | Default | Platforms | | --------- | ------- | ----------------- | diff --git a/docs/docs/api-reference/enriched-text.md b/docs/docs/api-reference/enriched-text.md index 7f03c96b1..66d0e3508 100644 --- a/docs/docs/api-reference/enriched-text.md +++ b/docs/docs/api-reference/enriched-text.md @@ -90,6 +90,8 @@ If `true`, external HTML (for example from Google Docs, Word, or web pages) is normalized before rendering. This converts arbitrary HTML into the canonical tag subset that the enriched parser understands. See [Normalization](/fundamentals/core-concepts#normalization). +If `false`, only the editor's own HTML (wrapped in ``) is parsed and any +other value is shown as plain text. | Type | Default | Platforms | | --------- | ------- | ----------------- | diff --git a/ios/EnrichedTextInputView.mm b/ios/EnrichedTextInputView.mm index b38d56f54..045012fd5 100644 --- a/ios/EnrichedTextInputView.mm +++ b/ios/EnrichedTextInputView.mm @@ -2275,7 +2275,9 @@ - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { parseToHtmlFromRange:NSMakeRange(0, textView.textStorage.string.length) host:self]; NSString *initiallyProcessedHtml = [parser initiallyProcessHtml:currentHtml]; - [parser replaceWholeFromHtml:initiallyProcessedHtml]; + if (initiallyProcessedHtml != nullptr) { + [parser replaceWholeFromHtml:initiallyProcessedHtml]; + } textView.selectedRange = prevSelectedRange; [self anyTextMayHaveBeenModified]; diff --git a/ios/htmlParser/HtmlParser.mm b/ios/htmlParser/HtmlParser.mm index 5a3e7e637..7562d9c5e 100644 --- a/ios/htmlParser/HtmlParser.mm +++ b/ios/htmlParser/HtmlParser.mm @@ -232,35 +232,12 @@ + (NSString *_Nullable)initiallyProcessHtml:(NSString *_Nonnull)html [htmlWithoutSpaces hasSuffix:@""]; if (isWrapped) { - // remove html tags, might be with newlines or without them + // Editor's own HTML: remove the html tags; their surrounding newlines were + // already stripped. Body tags are removed too. fixedHtml = [htmlWithoutSpaces copy]; - // firstly remove newlined html tags if any: - fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"\n" - withString:@""]; - fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"\n" - withString:@""]; - // fallback; remove html tags without their newlines - fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"" - withString:@""]; - fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"" - withString:@""]; - - // Additionally, try getting the content from between body tags if there - // are some: - - // Firstly make sure there are no newlines between them. - fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"
\n" - withString:@""]; - fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"\n" - withString:@""]; - // Then, if there actually are body tags, use the content between them. - NSRange openingBodyRange = [htmlWithoutSpaces rangeOfString:@""]; - NSRange closingBodyRange = [htmlWithoutSpaces rangeOfString:@""]; - if (openingBodyRange.length != 0 && closingBodyRange.length != 0) { - NSInteger newStart = openingBodyRange.location + 6; - NSInteger newEnd = closingBodyRange.location - 1; - fixedHtml = [htmlWithoutSpaces - substringWithRange:NSMakeRange(newStart, newEnd - newStart + 1)]; + for (NSString *tag in @[ @"", @"", @"", @"" ]) { + fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:tag + withString:@""]; } } else if (useHtmlNormalizer) { // External HTML (from Google Docs, Word, web pages, etc.) diff --git a/ios/inputHtmlParser/InputHtmlParser.mm b/ios/inputHtmlParser/InputHtmlParser.mm index 18011cd92..e3deda174 100644 --- a/ios/inputHtmlParser/InputHtmlParser.mm +++ b/ios/inputHtmlParser/InputHtmlParser.mm @@ -227,8 +227,16 @@ - (void)applyProcessedAlignments:(NSArraya
', true], + ['\na
\n', true], + ['a
', false], + ['a
', false], +])('isInternalHtml(%j) is %s', (html, expected) => { + expect(isInternalHtml(html)).toBe(expected); +}); + +test.each([ + ['', ''], + ['a\nb', 'a
b
'], + ['a\r\n\r\nb', 'a
b
'], + [' x & y', '<b>x</b> & y
'], +])('plainTextToHtml(%j) is %j', (text, expected) => { + expect(plainTextToHtml(text)).toBe(expected); +}); + +describe('prepareIncomingHtml', () => { + test.each([true, false])( + 'uses the editor HTML as is (useHtmlNormalizer=%s)', + (useHtmlNormalizer) => { + expect( + prepareIncomingHtml('a
', useHtmlNormalizer) + ).toBe('a
'); + expect(normalizeSpy).not.toHaveBeenCalled(); + } + ); + + test('normalizes other HTML with the normalizer on', () => { + expect(prepareIncomingHtml('a', true)).toBe('a'); + }); + + test('shows other HTML as plain text with the normalizer off', () => { + expect(prepareIncomingHtml('a', false)).toBe( + '<b>a</b>
' + ); + }); +}); + +describe('preparePastedHtmlForTiptap', () => { + test('normalizes -wrapped clipboard HTML', () => { + preparePastedHtmlForTiptap( + 'a', + true + ); + expect(normalizeSpy).toHaveBeenCalledTimes(1); + }); + + test('keeps clipboard HTML as HTML with the normalizer off', () => { + expect(preparePastedHtmlForTiptap('a', false)).toBe('a'); + }); +}); + +describe('prepareHtmlForWeb', () => { + test('drops layout whitespace of pretty-printed editor HTML', () => { + const html = + '\na b
\n\n\n'; + expect(prepareHtmlForWeb(html, true)).toBe( + 'q
\n
a b
x
' + ); + }); + + test('keeps whitespace in normalized HTML', () => { + expect(prepareHtmlForWeb('a b', true)).toBe( + 'a b' + ); + }); +}); diff --git a/src/web/__tests__/pasteExternalHtmlAsText.test.ts b/src/web/__tests__/pasteExternalHtmlAsText.test.ts new file mode 100644 index 000000000..97a10f3da --- /dev/null +++ b/src/web/__tests__/pasteExternalHtmlAsText.test.ts @@ -0,0 +1,52 @@ +import type { EditorView } from '@tiptap/pm/view'; +import { handlePasteExternalHtmlAsText } from '../utils/pasteExternalHtmlAsText'; + +function paste( + clipboard: Recordq
a
' }, + false, + ], + ])( + 'leaves the paste to the editor when %s', + (_, clipboard, useHtmlNormalizer) => { + expect(paste(clipboard, useHtmlNormalizer).handled).toBe(false); + } + ); +}); diff --git a/src/web/normalization/incomingHtml.ts b/src/web/normalization/incomingHtml.ts new file mode 100644 index 000000000..51c7c523d --- /dev/null +++ b/src/web/normalization/incomingHtml.ts @@ -0,0 +1,45 @@ +import type { SanitizationConfig } from '../../types'; +import { sanitizeHtml } from '../sanitization/htmlSanitizer'; +import { normalizeHtml } from './htmlNormalizer'; + +/** + * The editor's own HTML is wrapped in ...; surrounding whitespace + * is ignored. + */ +export function isInternalHtml(html: string): boolean { + const trimmed = html.trim(); + return trimmed.startsWith('') && trimmed.endsWith(''); +} + +/** + * Turns a value (defaultValue, setValue, children) into canonical HTML: + * - the editor's own HTML is used as is, + * - other HTML is normalized when the normalizer is on, + * - otherwise the value is shown as plain text. + */ +export function prepareIncomingHtml( + html: string, + useHtmlNormalizer: boolean | undefined, + sanitizationConfig?: SanitizationConfig +): string { + // Checked before sanitization, which drops the wrapper. + if (isInternalHtml(html)) return sanitizeHtml(html, sanitizationConfig); + if (!useHtmlNormalizer) return plainTextToHtml(html); + return normalizeHtml(sanitizeHtml(html, sanitizationConfig)); +} + +/** A paragraph per line, an empty line as${escapeHtml(line)}
`)) + .join(''); +} + +function escapeHtml(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>'); +} diff --git a/src/web/normalization/prepareHtmlForWeb.ts b/src/web/normalization/prepareHtmlForWeb.ts index 29ad25f30..6eabc5c87 100644 --- a/src/web/normalization/prepareHtmlForWeb.ts +++ b/src/web/normalization/prepareHtmlForWeb.ts @@ -1,17 +1,21 @@ -import { normalizeHtml } from './htmlNormalizer'; +import type { SanitizationConfig } from '../../types'; +import { isInternalHtml, prepareIncomingHtml } from './incomingHtml'; import { withBaseFontFamilyFallback } from '../styleConversion/enrichedStyleToCSSVariables'; export function prepareHtmlForWeb( html: string, - useHtmlNormalizer: boolean | undefined + useHtmlNormalizer: boolean | undefined, + sanitizationConfig?: SanitizationConfig ): string { - if (useHtmlNormalizer) { - html = normalizeHtml(html); - } + const isInternal = isInternalHtml(html); + html = prepareIncomingHtml(html, useHtmlNormalizer, sanitizationConfig); const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); + if (isInternal) { + removeLayoutWhitespace(doc.body); + } wrapBareLiContentInParagraph(doc); checkboxHtmlToWeb(doc); addFontFamilyFallback(doc); @@ -19,6 +23,24 @@ export function prepareHtmlForWeb( return doc.body.innerHTML; } +/* + * The editor's HTML can be pretty-printed. That whitespace would render as empty + * lines, so drop whitespace-only text outside of text tags. + */ +function removeLayoutWhitespace(body: HTMLElement) { + const containers = [ + body, + ...body.querySelectorAll('ul, ol, blockquote, codeblock'), + ]; + for (const container of containers) { + for (const node of Array.from(container.childNodes)) { + if (node.nodeType === Node.TEXT_NODE && !node.textContent?.trim()) { + node.remove(); + } + } + } +} + /* * Native list format: *