Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/docs/react-native/api-reference/style-properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,15 @@ Nonfinite dimensions fall back to their defaults and negative dimensions clamp t
Pills are drawn by the native text stack, so `pill` applies on **iOS and Android only**. The web build and macOS render those links as ordinary links with the variant's colors and font. The [Link pills](/react-native/guides/link-pills) guide covers the rest: per-link content, line height, icon sources and behavior.
:::

#### Inline link icons {#inline-icon}

A variant's `inlineIcon` draws an icon before the link's own text, which stays ordinary link text and wraps across lines. It is ignored when the variant sets `pill`. iOS and Android only.

| Property | Type | Default | Description |
| --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------- |
| `iconUri` | `string` | - | Icon drawn at the text's font size. See [Icon sources](/react-native/guides/link-pills#icon-sources) |
| `iconTintColor` | `string` | No tint | Tints the icon and keeps its alpha |

### Strong-specific

| Property | Type | Default | Description |
Expand Down
12 changes: 12 additions & 0 deletions docs/docs/react-native/guides/link-pills.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ For text that [streams in](/rich-text-formatting/markdown-streaming), set the bl
- A pill inside an unrevealed spoiler is hidden with the rest of the spoiler.
- A long-pressed pill can open a [link menu](/react-native/guides/link-menus) on iOS 17+; the menu is titled with the pill's label.

## Inline icons {#inline-icons}

A pill is one unit, so a long label is cut off at the end of the line. For links that show their own text and need to wrap, such as titles, give the variant an `inlineIcon` instead of `pill`:

```tsx
linkVariants: {
'^app://thread/': { color: '#4F46E5', inlineIcon: { iconUri: 'thread_icon', iconTintColor: '#4F46E5' } },
}
```

The icon is drawn before the link text, on the same line as its first word, and the text wraps like any other link. The variant's `color`, `underline`, `backgroundColor` and `fontFamily` apply to the text. The icon is not part of the text: copy, export, the accessible name and link menus see only the link text. `inlineIcon` takes the same [icon sources](#icon-sources) as pills, and is ignored when the variant also sets `pill`.

## Icon sources {#icon-sources}

Both `pill.iconUri` and a `linkPillContent` entry's `iconUri` take the same sources. Icons are drawn at the label's font size.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ it('requires an explicit pill opt-in and preserves ordinary link overrides', ()
borderColor: normalizeColor('transparent'),
maxWidth: 0,
},
inlineIcon: { iconUri: '', iconTintColor: undefined },
});
});

Expand Down Expand Up @@ -227,3 +228,48 @@ it('passes a per-link icon tint and treats a tint change as a content change', (
expect(isLinkPillContentEqual(make('#abcdef'), make('#123456'))).toBe(false);
expect(isLinkPillContentEqual(make(), make('transparent'))).toBe(false);
});

it('passes an inline icon and its tint to native', () => {
const style = normalizeMarkdownStyle({
linkVariants: {
'^app:': {
inlineIcon: { iconUri: 'file:///icon.png', iconTintColor: '#abcdef' },
},
},
});
expect(style.linkVariants[0]?.inlineIcon).toEqual({
iconUri: 'file:///icon.png',
iconTintColor: normalizeColor('#abcdef'),
});
expect(style.linkVariants[0]?.pill.enabled).toBe(false);
expect(
normalizeWebStyle({
linkVariants: { '^app:': { inlineIcon: { iconUri: 'icon.png' } } },
}).linkVariants[0]?.inlineIcon
).toEqual({ iconUri: 'icon.png', iconTintColor: undefined });
});

it.each([true, {}])('drops the inline icon of a pill variant (%s)', (pill) => {
const style = normalizeMarkdownStyle({
linkVariants: {
'^app:': {
pill,
inlineIcon: { iconUri: 'file:///icon.png', iconTintColor: '#abcdef' },
},
},
});
expect(style.linkVariants[0]?.pill.enabled).toBe(true);
expect(style.linkVariants[0]?.inlineIcon).toEqual({
iconUri: '',
iconTintColor: undefined,
});
});

it('does not reuse a cached style whose variant has the same number of keys', () => {
normalizeMarkdownStyle({ linkVariants: { '^key:': { pill: undefined } } });
expect(
normalizeMarkdownStyle({
linkVariants: { '^key:': { inlineIcon: { iconUri: 'icon.png' } } },
}).linkVariants[0]?.inlineIcon.iconUri
).toBe('icon.png');
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import android.view.ActionMode
import android.view.KeyEvent
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatTextView
import com.swmansion.enriched.markdown.spans.LinkIconSpan
import com.swmansion.enriched.markdown.spans.LinkPillSpan
import com.swmansion.enriched.markdown.spans.TextBackgroundDrawer
import com.swmansion.enriched.markdown.utils.text.span.prepareWidthAwareSpans
Expand Down Expand Up @@ -73,6 +74,7 @@ abstract class AccessibleMarkdownTextView
val contentWidth = width - compoundPaddingLeft - compoundPaddingRight
if (contentWidth > 0) prepareWidthAwareSpans(text, contentWidth)
LinkPillSpan.registerView(text, this)
LinkIconSpan.registerView(text, this)
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@ package com.swmansion.enriched.markdown.renderer

import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.CharacterStyle
import android.text.style.ReplacementSpan
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
import com.swmansion.enriched.markdown.spans.LinkFontSpan
import com.swmansion.enriched.markdown.spans.LinkIconSpan
import com.swmansion.enriched.markdown.spans.LinkPillSpan
import com.swmansion.enriched.markdown.spans.LinkSpan
import com.swmansion.enriched.markdown.spans.SpoilerSpan
import com.swmansion.enriched.markdown.utils.text.extensions.applyBlockStyleFont
import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
import java.text.BreakIterator
import kotlin.math.max
import kotlin.math.min

private const val MAX_ICON_RUN = 24

class LinkRenderer(
private val config: RendererConfig,
Expand All @@ -28,6 +36,19 @@ class LinkRenderer(

factory.renderWithSpan(builder, { factory.renderChildren(node, builder, onLinkPress, onLinkLongPress) }) { start, end, blockStyle ->
val variant = factory.styleCache.resolvedVariantForUrl(url)
val inlineIcon = variant?.inlineIcon?.takeIf { builder.getSpans(start, end, ReplacementSpan::class.java).isEmpty() }
val linkSpan =
LinkSpan(
url,
onLinkPress,
onLinkLongPress,
factory.styleCache,
blockStyle,
factory.context,
recognizedLink = recognizedLink,
keepsCodeFont = recognizedLink && node.children.any { it.type == MarkdownASTNode.NodeType.Code },
appliesFont = inlineIcon == null,
)
if (variant?.pill != null && canPresentAsPill(builder, factory, start, end)) {
val fontFamily = variant.fontFamily.ifEmpty { factory.styleCache.linkFontFamily }.ifEmpty { blockStyle.fontFamily }
val font = fontProbe.apply { applyBlockStyleFont(blockStyle.copy(fontFamily = fontFamily), factory.context) }
Expand All @@ -46,23 +67,76 @@ class LinkRenderer(
// need to come after the block spans, and a late insertion makes the builder re-sort.
builder.setSpan(pill, start, end, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE)
factory.runAfterRender { text -> pill.resolveLeadingMargin(text, text.getSpanStart(pill), text.getSpanEnd(pill)) }
} else if (inlineIcon != null) {
// The link font is applied while measuring, not only while drawing, so the text wraps where it
// is drawn. Set after the children's spans: their fonts lose to the link's, an enclosing
// bold or italic set later still applies.
builder.setSpan(LinkFontSpan(linkSpan), start, end, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE)
// Leading whitespace can sit in a run of its own (a soft line break), and a replacement
// spanning two runs is drawn once per run, so the icon starts at the first visible character.
val iconStart = (start until end).firstOrNull { !builder[it].isWhitespace() }
if (iconStart != null) {
val icon = LinkIconSpan(inlineIcon, linkSpan, blockStyle.fontSize, factory.context, config.style.imageRequestHeaders)
builder.setSpan(icon, iconStart, iconRunEnd(builder, iconStart, end), SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE)
factory.runAfterRender {
val iconSpanStart = builder.getSpanStart(icon)
if (iconSpanStart < 0) return@runAfterRender
// Bidi layout treats a replacement span as neutral, so in a paragraph with right-to-left
// text the covered word could move, or set the paragraph's direction. There the link
// keeps its text without the icon.
if (paragraphHasRightToLeft(builder, iconSpanStart)) {
builder.removeSpan(icon)
return@runAfterRender
}
// Deferred spans (superscript) are in place only now, and their edges end the icon too.
val iconSpanEnd = iconRunEnd(builder, iconSpanStart, builder.getSpanEnd(linkSpan))
if (iconSpanEnd != builder.getSpanEnd(icon)) builder.setSpan(icon, iconSpanStart, iconSpanEnd, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE)
}
}
}
builder.setSpan(
LinkSpan(
url,
onLinkPress,
onLinkLongPress,
factory.styleCache,
blockStyle,
factory.context,
recognizedLink = recognizedLink,
keepsCodeFont = recognizedLink && node.children.any { it.type == MarkdownASTNode.NodeType.Code },
),
start,
end,
SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE,
)
builder.setSpan(linkSpan, start, end, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE)
}
}

/**
* Where the icon span that starts at [start] ends: the first point the line may break, so the
* icon stays with its first word. A line can break on either side of a replacement span, so
* covering less would let that word split after its first letter. Stops where any text style
* changes, since a replacement is measured once per run and drawn with one paint, and after
* [MAX_ICON_RUN] characters, so a long unbroken token still wraps.
*/
private fun iconRunEnd(
builder: SpannableStringBuilder,
start: Int,
end: Int,
): Int {
val text = builder.subSequence(start, end).toString()
val characters = BreakIterator.getCharacterInstance().apply { setText(text) }
val firstCharacter = characters.following(0).takeIf { it != BreakIterator.DONE } ?: text.length
val lines = BreakIterator.getLineInstance().apply { setText(text) }
var wordEnd = lines.following(0).takeIf { it != BreakIterator.DONE } ?: text.length
while (wordEnd > firstCharacter && text[wordEnd - 1].isWhitespace()) wordEnd--
val limit = min(builder.nextSpanTransition(start, end, CharacterStyle::class.java) - start, MAX_ICON_RUN)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
var runEnd = min(wordEnd, limit)
if (runEnd > firstCharacter && !characters.isBoundary(runEnd)) runEnd = characters.preceding(runEnd)
return start + max(firstCharacter, runEnd)
}

private fun paragraphHasRightToLeft(
text: CharSequence,
position: Int,
): Boolean {
if (position < 0) return false
var index = position
while (index > 0 && text[index - 1] != '\n') index--
while (index < text.length && text[index] != '\n') {
val codePoint = Character.codePointAt(text, index)
when (Character.getDirectionality(codePoint)) {
Character.DIRECTIONALITY_RIGHT_TO_LEFT, Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC -> return true
}
index += Character.charCount(codePoint)
}
return false
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import com.swmansion.enriched.markdown.parser.MarkdownASTNode
import com.swmansion.enriched.markdown.parser.MarkdownASTNode.NodeType
import com.swmansion.enriched.markdown.renderer.Renderer
import com.swmansion.enriched.markdown.spans.ImageSpan
import com.swmansion.enriched.markdown.spans.LinkIconSpan
import com.swmansion.enriched.markdown.spans.LinkPillSpan
import com.swmansion.enriched.markdown.spans.TextBackgroundDrawer
import com.swmansion.enriched.markdown.spoiler.SpoilerCapable
Expand Down Expand Up @@ -418,6 +419,7 @@ class TableContainerView(
.getSpans(0, data.attributedText.length, ImageSpan::class.java)
.forEach { span -> span.registerTextView(cellTextView) { scheduleImageRemeasure() } }
LinkPillSpan.registerView(data.attributedText, cellTextView) { scheduleImageRemeasure() }
LinkIconSpan.registerView(data.attributedText, cellTextView) { scheduleImageRemeasure() }
}

private var imageRemeasurePending = false
Expand Down
Loading