Files
Mohamed Boudra 80c44321cc Move the Markdown engine into the repository and fix two Android list layouts (#10499)
* chore(app): vendor react-native-enriched-markdown with the Paseo patch applied

Copy react-native-enriched-markdown@1.2.0-nightly-20261014-766fc0e67 (upstream
software-mansion/enriched-markdown 766fc0e67) into
packages/react-native-enriched-markdown, with
patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch
applied. Nothing else changes in this commit; the package is not a workspace yet.

Reproduce:

  npm pack react-native-enriched-markdown@1.2.0-nightly-20261014-766fc0e67
  tar xzf react-native-enriched-markdown-*.tgz
  mkdir -p t/node_modules && mv package t/node_modules/react-native-enriched-markdown
  (cd t && git init -q && git apply ../patches/react-native-enriched-markdown+*.patch)
  diff -r t/node_modules/react-native-enriched-markdown packages/react-native-enriched-markdown

The diff is empty.

* chore(app): consume react-native-enriched-markdown from its workspace

Make packages/react-native-enriched-markdown a private workspace and point the
app at it, then remove the patch-package patch it replaces.

- package.json: private, version follows the root like every workspace, only the
  postinstall script that downloads tree-sitter grammars. Upstream's
  devDependencies would install a second react-native, so they are gone.
- The package keeps its name, so autolinking, the Gradle project
  :react-native-enriched-markdown, the CocoaPods spec and imports are unchanged.
- Lockfile: drop the nested registry copy under packages/app/node_modules; npm
  links node_modules/react-native-enriched-markdown to the workspace.
- Formatting, lint and knip skip the vendored code. CI routes changes to it
  through the app and browser suites.
- The codegen test checks the vendored package's generated props.
- docs/markdown-renderer.md describes the fork and how to edit it.

* fix(app): keep numbered sub-list markers off their text on Android

From #9964, moved from the package patch into the vendored package.

On Android, a numbered list nested in a bulleted item drew "1." over
the first letters of each item. A nested item's text indent summed the
root list's narrow bullet column with a fixed marginLeft, while its
marker was right-aligned to its own wider "99." column, so the number
landed on the text. iOS already indents from the item's own column.

Backport the Android hunks of upstream enriched-markdown #1015 (size
the number column to the widest marker) and #1023 (nested items start
their text from their own marker column).

test:android now also runs the backported ListRenderingTest and
TaskListInteractionTest suites. docs/markdown-renderer.md lists the
fork's backports, this one and #924, which the removed postinstall
comment used to track.

The vendored tree equals the #9964 patch applied to the pristine
package.

* fix(app): keep Android assistant replies inside their turns

From #10380, moved from the package patch into the vendored package.

On Android, an assistant reply with blockquotes nested inside a list
could overlap its "Worked for ..." footer and the next user message:
the displayed text and the layout measurement applied spans in
different orders, and the list-wide line height inflated the blockquote
spacers when it ran after them.

Use the same span order for Android Markdown measurement and display.
Apply list line height before blockquote spacers so nested quotes keep
their configured padding and the reply fits above the turn footer.

test:android now also runs ListBlockquoteMeasurementTest.

Applied on top of #9964; the two changes share only ListRenderer.kt,
where #10380's import and line-height call sit beside #9964's marker
width code. Every other file equals the #10380 patch applied to the
pristine package.

* chore(app): match the vendored Markdown web block renderer source to its build

The package patch changed lib/module/web/renderers/BlockRenderers.js (the
renderers.codeBlock override and the zoom-in cursor on images) but not
src/web/renderers/BlockRenderers.tsx. The app runs lib, so behavior does
not change. Port both changes into src so src stays the source of lib.
2026-11-23 10:15:43 +07:00

314 lines
10 KiB
Objective-C

#import "ENRMMathContainerView.h"
#import "ENRMAccessibilityLabels.h"
#import "ENRMFeatureFlags.h"
#import "ENRMHorizontalScrollView.h"
#include <TargetConditionals.h>
#if ENRICHED_MARKDOWN_MATH
#import "ENRMMathFallback.h"
#import "PasteboardUtils.h"
#if __has_include("ReactNativeEnrichedMarkdown-Swift.h")
#import "ReactNativeEnrichedMarkdown-Swift.h"
#elif __has_include(<ReactNativeEnrichedMarkdown/ReactNativeEnrichedMarkdown-Swift.h>)
#import <ReactNativeEnrichedMarkdown/ReactNativeEnrichedMarkdown-Swift.h>
#endif
#if TARGET_OS_OSX
#import "ENRMMenuAction.h"
#endif
#endif
#if ENRICHED_MARKDOWN_MATH
@interface ENRMRaTeXCanvasView : RCTUIView
@property (nonatomic, strong, nullable) ENRMRaTeXRenderResult *renderResult;
// Visible-source fallback when RaTeX cannot parse the block, drawn wrapped;
// see ENRMMathFallback.h.
@property (nonatomic, strong, nullable) NSAttributedString *fallbackSource;
@end
@implementation ENRMRaTeXCanvasView
- (void)drawRect:(CGRect)rect
{
if (!_renderResult) {
if (_fallbackSource) {
[_fallbackSource drawWithRect:self.bounds options:NSStringDrawingUsesLineFragmentOrigin context:nil];
}
return;
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
if (!ctx)
return;
[_renderResult drawIn:ctx];
}
- (CGSize)intrinsicContentSize
{
if (!_renderResult)
return CGSizeZero;
return CGSizeMake(ceil(_renderResult.width), ceil(_renderResult.totalHeight));
}
@end
#if !TARGET_OS_OSX
@interface ENRMMathContainerView () <UIContextMenuInteractionDelegate>
@property (nonatomic, strong, readonly) ENRMHorizontalScrollView *scrollView;
#else
@interface ENRMMathContainerView ()
#endif
@property (nonatomic, strong, readonly) ENRMRaTeXCanvasView *mathView;
@property (nonatomic, copy, readwrite) NSString *cachedLatex;
@end
@implementation ENRMMathContainerView {
BOOL _parseFailed;
NSString *_parseMessage;
}
- (void)reportLatexErrorIfNeeded
{
if (_parseFailed && self.onLatexError) {
self.onLatexError(_cachedLatex, _parseMessage ?: @"", YES);
}
}
- (instancetype)initWithConfig:(StyleConfig *)config
{
self = [super initWithFrame:CGRectZero];
if (self) {
_config = config;
_cachedLatex = @"";
_dynamicProps = [[ENRMDynamicBlockProps alloc] init];
_mathView = [[ENRMRaTeXCanvasView alloc] initWithFrame:CGRectZero];
_mathView.backgroundColor = [RCTUIColor clearColor];
#if !TARGET_OS_OSX
_scrollView = [[ENRMHorizontalScrollView alloc] init];
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.showsHorizontalScrollIndicator = YES;
_scrollView.alwaysBounceHorizontal = NO;
_scrollView.scrollEnabled = NO;
[self addSubview:_scrollView];
[_scrollView addSubview:_mathView];
self.isAccessibilityElement = YES;
UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self];
[self addInteraction:contextMenu];
#else
[self addSubview:_mathView];
#endif
}
return self;
}
- (void)applyLatex:(NSString *)latex
{
_cachedLatex = [latex copy];
_parseFailed = NO;
_parseMessage = nil;
StyleConfig *config = self.config;
NSError *error = nil;
ENRMRaTeXRenderResult *result = [ENRMRaTeXBridge parse:latex
displayMode:YES
fontSize:config.mathFontSize
color:config.mathColor
error:&error];
if (!result) {
_parseFailed = YES;
_parseMessage = error.localizedDescription ?: @"";
[self reportLatexErrorIfNeeded];
}
_mathView.renderResult = result;
_mathView.fallbackSource = result ? nil : ENRMMathFallbackString(latex, @"$$", config.mathFontSize, config.mathColor);
CGFloat padding = config.mathPadding;
_mathView.frame = CGRectMake(padding, padding, ceil(result.width), ceil(result.totalHeight));
self.backgroundColor = config.mathBackgroundColor;
[_mathView invalidateIntrinsicContentSize];
#if !TARGET_OS_OSX
[_mathView setNeedsDisplay];
#else
[_mathView setNeedsDisplay:YES];
#endif
[self setNeedsLayout];
}
#if !TARGET_OS_OSX
- (UIContextMenuConfiguration *)contextMenuInteraction:(UIContextMenuInteraction *)interaction
configurationForMenuAtLocation:(CGPoint)location
{
if (!self.dynamicProps.enableBlockContextMenu) {
return nil;
}
return [UIContextMenuConfiguration
configurationWithIdentifier:nil
previewProvider:nil
actionProvider:^UIMenu *(NSArray<UIMenuElement *> *suggestedActions) {
UIAction *copyPlainText =
[UIAction actionWithTitle:self.dynamicProps.menuCopyLabel
image:[RCTUIImage systemImageNamed:@"doc.on.doc"]
identifier:nil
handler:^(__kindof UIAction *action) { [self copyLatexToPasteboard]; }];
UIAction *copyMarkdown =
[UIAction actionWithTitle:self.dynamicProps.menuCopyAsMarkdownLabel
image:[RCTUIImage systemImageNamed:@"doc.text"]
identifier:nil
handler:^(__kindof UIAction *action) { [self copyMarkdownToPasteboard]; }];
return [UIMenu menuWithTitle:@"" children:@[ copyPlainText, copyMarkdown ]];
}];
}
#endif
#if TARGET_OS_OSX
- (NSMenu *)menuForEvent:(NSEvent *)event
{
if (!self.dynamicProps.enableBlockContextMenu) {
return nil;
}
NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
[menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyLabel, ^{ [self copyLatexToPasteboard]; })];
[menu addItem:ENRMCreateMenuItem(self.dynamicProps.menuCopyAsMarkdownLabel, ^{ [self copyMarkdownToPasteboard]; })];
return menu;
}
#endif
- (void)copyLatexToPasteboard
{
copyStringToPasteboard(_cachedLatex);
}
- (void)copyMarkdownToPasteboard
{
copyStringToPasteboard([NSString stringWithFormat:@"$$\n%@\n$$", _cachedLatex]);
}
- (CGSize)mathViewIntrinsicSize
{
return _mathView.intrinsicContentSize;
}
- (CGFloat)measureHeight:(CGFloat)maxWidth
{
CGFloat padding = self.config.mathPadding;
if (!_mathView.renderResult && _mathView.fallbackSource) {
CGFloat available = MAX(maxWidth - padding * 2, 1);
CGRect bounds = [_mathView.fallbackSource boundingRectWithSize:CGSizeMake(available, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return ceil(bounds.size.height) + padding * 2;
}
return [self mathViewIntrinsicSize].height + padding * 2;
}
+ (CGFloat)measureHeightForLatex:(NSString *)latex config:(StyleConfig *)config maxWidth:(CGFloat)maxWidth
{
CGFloat padding = config.mathPadding;
ENRMRaTeXRenderResult *result = [ENRMRaTeXBridge parse:latex
displayMode:YES
fontSize:config.mathFontSize
color:config.mathColor];
if (result) {
return ceil(result.totalHeight) + padding * 2;
}
NSAttributedString *fallbackSource = ENRMMathFallbackString(latex, @"$$", config.mathFontSize, config.mathColor);
if (!fallbackSource) {
return 0;
}
CGFloat available = MAX(maxWidth - padding * 2, 1);
CGRect bounds = [fallbackSource boundingRectWithSize:CGSizeMake(available, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return ceil(bounds.size.height) + padding * 2;
}
- (CGFloat)alignedOriginXForWidth:(CGFloat)formulaWidth inBounds:(CGFloat)boundsWidth padding:(CGFloat)padding
{
CGFloat available = boundsWidth - padding * 2;
if (formulaWidth >= available)
return padding;
NSString *align = self.config.mathTextAlign;
if ([align isEqualToString:@"left"])
return padding;
if ([align isEqualToString:@"right"])
return padding + available - formulaWidth;
return padding + (available - formulaWidth) / 2.0;
}
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat padding = self.config.mathPadding;
if (!_mathView.renderResult && _mathView.fallbackSource) {
// Fallback source fills the available width and wraps; no horizontal scroll.
#if !TARGET_OS_OSX
_scrollView.frame = self.bounds;
_scrollView.contentSize = self.bounds.size;
_scrollView.contentOffset = CGPointZero;
_scrollView.scrollEnabled = NO;
#endif
_mathView.frame = CGRectMake(padding, padding, MAX(self.bounds.size.width - padding * 2, 1),
MAX(self.bounds.size.height - padding * 2, 1));
#if !TARGET_OS_OSX
[_mathView setNeedsDisplay];
#else
[_mathView setNeedsDisplay:YES];
#endif
return;
}
CGSize intrinsicSize = [self mathViewIntrinsicSize];
CGFloat contentWidth = intrinsicSize.width + padding * 2;
CGFloat contentHeight = self.bounds.size.height;
BOOL overflows = contentWidth > self.bounds.size.width;
CGFloat originX = [self alignedOriginXForWidth:intrinsicSize.width inBounds:self.bounds.size.width padding:padding];
#if !TARGET_OS_OSX
_scrollView.frame = self.bounds;
_scrollView.contentSize = CGSizeMake(overflows ? contentWidth : self.bounds.size.width, contentHeight);
_scrollView.scrollEnabled = overflows;
_mathView.frame = CGRectMake(originX, padding, intrinsicSize.width, intrinsicSize.height);
#else
_mathView.frame = CGRectMake(originX, padding, intrinsicSize.width, intrinsicSize.height);
[_mathView setNeedsDisplay:YES];
#endif
}
#if TARGET_OS_OSX
- (void)layout
{
[super layout];
[self layoutSubviews];
}
#endif
- (NSString *)accessibilityLabel
{
return [_accessibilityLabels.mathEquation stringByReplacingOccurrencesOfString:@"{latex}"
withString:_cachedLatex ?: @""];
}
#if !TARGET_OS_OSX
- (UIAccessibilityTraits)accessibilityTraits
{
return UIAccessibilityTraitStaticText;
}
#endif
@end
#endif