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:(NSArray *)alignments } - (NSString *_Nullable)initiallyProcessHtml:(NSString *_Nonnull)html { - return [HtmlParser initiallyProcessHtml:html - useHtmlNormalizer:_input->useHtmlNormalizer]; + @try { + return [HtmlParser initiallyProcessHtml:html + useHtmlNormalizer:_input->useHtmlNormalizer]; + } @catch (NSException *exception) { + // nil makes the callers fall back to inserting the raw input as plain text + RCTLogWarn(@"[EnrichedTextInput]: Failed to process HTML: (%@), falling " + @"back to raw input.", + exception.reason); + return nil; + } } @end diff --git a/src/web/EnrichedText.tsx b/src/web/EnrichedText.tsx index cb864a52d..17aa9d7f9 100644 --- a/src/web/EnrichedText.tsx +++ b/src/web/EnrichedText.tsx @@ -18,7 +18,6 @@ import { } from './constants/classNames'; import { enrichedTextThemingToCSSProperties } from './styleConversion/enrichedThemingToCSSProperties'; import { buildMentionRulesCSS } from './styleConversion/buildMentionRulesCSS'; -import { sanitizeHtml } from './sanitization/htmlSanitizer'; import { prepareHtmlForWeb } from './normalization/prepareHtmlForWeb'; import { INLINE_IMAGE_CSS_VARIABLES } from './styleConversion/inlineImageCSSVariables'; import { useImageErrorFallback } from './htmlExtensions/useImageErrorFallback'; @@ -66,14 +65,9 @@ export const EnrichedText = memo( }, })); - const sanitizedHtml = useMemo( - () => sanitizeHtml(children, sanitizationConfig), - [children, sanitizationConfig] - ); - const finalHtml = useMemo( - () => prepareHtmlForWeb(sanitizedHtml, useHtmlNormalizer), - [sanitizedHtml, useHtmlNormalizer] + () => prepareHtmlForWeb(children, useHtmlNormalizer, sanitizationConfig), + [children, useHtmlNormalizer, sanitizationConfig] ); const [clampedHtml, setClampedHtml] = useState( diff --git a/src/web/EnrichedTextInput.tsx b/src/web/EnrichedTextInput.tsx index 2938cecb0..0c367f8f7 100644 --- a/src/web/EnrichedTextInput.tsx +++ b/src/web/EnrichedTextInput.tsx @@ -31,6 +31,7 @@ import { useOnLinkDetected } from './tiptapWatchers/useOnLinkDetected'; import type { LinkEmitterState } from './tiptapWatchers/emitLinkDetected'; import { prepareHtmlForTiptap, + preparePastedHtmlForTiptap, normalizeHtmlFromTiptap, } from './normalization/tiptapHtmlNormalizer'; import { ENRICHED_TEXT_INPUT_DEFAULT_PROPS } from '../utils/EnrichedTextInputDefaultProps'; @@ -66,6 +67,7 @@ import { MergeAdjacentSameKindBlocksPlugin } from './pmPlugins/MergeAdjacentSame import { OrderedListMarkerWidthPlugin } from './pmPlugins/OrderedListMarkerWidthPlugin'; import { StripMarksInCodeBlockPlugin } from './pmPlugins/StripMarksInCodeBlockPlugin'; import { handleClipboardPasteImages } from './utils/pasteImages'; +import { handlePasteExternalHtmlAsText } from './utils/pasteExternalHtmlAsText'; import { MentionPlugin, setMention, @@ -311,18 +313,23 @@ export const EnrichedTextInput = ({ }, mousedown: (_view, event) => handleLinkMouseDown(event), }, - handlePaste: (_view, event) => + handlePaste: (view, event) => handleClipboardPasteImages( event, () => editorInstanceRef.current, () => onPasteImagesRef.current + ) || + handlePasteExternalHtmlAsText( + view, + event, + useHtmlNormalizerRef.current ), attributes: { autoCapitalize, enterkeyhint: returnKeyTypeToEnterKeyHint(returnKeyType), }, transformPastedHTML: (html) => { - return prepareHtmlForTiptap( + return preparePastedHtmlForTiptap( html, useHtmlNormalizerRef.current, sanitizationConfigRef.current diff --git a/src/web/__tests__/incomingHtml.test.ts b/src/web/__tests__/incomingHtml.test.ts new file mode 100644 index 000000000..936809e49 --- /dev/null +++ b/src/web/__tests__/incomingHtml.test.ts @@ -0,0 +1,90 @@ +import * as htmlNormalizer from '../normalization/htmlNormalizer'; +import { + isInternalHtml, + plainTextToHtml, + prepareIncomingHtml, +} from '../normalization/incomingHtml'; +import { preparePastedHtmlForTiptap } from '../normalization/tiptapHtmlNormalizer'; +import { prepareHtmlForWeb } from '../normalization/prepareHtmlForWeb'; + +let normalizeSpy: jest.SpyInstance; + +beforeEach(() => { + normalizeSpy = jest.spyOn(htmlNormalizer, 'normalizeHtml'); +}); + +afterEach(() => { + normalizeSpy.mockRestore(); +}); + +test.each([ + ['

a

', true], + ['\n

a

\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 = + '\n

a b

\n
\n\n' + + '
\n

q

\n
\n'; + expect(prepareHtmlForWeb(html, true)).toBe( + '

a b


' + + '

q

' + ); + }); + + 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: Record, + useHtmlNormalizer: boolean +): { handled: boolean; pasteText: jest.Mock } { + const pasteText = jest.fn(); + const view = { pasteText } as unknown as EditorView; + const event = { + clipboardData: { getData: (type: string) => clipboard[type] ?? '' }, + } as unknown as ClipboardEvent; + const handled = handlePasteExternalHtmlAsText(view, event, useHtmlNormalizer); + return { handled, pasteText }; +} + +describe('handlePasteExternalHtmlAsText', () => { + test('pastes external HTML as plain text with the normalizer off', () => { + const { handled, pasteText } = paste( + { 'text/html': 'a', 'text/plain': 'a' }, + false + ); + expect(handled).toBe(true); + expect(pasteText).toHaveBeenCalledWith('a'); + }); + + test('pastes nothing when there is no plain text', () => { + const { handled, pasteText } = paste({ 'text/html': 'a' }, false); + expect(handled).toBe(true); + expect(pasteText).not.toHaveBeenCalled(); + }); + + test.each([ + ['the normalizer is on', { 'text/html': 'a' }, true], + ['there is no HTML', { 'text/plain': 'a' }, false], + [ + 'the HTML is the editor HTML', + { 'text/html': 'a' }, + false, + ], + [ + 'the HTML is from a TipTap editor', + { 'text/html': '

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
, and any tags as literal text. */ +export function plainTextToHtml(text: string): string { + if (text === '') return ''; + return text + .split(/\r\n?|\n/) + .map((line) => (line === '' ? '
' : `

${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: *
    diff --git a/src/web/normalization/tiptapHtmlNormalizer.ts b/src/web/normalization/tiptapHtmlNormalizer.ts index 27745d1ef..e2fa2af81 100644 --- a/src/web/normalization/tiptapHtmlNormalizer.ts +++ b/src/web/normalization/tiptapHtmlNormalizer.ts @@ -6,19 +6,35 @@ import { } from './checkboxHtmlNormalizer'; import { normalizeColorToHex } from './colorNormalizer'; import { normalizeHtml } from './htmlNormalizer'; +import { prepareIncomingHtml } from './incomingHtml'; export function prepareHtmlForTiptap( html: string, useHtmlNormalizer: boolean | undefined, sanitizationConfig?: SanitizationConfig +): string { + return toTiptapFormat( + prepareIncomingHtml(html, useHtmlNormalizer, sanitizationConfig) + ); +} + +/** + * Clipboard HTML is treated as external even when -wrapped (Windows Chromium provides such format), + * so with the normalizer on, the editor's own copied HTML gets a harmless extra normalizer pass too. + * The plain-text fallback with the normalizer off is done in `handlePaste`. + */ +export function preparePastedHtmlForTiptap( + html: string, + useHtmlNormalizer: boolean | undefined, + sanitizationConfig?: SanitizationConfig ): string { html = sanitizeHtml(html, sanitizationConfig); - if (useHtmlNormalizer) { - html = normalizeHtml(html); - } + return toTiptapFormat(useHtmlNormalizer ? normalizeHtml(html) : html); +} + +function toTiptapFormat(html: string): string { html = checkboxHtmlForTiptap(html); - html = html.replace(//gi, '

    '); - return html; + return html.replace(//gi, '

    '); } export function normalizeHtmlFromTiptap( diff --git a/src/web/utils/pasteExternalHtmlAsText.ts b/src/web/utils/pasteExternalHtmlAsText.ts new file mode 100644 index 000000000..0ceabd87c --- /dev/null +++ b/src/web/utils/pasteExternalHtmlAsText.ts @@ -0,0 +1,29 @@ +import type { EditorView } from '@tiptap/pm/view'; +import { isInternalHtml } from '../normalization/incomingHtml'; + +/** + * With the normalizer off, pastes HTML that isn't the editor's own as plain text + * (or nothing, if there is none). Our own HTML is recognised by the same + * wrapper check, or `data-pm-slice`, because HTML copied from a TipTap editor has no + * wrapper. + */ +export function handlePasteExternalHtmlAsText( + view: EditorView, + event: ClipboardEvent, + useHtmlNormalizer: boolean | undefined +): boolean { + const html = event.clipboardData?.getData('text/html'); + if ( + useHtmlNormalizer || + !html || + isInternalHtml(html) || + html.includes('data-pm-slice') + ) { + return false; + } + + const text = event.clipboardData?.getData('text/plain'); + // No event is passed on, so this handler doesn't run again for this paste. + if (text) view.pasteText(text); + return true; +}