diff --git a/android/src/main/java/com/swmansion/enriched/common/GumboNormalizer.kt b/android/src/main/java/com/swmansion/enriched/common/GumboNormalizer.kt index 7f6ae0944..5ea5e4060 100644 --- a/android/src/main/java/com/swmansion/enriched/common/GumboNormalizer.kt +++ b/android/src/main/java/com/swmansion/enriched/common/GumboNormalizer.kt @@ -1,5 +1,8 @@ package com.swmansion.enriched.common object GumboNormalizer { - external fun normalizeHtml(html: String): String? + external fun normalizeHtml( + html: String, + ignoredStylesMask: Int, + ): String? } diff --git a/android/src/main/java/com/swmansion/enriched/text/EnrichedTextView.kt b/android/src/main/java/com/swmansion/enriched/text/EnrichedTextView.kt index 3b92a2d08..cc32ef532 100644 --- a/android/src/main/java/com/swmansion/enriched/text/EnrichedTextView.kt +++ b/android/src/main/java/com/swmansion/enriched/text/EnrichedTextView.kt @@ -67,6 +67,14 @@ class EnrichedTextView : AppCompatTextView { var useHtmlNormalizer = false + var ignoredStylesMask = 0 + set(value) { + if (field == value) return + field = value + // re-parse the current text with the new set of styles + valueDirty = true + } + constructor(context: Context) : super(context) { prepareComponent() } @@ -227,7 +235,7 @@ class EnrichedTextView : AppCompatTextView { text: String, style: EnrichedTextStyle, ): CharSequence? { - val normalized = GumboNormalizer.normalizeHtml(text) ?: return null + val normalized = GumboNormalizer.normalizeHtml(text, ignoredStylesMask) ?: return null return try { val parsed: Spanned = EnrichedParser.fromHtml(normalized, style, spannableFactory) diff --git a/android/src/main/java/com/swmansion/enriched/text/EnrichedTextViewManager.kt b/android/src/main/java/com/swmansion/enriched/text/EnrichedTextViewManager.kt index 5f487a90d..1587ad69f 100644 --- a/android/src/main/java/com/swmansion/enriched/text/EnrichedTextViewManager.kt +++ b/android/src/main/java/com/swmansion/enriched/text/EnrichedTextViewManager.kt @@ -144,6 +144,13 @@ class EnrichedTextViewManager : view?.useHtmlNormalizer = value } + override fun setIgnoredStylesMask( + view: EnrichedTextView?, + value: Int, + ) { + view?.ignoredStylesMask = value + } + override fun onAfterUpdateTransaction(view: EnrichedTextView) { view.afterUpdateTransaction() } diff --git a/android/src/main/java/com/swmansion/enriched/text/MeasurementStore.kt b/android/src/main/java/com/swmansion/enriched/text/MeasurementStore.kt index d032f8320..9eb7cdc58 100644 --- a/android/src/main/java/com/swmansion/enriched/text/MeasurementStore.kt +++ b/android/src/main/java/com/swmansion/enriched/text/MeasurementStore.kt @@ -116,7 +116,7 @@ object MeasurementStore { } try { - val textToParse = if (isInternalHtml) text else GumboNormalizer.normalizeHtml(text) + val textToParse = if (isInternalHtml) text else GumboNormalizer.normalizeHtml(text, ignoredStylesMaskFromProps(props)) val style = props?.getMap("htmlStyle") ?: return text val allowFontScaling = allowFontScalingFromProps(props) val enrichedStyle = EnrichedTextStyle.fromReadableMap(context as ReactContext, fontSize, style, allowFontScaling) @@ -137,6 +137,13 @@ object MeasurementStore { return props.getBoolean("useHtmlNormalizer") } + private fun ignoredStylesMaskFromProps(props: ReadableMap?): Int { + if (props == null || !props.hasKey("ignoredStylesMask") || props.isNull("ignoredStylesMask")) { + return 0 + } + return props.getInt("ignoredStylesMask") + } + private fun lineHeightFromProps(props: ReadableMap?): Float { if (props == null || !props.hasKey("lineHeight") || props.isNull("lineHeight")) { return 0f diff --git a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt index 7e7342731..fb95ab609 100644 --- a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt +++ b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt @@ -132,6 +132,9 @@ class EnrichedTextInputView : var experimentalSynchronousEvents: Boolean = false var useHtmlNormalizer: Boolean = false + // Only affects HTML parsed from now on, the current content is kept as it is + var ignoredStylesMask: Int = 0 + // Pair: (trigger, style) var textShortcuts: List> = emptyList() @@ -440,7 +443,7 @@ class EnrichedTextInputView : private fun normalizeHtmlIfNeeded(text: CharSequence): CharSequence { if (!useHtmlNormalizer) return text - val normalized = GumboNormalizer.normalizeHtml(text.toString()) ?: return text + val normalized = GumboNormalizer.normalizeHtml(text.toString(), ignoredStylesMask) ?: return text return try { val parsed = EnrichedParser.fromHtml(normalized, htmlStyle, spannableFactory, linkRegex) diff --git a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt index 9cf0293da..b57b46e0d 100644 --- a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt +++ b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputViewManager.kt @@ -331,6 +331,13 @@ class EnrichedTextInputViewManager : view?.useHtmlNormalizer = value } + override fun setIgnoredStylesMask( + view: EnrichedTextInputView?, + value: Int, + ) { + view?.ignoredStylesMask = value + } + override fun setTextShortcuts( view: EnrichedTextInputView?, value: ReadableArray?, diff --git a/android/src/main/new_arch/GumboNormalizerJni.cpp b/android/src/main/new_arch/GumboNormalizerJni.cpp index ef04c4b26..3debd732c 100644 --- a/android/src/main/new_arch/GumboNormalizerJni.cpp +++ b/android/src/main/new_arch/GumboNormalizerJni.cpp @@ -4,9 +4,10 @@ extern "C" JNIEXPORT jstring JNICALL Java_com_swmansion_enriched_common_GumboNormalizer_normalizeHtml( - JNIEnv *env, jclass /*cls*/, jstring htmlJString) { + JNIEnv *env, jclass /*cls*/, jstring htmlJString, jint ignoredStylesMask) { const char *htmlChars = env->GetStringUTFChars(htmlJString, nullptr); - std::string result = GumboParser::normalizeHtml(htmlChars); + std::string result = GumboParser::normalizeHtml( + htmlChars, static_cast(ignoredStylesMask)); env->ReleaseStringUTFChars(htmlJString, htmlChars); if (result.empty()) return nullptr; diff --git a/android/src/main/new_arch/react/renderer/components/ReactNativeEnrichedSpec/conversions.h b/android/src/main/new_arch/react/renderer/components/ReactNativeEnrichedSpec/conversions.h index 782e3895b..8be39bd32 100644 --- a/android/src/main/new_arch/react/renderer/components/ReactNativeEnrichedSpec/conversions.h +++ b/android/src/main/new_arch/react/renderer/components/ReactNativeEnrichedSpec/conversions.h @@ -39,6 +39,7 @@ inline folly::dynamic toDynamic(const EnrichedTextViewProps &props) { serializedProps["ellipsizeMode"] = props.ellipsizeMode; serializedProps["allowFontScaling"] = props.allowFontScaling; serializedProps["useHtmlNormalizer"] = props.useHtmlNormalizer; + serializedProps["ignoredStylesMask"] = props.ignoredStylesMask; serializedProps["htmlStyle"] = toDynamic(props.htmlStyle); return serializedProps; diff --git a/cpp/parser/GumboNormalizer.c b/cpp/parser/GumboNormalizer.c index f12a7266d..242562ec3 100644 --- a/cpp/parser/GumboNormalizer.c +++ b/cpp/parser/GumboNormalizer.c @@ -25,6 +25,8 @@ #pragma GCC diagnostic pop #endif +#include "IgnoredStyles.h" + #include #include #include @@ -1222,11 +1224,221 @@ static GumboNode *find_body(GumboNode *root) { return root; } +/* ------------------------------------------------------------------ */ +/* Ignored styles filtering (`ignoredStyles` prop) */ +/* ------------------------------------------------------------------ */ + +/* Runs as a second pass over the normalizer's own output, so it only has to + * understand the canonical tag subset. An ignored inline style, blockquote + * or codeblock is unwrapped (its content stays), an ignored heading or list + * item becomes a plain paragraph and an ignored image is dropped. */ + +static void append_escaped_text(buffer_t *out, const char *text) { + for (const char *c = text; *c; c++) { + switch (*c) { + case '<': + buffer_append_str(out, "<"); + break; + case '>': + buffer_append_str(out, ">"); + break; + case '&': + buffer_append_str(out, "&"); + break; + default: + buffer_append(out, c, 1); + break; + } + } +} + +static uint32_t style_flag_for_tag(const char *tag, GumboElement *el) { + if (strcmp(tag, "b") == 0) + return IGNORED_STYLE_BOLD; + if (strcmp(tag, "i") == 0) + return IGNORED_STYLE_ITALIC; + if (strcmp(tag, "u") == 0) + return IGNORED_STYLE_UNDERLINE; + if (strcmp(tag, "s") == 0) + return IGNORED_STYLE_STRIKETHROUGH; + if (strcmp(tag, "code") == 0) + return IGNORED_STYLE_INLINE_CODE; + if (strcmp(tag, "a") == 0) + return IGNORED_STYLE_LINK; + if (strcmp(tag, "mention") == 0) + return IGNORED_STYLE_MENTION; + if (strcmp(tag, "span") == 0) + return IGNORED_STYLE_CUSTOM_STYLE; + if (strcmp(tag, "img") == 0) + return IGNORED_STYLE_IMAGE; + if (strcmp(tag, "h1") == 0) + return IGNORED_STYLE_H1; + if (strcmp(tag, "h2") == 0) + return IGNORED_STYLE_H2; + if (strcmp(tag, "h3") == 0) + return IGNORED_STYLE_H3; + if (strcmp(tag, "h4") == 0) + return IGNORED_STYLE_H4; + if (strcmp(tag, "h5") == 0) + return IGNORED_STYLE_H5; + if (strcmp(tag, "h6") == 0) + return IGNORED_STYLE_H6; + if (strcmp(tag, "codeblock") == 0) + return IGNORED_STYLE_CODE_BLOCK; + if (strcmp(tag, "blockquote") == 0) + return IGNORED_STYLE_BLOCK_QUOTE; + if (strcmp(tag, "ol") == 0) + return IGNORED_STYLE_ORDERED_LIST; + if (strcmp(tag, "ul") == 0) + return is_checkbox_list(el) ? IGNORED_STYLE_CHECKBOX_LIST + : IGNORED_STYLE_UNORDERED_LIST; + return 0; +} + +static void filter_node(GumboNode *node, buffer_t *out, uint32_t ignored); + +static void filter_children(GumboNode *node, buffer_t *out, uint32_t ignored) { + if (!is_element(node)) + return; + GumboVector *children = &node->v.element.children; + for (unsigned int i = 0; i < children->length; i++) + filter_node(children->data[i], out, ignored); +} + +static void filter_emit_attributes(GumboElement *el, const char *tag, + buffer_t *out, uint32_t ignored) { + for (unsigned int i = 0; i < el->attributes.length; i++) { + GumboAttribute *attr = (GumboAttribute *)el->attributes.data[i]; + // on alignable tags, `style` only ever holds text-align + if ((ignored & IGNORED_STYLE_ALIGNMENT) && + strcmp(attr->name, "style") == 0 && is_alignable_tag(tag)) + continue; + buffer_append_str(out, " "); + buffer_append_str(out, attr->name); + if (strcmp(attr->name, "checked") == 0) + continue; + buffer_append_str(out, "=\""); + append_escaped_attr_value(out, attr->value, strlen(attr->value)); + buffer_append_str(out, "\""); + } +} + +/* Emits the node's content as a plain paragraph that keeps the text-align of + * align_el (the node itself, or the list a list item belongs to). */ +static void filter_emit_paragraph(GumboNode *node, GumboElement *align_el, + buffer_t *out, uint32_t ignored) { + buffer_t inner = buffer_create(64); + filter_children(node, &inner, ignored); + if (inner.len == 0) { + buffer_append_str(out, "
"); + } else { + buffer_append_str(out, ""); + buffer_append(out, inner.data, inner.len); + buffer_append_str(out, "

"); + } + free(inner.data); +} + +static void filter_node(GumboNode *node, buffer_t *out, uint32_t ignored) { + if (!node) + return; + if (is_text(node)) { + append_escaped_text(out, node->v.text.text); + return; + } + if (!is_element(node)) + return; + + GumboElement *el = &node->v.element; + char tag[64]; + if (!get_tag_name(node, tag, sizeof(tag))) { + filter_children(node, out, ignored); + return; + } + + uint32_t style = style_flag_for_tag(tag, el); + if (style & ignored) { + if (style == IGNORED_STYLE_IMAGE) + return; + + if (style & IGNORED_STYLE_HEADINGS) { + filter_emit_paragraph(node, el, out, ignored); + return; + } + + if (strcmp(tag, "ul") == 0 || strcmp(tag, "ol") == 0) { + GumboVector *items = &el->children; + for (unsigned int i = 0; i < items->length; i++) { + char item_tag[64]; + GumboNode *item = items->data[i]; + if (get_tag_name(item, item_tag, sizeof(item_tag)) && + strcmp(item_tag, "li") == 0) { + filter_emit_paragraph(item, el, out, ignored); + } else { + filter_node(item, out, ignored); + } + } + return; + } + + // inline styles, blockquotes and codeblocks (whose content is already + // made of paragraphs) are unwrapped + filter_children(node, out, ignored); + return; + } + + buffer_append_str(out, "<"); + buffer_append_str(out, tag); + filter_emit_attributes(el, tag, out, ignored); + if (strcmp(tag, "br") == 0) { + buffer_append_str(out, ">"); + return; + } + if (strcmp(tag, "img") == 0) { + buffer_append_str(out, " />"); + return; + } + buffer_append_str(out, ">"); + filter_children(node, out, ignored); + buffer_append_str(out, ""); +} + +static char *filter_ignored_styles(const char *normalized, uint32_t ignored) { + // An explicit keeps leading whitespace, which the HTML5 parser + // would otherwise drop before the body starts. + buffer_t source = buffer_create(strlen(normalized) + 7); + buffer_append_str(&source, ""); + buffer_append_str(&source, normalized); + + GumboOutput *output = + gumbo_parse_with_options(&kGumboDefaultOptions, source.data, source.len); + if (!output) { + free(source.data); + return NULL; + } + + GumboNode *body = find_body(output->root); + if (!body) + body = output->root; + + buffer_t buf = buffer_create(source.len); + filter_children(body, &buf, ignored); + + gumbo_destroy_output(&kGumboDefaultOptions, output); + free(source.data); + return buffer_finish(&buf); +} + /* ------------------------------------------------------------------ */ /* Public API */ /* ------------------------------------------------------------------ */ -char *normalize_html(const char *html, size_t len) { +char *normalize_html(const char *html, size_t len, uint32_t ignored_styles) { if (!html || len == 0) return NULL; @@ -1243,7 +1455,14 @@ char *normalize_html(const char *html, size_t len) { walk_children(body, &buf, NULL); gumbo_destroy_output(&kGumboDefaultOptions, output); - return buffer_finish(&buf); + char *normalized = buffer_finish(&buf); + + if (!normalized || ignored_styles == 0) + return normalized; + + char *filtered = filter_ignored_styles(normalized, ignored_styles); + free(normalized); + return filtered; } void free_normalized_html(char *result) { free(result); } diff --git a/cpp/parser/GumboParser.cpp b/cpp/parser/GumboParser.cpp index fbb9589cc..adec41a7c 100644 --- a/cpp/parser/GumboParser.cpp +++ b/cpp/parser/GumboParser.cpp @@ -2,12 +2,13 @@ // C functions defined in GumboNormalizer.c (compiled as C) extern "C" { -char *normalize_html(const char *html, size_t len); +char *normalize_html(const char *html, size_t len, uint32_t ignored_styles); void free_normalized_html(char *result); } -std::string GumboParser::normalizeHtml(const std::string &html) { - char *raw = normalize_html(html.c_str(), html.size()); +std::string GumboParser::normalizeHtml(const std::string &html, + uint32_t ignoredStyles) { + char *raw = normalize_html(html.c_str(), html.size(), ignoredStyles); if (!raw) return {}; std::string result(raw); diff --git a/cpp/parser/GumboParser.hpp b/cpp/parser/GumboParser.hpp index 789e1aac9..01bf66276 100644 --- a/cpp/parser/GumboParser.hpp +++ b/cpp/parser/GumboParser.hpp @@ -6,6 +6,9 @@ #pragma once +#include "IgnoredStyles.h" + +#include #include /** @@ -16,8 +19,12 @@ class GumboParser { /** * Normalize an HTML string into the canonical subset. * - * @param html UTF-8 encoded HTML fragment or full document. - * @return Canonical HTML string, or empty string on failure. + * @param html UTF-8 encoded HTML fragment or full document. + * @param ignoredStyles Bitmask of IGNORED_STYLE_* flags left out of the output. + * 0 keeps every style. + * @return Canonical HTML string, or empty string on + * failure. */ - static std::string normalizeHtml(const std::string &html); + static std::string normalizeHtml(const std::string &html, + uint32_t ignoredStyles = 0); }; diff --git a/cpp/parser/IgnoredStyles.h b/cpp/parser/IgnoredStyles.h new file mode 100644 index 000000000..4710ae36c --- /dev/null +++ b/cpp/parser/IgnoredStyles.h @@ -0,0 +1,37 @@ +/** + * Bit flags for the styles that the `ignoredStyles` prop can leave out when + * external HTML is normalized. + * + * The bit order must stay in sync with `STYLE_BITS` in + * src/utils/ignoredStyles.ts, which builds the mask passed to native. + */ + +#pragma once + +#include + +#define IGNORED_STYLE_BOLD ((uint32_t)1 << 0) +#define IGNORED_STYLE_ITALIC ((uint32_t)1 << 1) +#define IGNORED_STYLE_UNDERLINE ((uint32_t)1 << 2) +#define IGNORED_STYLE_STRIKETHROUGH ((uint32_t)1 << 3) +#define IGNORED_STYLE_INLINE_CODE ((uint32_t)1 << 4) +#define IGNORED_STYLE_H1 ((uint32_t)1 << 5) +#define IGNORED_STYLE_H2 ((uint32_t)1 << 6) +#define IGNORED_STYLE_H3 ((uint32_t)1 << 7) +#define IGNORED_STYLE_H4 ((uint32_t)1 << 8) +#define IGNORED_STYLE_H5 ((uint32_t)1 << 9) +#define IGNORED_STYLE_H6 ((uint32_t)1 << 10) +#define IGNORED_STYLE_CODE_BLOCK ((uint32_t)1 << 11) +#define IGNORED_STYLE_BLOCK_QUOTE ((uint32_t)1 << 12) +#define IGNORED_STYLE_ORDERED_LIST ((uint32_t)1 << 13) +#define IGNORED_STYLE_UNORDERED_LIST ((uint32_t)1 << 14) +#define IGNORED_STYLE_CHECKBOX_LIST ((uint32_t)1 << 15) +#define IGNORED_STYLE_LINK ((uint32_t)1 << 16) +#define IGNORED_STYLE_IMAGE ((uint32_t)1 << 17) +#define IGNORED_STYLE_MENTION ((uint32_t)1 << 18) +#define IGNORED_STYLE_ALIGNMENT ((uint32_t)1 << 19) +#define IGNORED_STYLE_CUSTOM_STYLE ((uint32_t)1 << 20) + +#define IGNORED_STYLE_HEADINGS \ + (IGNORED_STYLE_H1 | IGNORED_STYLE_H2 | IGNORED_STYLE_H3 | IGNORED_STYLE_H4 | \ + IGNORED_STYLE_H5 | IGNORED_STYLE_H6) diff --git a/cpp/tests/GumboParserTest.cpp b/cpp/tests/GumboParserTest.cpp index 5075f1185..2e89a6a55 100644 --- a/cpp/tests/GumboParserTest.cpp +++ b/cpp/tests/GumboParserTest.cpp @@ -837,3 +837,142 @@ TEST(GumboParserTest, NestedSpans) { "

AB

"); } + +TEST(GumboParserTest, IgnoredInlineStylesAreUnwrapped) { + EXPECT_EQ( + GumboParser::normalizeHtml("

ab

", IGNORED_STYLE_BOLD), + "

ab

"); + // styles mapped from other tags or from CSS are filtered too + EXPECT_EQ( + GumboParser::normalizeHtml("x y", + IGNORED_STYLE_BOLD | IGNORED_STYLE_ITALIC), + "x y"); + EXPECT_EQ( + GumboParser::normalizeHtml("x", + IGNORED_STYLE_BOLD), + "x"); + EXPECT_EQ(GumboParser::normalizeHtml("abc", + IGNORED_STYLE_UNDERLINE | + IGNORED_STYLE_STRIKETHROUGH | + IGNORED_STYLE_INLINE_CODE), + "abc"); + EXPECT_EQ( + GumboParser::normalizeHtml( + "link", IGNORED_STYLE_LINK), + "link"); + EXPECT_EQ( + GumboParser::normalizeHtml("@John", + IGNORED_STYLE_MENTION), + "@John"); +} + +TEST(GumboParserTest, IgnoredCustomStyle) { + EXPECT_EQ(GumboParser::normalizeHtml( + "x", + IGNORED_STYLE_CUSTOM_STYLE), + "x"); + // other styles from the same span are kept, and the other way around + EXPECT_EQ(GumboParser::normalizeHtml( + "x", + IGNORED_STYLE_CUSTOM_STYLE), + "x"); + EXPECT_EQ(GumboParser::normalizeHtml( + "x", + IGNORED_STYLE_BOLD), + "x"); + // Google Docs puts fonts and colors on every span + EXPECT_EQ(GumboParser::normalizeHtml( + "

Bold text

", + IGNORED_STYLE_CUSTOM_STYLE), + "

Bold text

"); +} + +TEST(GumboParserTest, IgnoredBlockStylesBecomeParagraphs) { + EXPECT_EQ( + GumboParser::normalizeHtml("

x

y

", IGNORED_STYLE_H1), + "

x

y

"); + EXPECT_EQ(GumboParser::normalizeHtml( + "

x

", IGNORED_STYLE_H3), + "

x

"); + EXPECT_EQ(GumboParser::normalizeHtml("

", IGNORED_STYLE_H1), "
"); + EXPECT_EQ( + GumboParser::normalizeHtml("
x
", IGNORED_STYLE_CODE_BLOCK), + "

x

"); + EXPECT_EQ( + GumboParser::normalizeHtml("

a

b

", + IGNORED_STYLE_CODE_BLOCK), + "

a

b

"); + EXPECT_EQ(GumboParser::normalizeHtml("
x
", + IGNORED_STYLE_BLOCK_QUOTE), + "

x

"); +} + +TEST(GumboParserTest, IgnoredListsBecomeParagraphs) { + EXPECT_EQ(GumboParser::normalizeHtml( + "
  • a
  • c
", + IGNORED_STYLE_UNORDERED_LIST), + "

a


c

"); + // list alignment moves to the paragraphs + EXPECT_EQ(GumboParser::normalizeHtml( + "
  1. a
", + IGNORED_STYLE_ORDERED_LIST), + "

a

"); + EXPECT_EQ(GumboParser::normalizeHtml( + "
  • a
  • b
", + IGNORED_STYLE_CHECKBOX_LIST), + "

a

b

"); + // unordered and checkbox lists are independent + EXPECT_EQ(GumboParser::normalizeHtml( + "
  • a
  • b
", + IGNORED_STYLE_UNORDERED_LIST), + "
  • a
  • b
"); + EXPECT_EQ(GumboParser::normalizeHtml("
  • a
", + IGNORED_STYLE_CHECKBOX_LIST), + "
  • a
"); +} + +TEST(GumboParserTest, IgnoredImagesAndAlignment) { + EXPECT_EQ(GumboParser::normalizeHtml( + "

ab

", + IGNORED_STYLE_IMAGE), + "

ab

"); + EXPECT_EQ(GumboParser::normalizeHtml("
", + IGNORED_STYLE_UNORDERED_LIST | + IGNORED_STYLE_IMAGE), + "
"); + EXPECT_EQ(GumboParser::normalizeHtml("

x

", + IGNORED_STYLE_ALIGNMENT), + "

x

"); + EXPECT_EQ(GumboParser::normalizeHtml( + "
  • x
", + IGNORED_STYLE_ALIGNMENT), + "
  • x
"); + EXPECT_EQ( + GumboParser::normalizeHtml("

x

", + IGNORED_STYLE_H3 | IGNORED_STYLE_ALIGNMENT), + "

x

"); +} + +TEST(GumboParserTest, IgnoredStylesKeepContent) { + // other tags, attributes, escaping and whitespace are untouched + EXPECT_EQ(GumboParser::normalizeHtml( + "

ab

", + IGNORED_STYLE_BOLD), + "

ab

"); + EXPECT_EQ(GumboParser::normalizeHtml("

a <b> & c

", + IGNORED_STYLE_BOLD), + "

a <b> & c

"); + EXPECT_EQ( + GumboParser::normalizeHtml(" lead", IGNORED_STYLE_BOLD), + " lead"); + EXPECT_EQ( + GumboParser::normalizeHtml("

a


b

", IGNORED_STYLE_BOLD), + "

a


b

"); + // every style ignored leaves plain text + EXPECT_EQ(GumboParser::normalizeHtml("hello world", 0xFFFFFFFF), + "hello world"); +} diff --git a/docs/docs/api-reference/enriched-text-input.md b/docs/docs/api-reference/enriched-text-input.md index eb4339d43..bf1765d45 100644 --- a/docs/docs/api-reference/enriched-text-input.md +++ b/docs/docs/api-reference/enriched-text-input.md @@ -72,6 +72,7 @@ interface EnrichedTextInputProps extends Omit { textShortcuts?: TextShortcut[]; androidExperimentalSynchronousEvents?: boolean; useHtmlNormalizer?: boolean; + ignoredStyles?: EnrichedStyleName[]; allowFontScaling?: boolean; } ``` @@ -205,6 +206,79 @@ Customizes the appearance of HTML elements inside the editor. See | ----------- | -------------------------------------------------- | ----------------- | | `HtmlStyle` | default values from [`HtmlStyle`](#htmlstyle-type) | Android, iOS, Web | +### `ignoredStyles` {#ignoredstyles} + +Styles to leave out when external HTML is normalized - for example rich text +pasted from Google Docs, Word, or web pages, or HTML passed to `defaultValue` or +`setValue` that doesn't come from the editor. +The text itself is always kept: + +- inline styles, links, mentions and custom styles (colors, font sizes and font + families) are removed, +- headings and list items become plain paragraphs, and code blocks and block + quotes are unwrapped into paragraphs, +- images are dropped, +- text alignment falls back to the default one. + +By default no style is ignored. Changing `ignoredStyles` only affects HTML parsed +afterwards - the input's current content is kept as it is. + +```tsx +// keep the formatting of pasted content, but drop its colors, fonts and images + +``` + +```ts +type EnrichedStyleName = + | 'bold' + | 'italic' + | 'underline' + | 'strikeThrough' + | 'inlineCode' + | 'h1' + | 'h2' + | 'h3' + | 'h4' + | 'h5' + | 'h6' + | 'codeBlock' + | 'blockQuote' + | 'orderedList' + | 'unorderedList' + | 'link' + | 'image' + | 'mention' + | 'checkboxList' + | 'alignment' + | 'customStyle'; +``` + +| Type | Default | Platforms | +| --------------------- | ------- | ----------------- | +| `EnrichedStyleName[]` | `[]` | Android, iOS, Web | + +:::note + +`ignoredStyles` only works when the HTML normalizer is in use +([`useHtmlNormalizer`](#usehtmlnormalizer) is `true`, the default). With the +normalizer disabled, the prop has no effect. + +::: + +:::info + +HTML produced by the editor itself (wrapped in `` tags, like the output +of [`getHTML`](#gethtml) and [`onChangeHtml`](#onchangehtml)) is never +filtered, so saved content keeps all of its styles. On Android and iOS this +also covers content copied and pasted within the editor. On web, content copied +from the editor is treated as external HTML when it's pasted back. + +`ignoredStyles` only affects parsing. Styles can still be applied with the +editor's methods (e.g. [`toggleBold`](#togglebold)), text shortcuts and +automatic link detection. + +::: + ### `mentionIndicators` {#mentionindicators} The recognized mention indicators. Each item must be a 1-character string. See diff --git a/docs/docs/api-reference/enriched-text.md b/docs/docs/api-reference/enriched-text.md index 7c9e6fc82..2f3566961 100644 --- a/docs/docs/api-reference/enriched-text.md +++ b/docs/docs/api-reference/enriched-text.md @@ -31,6 +31,7 @@ interface EnrichedTextProps extends ViewProps { style?: TextStyle; htmlStyle?: EnrichedTextHtmlStyle; useHtmlNormalizer?: boolean; + ignoredStyles?: EnrichedStyleName[]; sanitizationConfig?: SanitizationConfig; ellipsizeMode?: 'head' | 'middle' | 'tail' | 'clip'; numberOfLines?: number; @@ -95,6 +96,46 @@ tag subset that the enriched parser understands. See | --------- | ------- | ----------------- | | `boolean` | `true` | Android, iOS, Web | +### `ignoredStyles` {#ignoredstyles} + +Styles to leave out when external HTML passed as `children` is normalized - that +is, any HTML that doesn't come from +[`EnrichedTextInput`](/api-reference/enriched-text-input). +The text itself is always kept: + +- inline styles, links, mentions and custom styles (colors, font sizes and font + families) are removed, +- headings and list items become plain paragraphs, and code blocks and block + quotes are unwrapped into paragraphs, +- images are dropped, +- text alignment falls back to the default one. + +By default no style is ignored. Changing `ignoredStyles` re-parses the current +`children`, so styles you remove from the list are rendered again. + +```tsx +// render headings as plain paragraphs + + {html} + +``` + +See [`EnrichedStyleName`](/api-reference/enriched-text-input#ignoredstyles) for +the available style names. + +| Type | Default | Platforms | +| --------------------- | ------- | ----------------- | +| `EnrichedStyleName[]` | `[]` | Android, iOS, Web | + +:::note + +`ignoredStyles` only works when the HTML normalizer is in use +([`useHtmlNormalizer`](#usehtmlnormalizer) is `true`, the default). With the +normalizer disabled, the prop has no effect. HTML produced by +`EnrichedTextInput` (wrapped in `` tags) is never filtered. + +::: + ### `sanitizationConfig` {#sanitizationconfig} Web-only configuration for the HTML sanitization step applied to `children` diff --git a/docs/docs/core-functionalities/rendering-rich-text.mdx b/docs/docs/core-functionalities/rendering-rich-text.mdx index a56f1d9a3..00d310df0 100644 --- a/docs/docs/core-functionalities/rendering-rich-text.mdx +++ b/docs/docs/core-functionalities/rendering-rich-text.mdx @@ -60,6 +60,9 @@ the only shape difference from the input's `htmlStyle`. See the - **`useHtmlNormalizer`** - normalize external or messy HTML into the library's canonical tag subset before rendering. Defaults to `true`. See [Normalization](/fundamentals/core-concepts#normalization). +- **`ignoredStyles`** - leave the listed styles out when normalizing external + HTML, e.g. to render headings as plain paragraphs. See + [`ignoredStyles`](/api-reference/enriched-text#ignoredstyles). - **`allowFontScaling`** - whether to respect the system's accessibility font scaling settings. :::note diff --git a/docs/docs/fundamentals/core-concepts.md b/docs/docs/fundamentals/core-concepts.md index e391df2b9..1f6d9168d 100644 --- a/docs/docs/fundamentals/core-concepts.md +++ b/docs/docs/fundamentals/core-concepts.md @@ -57,6 +57,12 @@ HTML can be messy. Whether users paste rich text from applications like Google D To handle this, both components provide a `useHtmlNormalizer` prop that normalizes incoming HTML. The normalizer cleans and restructures the input into the predictable format the library relies on (e.g., it maps `` to ``, unwraps `
` containers into `

` tags, and strips unsupported tags). The `useHtmlNormalizer` prop defaults to `true`. +While normalizing, you can also leave out chosen styles with the +`ignoredStyles` prop - for example to keep the formatting of pasted content, but +drop its colors and fonts. See `ignoredStyles` in +[`EnrichedTextInput`](/api-reference/enriched-text-input#ignoredstyles) and +[`EnrichedText`](/api-reference/enriched-text#ignoredstyles). + All supported and canonical tags are listed in [Supported tags](/fundamentals/html-format-and-supported-tags). ## Two components, one HTML format diff --git a/ios/EnrichedTextInputView.h b/ios/EnrichedTextInputView.h index 4d0e71b57..c47f0dee9 100644 --- a/ios/EnrichedTextInputView.h +++ b/ios/EnrichedTextInputView.h @@ -35,6 +35,8 @@ NS_ASSUME_NONNULL_BEGIN BOOL blockEmitting; @public BOOL useHtmlNormalizer; +@public + uint32_t ignoredStylesMask; @public NSValue *dotReplacementRange; @public diff --git a/ios/EnrichedTextInputView.mm b/ios/EnrichedTextInputView.mm index 7731542b5..98fd5bc4d 100644 --- a/ios/EnrichedTextInputView.mm +++ b/ios/EnrichedTextInputView.mm @@ -695,6 +695,12 @@ - (void)updateProps:(Props::Shared const &)props useHtmlNormalizer = newViewProps.useHtmlNormalizer; } + // ignoredStylesMask (ignoredStyles prop) - only affects HTML parsed from now + // on, the current content is kept as it is + if (newViewProps.ignoredStylesMask != oldViewProps.ignoredStylesMask) { + ignoredStylesMask = (uint32_t)newViewProps.ignoredStylesMask; + } + // textShortcuts bool textShortcutsChanged = newViewProps.textShortcuts.size() != oldViewProps.textShortcuts.size(); diff --git a/ios/EnrichedTextView.h b/ios/EnrichedTextView.h index 58e7ae069..cfd9904a0 100644 --- a/ios/EnrichedTextView.h +++ b/ios/EnrichedTextView.h @@ -24,6 +24,8 @@ NS_ASSUME_NONNULL_BEGIN NSMutableDictionary *defaultTypingAttributes; @public BOOL useHtmlNormalizer; +@public + uint32_t ignoredStylesMask; } - (CGSize)measureSize:(CGFloat)maxWidth; + (CGSize)measureSnapshot:(NSAttributedString *)snapshot diff --git a/ios/EnrichedTextView.mm b/ios/EnrichedTextView.mm index f6d387d4a..666aa2c93 100644 --- a/ios/EnrichedTextView.mm +++ b/ios/EnrichedTextView.mm @@ -590,6 +590,13 @@ - (void)updateProps:(Props::Shared const &)props useHtmlNormalizer = newViewProps.useHtmlNormalizer; } + // ignoredStylesMask (ignoredStyles prop) + if (newViewProps.ignoredStylesMask != oldViewProps.ignoredStylesMask) { + ignoredStylesMask = (uint32_t)newViewProps.ignoredStylesMask; + // re-parse the current content with the new set of styles + textChanged = YES; + } + // allowFontScaling if (newViewProps.allowFontScaling != oldViewProps.allowFontScaling) { [newConfig setAllowFontScaling:newViewProps.allowFontScaling]; diff --git a/ios/htmlParser/HtmlParser.h b/ios/htmlParser/HtmlParser.h index 4258a9eb1..a09f4550c 100644 --- a/ios/htmlParser/HtmlParser.h +++ b/ios/htmlParser/HtmlParser.h @@ -6,7 +6,8 @@ @interface HtmlParser : NSObject + (NSString *_Nullable)initiallyProcessHtml:(NSString *_Nonnull)html - useHtmlNormalizer:(BOOL)useHtmlNormalizer; + useHtmlNormalizer:(BOOL)useHtmlNormalizer + ignoredStyles:(uint32_t)ignoredStyles; + (NSArray *_Nonnull)getTextAndStylesFromHtml:(NSString *_Nonnull)fixedHtml config:(EnrichedConfig *_Nullable)config; + (NSString *_Nonnull)parseToHtmlFromRange:(NSRange)range diff --git a/ios/htmlParser/HtmlParser.mm b/ios/htmlParser/HtmlParser.mm index 45853dee1..d86f95d18 100644 --- a/ios/htmlParser/HtmlParser.mm +++ b/ios/htmlParser/HtmlParser.mm @@ -141,11 +141,13 @@ + (NSString *)stringByAddingNewlinesToTag:(NSString *)tag * canonical tag subset using the Gumbo-based C++ normalizer. * * Converts: strong → b, em → i, span style="font-weight:bold" → b, - * strips unknown tags while preserving text + * strips unknown tags while preserving text. Styles in ignoredStyles are left + * out. */ -+ (NSString *_Nullable)normalizeExternalHtml:(NSString *_Nonnull)html { ++ (NSString *_Nullable)normalizeExternalHtml:(NSString *_Nonnull)html + ignoredStyles:(uint32_t)ignoredStyles { std::string result = - GumboParser::normalizeHtml(std::string([html UTF8String])); + GumboParser::normalizeHtml(std::string([html UTF8String]), ignoredStyles); if (result.empty()) return nil; return [NSString stringWithUTF8String:result.c_str()]; @@ -211,7 +213,8 @@ + (NSDictionary *)prepareCheckboxListStyleValue:(NSValue *)rangeValue } + (NSString *_Nullable)initiallyProcessHtml:(NSString *_Nonnull)html - useHtmlNormalizer:(BOOL)useHtmlNormalizer { + useHtmlNormalizer:(BOOL)useHtmlNormalizer + ignoredStyles:(uint32_t)ignoredStyles { NSString *htmlWithoutSpaces = [self stripExtraWhiteSpacesAndNewlines:html]; NSString *fixedHtml = nullptr; @@ -239,7 +242,8 @@ + (NSString *_Nullable)initiallyProcessHtml:(NSString *_Nonnull)html // External HTML (from Google Docs, Word, web pages, etc.) // Run through the Gumbo-based normalizer to convert arbitrary HTML // into our canonical tag subset. - NSString *normalized = [self normalizeExternalHtml:html]; + NSString *normalized = [self normalizeExternalHtml:html + ignoredStyles:ignoredStyles]; if (normalized != nil) { fixedHtml = normalized; } diff --git a/ios/inputHtmlParser/InputHtmlParser.mm b/ios/inputHtmlParser/InputHtmlParser.mm index 18011cd92..e624e1ff4 100644 --- a/ios/inputHtmlParser/InputHtmlParser.mm +++ b/ios/inputHtmlParser/InputHtmlParser.mm @@ -228,7 +228,8 @@ - (void)applyProcessedAlignments:(NSArray *)alignments - (NSString *_Nullable)initiallyProcessHtml:(NSString *_Nonnull)html { return [HtmlParser initiallyProcessHtml:html - useHtmlNormalizer:_input->useHtmlNormalizer]; + useHtmlNormalizer:_input->useHtmlNormalizer + ignoredStyles:_input->ignoredStylesMask]; } @end diff --git a/ios/textHtmlParser/TextHtmlParser.mm b/ios/textHtmlParser/TextHtmlParser.mm index d8287bec4..9b8d56e16 100644 --- a/ios/textHtmlParser/TextHtmlParser.mm +++ b/ios/textHtmlParser/TextHtmlParser.mm @@ -22,7 +22,8 @@ - (void)replaceWholeFromHtml:(NSString *_Nonnull)html { @try { NSString *normalized = [HtmlParser initiallyProcessHtml:html - useHtmlNormalizer:_view->useHtmlNormalizer]; + useHtmlNormalizer:_view->useHtmlNormalizer + ignoredStyles:_view->ignoredStylesMask]; if (normalized == nil) { [_view->textView.textStorage setAttributedString:[[NSAttributedString alloc] diff --git a/src/index.native.tsx b/src/index.native.tsx index 8f7473c7a..210e97541 100644 --- a/src/index.native.tsx +++ b/src/index.native.tsx @@ -6,6 +6,8 @@ export type { OnChangeTextEvent, OnChangeHtmlEvent, OnChangeStateEvent, + EnrichedStyleName, + StyleState, OnLinkDetected, OnMentionDetected, OnChangeSelectionEvent, diff --git a/src/index.tsx b/src/index.tsx index e6b4e654a..ba241498a 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -7,6 +7,8 @@ export type { OnChangeTextEvent, OnChangeHtmlEvent, OnChangeStateEvent, + EnrichedStyleName, + StyleState, OnLinkDetected, OnMentionDetected, OnChangeSelectionEvent, diff --git a/src/native/EnrichedText.tsx b/src/native/EnrichedText.tsx index 6a5697cbc..6a49a6151 100644 --- a/src/native/EnrichedText.tsx +++ b/src/native/EnrichedText.tsx @@ -21,6 +21,7 @@ import EnrichedTextNativeComponent, { } from '../spec/EnrichedTextNativeComponent'; import { nullthrows } from '../utils/nullthrows'; import { normalizeEnrichedTextHtmlStyle } from '../utils/normalizeHtmlStyle'; +import { getIgnoredStylesMask } from '../utils/ignoredStyles'; import type { EnrichedTextProps } from '../types'; type ComponentType = ComponentRef>; @@ -31,6 +32,7 @@ export const EnrichedText = ({ style, htmlStyle: _htmlStyle = {}, useHtmlNormalizer = true, + ignoredStyles = [], ellipsizeMode = 'tail', numberOfLines = 0, selectable = false, @@ -113,6 +115,7 @@ export const EnrichedText = ({ style={style} htmlStyle={htmlStyle} useHtmlNormalizer={useHtmlNormalizer} + ignoredStylesMask={getIgnoredStylesMask(ignoredStyles)} ellipsizeMode={ellipsizeMode} numberOfLines={numberOfLines} selectable={selectable} diff --git a/src/native/EnrichedTextInput.tsx b/src/native/EnrichedTextInput.tsx index 67817c1c9..d86d60190 100644 --- a/src/native/EnrichedTextInput.tsx +++ b/src/native/EnrichedTextInput.tsx @@ -28,6 +28,7 @@ import { normalizeHtmlStyle } from '../utils/normalizeHtmlStyle'; import { toNativeRegexConfig } from '../utils/regexParser'; import { nullthrows } from '../utils/nullthrows'; import { ENRICHED_TEXT_INPUT_DEFAULT_PROPS } from '../utils/EnrichedTextInputDefaultProps'; +import { getIgnoredStylesMask } from '../utils/ignoredStyles'; import type { ContextMenuItem, EnrichedTextInputProps, @@ -97,6 +98,7 @@ export const EnrichedTextInput = ({ textShortcuts = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.textShortcuts, androidExperimentalSynchronousEvents = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.androidExperimentalSynchronousEvents, useHtmlNormalizer = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.useHtmlNormalizer, + ignoredStyles = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.ignoredStyles, scrollEnabled = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.scrollEnabled, allowFontScaling = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.allowFontScaling, ...rest @@ -411,6 +413,7 @@ export const EnrichedTextInput = ({ androidExperimentalSynchronousEvents } useHtmlNormalizer={useHtmlNormalizer} + ignoredStylesMask={getIgnoredStylesMask(ignoredStyles)} scrollEnabled={scrollEnabled} allowFontScaling={allowFontScaling} {...rest} diff --git a/src/spec/EnrichedTextInputNativeComponent.ts b/src/spec/EnrichedTextInputNativeComponent.ts index 0f90daaf9..fc7e9593f 100644 --- a/src/spec/EnrichedTextInputNativeComponent.ts +++ b/src/spec/EnrichedTextInputNativeComponent.ts @@ -423,6 +423,8 @@ export interface NativeProps extends ViewProps { // Experimental androidExperimentalSynchronousEvents: boolean; useHtmlNormalizer: boolean; + // Styles the HTML normalizer leaves out + ignoredStylesMask: CodegenTypes.Int32; } type ComponentType = HostComponent; diff --git a/src/spec/EnrichedTextNativeComponent.ts b/src/spec/EnrichedTextNativeComponent.ts index fcb54b471..efad7eccc 100644 --- a/src/spec/EnrichedTextNativeComponent.ts +++ b/src/spec/EnrichedTextNativeComponent.ts @@ -86,6 +86,8 @@ export interface NativeProps extends ViewProps { text: string; htmlStyle?: EnrichedTextHtmlStyleInternal; useHtmlNormalizer: boolean; + // Styles the HTML normalizer leaves out + ignoredStylesMask: CodegenTypes.Int32; allowFontScaling?: boolean; // ReactNative TextProps diff --git a/src/types.ts b/src/types.ts index fbe606487..6a7d2f266 100644 --- a/src/types.ts +++ b/src/types.ts @@ -292,102 +292,44 @@ export interface OnChangeHtmlEvent { value: string; } -export interface OnChangeStateEvent { - bold: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - italic: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - underline: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - strikeThrough: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - inlineCode: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - h1: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - h2: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - h3: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - h4: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - h5: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - h6: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - codeBlock: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - blockQuote: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - orderedList: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - unorderedList: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - link: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - image: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - mention: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; - checkboxList: { - isActive: boolean; - isConflicting: boolean; - isBlocking: boolean; - }; +/** + * Name of a style. These are the keys of `OnChangeStateEvent`, and the values + * accepted by the `ignoredStyles` prop. + */ +export type EnrichedStyleName = + | 'bold' + | 'italic' + | 'underline' + | 'strikeThrough' + | 'inlineCode' + | 'h1' + | 'h2' + | 'h3' + | 'h4' + | 'h5' + | 'h6' + | 'codeBlock' + | 'blockQuote' + | 'orderedList' + | 'unorderedList' + | 'link' + | 'image' + | 'mention' + | 'checkboxList' + | 'alignment' + | 'customStyle'; + +/** State of a style within the current selection. */ +export interface StyleState { + isActive: boolean; + isConflicting: boolean; + isBlocking: boolean; +} + +export interface OnChangeStateEvent extends Record< + Exclude, + StyleState +> { alignment: string; customStyle: { foregroundColor: string; @@ -839,6 +781,21 @@ export interface EnrichedTextInputProps extends Omit { */ useHtmlNormalizer?: boolean; + /** + * Styles that are left out when external HTML (e.g. pasted content, or HTML + * passed to `defaultValue` / `setValue` that wasn't produced by the editor) + * is normalized: inline styles are removed, block styles (headings, lists, + * quotes, code blocks) become plain paragraphs and images are dropped. The + * text itself is always kept. + * + * Defaults to `[]` - every style is parsed. + * + * Only applies when `useHtmlNormalizer` is enabled. HTML produced by the + * editor itself (e.g. from `onChangeHtml`, or copied within the editor) + * is never filtered. + */ + ignoredStyles?: EnrichedStyleName[]; + /** * Web-only configuration for the HTML sanitization step. * @@ -899,6 +856,19 @@ export interface EnrichedTextProps extends ViewProps { */ useHtmlNormalizer?: boolean; + /** + * Styles that are left out when external HTML (HTML that wasn't produced by + * `EnrichedTextInput`) is normalized: inline styles are removed, block + * styles (headings, lists, quotes, code blocks) become plain paragraphs and + * images are dropped. The text itself is always kept. + * + * Defaults to `[]` - every style is parsed. + * + * Only applies when `useHtmlNormalizer` is enabled. HTML produced by + * `EnrichedTextInput` is never filtered. + */ + ignoredStyles?: EnrichedStyleName[]; + /** * Web-only configuration for the HTML sanitization step. * diff --git a/src/utils/EnrichedTextInputDefaultProps.ts b/src/utils/EnrichedTextInputDefaultProps.ts index 0cf2b3170..a44ef74d9 100644 --- a/src/utils/EnrichedTextInputDefaultProps.ts +++ b/src/utils/EnrichedTextInputDefaultProps.ts @@ -1,4 +1,4 @@ -import type { TextShortcut } from '../types'; +import type { EnrichedStyleName, TextShortcut } from '../types'; export const ENRICHED_TEXT_INPUT_DEFAULT_PROPS = { mentionIndicators: ['@'], @@ -8,6 +8,7 @@ export const ENRICHED_TEXT_INPUT_DEFAULT_PROPS = { scrollEnabled: true, androidExperimentalSynchronousEvents: false, useHtmlNormalizer: true, + ignoredStyles: [] as EnrichedStyleName[], allowFontScaling: true, textShortcuts: [ { trigger: '- ', style: 'unordered_list' }, diff --git a/src/utils/ignoredStyles.ts b/src/utils/ignoredStyles.ts new file mode 100644 index 000000000..c6d683511 --- /dev/null +++ b/src/utils/ignoredStyles.ts @@ -0,0 +1,55 @@ +/* eslint-disable no-bitwise -- the styles are passed to native as a bitmask */ +import type { EnrichedStyleName } from '../types'; + +// Bit position of every style in the mask passed to the HTML normalizer. +// Must stay in sync with cpp/parser/IgnoredStyles.h. +const STYLE_BITS: Record = { + bold: 0, + italic: 1, + underline: 2, + strikeThrough: 3, + inlineCode: 4, + h1: 5, + h2: 6, + h3: 7, + h4: 8, + h5: 9, + h6: 10, + codeBlock: 11, + blockQuote: 12, + orderedList: 13, + unorderedList: 14, + checkboxList: 15, + link: 16, + image: 17, + mention: 18, + alignment: 19, + customStyle: 20, +}; + +export const IGNORABLE_STYLES = Object.keys(STYLE_BITS) as EnrichedStyleName[]; + +/** + * Converts the `ignoredStyles` prop into the mask of styles the normalizer + * leaves out. No ignored styles (the default) gives 0. + */ +export function getIgnoredStylesMask( + ignoredStyles: readonly EnrichedStyleName[] +): number { + let mask = 0; + for (const style of ignoredStyles) { + const bit = STYLE_BITS[style]; + // ignore unknown names coming from untyped code + if (bit !== undefined) { + mask |= 1 << bit; + } + } + return mask; +} + +export function isStyleIgnored( + ignoredStylesMask: number, + style: EnrichedStyleName +): boolean { + return (ignoredStylesMask & (1 << STYLE_BITS[style])) !== 0; +} diff --git a/src/web/EnrichedText.tsx b/src/web/EnrichedText.tsx index cb864a52d..b8b7affab 100644 --- a/src/web/EnrichedText.tsx +++ b/src/web/EnrichedText.tsx @@ -20,6 +20,8 @@ import { enrichedTextThemingToCSSProperties } from './styleConversion/enrichedTh import { buildMentionRulesCSS } from './styleConversion/buildMentionRulesCSS'; import { sanitizeHtml } from './sanitization/htmlSanitizer'; import { prepareHtmlForWeb } from './normalization/prepareHtmlForWeb'; +import { isEnrichedHtml } from './normalization/htmlNormalizer'; +import { getIgnoredStylesMask } from '../utils/ignoredStyles'; import { INLINE_IMAGE_CSS_VARIABLES } from './styleConversion/inlineImageCSSVariables'; import { useImageErrorFallback } from './htmlExtensions/useImageErrorFallback'; import { usePressInteractions } from './htmlExtensions/usePressInteractions'; @@ -42,6 +44,7 @@ export const EnrichedText = memo( numberOfLines = 0, selectable = false, useHtmlNormalizer = true, + ignoredStyles = [], sanitizationConfig, onFocus, onBlur, @@ -71,9 +74,15 @@ export const EnrichedText = memo( [children, sanitizationConfig] ); + // checked before sanitization, which drops the wrapper + const ignoredStylesMask = isEnrichedHtml(children) + ? 0 + : getIgnoredStylesMask(ignoredStyles); + const finalHtml = useMemo( - () => prepareHtmlForWeb(sanitizedHtml, useHtmlNormalizer), - [sanitizedHtml, useHtmlNormalizer] + () => + prepareHtmlForWeb(sanitizedHtml, useHtmlNormalizer, ignoredStylesMask), + [sanitizedHtml, useHtmlNormalizer, ignoredStylesMask] ); const [clampedHtml, setClampedHtml] = useState( diff --git a/src/web/EnrichedTextInput.tsx b/src/web/EnrichedTextInput.tsx index 9f186965e..95f5d9ff4 100644 --- a/src/web/EnrichedTextInput.tsx +++ b/src/web/EnrichedTextInput.tsx @@ -34,6 +34,7 @@ import { normalizeHtmlFromTiptap, } from './normalization/tiptapHtmlNormalizer'; import { ENRICHED_TEXT_INPUT_DEFAULT_PROPS } from '../utils/EnrichedTextInputDefaultProps'; +import { getIgnoredStylesMask } from '../utils/ignoredStyles'; import { enrichedInputStyleToCSSProperties } from './styleConversion/enrichedInputStyleToCSSProperties'; import { enrichedInputThemingToCSSProperties } from './styleConversion/enrichedThemingToCSSProperties'; import { buildMentionRulesCSS } from './styleConversion/buildMentionRulesCSS'; @@ -127,17 +128,21 @@ export const EnrichedTextInput = ({ linkRegex, htmlStyle, useHtmlNormalizer = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.useHtmlNormalizer, + ignoredStyles = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.ignoredStyles, sanitizationConfig, textShortcuts = ENRICHED_TEXT_INPUT_DEFAULT_PROPS.textShortcuts, }: EnrichedTextInputProps) => { assertBrowserEnvironment('EnrichedTextInput'); + const ignoredStylesMask = getIgnoredStylesMask(ignoredStyles); + const tiptapContent = defaultValue != null ? prepareHtmlForTiptap( defaultValue, useHtmlNormalizer, - sanitizationConfig + sanitizationConfig, + ignoredStylesMask ) : defaultValue; @@ -164,6 +169,7 @@ export const EnrichedTextInput = ({ const onLinkPressRef = useStableRef(onLinkPress); const useHtmlNormalizerRef = useStableRef(useHtmlNormalizer); const sanitizationConfigRef = useStableRef(sanitizationConfig); + const ignoredStylesMaskRef = useStableRef(ignoredStylesMask); const mentionCallbacksRef = useStableRef(mentionCallbacks); const textShortcutsRef = useStableRef(textShortcuts); @@ -309,7 +315,8 @@ export const EnrichedTextInput = ({ return prepareHtmlForTiptap( html, useHtmlNormalizerRef.current, - sanitizationConfigRef.current + sanitizationConfigRef.current, + ignoredStylesMaskRef.current ); }, }, @@ -363,7 +370,8 @@ export const EnrichedTextInput = ({ prepareHtmlForTiptap( value, useHtmlNormalizerRef.current, - sanitizationConfigRef.current + sanitizationConfigRef.current, + ignoredStylesMaskRef.current ) ) ), @@ -452,7 +460,13 @@ export const EnrichedTextInput = ({ ); }, }), - [editor, mentionIndicatorsRef, useHtmlNormalizerRef, sanitizationConfigRef] + [ + editor, + mentionIndicatorsRef, + useHtmlNormalizerRef, + sanitizationConfigRef, + ignoredStylesMaskRef, + ] ); const editorStyle: CSSProperties = useMemo( diff --git a/src/web/__tests__/ignoredStyles.test.ts b/src/web/__tests__/ignoredStyles.test.ts new file mode 100644 index 000000000..b0f049f82 --- /dev/null +++ b/src/web/__tests__/ignoredStyles.test.ts @@ -0,0 +1,223 @@ +/* + * Port of the ignoredStyles tests from cpp/tests/GumboParserTest.cpp, the + * expected outputs are the same as the native normalizer's outputs + */ +import type { EnrichedStyleName } from '../../types'; +import { + IGNORABLE_STYLES, + getIgnoredStylesMask, +} from '../../utils/ignoredStyles'; +import { isEnrichedHtml, normalizeHtml } from '../normalization/htmlNormalizer'; +import { prepareHtmlForTiptap } from '../normalization/tiptapHtmlNormalizer'; + +const ignoring = (...styles: EnrichedStyleName[]) => + getIgnoredStylesMask(styles); + +describe('getIgnoredStylesMask', () => { + test('no ignored styles keeps every style', () => { + expect(getIgnoredStylesMask([])).toBe(0); + }); + + test('every style ignored sets every bit', () => { + expect(getIgnoredStylesMask(IGNORABLE_STYLES)).toBe(2 ** 21 - 1); + }); + + test('bits follow cpp/parser/IgnoredStyles.h', () => { + expect(ignoring('bold')).toBe(2 ** 0); + expect(ignoring('h1')).toBe(2 ** 5); + expect(ignoring('checkboxList')).toBe(2 ** 15); + expect(ignoring('customStyle')).toBe(2 ** 20); + expect(ignoring('bold', 'customStyle')).toBe(2 ** 0 + 2 ** 20); + }); + + test('unknown names are ignored', () => { + expect(getIgnoredStylesMask(['bold', 'nope' as EnrichedStyleName])).toBe( + getIgnoredStylesMask(['bold']) + ); + }); +}); + +describe('normalizeHtml with ignored styles', () => { + describe('IgnoredInlineStylesAreUnwrapped', () => { + test.each<[string, number, string]>([ + ['

ab

', ignoring('bold'), '

ab

'], + ['x y', ignoring('bold', 'italic'), 'x y'], + ['x', ignoring('bold'), 'x'], + [ + 'abc', + ignoring('underline', 'strikeThrough', 'inlineCode'), + 'abc', + ], + [ + 'link', + ignoring('link'), + 'link', + ], + [ + '@John', + ignoring('mention'), + '@John', + ], + ])('%s (mask %d) → %s', (input, mask, expected) => { + expect(normalizeHtml(input, mask)).toBe(expected); + }); + }); + + describe('IgnoredCustomStyle', () => { + test.each<[string, number, string]>([ + [ + 'x', + ignoring('customStyle'), + 'x', + ], + [ + 'x', + ignoring('customStyle'), + 'x', + ], + [ + 'x', + ignoring('bold'), + 'x', + ], + [ + '

Bold text

', + ignoring('customStyle'), + '

Bold text

', + ], + ])('%s (mask %d) → %s', (input, mask, expected) => { + expect(normalizeHtml(input, mask)).toBe(expected); + }); + }); + + describe('IgnoredBlockStylesBecomeParagraphs', () => { + test.each<[string, number, string]>([ + ['

x

y

', ignoring('h1'), '

x

y

'], + [ + '

x

', + ignoring('h3'), + '

x

', + ], + ['

', ignoring('h1'), '
'], + ['
x
', ignoring('codeBlock'), '

x

'], + [ + '

a

b

', + ignoring('codeBlock'), + '

a

b

', + ], + ['
x
', ignoring('blockQuote'), '

x

'], + ])('%s (mask %d) → %s', (input, mask, expected) => { + expect(normalizeHtml(input, mask)).toBe(expected); + }); + }); + + describe('IgnoredListsBecomeParagraphs', () => { + test.each<[string, number, string]>([ + [ + '
  • a
  • c
', + ignoring('unorderedList'), + '

a


c

', + ], + [ + '
  1. a
', + ignoring('orderedList'), + '

a

', + ], + [ + '
  • a
  • b
', + ignoring('checkboxList'), + '

a

b

', + ], + [ + '
  • a
  • b
', + ignoring('unorderedList'), + '
  • a
  • b
', + ], + ['
  • a
', ignoring('checkboxList'), '
  • a
'], + ])('%s (mask %d) → %s', (input, mask, expected) => { + expect(normalizeHtml(input, mask)).toBe(expected); + }); + }); + + describe('IgnoredImagesAndAlignment', () => { + test.each<[string, number, string]>([ + [ + '

ab

', + ignoring('image'), + '

ab

', + ], + [ + '
', + ignoring('unorderedList', 'image'), + '
', + ], + [ + '

x

', + ignoring('alignment'), + '

x

', + ], + [ + '
  • x
', + ignoring('alignment'), + '
  • x
', + ], + [ + '

x

', + ignoring('h3', 'alignment'), + '

x

', + ], + ])('%s (mask %d) → %s', (input, mask, expected) => { + expect(normalizeHtml(input, mask)).toBe(expected); + }); + }); + + describe('IgnoredStylesKeepContent', () => { + test.each<[string, number, string]>([ + [ + '

ab

', + ignoring('bold'), + '

ab

', + ], + [ + '

a <b> & c

', + ignoring('bold'), + '

a <b> & c

', + ], + [' lead', ignoring('bold'), ' lead'], + ['

a


b

', ignoring('bold'), '

a


b

'], + [ + 'hello world', + getIgnoredStylesMask(IGNORABLE_STYLES), + 'hello world', + ], + ])('%s (mask %d) → %s', (input, mask, expected) => { + expect(normalizeHtml(input, mask)).toBe(expected); + }); + }); +}); + +describe('editor HTML is never filtered', () => { + test.each([ + ['

x

', true], + [' \n

x

\n\n', true], + ['

x

', false], + ['

x

', false], + ])('isEnrichedHtml(%j) → %s', (html, expected) => { + expect(isEnrichedHtml(html)).toBe(expected); + }); + + test('prepareHtmlForTiptap filters external HTML only', () => { + const mask = getIgnoredStylesMask(IGNORABLE_STYLES); + expect(prepareHtmlForTiptap('

x

', true, undefined, mask)).toBe( + '

x

' + ); + expect( + prepareHtmlForTiptap( + '

x

', + true, + undefined, + mask + ) + ).toBe('

x

'); + }); +}); diff --git a/src/web/normalization/htmlNormalizer.ts b/src/web/normalization/htmlNormalizer.ts index 670995cf8..ad7d5d3a5 100644 --- a/src/web/normalization/htmlNormalizer.ts +++ b/src/web/normalization/htmlNormalizer.ts @@ -3,6 +3,9 @@ * Mirrors the native GumboNormalizer (cpp/parser/GumboNormalizer.c) */ +import type { EnrichedStyleName } from '../../types'; +import { isStyleIgnored } from '../../utils/ignoredStyles'; + type CssStyles = { bold: boolean; italic: boolean; @@ -824,11 +827,157 @@ function walkNode( out.buf += ``; } -export function normalizeHtml(html: string): string { +// --- Ignored styles filtering (`ignoredStyles` prop) --- + +// Runs as a second pass over the normalizer's own output, so it only has to +// understand the canonical tag subset. An ignored inline style, blockquote +// or codeblock is unwrapped (its content stays), an ignored heading or list +// item becomes a plain paragraph and an ignored image is dropped. + +const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']); + +function styleForTag(tag: string, el: Element): EnrichedStyleName | null { + switch (tag) { + case 'b': + return 'bold'; + case 'i': + return 'italic'; + case 'u': + return 'underline'; + case 's': + return 'strikeThrough'; + case 'code': + return 'inlineCode'; + case 'a': + return 'link'; + case 'mention': + return 'mention'; + case 'span': + return 'customStyle'; + case 'img': + return 'image'; + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + return tag; + case 'codeblock': + return 'codeBlock'; + case 'blockquote': + return 'blockQuote'; + case 'ol': + return 'orderedList'; + case 'ul': + return isCheckboxList(el) ? 'checkboxList' : 'unorderedList'; + default: + return null; + } +} + +function filterChildren(node: Node, ignored: number): string { + let out = ''; + for (const child of Array.from(node.childNodes)) { + out += filterNode(child, ignored); + } + return out; +} + +function filterAttributes(el: Element, tag: string, ignored: number) { + let out = ''; + for (const attr of Array.from(el.attributes)) { + // on alignable tags, `style` only ever holds text-align + if ( + attr.name === 'style' && + ALIGN_TAGS.has(tag) && + isStyleIgnored(ignored, 'alignment') + ) { + continue; + } + out += + attr.name === 'checked' + ? ' checked' + : ` ${attr.name}="${escapeText(attr.value)}"`; + } + return out; +} + +// Emits the node's content as a plain paragraph that keeps the text-align of +// alignEl (the node itself, or the list a list item belongs to). +function filterParagraph( + node: Element, + alignEl: Element, + ignored: number +): string { + const inner = filterChildren(node, ignored); + if (inner === '') return '
'; + const align = isStyleIgnored(ignored, 'alignment') + ? '' + : emitAlignment(alignEl, 'p'); + return `${inner}

`; +} + +function filterNode(node: Node, ignored: number): string { + if (isText(node)) return escapeText(node.textContent ?? ''); + if (!isElement(node)) return ''; + + const tag = node.tagName.toLowerCase(); + const style = styleForTag(tag, node); + + if (style && isStyleIgnored(ignored, style)) { + if (style === 'image') return ''; + + if (HEADING_TAGS.has(tag)) return filterParagraph(node, node, ignored); + + if (tag === 'ul' || tag === 'ol') { + let out = ''; + for (const item of Array.from(node.childNodes)) { + out += + isElement(item) && item.tagName.toLowerCase() === 'li' + ? filterParagraph(item, node, ignored) + : filterNode(item, ignored); + } + return out; + } + + // inline styles, blockquotes and codeblocks (whose content is already + // made of paragraphs) are unwrapped + return filterChildren(node, ignored); + } + + const attrs = filterAttributes(node, tag, ignored); + if (tag === 'br') return ``; + if (tag === 'img') return ``; + return `<${tag}${attrs}>${filterChildren(node, ignored)}`; +} + +function filterIgnoredStyles(html: string, ignored: number): string { + const parser = new DOMParser(); + const doc = parser.parseFromString(`${html}`, 'text/html'); + return filterChildren(doc.body, ignored); +} + +/** + * True for HTML produced by the editor itself (wrapped in ), + * the same check the native parsers use to skip the normalizer. + */ +export function isEnrichedHtml(html: string): boolean { + const trimmed = html.trim(); + return trimmed.startsWith('') && trimmed.endsWith(''); +} + +/** + * @param ignoredStylesMask styles left out of the output (see + * src/utils/ignoredStyles.ts), 0 keeps every style + */ +export function normalizeHtml(html: string, ignoredStylesMask = 0): string { const parser = new DOMParser(); const doc = parser.parseFromString(`${html}`, 'text/html'); const body = doc.body; const out = { buf: '' }; walkChildren(body, out, null); - return out.buf; + + if (ignoredStylesMask === 0) return out.buf; + return filterIgnoredStyles(out.buf, ignoredStylesMask); } diff --git a/src/web/normalization/prepareHtmlForWeb.ts b/src/web/normalization/prepareHtmlForWeb.ts index 29ad25f30..ae178e062 100644 --- a/src/web/normalization/prepareHtmlForWeb.ts +++ b/src/web/normalization/prepareHtmlForWeb.ts @@ -3,10 +3,11 @@ import { withBaseFontFamilyFallback } from '../styleConversion/enrichedStyleToCS export function prepareHtmlForWeb( html: string, - useHtmlNormalizer: boolean | undefined + useHtmlNormalizer: boolean | undefined, + ignoredStylesMask = 0 ): string { if (useHtmlNormalizer) { - html = normalizeHtml(html); + html = normalizeHtml(html, ignoredStylesMask); } const parser = new DOMParser(); diff --git a/src/web/normalization/tiptapHtmlNormalizer.ts b/src/web/normalization/tiptapHtmlNormalizer.ts index 27745d1ef..e9304ea2d 100644 --- a/src/web/normalization/tiptapHtmlNormalizer.ts +++ b/src/web/normalization/tiptapHtmlNormalizer.ts @@ -5,16 +5,19 @@ import { checkboxHtmlFromTiptap, } from './checkboxHtmlNormalizer'; import { normalizeColorToHex } from './colorNormalizer'; -import { normalizeHtml } from './htmlNormalizer'; +import { isEnrichedHtml, normalizeHtml } from './htmlNormalizer'; export function prepareHtmlForTiptap( html: string, useHtmlNormalizer: boolean | undefined, - sanitizationConfig?: SanitizationConfig + sanitizationConfig?: SanitizationConfig, + ignoredStylesMask = 0 ): string { + // the editor's own HTML is never filtered, like on native + const mask = isEnrichedHtml(html) ? 0 : ignoredStylesMask; html = sanitizeHtml(html, sanitizationConfig); if (useHtmlNormalizer) { - html = normalizeHtml(html); + html = normalizeHtml(html, mask); } html = checkboxHtmlForTiptap(html); html = html.replace(//gi, '

');