react-native-enriched-markdown-scaffold 1.0.2-scaffold.10 → 1.0.2-scaffold.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -663,6 +663,9 @@ class EnrichedMarkdown
663
663
  }
664
664
 
665
665
  is RenderedSegment.Math -> {
666
+ mathContainerClass
667
+ ?.getMethod("setHighlighted", Boolean::class.javaPrimitiveType)
668
+ ?.invoke(view, segment.highlighted)
666
669
  mathContainerClass
667
670
  ?.getMethod("applyLatex", String::class.java)
668
671
  ?.invoke(view, segment.latex)
@@ -806,6 +809,7 @@ class EnrichedMarkdown
806
809
  runCatching {
807
810
  resolvedClass.getMethod("setOnMenuSuppressed", Function2::class.java).invoke(view, onMenuSuppressed)
808
811
  }.onFailure { Log.e(TAG, "Failed to set onMenuSuppressed on math view", it) }
812
+ resolvedClass.getMethod("setHighlighted", Boolean::class.javaPrimitiveType).invoke(view, segment.highlighted)
809
813
  resolvedClass.getMethod("applyLatex", String::class.java).invoke(view, segment.latex)
810
814
  view
811
815
  } catch (e: Exception) {
@@ -13,7 +13,16 @@ class HighlightRenderer : NodeRenderer {
13
13
  onLinkLongPress: ((String) -> Unit)?,
14
14
  factory: RendererFactory,
15
15
  ) {
16
- factory.renderWithSpan(builder, { factory.renderChildren(node, builder, onLinkPress, onLinkLongPress) }) { start, end, blockStyle ->
16
+ val renderChildren = {
17
+ val wasInHighlight = factory.inHighlight
18
+ factory.inHighlight = true
19
+ try {
20
+ factory.renderChildren(node, builder, onLinkPress, onLinkLongPress)
21
+ } finally {
22
+ factory.inHighlight = wasInHighlight
23
+ }
24
+ }
25
+ factory.renderWithSpan(builder, renderChildren) { start, end, blockStyle ->
17
26
  builder.setSpan(
18
27
  HighlightSpan(factory.styleCache, blockStyle),
19
28
  start,
@@ -32,6 +32,13 @@ class RendererFactory(
32
32
 
33
33
  val styleCache = SpanStyleCache(config.style)
34
34
 
35
+ /**
36
+ * Rendering inside a `==…==` span: a formula there takes the highlight colour, which a
37
+ * span over the text cannot give it. Read by the maths renderer, which lives in the
38
+ * optional math source set and cannot be reached from [HighlightRenderer].
39
+ */
40
+ var inHighlight: Boolean = false
41
+
35
42
  /**
36
43
  * Spans registered here are applied after the full document tree is rendered, so they
37
44
  * always end up after block-level spans in the SpannableStringBuilder's internal array.
@@ -63,6 +70,7 @@ class RendererFactory(
63
70
  fun resetForNewRender() {
64
71
  blockStyleContext.resetForNewRender()
65
72
  deferredSpans.clear()
73
+ inHighlight = false
66
74
  }
67
75
 
68
76
  fun createImageSpan(
@@ -25,6 +25,7 @@ sealed interface RenderedSegment {
25
25
 
26
26
  data class Math(
27
27
  val latex: String,
28
+ val highlighted: Boolean,
28
29
  override val signature: Long,
29
30
  ) : RenderedSegment
30
31
 
@@ -56,7 +57,10 @@ object MarkdownSegmentRenderer {
56
57
  is MarkdownSegment.Math -> {
57
58
  var signature = SegmentSignature.signatureForNode(null) xor SegmentSignature.MATH_KIND_SALT
58
59
  signature = SegmentSignature.fnvMixString(signature, segment.latex)
59
- RenderedSegment.Math(segment.latex, signature)
60
+ val highlighted = segment.node.getAttribute("highlight") == "true"
61
+ // A highlight toggle keeps the latex, so it must change the signature or the view is skipped.
62
+ if (highlighted) signature = SegmentSignature.fnvMixString(signature, "highlight")
63
+ RenderedSegment.Math(segment.latex, highlighted, signature)
60
64
  }
61
65
 
62
66
  is MarkdownSegment.CodeBlock -> {
@@ -24,6 +24,9 @@ class MathInlineRenderer(
24
24
  if (latex.isEmpty()) return
25
25
 
26
26
  val blockStyle = factory.blockStyleContext.requireBlockStyle()
27
+ val mathColor = config.style.inlineMathStyle.color
28
+ // Inside `==…==` the formula takes the highlight colour, by the rule text follows.
29
+ val textColor = if (factory.inHighlight) factory.styleCache.getHighlightColorFor(mathColor) else mathColor
27
30
 
28
31
  val start = builder.length
29
32
  builder.append("\uFFFC")
@@ -34,7 +37,7 @@ class MathInlineRenderer(
34
37
  context = context,
35
38
  latex = latex,
36
39
  fontSize = blockStyle.fontSize,
37
- textColor = config.style.inlineMathStyle.color,
40
+ textColor = textColor,
38
41
  paddingVertical = config.style.inlineMathStyle.paddingVertical,
39
42
  fontWeight = config.style.inlineMathStyle.fontWeight,
40
43
  glyphOverflow = config.style.inlineMathStyle.glyphOverflow,
@@ -4,6 +4,7 @@ import android.content.ClipData
4
4
  import android.content.ClipboardManager
5
5
  import android.content.Context
6
6
  import android.graphics.Canvas
7
+ import android.graphics.Color
7
8
  import android.util.Log
8
9
  import android.view.Gravity
9
10
  import android.view.View
@@ -60,6 +61,24 @@ class MathContainerView(
60
61
 
61
62
  private val mathView = RaTeXCanvasView(context, mathStyle.glyphOverflow)
62
63
 
64
+ private val highlightBackgroundColor = styleConfig.highlightStyle.backgroundColor
65
+
66
+ // The highlight colour as text resolves it: the paragraph colour left in place means
67
+ // "inherit", which for a formula is its own colour.
68
+ private val highlightColor =
69
+ styleConfig.highlightStyle.color.let { if (it == styleConfig.paragraphStyle.color) mathStyle.color else it }
70
+
71
+ // Set reflectively, before applyLatex: a `==$$…$$==` block washes the formula's own
72
+ // frame and parses the formula in the highlight colour. Changed afterwards, the cached
73
+ // latex is parsed again.
74
+ var highlighted: Boolean = false
75
+ set(value) {
76
+ val changed = field != value
77
+ field = value
78
+ mathView.setBackgroundColor(if (value) highlightBackgroundColor else Color.TRANSPARENT)
79
+ if (changed && cachedLatex.isNotEmpty()) applyLatex(cachedLatex)
80
+ }
81
+
63
82
  init {
64
83
  setBackgroundColor(mathStyle.backgroundColor)
65
84
 
@@ -106,7 +125,8 @@ class MathContainerView(
106
125
  fun applyLatex(latex: String) {
107
126
  cachedLatex = latex
108
127
  try {
109
- val displayList = RaTeXEngine.parseBlocking(latex, displayMode = true, color = mathStyle.color)
128
+ val color = if (highlighted) highlightColor else mathStyle.color
129
+ val displayList = RaTeXEngine.parseBlocking(latex, displayMode = true, color = color)
110
130
  mathView.renderer =
111
131
  RaTeXRenderer(displayList, mathStyle.fontSize, ratexTypefaceLoader(mathStyle.fontWeight))
112
132
  } catch (e: Exception) {
@@ -386,12 +386,31 @@ bool isSeparatorNode(const MarkdownASTNode &node) {
386
386
  (node.type == NodeType::Text && node.content.find_first_not_of(" \t\n\r") == std::string::npos);
387
387
  }
388
388
 
389
+ // The display math a paragraph child stands for: the node itself, or the one display-math
390
+ // node a `==$$x$$==` highlight wraps. The highlight cannot survive promotion as a span
391
+ // (a block is not inline text), so the caller carries it over as the `highlight` attribute.
392
+ std::shared_ptr<MarkdownASTNode> displayMathOf(const std::shared_ptr<MarkdownASTNode> &node) {
393
+ if (isDisplayMathNode(*node))
394
+ return node;
395
+ if (node->type != NodeType::Highlight)
396
+ return nullptr;
397
+ std::shared_ptr<MarkdownASTNode> math;
398
+ for (const auto &child : node->children) {
399
+ if (isSeparatorNode(*child))
400
+ continue;
401
+ if (math || !isDisplayMathNode(*child))
402
+ return nullptr;
403
+ math = child;
404
+ }
405
+ return math;
406
+ }
407
+
389
408
  // A display-math node is "isolated" — i.e. block-level — when at least one of its
390
409
  // neighbours is a boundary: the paragraph edge, or a separator (LineBreak / blank
391
410
  // text). Display math flanked by real text on BOTH sides (e.g. `a $$x$$ b`) is
392
411
  // genuinely inline and is left in place.
393
412
  bool isIsolatedDisplayMath(const std::vector<std::shared_ptr<MarkdownASTNode>> &children, size_t i) {
394
- if (!isDisplayMathNode(*children[i]))
413
+ if (!displayMathOf(children[i]))
395
414
  return false;
396
415
  bool leftBoundary = (i == 0) || isSeparatorNode(*children[i - 1]);
397
416
  bool rightBoundary = (i + 1 >= children.size()) || isSeparatorNode(*children[i + 1]);
@@ -446,7 +465,10 @@ splitParagraphAroundDisplayMath(const std::vector<std::shared_ptr<MarkdownASTNod
446
465
  for (size_t i = 0; i < children.size(); ++i) {
447
466
  if (isIsolatedDisplayMath(children, i)) {
448
467
  flushInlineRun();
449
- result.push_back(children[i]);
468
+ auto math = displayMathOf(children[i]);
469
+ if (math != children[i])
470
+ math->setAttribute("highlight", "true");
471
+ result.push_back(math);
450
472
  } else {
451
473
  inlineRun.push_back(children[i]);
452
474
  }
@@ -405,7 +405,10 @@ static char kENRMSegmentFadeAnimatorKey;
405
405
  return view;
406
406
  }
407
407
  updateView:^(RCTUIView *view, ENRMRenderedSegment *segment) {
408
- [(ENRMMathContainerView *)view applyLatex:((ENRMMathSegment *)segment.mathSegment).latex];
408
+ ENRMMathSegment *mathSegment = (ENRMMathSegment *)segment.mathSegment;
409
+ ENRMMathContainerView *mathView = (ENRMMathContainerView *)view;
410
+ mathView.highlighted = mathSegment.highlighted;
411
+ [mathView applyLatex:mathSegment.latex];
409
412
  }]];
410
413
  #endif
411
414
 
@@ -1020,6 +1023,7 @@ static char kENRMSegmentFadeAnimatorKey;
1020
1023
  mathView.menuOptions = [self blockMenuOptions];
1021
1024
  mathView.onCopyRequest = [self blockCopyRequestForSource:@"math"];
1022
1025
  mathView.onMenuSuppressed = [self blockMenuSuppressedForSource:@"math" view:mathView];
1026
+ mathView.highlighted = mathSegment.highlighted;
1023
1027
  [mathView applyLatex:mathSegment.latex];
1024
1028
  return mathView;
1025
1029
  }
@@ -27,7 +27,14 @@
27
27
  ENRMMathInlineAttachment *attachment = [[ENRMMathInlineAttachment alloc] init];
28
28
  attachment.latex = latex;
29
29
  attachment.fontSize = currentFont ? currentFont.pointSize : [_config paragraphFontSize];
30
- attachment.mathTextColor = [_config inlineMathColor];
30
+ RCTUIColor *mathColor = [_config inlineMathColor];
31
+ if (context.inHighlight) {
32
+ mathColor = [RenderContext calculateHighlightColor:[_config highlightColor]
33
+ paragraphColor:[_config paragraphColor]
34
+ blockColor:mathColor]
35
+ ?: mathColor;
36
+ }
37
+ attachment.mathTextColor = mathColor;
31
38
  attachment.containerPaddingVertical = [_config inlineMathPaddingVertical];
32
39
  attachment.bold = ENRMMathFontWeightIsBold([_config inlineMathFontWeight]);
33
40
  attachment.glyphOverflow = [_config inlineMathGlyphOverflow];
@@ -10,11 +10,17 @@ NSString *const HighlightAttributeName = @"EnrichedMarkdownHighlight";
10
10
 
11
11
  #pragma mark - Rendering
12
12
 
13
+ - (id)takeContextSnapshot:(RenderContext *)context
14
+ {
15
+ return [context snapshotScope];
16
+ }
17
+
13
18
  - (void)renderNodeContent:(MarkdownASTNode *)node
14
19
  into:(NSMutableAttributedString *)output
15
20
  context:(RenderContext *)context
16
21
  {
17
22
  NSUInteger start = output.length;
23
+ context.inHighlight = YES;
18
24
  [_rendererFactory renderChildrenOfNode:node into:output context:context];
19
25
 
20
26
  NSRange range = NSMakeRange(start, output.length - start);
@@ -45,6 +45,9 @@ typedef NS_ENUM(NSInteger, ListType) { ListTypeUnordered, ListTypeOrdered };
45
45
  @property (nonatomic, assign) BOOL allowFontScaling;
46
46
  @property (nonatomic, assign) CGFloat maxFontSizeMultiplier;
47
47
  @property (nonatomic, assign) NSInteger taskItemCount;
48
+ /// Rendering inside a `==…==` span: a formula there takes the highlight colour,
49
+ /// which the attributed string's foreground cannot give an attachment.
50
+ @property (nonatomic, assign) BOOL inHighlight;
48
51
 
49
52
  - (instancetype)init;
50
53
  - (void)reset;
@@ -25,6 +25,7 @@ static NSArray<NSString *> *ENRMScopedKeyPaths(void)
25
25
  @"listType",
26
26
  @"listItemNumber",
27
27
  @"accumulatedIndent",
28
+ @"inHighlight",
28
29
  ];
29
30
  });
30
31
  return keyPaths;
@@ -301,6 +302,7 @@ static NSArray<NSString *> *ENRMScopedKeyPaths(void)
301
302
  _listItemNumber = 0;
302
303
  _accumulatedIndent = 0;
303
304
  _taskItemCount = 0;
305
+ _inHighlight = NO;
304
306
 
305
307
  // Revert shared style object to baseline defaults
306
308
  _currentBlockStyle.fontSize = 0;
@@ -26,7 +26,8 @@ typedef NS_ENUM(NSInteger, ENRMSegmentKind) {
26
26
 
27
27
  @interface ENRMMathSegment : NSObject
28
28
  @property (nonatomic, strong) NSString *latex;
29
- + (instancetype)segmentWithLatex:(NSString *)latex;
29
+ @property (nonatomic, assign) BOOL highlighted;
30
+ + (instancetype)segmentWithLatex:(NSString *)latex highlighted:(BOOL)highlighted;
30
31
  @end
31
32
 
32
33
  @interface ENRMCodeBlockSegment : NSObject
@@ -22,11 +22,12 @@
22
22
  @end
23
23
 
24
24
  @implementation ENRMMathSegment
25
- + (instancetype)segmentWithLatex:(NSString *)latex
25
+ + (instancetype)segmentWithLatex:(NSString *)latex highlighted:(BOOL)highlighted
26
26
  {
27
27
  NSParameterAssert(latex != nil);
28
28
  ENRMMathSegment *segment = [[ENRMMathSegment alloc] init];
29
29
  segment.latex = latex;
30
+ segment.highlighted = highlighted;
30
31
  return segment;
31
32
  }
32
33
  @end
@@ -26,7 +26,8 @@ static NSArray *ENRMSplitASTIntoSegments(MarkdownASTNode *root)
26
26
  [currentTextNodes removeAllObjects];
27
27
  }
28
28
  NSString *latex = child.children.count > 0 ? child.children.firstObject.content : child.content;
29
- [segments addObject:[ENRMMathSegment segmentWithLatex:latex ?: @""]];
29
+ BOOL highlighted = [child.attributes[@"highlight"] isEqualToString:@"true"];
30
+ [segments addObject:[ENRMMathSegment segmentWithLatex:latex ?: @"" highlighted:highlighted]];
30
31
  #else
31
32
  // TODO: Fix block math rendering on macOS. Adding ENRMMathContainerView as a
32
33
  // segment causes all preceding text segments to become invisible.
@@ -86,6 +87,9 @@ NSArray<ENRMRenderedSegment *> *ENRMRenderSegmentsFromAST(MarkdownASTNode *ast,
86
87
  signature ^= (uint8_t)*utf8++;
87
88
  signature *= 1099511628211ULL;
88
89
  }
90
+ // A highlight toggle keeps the latex, so it must change the signature or the view is skipped.
91
+ signature ^= mathSegment.highlighted ? 1ULL : 0ULL;
92
+ signature *= 1099511628211ULL;
89
93
  [renderedSegments addObject:[ENRMRenderedSegment mathSegmentWithSegment:mathSegment signature:signature]];
90
94
  }
91
95
  #endif
@@ -24,6 +24,11 @@ NS_ASSUME_NONNULL_BEGIN
24
24
  + (CGFloat)measureHeightForLatex:(NSString *)latex config:(StyleConfig *)config maxWidth:(CGFloat)maxWidth;
25
25
 
26
26
  @property (nonatomic, strong) StyleConfig *config;
27
+
28
+ /// A `==$$…$$==` block: the formula's own frame takes the highlight background
29
+ /// and the formula the highlight colour. Set it before `applyLatex:`; a change
30
+ /// afterwards parses the cached latex again.
31
+ @property (nonatomic, assign) BOOL highlighted;
27
32
  @property (nonatomic, copy, readonly) NSString *cachedLatex;
28
33
  @property (nonatomic, strong, nullable) ENRMAccessibilityLabels *accessibilityLabels;
29
34
 
@@ -2,6 +2,7 @@
2
2
  #import "ENRMAccessibilityLabels.h"
3
3
  #import "ENRMFeatureFlags.h"
4
4
  #import "ENRMMathFontWeight.h"
5
+ #import "RenderContext.h"
5
6
  #include <TargetConditionals.h>
6
7
 
7
8
  #if ENRICHED_MARKDOWN_MATH
@@ -94,20 +95,43 @@
94
95
  return self;
95
96
  }
96
97
 
98
+ - (void)setHighlighted:(BOOL)highlighted
99
+ {
100
+ BOOL changed = _highlighted != highlighted;
101
+ _highlighted = highlighted;
102
+ _mathView.backgroundColor = highlighted ? self.config.highlightBackgroundColor : [RCTUIColor clearColor];
103
+ if (changed && _cachedLatex.length > 0) {
104
+ [self applyLatex:_cachedLatex];
105
+ }
106
+ }
107
+
108
+ - (RCTUIColor *)formulaColor
109
+ {
110
+ StyleConfig *config = self.config;
111
+ if (!_highlighted) {
112
+ return config.mathColor;
113
+ }
114
+ return [RenderContext calculateHighlightColor:config.highlightColor
115
+ paragraphColor:config.paragraphColor
116
+ blockColor:config.mathColor]
117
+ ?: config.mathColor;
118
+ }
119
+
97
120
  - (void)applyLatex:(NSString *)latex
98
121
  {
99
122
  _cachedLatex = [latex copy];
100
123
 
101
124
  StyleConfig *config = self.config;
125
+ RCTUIColor *color = [self formulaColor];
102
126
 
103
127
  ENRMRaTeXRenderResult *result = [ENRMRaTeXBridge parse:latex
104
128
  displayMode:YES
105
129
  fontSize:config.mathFontSize
106
- color:config.mathColor
130
+ color:color
107
131
  bold:ENRMMathFontWeightIsBold(config.mathFontWeight)
108
132
  glyphOverflow:config.mathGlyphOverflow];
109
133
  _mathView.renderResult = result;
110
- _mathView.fallbackSource = result ? nil : ENRMMathFallbackString(latex, @"$$", config.mathFontSize, config.mathColor);
134
+ _mathView.fallbackSource = result ? nil : ENRMMathFallbackString(latex, @"$$", config.mathFontSize, color);
111
135
 
112
136
  CGFloat padding = config.mathPadding;
113
137
  _mathView.frame = CGRectMake(padding, padding, ceil(result.width), ceil(result.totalHeight));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-enriched-markdown-scaffold",
3
- "version": "1.0.2-scaffold.10",
3
+ "version": "1.0.2-scaffold.12",
4
4
  "description": "Markdown-based Rich Text solution for React Native",
5
5
  "main": "./lib/module/index",
6
6
  "module": "./lib/module/index",