Files
paseo/packages/react-native-enriched-markdown/ios/input/ENRMBlockStore.mm
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

276 lines
9.8 KiB
Plaintext

#import "ENRMBlockStore.h"
#import "ENRMRangeEditAdjustment.h"
#import "ENRMRangeStoreUtils.h"
/// Expands a selection to cover whole paragraphs (line-scoped block boundaries).
/// Clamps unconditionally so out-of-bounds input can't reach
/// paragraphRangeForRange: (which raises on an invalid range).
static NSRange paragraphBoundsForRange(NSRange range, NSString *text)
{
if (text.length == 0) {
return NSMakeRange(0, 0);
}
NSUInteger location = MIN(range.location, text.length);
NSUInteger length = MIN(range.length, text.length - location);
return [text paragraphRangeForRange:NSMakeRange(location, length)];
}
@implementation ENRMBlockStore {
NSMutableArray<ENRMBlockRange *> *_ranges;
}
- (instancetype)init
{
if (self = [super init]) {
_ranges = [NSMutableArray array];
}
return self;
}
- (NSArray<ENRMBlockRange *> *)allRanges
{
return [_ranges copy];
}
- (nullable ENRMBlockRange *)blockStartingAtLocation:(NSUInteger)location
{
NSInteger lo = 0;
NSInteger hi = (NSInteger)_ranges.count - 1;
while (lo <= hi) {
NSInteger mid = (lo + hi) / 2;
NSUInteger start = _ranges[(NSUInteger)mid].range.location;
if (start < location) {
lo = mid + 1;
} else if (start > location) {
hi = mid - 1;
} else {
return _ranges[(NSUInteger)mid];
}
}
return nil;
}
// Incoming ranges are trusted to be non-overlapping and line-scoped — the
// parser owns that invariant (md4c block structure never overlaps at the same
// nesting level, and nested containers are not yet mapped). Revisit enforcement
// here if a container block type (list, blockquote) is added.
- (void)setRanges:(NSArray<ENRMBlockRange *> *)ranges
{
_ranges = [[ranges sortedArrayUsingComparator:^NSComparisonResult(ENRMBlockRange *first, ENRMBlockRange *second) {
if (first.range.location < second.range.location)
return NSOrderedAscending;
if (first.range.location > second.range.location)
return NSOrderedDescending;
return NSOrderedSame;
}] mutableCopy];
[self recomputeListMetadata];
}
- (void)clearAll
{
[_ranges removeAllObjects];
}
/// Drops any stored block overlapping `paragraphRange` so a replacement can be
/// inserted cleanly. Blocks are line-scoped and never partially overlap, so a
/// touched block is removed wholesale.
- (void)removeBlocksOverlappingRange:(NSRange)paragraphRange
{
NSUInteger removeStart = paragraphRange.location;
NSUInteger removeEnd = NSMaxRange(paragraphRange);
NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet];
for (NSUInteger idx = 0; idx < _ranges.count; idx++) {
ENRMBlockRange *existing = _ranges[idx];
NSUInteger existingStart = existing.range.location;
NSUInteger existingEnd = NSMaxRange(existing.range);
// A zero-length anchor occupies a point, so the half-open overlap test
// never matches it; drop one whose anchor lies within the removal bounds.
if (existing.range.length == 0) {
if (existingStart >= removeStart && existingStart <= removeEnd) {
[indexesToRemove addIndex:idx];
}
continue;
}
if (existingEnd <= removeStart || existingStart >= removeEnd) {
continue;
}
[indexesToRemove addIndex:idx];
}
ENRMRemoveIndexesInReverse(_ranges, indexesToRemove);
}
- (void)setBlockType:(ENRMInputBlockType)type
level:(NSInteger)level
forParagraphRange:(NSRange)range
inText:(NSString *)text
{
NSRange paragraphRange = paragraphBoundsForRange(range, text);
[self removeBlocksOverlappingRange:paragraphRange];
paragraphRange = ENRMTrimLineTerminators(paragraphRange, text);
if (paragraphRange.length == 0 && !ENRMBlockTypePersistsWhenEmpty(type)) {
return;
}
ENRMBlockRange *blockRange = [ENRMBlockRange rangeWithType:type range:paragraphRange level:level];
NSUInteger insertAt = ENRMSortedInsertionIndex(
_ranges, blockRange.range.location, ^NSUInteger(id range) { return ((ENRMBlockRange *)range).range.location; });
[_ranges insertObject:blockRange atIndex:insertAt];
}
- (void)removeBlockInParagraphRange:(NSRange)range inText:(NSString *)text
{
NSRange paragraphRange = paragraphBoundsForRange(range, text);
[self removeBlocksOverlappingRange:paragraphRange];
}
- (void)adjustForEditAtLocation:(NSUInteger)editLocation
deletedLength:(NSUInteger)deletedLength
insertedLength:(NSUInteger)insertedLength
{
if (deletedLength == 0 && insertedLength == 0)
return;
NSUInteger deleteEnd = editLocation + deletedLength;
NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet];
for (NSUInteger idx = 0; idx < _ranges.count; idx++) {
ENRMBlockRange *blockRange = _ranges[idx];
BOOL persists = ENRMBlockTypePersistsWhenEmpty(blockRange.type);
// Zero-length anchors don't follow the shared adjustment: one at the edit
// location stays put (normalize grows it over the typed text), one past
// the edit shifts with it, one inside the deletion is dropped.
if (blockRange.range.length == 0) {
if (!persists) {
[indexesToRemove addIndex:idx];
} else if (blockRange.range.location >= deleteEnd && blockRange.range.location > editLocation) {
blockRange.range = NSMakeRange(blockRange.range.location - deletedLength + insertedLength, 0);
} else if (blockRange.range.location > editLocation) {
[indexesToRemove addIndex:idx]; // anchor sat inside the deleted region
}
continue;
}
ENRMAdjustedRange adjusted = ENRMAdjustRangeForEdit(blockRange.range, editLocation, deletedLength, insertedLength,
/* inheritsReplacementAtStart */ YES,
/* growsAtStartOnInsert */ YES);
if (adjusted.shouldRemove) {
// A persisting block deleted exactly to its end collapses to a zero-length
// anchor (the line's newline survived, so the line stays the block); a
// deletion running past its end removed the line, so drop the block with it.
if (persists && NSMaxRange(blockRange.range) == deleteEnd && blockRange.range.location >= editLocation) {
blockRange.range = NSMakeRange(editLocation, 0);
} else {
[indexesToRemove addIndex:idx];
}
continue;
}
blockRange.range = adjusted.range;
}
ENRMRemoveIndexesInReverse(_ranges, indexesToRemove);
// Prune zero-length ranges, but keep zero-length persisting blocks: they anchor
// an emptied-but-still-present heading/bullet line (see the collapse rule above).
NSMutableIndexSet *emptyIndexes = [NSMutableIndexSet indexSet];
for (NSUInteger idx = 0; idx < _ranges.count; idx++) {
ENRMBlockRange *range = _ranges[idx];
if (range.range.length == 0 && !ENRMBlockTypePersistsWhenEmpty(range.type)) {
[emptyIndexes addIndex:idx];
}
}
if (emptyIndexes.count > 0) {
ENRMRemoveIndexesInReverse(_ranges, emptyIndexes);
}
}
- (void)normalizeToLineBoundsInText:(NSString *)text
{
if (_ranges.count == 0) {
return;
}
NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet];
NSInteger previousEnd = -1;
for (NSUInteger idx = 0; idx < _ranges.count; idx++) {
ENRMBlockRange *blockRange = _ranges[idx];
NSRange lineRange = paragraphBoundsForRange(NSMakeRange(blockRange.range.location, 0), text);
lineRange = ENRMTrimLineTerminators(lineRange, text);
BOOL emptyLine = lineRange.length == 0;
if ((emptyLine && !ENRMBlockTypePersistsWhenEmpty(blockRange.type)) ||
(NSInteger)lineRange.location <= previousEnd) {
// Dedup: drop a range that resolves to an already-claimed paragraph. This is a
// legitimate self-heal path (a heading anchor and the block it merges into can
// briefly share a start after a line-join), so it is deliberately silent — it
// cannot distinguish that benign case from genuine corruption, so it does not
// assert here.
[indexesToRemove addIndex:idx];
continue;
}
blockRange.range = lineRange;
previousEnd = (NSInteger)NSMaxRange(lineRange);
}
ENRMRemoveIndexesInReverse(_ranges, indexesToRemove);
[self recomputeListMetadata];
}
/// Clamps list depths to valid ancestry (an item nests at most one level under
/// the previous adjacent list item — CommonMark cannot represent orphan nesting)
/// and renumbers ordered items among their adjacent same-depth, same-type run.
- (void)recomputeListMetadata
{
NSInteger prevEnd = -2;
NSInteger prevDepth = -1;
NSInteger counters[kENRMMaxListDepth + 2];
ENRMInputBlockType counterTypes[kENRMMaxListDepth + 2];
memset(counters, 0, sizeof(counters));
memset(counterTypes, 0, sizeof(counterTypes));
for (ENRMBlockRange *blockRange in _ranges) {
if (!ENRMBlockTypeIsListItem(blockRange.type)) {
prevDepth = -1;
continue;
}
BOOL adjacent = prevDepth >= 0 && (NSInteger)blockRange.range.location == prevEnd + 1;
if (!adjacent) {
memset(counters, 0, sizeof(counters));
memset(counterTypes, 0, sizeof(counterTypes));
}
// Coerce into [0, kENRMMaxListDepth] before ancestry-clamping: parser and
// indent commands cap their depths, but this pass indexes the counter
// arrays by depth, so an out-of-bounds level must never survive it.
NSInteger maxDepth = MIN(adjacent ? prevDepth + 1 : 0, kENRMMaxListDepth);
if (blockRange.level > maxDepth) {
blockRange.level = maxDepth;
} else if (blockRange.level < 0) {
blockRange.level = 0;
}
NSInteger depth = blockRange.level;
for (NSInteger i = depth + 1; i <= kENRMMaxListDepth + 1; i++) {
counters[i] = 0;
counterTypes[i] = (ENRMInputBlockType)0;
}
if (counterTypes[depth] != blockRange.type) {
counters[depth] = 0;
counterTypes[depth] = blockRange.type;
}
counters[depth]++;
blockRange.ordinal = counters[depth];
prevEnd = (NSInteger)NSMaxRange(blockRange.range);
prevDepth = blockRange.level;
}
}
@end