Files
paseo/packages/react-native-enriched-markdown/ios/utils/TaskListTapUtils.m
T
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

251 lines
11 KiB
Objective-C

#import "TaskListTapUtils.h"
#import "ENRMUIKit.h"
#import "LastElementUtils.h"
#import "ListItemRenderer.h"
#import "ParagraphStyleUtils.h"
#import "StyleConfig.h"
#include <TargetConditionals.h>
TaskListHitTestResult taskListHitTest(ENRMPlatformTextView *textView, ENRMTapRecognizer *recognizer)
{
const TaskListHitTestResult notFound = {.found = NO, .index = 0, .checked = NO, .itemRange = {0, 0}};
NSLayoutManager *layoutManager = textView.layoutManager;
NSTextContainer *textContainer = textView.textContainer;
CGPoint tapPoint = [recognizer locationInView:textView];
NSUInteger glyphIndex = [layoutManager glyphIndexForPoint:tapPoint inTextContainer:textContainer];
NSUInteger charIndex = [layoutManager characterIndexForGlyphAtIndex:glyphIndex];
NSAttributedString *attrText = ENRMGetAttributedText(textView);
if (charIndex >= attrText.length) {
return notFound;
}
NSDictionary *attributes = [attrText attributesAtIndex:charIndex effectiveRange:NULL];
BOOL isTaskItem = [attributes[TaskItemAttribute] boolValue];
if (!isTaskItem) {
return notFound;
}
NSParagraphStyle *style = attributes[NSParagraphStyleAttributeName];
CGFloat checkboxWidth = style ? style.firstLineHeadIndent : 0;
BOOL isRTL = ENRMParagraphIsRTL(style);
if (isRTL) {
CGFloat viewWidth = textView.bounds.size.width;
if (tapPoint.x <= viewWidth - checkboxWidth) {
return notFound;
}
} else {
if (tapPoint.x >= checkboxWidth) {
return notFound;
}
}
NSInteger taskIndex = [attributes[TaskIndexAttribute] integerValue];
NSRange fullItemRange = taskListItemFullRange(textView, taskIndex);
if (fullItemRange.location == NSNotFound) {
[attrText attribute:TaskItemAttribute atIndex:charIndex effectiveRange:&fullItemRange];
}
return (TaskListHitTestResult){.found = YES,
.index = taskIndex,
.checked = [attributes[TaskCheckedAttribute] boolValue],
.itemRange = fullItemRange};
}
NSRange taskListItemFullRange(ENRMPlatformTextView *textView, NSInteger taskIndex)
{
NSAttributedString *attrText = ENRMGetAttributedText(textView);
__block NSRange fullItemRange = NSMakeRange(NSNotFound, 0);
[attrText enumerateAttribute:TaskIndexAttribute
inRange:NSMakeRange(0, attrText.length)
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value && [value integerValue] == taskIndex) {
NSDictionary *rangeAttrs = [attrText attributesAtIndex:range.location effectiveRange:NULL];
if ([rangeAttrs[TaskItemAttribute] boolValue]) {
if (fullItemRange.location == NSNotFound) {
fullItemRange = range;
} else {
NSUInteger newStart = MIN(fullItemRange.location, range.location);
NSUInteger newEnd = MAX(NSMaxRange(fullItemRange), NSMaxRange(range));
fullItemRange = NSMakeRange(newStart, newEnd - newStart);
}
}
}
}];
return fullItemRange;
}
NSString *taskListItemText(ENRMPlatformTextView *textView, NSRange itemRange)
{
NSAttributedString *attrString = ENRMGetAttributedText(textView);
NSUInteger textLength = attrString.length;
if (itemRange.location >= textLength || itemRange.length == 0) {
return @"";
}
NSUInteger safeEnd = MIN(NSMaxRange(itemRange), textLength);
NSRange safeRange = NSMakeRange(itemRange.location, safeEnd - itemRange.location);
NSString *sourceString = attrString.string;
NSRange newlineRange = [sourceString rangeOfString:@"\n" options:0 range:safeRange];
NSRange finalRange = safeRange;
if (newlineRange.location != NSNotFound) {
finalRange.length = newlineRange.location - safeRange.location;
}
NSString *result = [sourceString substringWithRange:finalRange];
return [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
BOOL handleTaskListTap(ENRMPlatformTextView *textView, ENRMTapRecognizer *recognizer,
void (^handler)(NSInteger index, BOOL checked, NSString *itemText))
{
TaskListHitTestResult hit = taskListHitTest(textView, recognizer);
if (!hit.found)
return NO;
NSString *itemText = taskListItemText(textView, hit.itemRange);
handler(hit.index, hit.checked, itemText);
return YES;
}
NSString *toggleTaskListItemAtIndex(NSString *markdown, NSInteger targetIndex, BOOL checked)
{
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^([ \\t]*[-*+][ \\t]+)\\[[ xX]\\]"
options:NSRegularExpressionAnchorsMatchLines
error:nil];
NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:markdown
options:0
range:NSMakeRange(0, markdown.length)];
if (targetIndex < 0 || targetIndex >= (NSInteger)matches.count) {
return [markdown copy];
}
NSTextCheckingResult *match = matches[targetIndex];
NSRange prefixRange = [match rangeAtIndex:1];
NSString *prefix = [markdown substringWithRange:prefixRange];
NSString *replacement = [NSString stringWithFormat:@"%@[%@]", prefix, checked ? @" " : @"x"];
NSMutableString *result = [markdown mutableCopy];
[result replaceCharactersInRange:match.range withString:replacement];
return [result copy];
}
BOOL updateTaskListItemCheckedState(ENRMPlatformTextView *textView, NSInteger targetIndex, BOOL newChecked,
StyleConfig *config)
{
NSAttributedString *originalText = ENRMGetAttributedText(textView);
if (!originalText)
return NO;
NSRange targetItemRange = taskListItemFullRange(textView, targetIndex);
if (targetItemRange.location == NSNotFound)
return NO;
NSDictionary *attrs = [originalText attributesAtIndex:targetItemRange.location effectiveRange:NULL];
NSInteger nestingLevel = [attrs[ListDepthAttribute] integerValue] ?: 0;
NSMutableAttributedString *mutableText = [originalText mutableCopy];
RCTUIColor *checkedColor = [config taskListCheckedTextColor];
RCTUIColor *listStyleColor = [config listStyleColor];
BOOL shouldStrikethrough = [config taskListCheckedStrikethrough];
[mutableText
enumerateAttribute:ListDepthAttribute
inRange:targetItemRange
options:0
usingBlock:^(NSNumber *depth, NSRange segmentRange, BOOL *stop) {
if (depth && [depth integerValue] > nestingLevel)
return;
// Skip code block ranges — preserve CodeBlockRenderer styles.
NSNumber *isCodeBlock = [mutableText attribute:CodeBlockAttributeName
atIndex:segmentRange.location
effectiveRange:nil];
if ([isCodeBlock boolValue])
return;
[mutableText addAttribute:TaskCheckedAttribute value:@(newChecked) range:segmentRange];
if (newChecked) {
if (checkedColor) {
[mutableText addAttribute:NSForegroundColorAttributeName value:checkedColor range:segmentRange];
}
if (shouldStrikethrough) {
[mutableText addAttribute:NSStrikethroughStyleAttributeName
value:@(NSUnderlineStyleSingle)
range:segmentRange];
[mutableText addAttribute:NSStrikethroughColorAttributeName
value:(checkedColor ?: listStyleColor)range:segmentRange];
}
} else {
[mutableText removeAttribute:NSStrikethroughStyleAttributeName range:segmentRange];
[mutableText removeAttribute:NSStrikethroughColorAttributeName range:segmentRange];
if (listStyleColor) {
[mutableText addAttribute:NSForegroundColorAttributeName value:listStyleColor range:segmentRange];
} else {
[mutableText removeAttribute:NSForegroundColorAttributeName range:segmentRange];
}
}
}];
// The checkbox glyph is drawn from the marker descriptor, not from
// TaskCheckedAttribute — keep it in sync. Enumerated over the full text:
// for code-block-first items the anchor sits outside the metadata ranges.
[mutableText enumerateAttribute:ListItemMarkerStartAttribute
inRange:NSMakeRange(0, mutableText.length)
options:0
usingBlock:^(NSArray *markers, NSRange range, BOOL *stop) {
if (![markers isKindOfClass:[NSArray class]])
return;
for (ENRMListMarkerDescriptor *marker in markers) {
if (marker.isTask && marker.taskIndex == targetIndex) {
marker.isChecked = newChecked;
}
}
}];
ENRMSetAttributedText(textView, mutableText);
NSLayoutManager *layoutManager = textView.layoutManager;
if (layoutManager) {
[layoutManager invalidateLayoutForCharacterRange:targetItemRange actualCharacterRange:NULL];
[layoutManager invalidateDisplayForCharacterRange:targetItemRange];
}
ENRMSetNeedsDisplay(textView);
return YES;
}
BOOL handleTaskListTapWithSharedLogic(ENRMPlatformTextView *textView, ENRMTapRecognizer *recognizer,
NSString *__strong *cachedMarkdown, StyleConfig *config,
void (^eventEmitterBlock)(NSInteger index, BOOL checked, NSString *itemText),
void (^renderBlock)(NSString *updatedMarkdown))
{
return handleTaskListTap(textView, recognizer, ^(NSInteger index, BOOL checked, NSString *itemText) {
BOOL newChecked = !checked;
NSString *updatedMarkdown = toggleTaskListItemAtIndex(*cachedMarkdown, index, newChecked);
*cachedMarkdown = updatedMarkdown;
if (updateTaskListItemCheckedState(textView, index, newChecked, config)) {
eventEmitterBlock(index, newChecked, itemText);
} else {
renderBlock(updatedMarkdown);
eventEmitterBlock(index, newChecked, itemText);
}
});
}