Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix layout of nested blockquotes #202

Merged
merged 9 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,19 @@ public class MarkdownBlockquoteSpan implements MarkdownSpan, LeadingMarginSpan {
private final float borderWidth;
private final float marginLeft;
private final float paddingLeft;
private final int nestingLevel;

public MarkdownBlockquoteSpan(@ColorInt int borderColor, float borderWidth, float marginLeft, float paddingLeft) {
public MarkdownBlockquoteSpan(@ColorInt int borderColor, float borderWidth, float marginLeft, float paddingLeft, int nestingLevel) {
this.borderColor = borderColor;
this.borderWidth = PixelUtil.toPixelFromDIP(borderWidth);
this.marginLeft = PixelUtil.toPixelFromDIP(marginLeft);
this.paddingLeft = PixelUtil.toPixelFromDIP(paddingLeft);
this.nestingLevel = nestingLevel;
}

@Override
public int getLeadingMargin(boolean first) {
return (int) (marginLeft + borderWidth + paddingLeft);
return (int) (marginLeft + borderWidth + paddingLeft) * nestingLevel;
}

@Override
Expand All @@ -37,9 +39,12 @@ public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int ba
p.setStyle(Paint.Style.FILL);
p.setColor(borderColor);

float left = x + dir * marginLeft;
float right = x + dir * (marginLeft + borderWidth);
c.drawRect(left, top, right, bottom, p);
for (int level = 0; level < nestingLevel; level++) {
float shift = (marginLeft + borderWidth + paddingLeft) * level;
float left = x + dir * (marginLeft + shift);
float right = x + dir * (marginLeft + borderWidth + shift);
c.drawRect(left, top, right, bottom, p);
}

p.setStyle(originalStyle);
p.setColor(originalColor);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,16 @@ public void applyMarkdownFormatting(SpannableStringBuilder ssb) {
String type = range.getString("type");
int start = range.getInt("start");
int length = range.getInt("length");
int depth = range.optInt("depth", 1);
int end = start + length;
applyRange(ssb, type, start, end);
applyRange(ssb, type, start, end, depth);
}
} catch (JSONException e) {
// Do nothing
}
}

private void applyRange(SpannableStringBuilder ssb, String type, int start, int end) {
private void applyRange(SpannableStringBuilder ssb, String type, int start, int end, int depth) {
switch (type) {
case "bold":
setSpan(ssb, new MarkdownBoldSpan(), start, end);
Expand Down Expand Up @@ -156,7 +157,8 @@ private void applyRange(SpannableStringBuilder ssb, String type, int start, int
mMarkdownStyle.getBlockquoteBorderColor(),
mMarkdownStyle.getBlockquoteBorderWidth(),
mMarkdownStyle.getBlockquoteMarginLeft(),
mMarkdownStyle.getBlockquotePaddingLeft());
mMarkdownStyle.getBlockquotePaddingLeft(),
depth);
setSpan(ssb, span, start, end);
break;
default:
Expand Down
17 changes: 11 additions & 6 deletions ios/MarkdownLayoutManager.mm
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ - (void)drawBackgroundForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origi

[self enumerateLineFragmentsForGlyphRange:glyphsToShow usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer * _Nonnull textContainer, NSRange glyphRange, BOOL * _Nonnull stop) {
__block BOOL isBlockquote = NO;
__block int currentDepth = 0;
RCTMarkdownUtils *markdownUtils = [self valueForKey:@"markdownUtils"];
[markdownUtils.blockquoteRanges enumerateObjectsUsingBlock:^(NSValue *item, NSUInteger idx, BOOL * _Nonnull stop) {
NSRange range = [item rangeValue];
[markdownUtils.blockquoteRangesAndLevels enumerateObjectsUsingBlock:^(NSDictionary *item, NSUInteger idx, BOOL * _Nonnull stop) {
NSRange range = [[item valueForKey:@"range"] rangeValue];
currentDepth = [[item valueForKey:@"depth"] unsignedIntegerValue];
NSUInteger start = range.location;
NSUInteger end = start + range.length;
NSUInteger location = glyphRange.location;
Expand All @@ -21,13 +23,16 @@ - (void)drawBackgroundForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origi
if (isBlockquote) {
CGFloat paddingLeft = markdownUtils.backedTextInputView.textContainerInset.left;
CGFloat paddingTop = markdownUtils.backedTextInputView.textContainerInset.top;
CGFloat x = paddingLeft + markdownUtils.markdownStyle.blockquoteMarginLeft;
CGFloat y = paddingTop + rect.origin.y;
CGFloat width = markdownUtils.markdownStyle.blockquoteBorderWidth;
CGFloat height = rect.size.height;
CGRect lineRect = CGRectMake(x, y, width, height);
[markdownUtils.markdownStyle.blockquoteBorderColor setFill];
UIRectFill(lineRect);
CGFloat shift = markdownUtils.markdownStyle.blockquoteMarginLeft + markdownUtils.markdownStyle.blockquoteBorderWidth + markdownUtils.markdownStyle.blockquotePaddingLeft;
for (int level = 0; level < currentDepth; level++) {
CGFloat x = paddingLeft + (level * shift) + markdownUtils.markdownStyle.blockquoteMarginLeft;
CGRect lineRect = CGRectMake(x, y, width, height);
[markdownUtils.markdownStyle.blockquoteBorderColor setFill];
UIRectFill(lineRect);
}
}
}];
}
Expand Down
2 changes: 1 addition & 1 deletion ios/RCTMarkdownUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ NS_ASSUME_NONNULL_BEGIN
@interface RCTMarkdownUtils : NSObject

@property (nonatomic) RCTMarkdownStyle *markdownStyle;
@property (nonatomic) NSMutableArray<NSValue *> *blockquoteRanges;
@property (nonatomic) NSMutableArray<NSDictionary *> *blockquoteRangesAndLevels;
@property (weak, nonatomic) UIView<RCTBackedTextInputViewProtocol> *backedTextInputView;

- (instancetype)initWithBackedTextInputView:(UIView<RCTBackedTextInputViewProtocol> *)backedTextInputView;
Expand Down
10 changes: 7 additions & 3 deletions ios/RCTMarkdownUtils.mm
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,14 @@ - (NSAttributedString *)parseMarkdown:(nullable NSAttributedString *)input
// This is a workaround that applies the NSUnderlineStyleNone to the string before iterating over ranges which resolves this problem.
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:NSMakeRange(0, attributedString.length)];

_blockquoteRanges = [NSMutableArray new];
_blockquoteRangesAndLevels = [NSMutableArray new];

[ranges enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSDictionary *item = obj;
NSString *type = [item valueForKey:@"type"];
NSInteger location = [[item valueForKey:@"start"] unsignedIntegerValue];
NSInteger length = [[item valueForKey:@"length"] unsignedIntegerValue];
NSInteger depth = [[item valueForKey:@"depth"] unsignedIntegerValue] ?: 1;
NSRange range = NSMakeRange(location, length);

if ([type isEqualToString:@"bold"] || [type isEqualToString:@"italic"] || [type isEqualToString:@"code"] || [type isEqualToString:@"pre"] || [type isEqualToString:@"h1"]) {
Expand Down Expand Up @@ -103,12 +104,15 @@ - (NSAttributedString *)parseMarkdown:(nullable NSAttributedString *)input
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.linkColor range:range];
} else if ([type isEqualToString:@"blockquote"]) {
CGFloat indent = _markdownStyle.blockquoteMarginLeft + _markdownStyle.blockquoteBorderWidth + _markdownStyle.blockquotePaddingLeft;
CGFloat indent = (_markdownStyle.blockquoteMarginLeft + _markdownStyle.blockquoteBorderWidth + _markdownStyle.blockquotePaddingLeft) * depth;
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.firstLineHeadIndent = indent;
paragraphStyle.headIndent = indent;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
[_blockquoteRanges addObject:[NSValue valueWithRange:range]];
[_blockquoteRangesAndLevels addObject:@{
@"range": [NSValue valueWithRange:range],
@"depth": @(depth)
}];
} else if ([type isEqualToString:@"pre"]) {
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.preColor range:range];
NSRange rangeForBackground = [inputString characterAtIndex:range.location] == '\n' ? NSMakeRange(range.location + 1, range.length - 1) : range;
Expand Down
41 changes: 41 additions & 0 deletions parser/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -332,4 +332,45 @@ describe('trailing whitespace', () => {
]);
});
});

describe('nested blockquotes', () => {
test('without whitespace between syntax', () => {
expect('>>> Hello world').toBeParsedAs([
{type: 'blockquote', start: 0, length: 15, depth: 3},
{type: 'syntax', start: 0, length: 1},
{type: 'syntax', start: 1, length: 1},
{type: 'syntax', start: 2, length: 1},
]);
});

test('with whitespace between syntax', () => {
expect('> > > Hello world').toBeParsedAs([
{type: 'blockquote', start: 0, length: 17, depth: 3},
{type: 'syntax', start: 0, length: 1},
{type: 'syntax', start: 2, length: 1},
{type: 'syntax', start: 4, length: 1},
]);
});

test('different blockquote depths', () => {
expect('>> Hello 1\n> Hello 2').toBeParsedAs([
{type: 'blockquote', start: 0, length: 10, depth: 2},
{type: 'syntax', start: 0, length: 1},
{type: 'syntax', start: 1, length: 1},
{type: 'blockquote', start: 11, length: 9},
{type: 'syntax', start: 11, length: 1},
]);
});

test('with another style inside', () => {
expect('>> Hello *world*').toBeParsedAs([
{type: 'blockquote', start: 0, length: 16, depth: 2},
{type: 'syntax', start: 0, length: 1},
{type: 'syntax', start: 1, length: 1},
{type: 'syntax', start: 9, length: 1},
{type: 'bold', start: 10, length: 5},
{type: 'syntax', start: 15, length: 1},
]);
});
});
});
25 changes: 24 additions & 1 deletion parser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,28 @@ function sortRanges(ranges: Range[]) {
return ranges.sort((a, b) => a.start - b.start || b.length - a.length || getTagPriority(b.type) - getTagPriority(a.type) || 0);
}

function groupRanges(ranges: Range[]) {
const lastVisibleRangeIndex: {[key in MarkdownType]?: number} = {};

return ranges.reduce((acc, range) => {
const start = range.start;
const end = range.start + range.length;

const rangeWithSameStyleIndex = lastVisibleRangeIndex[range.type];
const sameStyleRange = rangeWithSameStyleIndex !== undefined ? acc[rangeWithSameStyleIndex] : undefined;

if (sameStyleRange && sameStyleRange.start <= start && sameStyleRange.start + sameStyleRange.length >= end && range.length > 1) {
// increment depth of overlapping range
sameStyleRange.depth = (sameStyleRange.depth || 1) + 1;
} else {
lastVisibleRangeIndex[range.type] = acc.length;
acc.push(range);
}

return acc;
}, [] as Range[]);
}

function parseExpensiMarkToRanges(markdown: string): Range[] {
const html = parseMarkdownToHTML(markdown);
const tokens = parseHTMLToTokens(html);
Expand All @@ -192,7 +214,8 @@ function parseExpensiMarkToRanges(markdown: string): Range[] {
return [];
}
const sortedRanges = sortRanges(ranges);
return sortedRanges;
const groupedRanges = groupRanges(sortedRanges);
return groupedRanges;
Comment on lines +217 to +218
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add some unit tests for nested blockquotes to verify that groupRanges indeed works correctly?

}

globalThis.parseExpensiMarkToRanges = parseExpensiMarkToRanges;
8 changes: 4 additions & 4 deletions parser/react-native-live-markdown-parser.js

Large diffs are not rendered by default.

16 changes: 15 additions & 1 deletion src/web/parserUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,20 @@ function addSubstringAsTextNode(root: HTMLElement, text: string, startIndex: num
}
}

function ungroupRanges(ranges: MarkdownRange[]): MarkdownRange[] {
const ungroupedRanges: MarkdownRange[] = [];
ranges.forEach((range) => {
if (!range.depth) {
ungroupedRanges.push(range);
}
const {depth, ...rangeWithoutDepth} = range;
Array.from({length: depth!}).forEach(() => {
ungroupedRanges.push(rangeWithoutDepth);
});
});
return ungroupedRanges;
}

function parseRangesToHTMLNodes(text: string, ranges: MarkdownRange[], markdownStyle: PartialMarkdownStyle = {}, disableInlineStyles = false): HTMLElement {
const root: HTMLElement = document.createElement('span');
root.className = 'root';
Expand All @@ -87,7 +101,7 @@ function parseRangesToHTMLNodes(text: string, ranges: MarkdownRange[], markdownS
return root;
}

const stack = [...ranges];
const stack = ungroupRanges(ranges);
const nestedStack: NestedNode[] = [{node: root, endIndex: textLength}];
let lastRangeEndIndex = 0;
while (stack.length > 0) {
Expand Down
Loading