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

280 lines
10 KiB
Objective-C

#import "ListItemRenderer.h"
#import "BlockquoteBorder.h"
#import "ENRMUIKit.h"
#import "LastElementUtils.h"
#import "MarkdownASTNode.h"
#import "ParagraphStyleUtils.h"
#import "RenderContext.h"
#import "RendererFactory.h"
#import "StyleConfig.h"
NSString *const ListDepthAttribute = @"ListDepth";
NSString *const ListTypeAttribute = @"ListType";
NSString *const ListItemNumberAttribute = @"ListItemNumber";
NSString *const ListItemMarkerStartAttribute = @"ListItemMarkerStart";
NSString *const TaskItemAttribute = @"TaskItem";
NSString *const TaskCheckedAttribute = @"TaskChecked";
NSString *const TaskIndexAttribute = @"TaskIndex";
@implementation ENRMListMarkerDescriptor
@end
// NSArray's -hash is its count, so plain one-marker arrays all collide in the
// table that uniques attribute dictionaries, and each list item probes past
// every earlier one. Hashing by the item's own marker keeps rendering linear.
@interface ENRMListMarkerArray : NSArray
@end
@implementation ENRMListMarkerArray {
NSArray<ENRMListMarkerDescriptor *> *_markers;
}
- (instancetype)initWithMarkers:(NSArray<ENRMListMarkerDescriptor *> *)markers
{
if (self = [super init]) {
_markers = [markers copy];
}
return self;
}
- (NSUInteger)count
{
return _markers.count;
}
- (id)objectAtIndex:(NSUInteger)index
{
return _markers[index];
}
- (NSUInteger)hash
{
return _markers.lastObject.hash;
}
@end
@interface ListItemRenderer ()
- (void)applyCheckedDecorationsTo:(NSMutableAttributedString *)output
range:(NSRange)range
nestingLevel:(NSInteger)nestingLevel;
@end
@implementation ListItemRenderer
- (void)renderNodeContent:(MarkdownASTNode *)node
into:(NSMutableAttributedString *)output
context:(RenderContext *)context
{
if (!context)
return;
context.listItemNumber++;
const NSInteger currentPosition = context.listItemNumber;
const NSInteger currentDepth = context.listDepth; // 1-based (1 = top level)
const BOOL isTask = [node.attributes[@"isTask"] isEqualToString:@"true"];
const BOOL isChecked = isTask && [node.attributes[@"taskChecked"] isEqualToString:@"true"];
NSInteger taskIndex = -1;
if (isTask) {
taskIndex = context.taskItemCount;
context.taskItemCount++;
}
// currentDepth - 1 handles the horizontal offset for nested lists
const NSInteger nestingLevel = currentDepth - 1;
const CGFloat baseMarkerWidth = isTask ? [_config effectiveListMarginLeftForTask]
: (context.listType == ListTypeOrdered) ? [_config effectiveListMarginLeftForNumber]
: [_config effectiveListMarginLeftForBullet];
const CGFloat blockquoteIndent =
blockquoteIndentForDepth(context.blockquoteDepth, [_config blockquoteBorderWidth] + [_config blockquoteGapWidth]);
const CGFloat totalIndent = blockquoteIndent + baseMarkerWidth + [_config effectiveListGapWidth] +
(nestingLevel * [_config listStyleMarginLeft]);
const NSUInteger startLocation = output.length;
// Manual save/restore — a scope snapshot would also roll back the listItemNumber increment
const CGFloat prevIndent = context.accumulatedIndent;
context.accumulatedIndent = totalIndent;
@try {
[_rendererFactory renderChildrenOfNode:node into:output context:context];
} @finally {
context.accumulatedIndent = prevIndent;
}
// Ensure every list item ends with a newline to prevent paragraph merging
if (output.length > startLocation && ![output.string hasSuffix:@"\n"]) {
[output appendAttributedString:kNewlineAttributedString];
}
const NSRange itemRange = NSMakeRange(startLocation, output.length - startLocation);
if (itemRange.length == 0)
return;
// Informs MarkdownAccessibilityElementBuilder about the specific boundaries of this list item
[context registerListItemRange:itemRange
position:currentPosition
depth:currentDepth
isOrdered:(context.listType == ListTypeOrdered)];
const CGFloat lineHeightConfig = [_config listStyleLineHeight];
// Boxing metadata for attributed string storage
NSMutableDictionary *metadata = [@{
ListDepthAttribute : @(nestingLevel),
ListTypeAttribute : @(context.listType),
ListItemNumberAttribute : @(currentPosition)
} mutableCopy];
if (isTask) {
metadata[TaskItemAttribute] = @YES;
metadata[TaskCheckedAttribute] = @(isChecked);
metadata[TaskIndexAttribute] = @(taskIndex);
}
// Preserve styles of nested sub-lists and code blocks by applying the list
// paragraph style only to the surviving gaps between them.
NSMutableArray<NSValue *> *skipRanges = [NSMutableArray array];
[output enumerateAttribute:CodeBlockAttributeName
inRange:itemRange
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
if ([value boolValue]) {
[skipRanges addObject:[NSValue valueWithRange:range]];
}
}];
[output enumerateAttribute:ListDepthAttribute
inRange:itemRange
options:0
usingBlock:^(id depthAttr, NSRange range, BOOL *stop) {
if (depthAttr && [depthAttr integerValue] > nestingLevel) {
[skipRanges addObject:[NSValue valueWithRange:range]];
}
}];
[skipRanges sortUsingComparator:^NSComparisonResult(NSValue *a, NSValue *b) {
NSUInteger la = [a rangeValue].location;
NSUInteger lb = [b rangeValue].location;
return la < lb ? NSOrderedAscending : (la > lb ? NSOrderedDescending : NSOrderedSame);
}];
void (^applyStyleToRange)(NSRange) = ^(NSRange range) {
if (range.length == 0)
return;
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.firstLineHeadIndent = totalIndent;
style.headIndent = totalIndent;
const CGFloat lineHeight = ENRMLineHeightWithLinkPills(output, range, lineHeightConfig);
if (lineHeight > 0) {
style.minimumLineHeight = lineHeight;
}
NSMutableDictionary *attributesToApply = [metadata mutableCopy];
attributesToApply[NSParagraphStyleAttributeName] = style;
[output addAttributes:attributesToApply range:range];
if (lineHeight > 0) {
applyBaselineOffset(output, range);
}
};
NSUInteger pos = itemRange.location;
const NSUInteger itemEnd = NSMaxRange(itemRange);
for (NSValue *val in skipRanges) {
NSRange skip = [val rangeValue];
if (pos < skip.location) {
applyStyleToRange(NSMakeRange(pos, skip.location - pos));
}
pos = MAX(pos, NSMaxRange(skip));
}
if (pos < itemEnd) {
applyStyleToRange(NSMakeRange(pos, itemEnd - pos));
}
ENRMListMarkerDescriptor *marker = [[ENRMListMarkerDescriptor alloc] init];
marker.isTask = isTask;
marker.isChecked = isChecked;
marker.taskIndex = taskIndex;
marker.listType = context.listType;
marker.number = currentPosition;
marker.depth = nestingLevel;
marker.indent = totalIndent;
// Anchor on the first content character so items that open with a code block
// or nested sublist still get their marker; fall back to startLocation for
// whitespace-only items.
NSUInteger anchorLocation = startLocation;
NSString *string = output.string;
for (NSUInteger i = startLocation; i < itemEnd; i++) {
if ([string characterAtIndex:i] != '\n') {
anchorLocation = i;
break;
}
}
// Cover the whole grapheme cluster: anchoring on a single UTF-16 code unit
// splits multi-unit graphemes (emoji surrogate pairs, ZWJ sequences) across
// two attribute runs, which drops the glyph and hides the marker for every
// item but the last.
const NSRange anchorRange = [string rangeOfComposedCharacterSequenceAtIndex:anchorLocation];
NSArray *existingMarkers = [output attribute:ListItemMarkerStartAttribute atIndex:anchorLocation effectiveRange:NULL];
NSArray *markers =
[existingMarkers isKindOfClass:[NSArray class]] ? [existingMarkers arrayByAddingObject:marker] : @[ marker ];
[output addAttribute:ListItemMarkerStartAttribute
value:[[ENRMListMarkerArray alloc] initWithMarkers:markers]
range:anchorRange];
if (isTask && isChecked) {
[self applyCheckedDecorationsTo:output range:itemRange nestingLevel:nestingLevel];
}
}
- (void)applyCheckedDecorationsTo:(NSMutableAttributedString *)output
range:(NSRange)range
nestingLevel:(NSInteger)nestingLevel
{
RCTUIColor *checkedColor = [_config taskListCheckedTextColor];
BOOL shouldStrikethrough = [_config taskListCheckedStrikethrough];
if (!checkedColor && !shouldStrikethrough) {
return;
}
NSMutableDictionary *checkedAttrs = [NSMutableDictionary dictionary];
if (checkedColor) {
checkedAttrs[NSForegroundColorAttributeName] = checkedColor;
}
if (shouldStrikethrough) {
checkedAttrs[NSStrikethroughStyleAttributeName] = @(NSUnderlineStyleSingle);
RCTUIColor *lineColor = checkedColor ?: [_config listStyleColor];
if (lineColor) {
checkedAttrs[NSStrikethroughColorAttributeName] = lineColor;
}
}
[output enumerateAttribute:ListDepthAttribute
inRange:range
options:0
usingBlock:^(NSNumber *depth, NSRange segmentRange, BOOL *stop) {
BOOL isNestedSubItem = (depth && [depth integerValue] > nestingLevel);
if (isNestedSubItem) {
return;
}
// Skip code block ranges — preserve CodeBlockRenderer styles.
NSNumber *isCodeBlock = [output attribute:CodeBlockAttributeName
atIndex:segmentRange.location
effectiveRange:nil];
if ([isCodeBlock boolValue]) {
return;
}
[output addAttributes:checkedAttrs range:segmentRange];
}];
}
@end