diff --git a/android/src/main/java/com/swmansion/enriched/common/MentionBackgroundDrawer.kt b/android/src/main/java/com/swmansion/enriched/common/MentionBackgroundDrawer.kt new file mode 100644 index 000000000..c3661ece0 --- /dev/null +++ b/android/src/main/java/com/swmansion/enriched/common/MentionBackgroundDrawer.kt @@ -0,0 +1,136 @@ +package com.swmansion.enriched.common + +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.Rect +import android.graphics.RectF +import android.text.Layout +import android.text.Spanned +import android.widget.TextView +import com.swmansion.enriched.common.spans.EnrichedMentionSpan + +// Mention backgrounds are drawn by the view instead of the span, because spans only get whole-line +// bounds and cannot round the corners of a single mention. +object MentionBackgroundDrawer { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + private val path = Path() + private val rect = RectF() + private val radii = FloatArray(8) + private val clipBounds = Rect() + + fun clipToTextBounds( + canvas: Canvas, + view: TextView, + layout: Layout, + ) { + val scrollX = view.scrollX + val scrollY = view.scrollY + val verticalSpace = view.height - view.compoundPaddingTop - view.compoundPaddingBottom + val maxScrollY = layout.height - verticalSpace + + val clipLeft = (view.compoundPaddingLeft + scrollX).toFloat() + val clipTop = if (scrollY == 0) 0f else (view.extendedPaddingTop + scrollY).toFloat() + val clipRight = (view.width - view.compoundPaddingRight + scrollX).toFloat() + val clipBottom = + (view.height + scrollY - if (scrollY == maxScrollY) 0 else view.extendedPaddingBottom) + .toFloat() + + canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom) + } + + // Must be called with the canvas translated to the layout origin and clipped to the visible text + // area before the text is drawn. Only lines inside the clip are drawn. + fun draw( + canvas: Canvas, + layout: Layout, + text: Spanned, + style: EnrichedStyle, + backgroundColorFor: (EnrichedMentionSpan, MentionStyle) -> Int = { _, mentionStyle -> + mentionStyle.backgroundColor + }, // lambda to handle press state bg color for enrichedText + ) { + if (!canvas.getClipBounds(clipBounds)) return + + val firstVisibleLine = layout.getLineForVertical(clipBounds.top) + val lastVisibleLine = layout.getLineForVertical(clipBounds.bottom) + val visibleStart = layout.getLineStart(firstVisibleLine) + val visibleEnd = layout.getLineEnd(lastVisibleLine) + + val spans = text.getSpans(visibleStart, visibleEnd, EnrichedMentionSpan::class.java) + for (span in spans) { + val mentionStyle = style.mentionsStyle[span.getIndicator()] ?: continue + val color = backgroundColorFor(span, mentionStyle) + if (Color.alpha(color) == 0) continue + + val start = text.getSpanStart(span) + val end = text.getSpanEnd(span) + + paint.color = color + drawSpanBackground( + canvas, + layout, + start, + end, + mentionStyle.borderRadius, + firstVisibleLine, + lastVisibleLine, + ) + } + } + + private fun drawSpanBackground( + canvas: Canvas, + layout: Layout, + start: Int, + end: Int, + radius: Float, + firstVisibleLine: Int, + lastVisibleLine: Int, + ) { + val firstLine = layout.getLineForOffset(start) + val lastLine = layout.getLineForOffset(end - 1) + + for (line in maxOf(firstLine, firstVisibleLine)..minOf(lastLine, lastVisibleLine)) { + val isFirst = line == firstLine + val isLast = line == lastLine + + val segmentStart = + if (isFirst) layout.getPrimaryHorizontal(start) else layout.getLineLeft(line) + val segmentEnd = + if (isLast) { + layout.getPrimaryHorizontal(end) + } else { + layout.getLineRight(line) + } + + rect.set( + segmentStart, + layout.getLineTop(line).toFloat(), + segmentEnd, + layout.getLineBottom(line).toFloat(), + ) + + // Only round the outer ends of a wrapped mention. + val leftRadius = if (isFirst) radius else 0f + val rightRadius = if (isLast) radius else 0f + // top-left + radii[0] = leftRadius + radii[1] = leftRadius + // top-right + radii[2] = rightRadius + radii[3] = rightRadius + // bottom-right + radii[4] = rightRadius + radii[5] = rightRadius + // bottom-left + radii[6] = leftRadius + radii[7] = leftRadius + + path.reset() + path.addRoundRect(rect, radii, Path.Direction.CW) + canvas.drawPath(path, paint) + } + } +} diff --git a/android/src/main/java/com/swmansion/enriched/common/MentionStyle.kt b/android/src/main/java/com/swmansion/enriched/common/MentionStyle.kt index e5a7d7c13..970866160 100644 --- a/android/src/main/java/com/swmansion/enriched/common/MentionStyle.kt +++ b/android/src/main/java/com/swmansion/enriched/common/MentionStyle.kt @@ -4,6 +4,7 @@ data class MentionStyle( val color: Int, val backgroundColor: Int, val underline: Boolean, + val borderRadius: Float = 0f, val pressColor: Int? = null, val pressBackgroundColor: Int? = null, ) diff --git a/android/src/main/java/com/swmansion/enriched/common/spans/EnrichedMentionSpan.kt b/android/src/main/java/com/swmansion/enriched/common/spans/EnrichedMentionSpan.kt index e323ecb72..a8e028bec 100644 --- a/android/src/main/java/com/swmansion/enriched/common/spans/EnrichedMentionSpan.kt +++ b/android/src/main/java/com/swmansion/enriched/common/spans/EnrichedMentionSpan.kt @@ -23,7 +23,6 @@ open class EnrichedMentionSpan( val mentionsStyle = enrichedStyle.mentionsStyle[indicator] ?: return textPaint.color = mentionsStyle.color - textPaint.bgColor = mentionsStyle.backgroundColor textPaint.isUnderlineText = mentionsStyle.underline } diff --git a/android/src/main/java/com/swmansion/enriched/text/EnrichedTextStyle.kt b/android/src/main/java/com/swmansion/enriched/text/EnrichedTextStyle.kt index 05281984a..0dde05c4c 100644 --- a/android/src/main/java/com/swmansion/enriched/text/EnrichedTextStyle.kt +++ b/android/src/main/java/com/swmansion/enriched/text/EnrichedTextStyle.kt @@ -120,7 +120,7 @@ data class EnrichedTextStyle( codeBlockRadius = parseFloat(codeblock, "borderRadius", allowFontScaling), inlineCodeColor = parseColor(context, inlineCode, "color"), inlineCodeBackgroundColor = parseColorWithOpacity(context, inlineCode, "backgroundColor"), - mentionsStyle = parseMentionsStyle(context, mentions), + mentionsStyle = parseMentionsStyle(context, mentions, allowFontScaling), allowFontScaling = allowFontScaling, ) } @@ -183,6 +183,7 @@ data class EnrichedTextStyle( private fun parseMentionsStyle( context: ReactContext, map: ReadableMap?, + allowFontScaling: Boolean, ): Map { val result = mutableMapOf() val iterator = map?.keySetIterator() ?: return result @@ -195,6 +196,7 @@ data class EnrichedTextStyle( color = parseColor(context, value, "color"), backgroundColor = parseColorWithOpacity(context, value, "backgroundColor"), underline = parseIsUnderline(value), + borderRadius = parseFloat(value, "borderRadius", allowFontScaling), pressColor = parseColor(context, value, "pressColor"), pressBackgroundColor = parseColorWithOpacity(context, value, "pressBackgroundColor"), ) 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..8cf10c70a 100644 --- a/android/src/main/java/com/swmansion/enriched/text/EnrichedTextView.kt +++ b/android/src/main/java/com/swmansion/enriched/text/EnrichedTextView.kt @@ -3,6 +3,7 @@ package com.swmansion.enriched.text import android.content.ClipData import android.content.ClipboardManager import android.content.Context +import android.graphics.Canvas import android.graphics.Color import android.graphics.text.LineBreaker import android.os.Build @@ -25,6 +26,7 @@ import com.facebook.react.views.text.ReactTypefaceUtils.parseFontWeight import com.swmansion.enriched.common.EnrichedConstants import com.swmansion.enriched.common.EnrichedSpanFlags import com.swmansion.enriched.common.GumboNormalizer +import com.swmansion.enriched.common.MentionBackgroundDrawer import com.swmansion.enriched.common.parser.EnrichedParser import com.swmansion.enriched.common.pixelFromSpOrDp import com.swmansion.enriched.text.spans.EnrichedTextImageSpan @@ -92,6 +94,28 @@ class EnrichedTextView : AppCompatTextView { setFontSize(EnrichedConstants.TEXT_DEFAULT_FONT_SIZE) } + override fun onDraw(canvas: Canvas) { + val currentLayout = layout + val spanned = text as? Spanned + val style = enrichedStyle + if (currentLayout != null && spanned != null && style != null) { + canvas.save() + MentionBackgroundDrawer.clipToTextBounds(canvas, this, currentLayout) + canvas.translate(totalPaddingLeft.toFloat(), totalPaddingTop.toFloat()) + MentionBackgroundDrawer.draw(canvas, currentLayout, spanned, style) { span, mentionStyle -> + val isPressed = (span as? EnrichedTextClickableSpan)?.isPressed == true + if (isPressed && mentionStyle.pressBackgroundColor != null) { + mentionStyle.pressBackgroundColor + } else { + mentionStyle.backgroundColor + } + } + canvas.restore() + } + + super.onDraw(canvas) + } + override fun onTouchEvent(event: MotionEvent): Boolean { val spanned = text as? Spanned val action = event.action diff --git a/android/src/main/java/com/swmansion/enriched/text/spans/EnrichedTextMentionSpan.kt b/android/src/main/java/com/swmansion/enriched/text/spans/EnrichedTextMentionSpan.kt index 9d49d988e..6abc8d3bb 100644 --- a/android/src/main/java/com/swmansion/enriched/text/spans/EnrichedTextMentionSpan.kt +++ b/android/src/main/java/com/swmansion/enriched/text/spans/EnrichedTextMentionSpan.kt @@ -35,15 +35,7 @@ class EnrichedTextMentionSpan( mentionsStyle.color } - val bgColor = - if (isPressed && mentionsStyle.pressBackgroundColor != null) { - mentionsStyle.pressBackgroundColor - } else { - mentionsStyle.backgroundColor - } - textPaint.color = color - textPaint.bgColor = bgColor } override fun onClick(view: View) { 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..9772099bd 100644 --- a/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt +++ b/android/src/main/java/com/swmansion/enriched/textinput/EnrichedTextInputView.kt @@ -5,6 +5,7 @@ import android.content.ClipboardManager import android.content.Context import android.graphics.BlendMode import android.graphics.BlendModeColorFilter +import android.graphics.Canvas import android.graphics.Color import android.graphics.Rect import android.graphics.text.LineBreaker @@ -41,6 +42,7 @@ import com.facebook.react.views.text.ReactTypefaceUtils.parseFontWeight import com.swmansion.enriched.common.EnrichedConstants import com.swmansion.enriched.common.EnrichedSpanFlags import com.swmansion.enriched.common.GumboNormalizer +import com.swmansion.enriched.common.MentionBackgroundDrawer import com.swmansion.enriched.common.parser.EnrichedParser import com.swmansion.enriched.common.pixelFromSpOrDp import com.swmansion.enriched.textinput.events.MentionHandler @@ -293,6 +295,20 @@ class EnrichedTextInputView : ) } + override fun onDraw(canvas: Canvas) { + val currentLayout = layout + val currentText = text + if (currentLayout != null && currentText != null) { + canvas.save() + MentionBackgroundDrawer.clipToTextBounds(canvas, this, currentLayout) + canvas.translate(totalPaddingLeft.toFloat(), totalPaddingTop.toFloat()) + MentionBackgroundDrawer.draw(canvas, currentLayout, currentText, htmlStyle) + canvas.restore() + } + + super.onDraw(canvas) + } + // https://github.com/facebook/react-native/blob/36df97f500aa0aa8031098caf7526db358b6ddc1/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt#L295C1-L296C1 override fun onTouchEvent(ev: MotionEvent): Boolean { when (ev.action) { diff --git a/android/src/main/java/com/swmansion/enriched/textinput/styles/HtmlStyle.kt b/android/src/main/java/com/swmansion/enriched/textinput/styles/HtmlStyle.kt index 5a67113a5..9e0a83281 100644 --- a/android/src/main/java/com/swmansion/enriched/textinput/styles/HtmlStyle.kt +++ b/android/src/main/java/com/swmansion/enriched/textinput/styles/HtmlStyle.kt @@ -247,7 +247,8 @@ class HtmlStyle : EnrichedStyle { val color = parseColor(value, "color") val backgroundColor = parseColorWithOpacity(value, "backgroundColor") val isUnderline = parseIsUnderline(value) - val parsedStyle = MentionStyle(color, backgroundColor, isUnderline) + val borderRadius = parseFloat(value, "borderRadius") + val parsedStyle = MentionStyle(color, backgroundColor, isUnderline, borderRadius) parsedMentionsStyle.put(key, parsedStyle) } diff --git a/apps/example-web/src/defaultHtmlStyle.ts b/apps/example-web/src/defaultHtmlStyle.ts index 10f10c0cc..6ef15ec7c 100644 --- a/apps/example-web/src/defaultHtmlStyle.ts +++ b/apps/example-web/src/defaultHtmlStyle.ts @@ -68,6 +68,7 @@ export const WEB_DEFAULT_HTML_STYLE: HtmlStyle = { backgroundColor: 'lightgreen', color: 'green', textDecorationLine: 'none', + borderRadius: 0, }, '#': { backgroundColor: 'lightblue', diff --git a/apps/example/src/constants/editorConfig.ts b/apps/example/src/constants/editorConfig.ts index f29ac11c0..f3b20aacf 100644 --- a/apps/example/src/constants/editorConfig.ts +++ b/apps/example/src/constants/editorConfig.ts @@ -113,6 +113,7 @@ export const htmlStyle = { color: 'green', backgroundColor: 'lightgreen', textDecorationLine: 'none', + borderRadius: 0, }, }, ol: { diff --git a/apps/example/src/constants/htmlStyle.ts b/apps/example/src/constants/htmlStyle.ts index 9bf3d790a..2d10e3a88 100644 --- a/apps/example/src/constants/htmlStyle.ts +++ b/apps/example/src/constants/htmlStyle.ts @@ -57,6 +57,7 @@ export const htmlStyle = { color: 'green', backgroundColor: 'lightgreen', textDecorationLine: 'none', + borderRadius: 0, }, }, ol: { diff --git a/docs/docs/api-reference/enriched-text-input.md b/docs/docs/api-reference/enriched-text-input.md index eb4339d43..f3b12adc0 100644 --- a/docs/docs/api-reference/enriched-text-input.md +++ b/docs/docs/api-reference/enriched-text-input.md @@ -1223,6 +1223,7 @@ interface MentionStyleProperties { color?: ColorValue; backgroundColor?: ColorValue; textDecorationLine?: 'underline' | 'none'; + borderRadius?: number; } ``` @@ -1278,6 +1279,9 @@ should be a record with indicators as keys and configs as values. [color](https://reactnative.dev/docs/colors) value, defaults to `yellow` - `textDecorationLine` - whether mentions are underlined; `'underline'` or `'none'`, defaults to `'underline'` +- `borderRadius` - corner radius of the mention background; defaults to `0`. + When a mention wraps onto multiple lines, only its outer corners (at the + start of the first line and the end of the last line) are rounded :::tip diff --git a/docs/docs/api-reference/enriched-text.md b/docs/docs/api-reference/enriched-text.md index 7c9e6fc82..7f03c96b1 100644 --- a/docs/docs/api-reference/enriched-text.md +++ b/docs/docs/api-reference/enriched-text.md @@ -260,6 +260,7 @@ interface EnrichedTextMentionStyleProperties { color?: ColorValue; backgroundColor?: ColorValue; textDecorationLine?: 'underline' | 'none'; + borderRadius?: number; pressColor?: ColorValue; pressBackgroundColor?: ColorValue; } diff --git a/docs/docs/core-functionalities/styling-the-input.mdx b/docs/docs/core-functionalities/styling-the-input.mdx index 26ba3c24a..8b4d32f98 100644 --- a/docs/docs/core-functionalities/styling-the-input.mdx +++ b/docs/docs/core-functionalities/styling-the-input.mdx @@ -62,17 +62,17 @@ to their React Native `TextStyle` counterparts. Some are platform-limited `htmlStyle` maps each supported element to a small config object. Anything you omit falls back to the built-in default. The available keys are: -| Key | Styles | Notable options | -| ------------ | -------------- | ----------------------------------------------------------- | -| `h1`–`h6` | Headings | `fontSize`, `bold` | -| `blockquote` | Blockquote | `borderColor`, `borderWidth`, `gapWidth`, `color` | -| `codeblock` | Code block | `color`, `backgroundColor`, `borderRadius` | -| `code` | Inline code | `color`, `backgroundColor` | -| `a` | Links | `color`, `textDecorationLine` | -| `mention` | Mentions | `color`, `backgroundColor`, `textDecorationLine` | -| `ol` | Ordered list | `markerColor`, `markerFontWeight`, `marginLeft`, `gapWidth` | -| `ul` | Unordered list | `bulletColor`, `bulletSize`, `marginLeft`, `gapWidth` | -| `ulCheckbox` | Checkbox list | `boxColor`, `boxSize`, `marginLeft`, `gapWidth` | +| Key | Styles | Notable options | +| ------------ | -------------- | ---------------------------------------------------------------- | +| `h1`–`h6` | Headings | `fontSize`, `bold` | +| `blockquote` | Blockquote | `borderColor`, `borderWidth`, `gapWidth`, `color` | +| `codeblock` | Code block | `color`, `backgroundColor`, `borderRadius` | +| `code` | Inline code | `color`, `backgroundColor` | +| `a` | Links | `color`, `textDecorationLine` | +| `mention` | Mentions | `color`, `backgroundColor`, `textDecorationLine`, `borderRadius` | +| `ol` | Ordered list | `markerColor`, `markerFontWeight`, `marginLeft`, `gapWidth` | +| `ul` | Unordered list | `bulletColor`, `bulletSize`, `marginLeft`, `gapWidth` | +| `ulCheckbox` | Checkbox list | `boxColor`, `boxSize`, `marginLeft`, `gapWidth` | The full list of properties, defaults, and platform notes lives in the [`EnrichedTextInput`](/api-reference/enriched-text-input#htmlstyle) reference. diff --git a/ios/EnrichedTextInputView.mm b/ios/EnrichedTextInputView.mm index 7731542b5..e9adc9eea 100644 --- a/ios/EnrichedTextInputView.mm +++ b/ios/EnrichedTextInputView.mm @@ -611,7 +611,7 @@ - (void)updateProps:(Props::Shared const &)props bool newSingleProps = NO; for (const auto &obj : newMentionStyle.items()) { - if (obj.second.isInt() || obj.second.isString()) { + if (obj.second.isNumber() || obj.second.isString()) { // we are in just a single MentionStyleProps object newSingleProps = YES; break; diff --git a/ios/EnrichedTextView.mm b/ios/EnrichedTextView.mm index f6d387d4a..5b3be9800 100644 --- a/ios/EnrichedTextView.mm +++ b/ios/EnrichedTextView.mm @@ -523,7 +523,7 @@ - (void)updateProps:(Props::Shared const &)props bool newSingleProps = NO; for (const auto &obj : newMentionStyle.items()) { - if (obj.second.isInt() || obj.second.isString()) { + if (obj.second.isNumber() || obj.second.isString()) { newSingleProps = YES; break; } else if (obj.second.isObject()) { diff --git a/ios/extensions/LayoutManagerExtension.mm b/ios/extensions/LayoutManagerExtension.mm index 19b19a120..a11b82d84 100644 --- a/ios/extensions/LayoutManagerExtension.mm +++ b/ios/extensions/LayoutManagerExtension.mm @@ -1,6 +1,7 @@ #import "LayoutManagerExtension.h" #import "ColorExtension.h" #import "interfaces/EnrichedViewHost.h" +#import "interfaces/MentionStyleProps.h" #import "interfaces/StyleHeaders.h" #import "utils/RangeUtils.h" #import "utils/WeakBox.h" @@ -60,6 +61,118 @@ - (void)my_drawBackgroundForGlyphRange:(NSRange)glyphRange [self drawBlockQuotes:host origin:origin visibleCharRange:visibleCharRange]; [self drawLists:host origin:origin visibleCharRange:visibleCharRange]; [self drawCodeBlocks:host origin:origin visibleCharRange:visibleCharRange]; + [self drawMentionBackgrounds:host + origin:origin + visibleCharRange:visibleCharRange]; +} + +- (void)drawMentionBackgrounds:(id)host + origin:(CGPoint)origin + visibleCharRange:(NSRange)visibleCharRange { + NSTextStorage *textStorage = host.textView.textStorage; + NSRange wholeText = NSMakeRange(0, textStorage.length); + NSMutableArray *ranges = [[NSMutableArray alloc] init]; + [textStorage enumerateAttribute:@"EnrichedMention" + inRange:visibleCharRange + options:0 + usingBlock:^(id _Nullable value, NSRange range, + BOOL *_Nonnull stop) { + if (value == nullptr || range.length == 0) { + return; + } + NSRange fullRange; + [textStorage attribute:@"EnrichedMention" + atIndex:range.location + longestEffectiveRange:&fullRange + inRange:wholeText]; + [ranges addObject:[NSValue valueWithRange:fullRange]]; + }]; + + for (NSValue *rangeValue in ranges) { + NSRange range = [rangeValue rangeValue]; + UIColor *bgColor = + [textStorage attribute:[MentionStyle getBackgroundAttributeName] + atIndex:range.location + effectiveRange:nullptr]; + if (bgColor == nullptr || CGColorGetAlpha(bgColor.CGColor) == 0) { + continue; + } + MentionParams *params = [textStorage attribute:@"EnrichedMention" + atIndex:range.location + effectiveRange:nullptr]; + MentionStyleProps *props = + [host.config mentionStylePropsForIndicator:params.indicator]; + UIFont *font = [textStorage attribute:NSFontAttributeName + atIndex:range.location + effectiveRange:nullptr]; + [bgColor setFill]; + + NSMutableArray *lineRects = [[NSMutableArray alloc] init]; + NSArray *nonNewlineRanges = [RangeUtils getNonNewlineRangesIn:host.textView + range:range]; + for (NSValue *subRangeValue in nonNewlineRanges) { + NSRange glyphRange = + [self glyphRangeForCharacterRange:[subRangeValue rangeValue] + actualCharacterRange:nullptr]; + [self + enumerateLineFragmentsForGlyphRange:glyphRange + usingBlock:^(CGRect rect, CGRect usedRect, + NSTextContainer *container, + NSRange lineGlyphRange, + BOOL *stop) { + NSRange lineRange = NSIntersectionRange( + lineGlyphRange, glyphRange); + // trailing whitespace at a soft wrap + // would get a background with nothing + // after it, so trim it off + if (NSMaxRange(lineRange) < + NSMaxRange(glyphRange)) { + lineRange = [self + trimTrailingWhitespaceFromGlyphRange: + lineRange + textStorage: + textStorage]; + } + if (lineRange.length == 0) { + return; + } + CGRect lineRect = [self + boundingRectForGlyphRange:lineRange + inTextContainer:container]; + [lineRects + addObject:[NSValue valueWithCGRect: + lineRect]]; + }]; + } + + // only the mention's start and end get rounded, so a wrapped mention + // still has 4 rounded corners in total + for (NSUInteger i = 0; i < lineRects.count; i++) { + CGRect bgRect = [self getTextAlignedUsedRect:[lineRects[i] CGRectValue] + font:font]; + bgRect.origin.x += origin.x; + bgRect.origin.y += origin.y; + + if (props.borderRadius <= 0) { + [[UIBezierPath bezierPathWithRect:bgRect] fill]; + continue; + } + + UIRectCorner corners = 0; + if (i == 0) { + corners = UIRectCornerTopLeft | UIRectCornerBottomLeft; + } + if (i == lineRects.count - 1) { + corners |= UIRectCornerTopRight | UIRectCornerBottomRight; + } + + CGFloat radius = MIN(props.borderRadius, bgRect.size.height / 2); + [[UIBezierPath bezierPathWithRoundedRect:bgRect + byRoundingCorners:corners + cornerRadii:CGSizeMake(radius, radius)] + fill]; + } + } } - (void)drawCodeBlocks:(id)host @@ -387,6 +500,24 @@ - (NSString *)getDecimalMarkerForList:(id)host return [NSString stringWithFormat:@"%ld.", (long)(itemNumber)]; } +// Drops whitespace glyphs from the end of a glyph range, used so a mention +// background that wraps doesn't extend past its last visible character. +- (NSRange)trimTrailingWhitespaceFromGlyphRange:(NSRange)glyphRange + textStorage:(NSTextStorage *)textStorage { + NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet]; + while (glyphRange.length > 0) { + NSUInteger charIndex = + [self characterIndexForGlyphAtIndex:NSMaxRange(glyphRange) - 1]; + if (charIndex >= textStorage.length || + ![whitespace characterIsMember:[textStorage.string + characterAtIndex:charIndex]]) { + break; + } + glyphRange.length--; + } + return glyphRange; +} + // Returns a usedRect adjusted to cover only the text portion of the line. // When minimumLineHeight expands the line box, extra space is added at the top // and text stays at the bottom. This strips that padding so markers align with diff --git a/ios/interfaces/MentionStyleProps.h b/ios/interfaces/MentionStyleProps.h index f83d1bc40..a1cd6aaba 100644 --- a/ios/interfaces/MentionStyleProps.h +++ b/ios/interfaces/MentionStyleProps.h @@ -8,6 +8,7 @@ @property UIColor *color; @property UIColor *backgroundColor; @property TextDecorationLineEnum decorationLine; +@property CGFloat borderRadius; + (NSDictionary *)getSinglePropsFromFollyDynamic:(folly::dynamic)folly; + (NSDictionary *)getComplexPropsFromFollyDynamic:(folly::dynamic)folly; diff --git a/ios/interfaces/MentionStyleProps.mm b/ios/interfaces/MentionStyleProps.mm index eddc29f1c..aa7012228 100644 --- a/ios/interfaces/MentionStyleProps.mm +++ b/ios/interfaces/MentionStyleProps.mm @@ -34,6 +34,12 @@ + (MentionStyleProps *)getSingleMentionStylePropsFromFollyDynamic: nativeProps.decorationLine = DecorationUnderline; } + if (folly["borderRadius"].isNumber()) { + nativeProps.borderRadius = folly["borderRadius"].asDouble(); + } else { + nativeProps.borderRadius = 0; + } + // text only if (folly["pressColor"].isNumber()) { facebook::react::SharedColor pressColor = facebook::react::SharedColor( diff --git a/ios/interfaces/StyleHeaders.h b/ios/interfaces/StyleHeaders.h index c664429f0..1ee66177e 100644 --- a/ios/interfaces/StyleHeaders.h +++ b/ios/interfaces/StyleHeaders.h @@ -46,6 +46,7 @@ @end @interface MentionStyle : StyleBase ++ (NSString *)getBackgroundAttributeName; - (void)addMention:(NSString *)indicator text:(NSString *)text attributes:(NSString *)attributes; diff --git a/ios/styles/MentionStyle.mm b/ios/styles/MentionStyle.mm index aa625c960..51f3e9173 100644 --- a/ios/styles/MentionStyle.mm +++ b/ios/styles/MentionStyle.mm @@ -8,6 +8,10 @@ // custom NSAttributedStringKey to differentiate from links static NSString *const MentionAttributeName = @"EnrichedMention"; +// holds the mention's background color, drawn by the layout manager instead of +// NSBackgroundColorAttributeName so the corners can be rounded +static NSString *const MentionBackgroundAttributeName = + @"EnrichedMentionBackground"; @implementation MentionStyle { NSValue *_activeMentionRange; @@ -17,6 +21,10 @@ @implementation MentionStyle { NSString *_lastEmittedMentionText; } ++ (NSString *)getBackgroundAttributeName { + return MentionBackgroundAttributeName; +} + + (StyleType)getType { return Mention; } @@ -55,7 +63,8 @@ - (void)applyStyling:(NSRange)range { NSForegroundColorAttributeName : styleProps.color, NSUnderlineColorAttributeName : styleProps.color, NSStrikethroughColorAttributeName : styleProps.color, - NSBackgroundColorAttributeName : + // backgrounds are drawn by the layout manager + MentionBackgroundAttributeName : [styleProps.backgroundColor colorWithResolvedAlpha], } mutableCopy]; diff --git a/ios/utils/EnrichedTextTouchHandler.mm b/ios/utils/EnrichedTextTouchHandler.mm index c5b9cad69..e5352bd97 100644 --- a/ios/utils/EnrichedTextTouchHandler.mm +++ b/ios/utils/EnrichedTextTouchHandler.mm @@ -6,6 +6,7 @@ #import "interfaces/MentionParams.h" #import "interfaces/MentionStyleProps.h" #import "interfaces/StyleBase.h" +#import "interfaces/StyleHeaders.h" @implementation EnrichedTextTouchHandler { NSRange _activeRange; @@ -121,7 +122,7 @@ - (void)updateVisualsPressed:(BOOL)pressed { newAttrs[NSStrikethroughColorAttributeName] = color; } if (bgColor) { - newAttrs[NSBackgroundColorAttributeName] = + newAttrs[[MentionStyle getBackgroundAttributeName]] = [bgColor colorWithResolvedAlpha]; } diff --git a/src/types.ts b/src/types.ts index fbe606487..78fe4db25 100644 --- a/src/types.ts +++ b/src/types.ts @@ -195,6 +195,7 @@ export interface MentionStyleProperties { color?: ColorValue; backgroundColor?: ColorValue; textDecorationLine?: 'underline' | 'none'; + borderRadius?: number; } export interface HtmlStyle { diff --git a/src/utils/defaultHtmlStyle.ts b/src/utils/defaultHtmlStyle.ts index 06666b7ad..dacb015af 100644 --- a/src/utils/defaultHtmlStyle.ts +++ b/src/utils/defaultHtmlStyle.ts @@ -49,6 +49,7 @@ export const DEFAULT_HTML_STYLE: Required = { color: 'blue', backgroundColor: 'yellow', textDecorationLine: 'underline', + borderRadius: 0, }, ol: { gapWidth: 16, diff --git a/src/web/styleConversion/buildMentionRulesCSS.ts b/src/web/styleConversion/buildMentionRulesCSS.ts index b6785c174..aa41a0ba1 100644 --- a/src/web/styleConversion/buildMentionRulesCSS.ts +++ b/src/web/styleConversion/buildMentionRulesCSS.ts @@ -58,6 +58,7 @@ ${textSelector} { color: var(${ET_MENTION_CSS_VARS.color(indicator)}, var(${ET_MENTION_CSS_VARS.color(MENTION_STYLE_DEFAULT_KEY)})); background-color: var(${ET_MENTION_CSS_VARS.backgroundColor(indicator)}, var(${ET_MENTION_CSS_VARS.backgroundColor(MENTION_STYLE_DEFAULT_KEY)})); text-decoration-line: var(${ET_MENTION_CSS_VARS.textDecorationLine(indicator)}, var(${ET_MENTION_CSS_VARS.textDecorationLine(MENTION_STYLE_DEFAULT_KEY)})); + border-radius: var(${ET_MENTION_CSS_VARS.borderRadius(indicator)}, var(${ET_MENTION_CSS_VARS.borderRadius(MENTION_STYLE_DEFAULT_KEY)})); transition: none; }`.trim() ); diff --git a/src/web/styleConversion/htmlStyleToCSSVariables.ts b/src/web/styleConversion/htmlStyleToCSSVariables.ts index c25a4859a..ba3539661 100644 --- a/src/web/styleConversion/htmlStyleToCSSVariables.ts +++ b/src/web/styleConversion/htmlStyleToCSSVariables.ts @@ -117,6 +117,8 @@ export const ET_MENTION_CSS_VARS = { `--et-mention-${indicatorToMentionCssKey(indicator)}-background-color`, textDecorationLine: (indicator: string) => `--et-mention-${indicatorToMentionCssKey(indicator)}-text-decoration-line`, + borderRadius: (indicator: string) => + `--et-mention-${indicatorToMentionCssKey(indicator)}-border-radius`, } as const; function setColorVar( @@ -236,6 +238,13 @@ function applyMentionVars( vars[ET_MENTION_CSS_VARS.textDecorationLine(indicator)] = mentionStyle.textDecorationLine; } + if (mentionStyle.borderRadius != null) { + setPxVar( + vars, + ET_MENTION_CSS_VARS.borderRadius(indicator), + mentionStyle.borderRadius + ); + } } }