#import "HTMLGenerator.h"
#import "BlockquoteBorder.h"
#import "CodeBackground.h"
#import "ENRMFeatureFlags.h"
#import "ENRMImageAttachment.h"
#import "ENRMLinkPillText.h"
#import "HighlightRenderer.h"
#if ENRICHED_MARKDOWN_MATH
#import "ENRMMathInlineAttachment.h"
#endif
#import "LastElementUtils.h"
#import "ListItemRenderer.h"
#import "ParagraphStyleUtils.h"
#import "RenderContext.h"
#import "RuntimeKeys.h"
#import "StyleConfig.h"
#import "ThematicBreakAttachment.h"
static NSString *const kObjectReplacementChar = @"\uFFFC";
static const CGFloat kBlockquoteVerticalPadding = 8.0;
static const CGFloat kBlockquoteParagraphSpacing = 4.0;
static const CGFloat kNestedBlockquoteTopMargin = 8.0;
static const CGFloat kDefaultListIndent = 24.0;
static const CGFloat kCodePadding = 2.0;
static const CGFloat kCodeBorderRadius = 4.0;
#pragma mark - Paragraph Types
typedef NS_ENUM(NSInteger, ParagraphType) {
ParagraphTypeNormal,
ParagraphTypeHeading1,
ParagraphTypeHeading2,
ParagraphTypeHeading3,
ParagraphTypeHeading4,
ParagraphTypeHeading5,
ParagraphTypeHeading6,
ParagraphTypeCodeBlock,
ParagraphTypeBlockquote,
ParagraphTypeListItemUnordered,
ParagraphTypeListItemOrdered,
ParagraphTypeTaskList
};
typedef struct {
NSRange range;
ParagraphType type;
NSInteger depth;
NSInteger listNumber;
BOOL isTaskChecked;
} ParagraphData;
#pragma mark - Cached Style Config
/// Pre-fetched style values to avoid repeated StyleConfig method calls
@interface CachedStyles : NSObject
@property (nonatomic, copy) NSString *paragraphColor;
@property (nonatomic, copy) NSString *strongColor;
@property (nonatomic, copy) NSString *emphasisColor;
@property (nonatomic, copy) NSString *codeColor;
@property (nonatomic, copy) NSString *codeBackgroundColor;
@property (nonatomic, copy) NSString *codeBlockColor;
@property (nonatomic, copy) NSString *codeBlockBackgroundColor;
@property (nonatomic, copy) NSString *blockquoteColor;
@property (nonatomic, copy) NSString *blockquoteBackgroundColor;
@property (nonatomic, copy) NSString *blockquoteBorderColor;
@property (nonatomic, copy) NSString *listStyleColor;
@property (nonatomic, copy) NSString *taskCheckedColor;
@property (nonatomic, copy) NSString *taskBorderColor;
@property (nonatomic, copy) NSString *taskCheckmarkColor;
@property (nonatomic) CGFloat taskCheckboxSize;
@property (nonatomic) CGFloat taskCheckboxBorderRadius;
@property (nonatomic, copy) NSString *h1Color;
@property (nonatomic, copy) NSString *h2Color;
@property (nonatomic, copy) NSString *h3Color;
@property (nonatomic, copy) NSString *h4Color;
@property (nonatomic, copy) NSString *h5Color;
@property (nonatomic, copy) NSString *h6Color;
@property (nonatomic) CGFloat paragraphFontSize;
@property (nonatomic) CGFloat paragraphMarginBottom;
@property (nonatomic) CGFloat codeBlockFontSize;
@property (nonatomic) CGFloat codeBlockPadding;
@property (nonatomic) CGFloat codeBlockBorderRadius;
@property (nonatomic) CGFloat codeBlockMarginBottom;
@property (nonatomic) CGFloat blockquoteFontSize;
@property (nonatomic) CGFloat blockquoteBorderWidth;
@property (nonatomic) CGFloat blockquoteMarginBottom;
@property (nonatomic) CGFloat blockquoteGapWidth;
@property (nonatomic) CGFloat listStyleFontSize;
@property (nonatomic) CGFloat listStyleMarginBottom;
@property (nonatomic) CGFloat listStyleMarginLeft;
@property (nonatomic) CGFloat imageMarginBottom;
@property (nonatomic) CGFloat imageBorderRadius;
@property (nonatomic) CGFloat h1FontSize;
@property (nonatomic) CGFloat h2FontSize;
@property (nonatomic) CGFloat h3FontSize;
@property (nonatomic) CGFloat h4FontSize;
@property (nonatomic) CGFloat h5FontSize;
@property (nonatomic) CGFloat h6FontSize;
@property (nonatomic) CGFloat h1MarginBottom;
@property (nonatomic) CGFloat h2MarginBottom;
@property (nonatomic) CGFloat h3MarginBottom;
@property (nonatomic) CGFloat h4MarginBottom;
@property (nonatomic) CGFloat h5MarginBottom;
@property (nonatomic) CGFloat h6MarginBottom;
@property (nonatomic, copy) NSString *h1FontWeight;
@property (nonatomic, copy) NSString *h2FontWeight;
@property (nonatomic, copy) NSString *h3FontWeight;
@property (nonatomic, copy) NSString *h4FontWeight;
@property (nonatomic, copy) NSString *h5FontWeight;
@property (nonatomic, copy) NSString *h6FontWeight;
@property (nonatomic, copy) NSString *linkFontFamily;
@property (nonatomic, copy) NSString *linkColor;
@property (nonatomic) BOOL linkUnderline;
@property (nonatomic, copy) NSString *thematicBreakColor;
@property (nonatomic) CGFloat thematicBreakHeight;
@property (nonatomic) CGFloat thematicBreakMarginTop;
@property (nonatomic) CGFloat thematicBreakMarginBottom;
@property (nonatomic, copy) NSString *strikethroughColor;
@property (nonatomic, copy) NSString *underlineColor;
@property (nonatomic, copy) NSString *highlightColor;
@property (nonatomic, copy) NSString *highlightBackgroundColor;
@end
@implementation CachedStyles
@end
#pragma mark - Generator State
@interface GeneratorState : NSObject
@property (nonatomic) NSInteger currentListDepth;
@property (nonatomic) NSInteger currentBlockquoteDepth;
@property (nonatomic) BOOL inBlockquote;
@property (nonatomic) BOOL inCodeBlock;
@property (nonatomic) BOOL previousWasCodeBlock;
@property (nonatomic) BOOL previousWasBlockquote;
@property (nonatomic, strong) NSMutableArray",
img.imageURL];
} else {
[html appendFormat:
@"
", styles.imageMarginBottom, img.imageURL, styles.imageBorderRadius]; } } } else if ([attachment isKindOfClass:[ThematicBreakAttachment class]]) { [html appendFormat: @"
",
styles.thematicBreakHeight, styles.thematicBreakColor,
styles.thematicBreakMarginTop, styles.thematicBreakMarginBottom];
#if ENRICHED_MARKDOWN_MATH
} else if ([attachment isKindOfClass:[ENRMMathInlineAttachment class]]) {
ENRMMathInlineAttachment *math = (ENRMMathInlineAttachment *)attachment;
if (math.latex.length > 0) {
[html appendFormat:
@"%@",
styles.codeBackgroundColor, styles.codeColor, kCodePadding, kCodePadding * 2,
kCodeBorderRadius, escapeHTML(math.latex)];
}
#endif
}
return;
}
UIFont *font = attrs[NSFontAttributeName];
NSNumber *underline = attrs[NSUnderlineStyleAttributeName];
NSNumber *strikethrough = attrs[NSStrikethroughStyleAttributeName];
id linkAttr = attrs[NSLinkAttributeName];
BOOL isCode = isCodeSpan(attrs, isCodeBlock);
BOOL isBold = NO, isItalic = NO;
if (font) {
UIFontDescriptorSymbolicTraits traits = font.fontDescriptor.symbolicTraits;
isBold = (traits & UIFontDescriptorTraitBold) != 0;
isItalic = (traits & UIFontDescriptorTraitItalic) != 0;
}
BOOL isHighlight = [attrs[HighlightAttributeName] boolValue];
if (isHighlight) {
NSMutableString *markStyle = [NSMutableString
stringWithFormat:@"background-color: %@", styles.highlightBackgroundColor];
if (styles.highlightColor && ![styles.highlightColor isEqualToString:styles.paragraphColor]) {
[markStyle appendFormat:@"; color: %@", styles.highlightColor];
} else {
[markStyle appendString:@"; color: inherit"];
}
[html appendFormat:@"", markStyle];
}
if (linkAttr) {
NSString *href =
[linkAttr isKindOfClass:[NSURL class]] ? [(NSURL *)linkAttr absoluteString] : linkAttr;
if (styles.linkFontFamily.length > 0) {
[html appendFormat:
@"",
escapeHTML(href), styles.linkColor, styles.linkUnderline ? @"underline" : @"none",
styles.linkFontFamily];
} else {
[html appendFormat:@"",
escapeHTML(href), styles.linkColor,
styles.linkUnderline ? @"underline" : @"none"];
}
}
if (isCode) {
[html appendFormat:
@"",
styles.codeBackgroundColor, styles.codeColor, kCodePadding, kCodePadding * 2,
kCodeBorderRadius];
}
if (isBold) {
if (styles.strongColor && ![styles.strongColor isEqualToString:@"inherit"]) {
[html appendFormat:@"", styles.strongColor];
} else {
[html appendString:@""];
}
}
if (isItalic) {
if (styles.emphasisColor && ![styles.emphasisColor isEqualToString:@"inherit"]) {
[html appendFormat:@"", styles.emphasisColor];
} else {
[html appendString:@""];
}
}
if ([strikethrough integerValue] > 0) {
if (styles.strikethroughColor && ![styles.strikethroughColor isEqualToString:@"inherit"]) {
[html appendFormat:@""];
if (linkAttr)
[html appendString:@""];
if (isHighlight)
[html appendString:@""];
}];
}
#pragma mark - Block Handlers
static void handleCodeBlock(NSMutableString *html, NSMutableString *inlineContent, CachedStyles *styles,
GeneratorState *state)
{
if (!state.inCodeBlock) {
state.inCodeBlock = YES;
[html appendFormat:
@"", styles.strikethroughColor];
} else {
[html appendString:@""];
if (isBold)
[html appendString:@""];
if (isCode)
[html appendString:@""];
}
}
if ([underline integerValue] > 0 && !linkAttr) {
if (styles.underlineColor && ![styles.underlineColor isEqualToString:@"inherit"]) {
[html appendFormat:@"", styles.underlineColor];
} else {
[html appendString:@""];
}
}
[html appendString:escapeHTML(text)];
// Reverse order
if ([underline integerValue] > 0 && !linkAttr)
[html appendString:@""];
if ([strikethrough integerValue] > 0)
[html appendString:@""];
if (isItalic)
[html appendString:@"
",
styles.codeBlockBackgroundColor, styles.codeBlockPadding, styles.codeBlockBorderRadius,
styles.codeBlockMarginBottom, styles.codeBlockFontSize, styles.codeBlockColor];
} else if (state.previousWasCodeBlock) {
[html appendString:@"\n"];
}
[html appendString:inlineContent];
state.previousWasCodeBlock = YES;
}
static void handleBlockquote(NSMutableString *html, ParagraphData *para, NSMutableString *inlineContent,
CachedStyles *styles, GeneratorState *state)
{
NSInteger depth = para->depth;
// Reset if starting a new blockquote block
if (!state.previousWasBlockquote && state.inBlockquote) {
closeBlockquotes(html, state);
}
while (state.currentBlockquoteDepth > depth) {
[html appendString:@""];
state.currentBlockquoteDepth--;
}
while (state.currentBlockquoteDepth < depth) {
state.currentBlockquoteDepth++;
state.inBlockquote = YES;
if (state.currentBlockquoteDepth == 0) {
[html appendFormat:
@"",
styles.blockquoteBackgroundColor, styles.blockquoteBorderWidth, styles.blockquoteBorderColor,
kBlockquoteVerticalPadding, styles.blockquoteGapWidth, styles.blockquoteMarginBottom];
} else {
[html appendFormat:
@"",
styles.blockquoteBorderWidth, styles.blockquoteBorderColor, styles.blockquoteGapWidth,
kNestedBlockquoteTopMargin];
}
}
[html appendFormat:@"%@
",
kBlockquoteParagraphSpacing, styles.blockquoteColor, styles.blockquoteFontSize, inlineContent];
state.previousWasBlockquote = YES;
}
static void handleListItem(NSMutableString *html, ParagraphData *para, NSMutableString *inlineContent,
CachedStyles *styles, GeneratorState *state)
{
NSInteger depth = para->depth;
BOOL isOrdered = (para->type == ParagraphTypeListItemOrdered);
BOOL isTask = (para->type == ParagraphTypeTaskList);
NSInteger listTypeValue = isOrdered ? 1 : 0;
while (state.currentListDepth > depth) {
NSString *closeTag = ([state.openListTypes.lastObject integerValue] == 1) ? @"" : @"";
[html appendString:closeTag];
[state.openListTypes removeLastObject];
state.currentListDepth--;
}
// List type change at same depth (ul <-> ol)
if (state.currentListDepth == depth && state.openListTypes.count > 0) {
NSInteger currentType = [state.openListTypes.lastObject integerValue];
if (currentType != listTypeValue) {
NSString *closeTag = (currentType == 1) ? @"" : @"";
[html appendString:closeTag];
[state.openListTypes removeLastObject];
state.currentListDepth--;
}
}
CGFloat indent = styles.listStyleMarginLeft > 0 ? styles.listStyleMarginLeft : kDefaultListIndent;
while (state.currentListDepth < depth) {
state.currentListDepth++;
if (isOrdered) {
[html appendFormat:@"", indent];
} else {
NSString *listStyleType = isTask ? @"none" : @"disc";
[html appendFormat:@"", indent,
listStyleType];
}
[state.openListTypes addObject:@(listTypeValue)];
}
[html appendFormat:@"- ",
styles.listStyleMarginBottom, styles.listStyleColor, styles.listStyleFontSize];
if (isTask) {
CGFloat size = styles.taskCheckboxSize;
CGFloat radius = styles.taskCheckboxBorderRadius;
if (para->isTaskChecked) {
[html appendFormat:
@"✓ ",
size, size, radius, styles.taskCheckedColor, styles.taskCheckmarkColor, size - 2, size];
} else {
[html appendFormat:
@" ",
size, size, radius, styles.taskBorderColor];
}
}
[html appendFormat:@"%@
", inlineContent];
}
static void handleHeading(NSMutableString *html, ParagraphData *para, NSMutableString *inlineContent,
CachedStyles *styles)
{
NSInteger level = headingLevel(para->type);
CGFloat fontSize, marginBottom;
NSString *fontWeight, *color;
switch (level) {
case 1:
fontSize = styles.h1FontSize;
fontWeight = styles.h1FontWeight;
color = styles.h1Color;
marginBottom = styles.h1MarginBottom;
break;
case 2:
fontSize = styles.h2FontSize;
fontWeight = styles.h2FontWeight;
color = styles.h2Color;
marginBottom = styles.h2MarginBottom;
break;
case 3:
fontSize = styles.h3FontSize;
fontWeight = styles.h3FontWeight;
color = styles.h3Color;
marginBottom = styles.h3MarginBottom;
break;
case 4:
fontSize = styles.h4FontSize;
fontWeight = styles.h4FontWeight;
color = styles.h4Color;
marginBottom = styles.h4MarginBottom;
break;
case 5:
fontSize = styles.h5FontSize;
fontWeight = styles.h5FontWeight;
color = styles.h5Color;
marginBottom = styles.h5MarginBottom;
break;
case 6:
fontSize = styles.h6FontSize;
fontWeight = styles.h6FontWeight;
color = styles.h6Color;
marginBottom = styles.h6MarginBottom;
break;
default:
fontSize = 16;
fontWeight = @"normal";
color = @"inherit";
marginBottom = 0;
break;
}
[html appendFormat:@"%@ ",
(long)level, fontSize, fontWeight, color, marginBottom, inlineContent, (long)level];
}
static void handleParagraph(NSMutableString *html, NSMutableString *inlineContent, CachedStyles *styles)
{
[html appendFormat:@"%@
",
styles.paragraphMarginBottom, styles.paragraphColor, styles.paragraphFontSize, inlineContent];
}
#pragma mark - Main Generator
static NSString *dirAttrFromParagraphStyle(NSParagraphStyle *_Nullable style)
{
if (!style || style.baseWritingDirection == NSWritingDirectionNatural) {
return @"auto";
}
return style.baseWritingDirection == NSWritingDirectionRightToLeft ? @"rtl" : @"ltr";
}
NSString *_Nullable generateHTML(NSAttributedString *attributedString, StyleConfig *styleConfig)
{
if (!attributedString || attributedString.length == 0)
return nil;
attributedString = ENRMAttributedStringByExpandingLinkPills(attributedString, NULL);
CachedStyles *styles = cacheStyles(styleConfig);
NSParagraphStyle *firstParagraphStyle = [attributedString attribute:NSParagraphStyleAttributeName
atIndex:0
effectiveRange:NULL];
NSString *dirAttr = dirAttrFromParagraphStyle(firstParagraphStyle);
NSMutableString *html = [NSMutableString stringWithCapacity:attributedString.length * 2];
[html appendFormat:
@"",
dirAttr];
NSUInteger paragraphCount = 0;
NSData *paragraphsData = collectParagraphsData(attributedString, ¶graphCount);
ParagraphData *paragraphs = (ParagraphData *)paragraphsData.bytes;
GeneratorState *state = [[GeneratorState alloc] init];
NSMutableString *inlineBuffer = [NSMutableString stringWithCapacity:256];
for (NSUInteger i = 0; i < paragraphCount; i++) {
ParagraphData *para = ¶graphs[i];
NSString *content = [[attributedString.string substringWithRange:para->range]
stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
if (content.length == 0) {
state.previousWasBlockquote = NO;
continue;
}
[inlineBuffer setString:@""];
NSRange contentRange = para->range;
if (contentRange.length > 0 &&
[[attributedString.string substringWithRange:NSMakeRange(NSMaxRange(contentRange) - 1, 1)]
isEqualToString:@"\n"]) {
contentRange.length--;
}
BOOL isCodeBlockPara = (para->type == ParagraphTypeCodeBlock);
generateInlineHTML(inlineBuffer, attributedString, contentRange, styles, isCodeBlockPara);
if (isCodeBlockPara) {
handleCodeBlock(html, inlineBuffer, styles, state);
continue;
}
if (state.inCodeBlock) {
closeCodeBlock(html, state);
}
state.previousWasCodeBlock = NO;
if (para->type == ParagraphTypeBlockquote) {
handleBlockquote(html, para, inlineBuffer, styles, state);
continue;
}
if (state.inBlockquote) {
closeBlockquotes(html, state);
}
state.previousWasBlockquote = NO;
if (para->type == ParagraphTypeListItemUnordered || para->type == ParagraphTypeListItemOrdered ||
para->type == ParagraphTypeTaskList) {
handleListItem(html, para, inlineBuffer, styles, state);
continue;
}
if (state.currentListDepth >= 0) {
closeLists(html, state);
}
NSInteger hLevel = headingLevel(para->type);
if (hLevel > 0) {
handleHeading(html, para, inlineBuffer, styles);
continue;
}
handleParagraph(html, inlineBuffer, styles);
}
closeCodeBlock(html, state);
closeBlockquotes(html, state);
closeLists(html, state);
[html appendString:@""];
return html;
}
#pragma mark - Table HTML Generator
typedef NSString *HTMLString;
static NSString *alignmentToCSS(NSTextAlignment alignment)
{
switch (alignment) {
case NSTextAlignmentCenter:
return @"center";
case NSTextAlignmentRight:
return @"right";
case NSTextAlignmentJustified:
return @"justify";
default:
return @"left";
}
}
static NSString *styleForCell(BOOL isHeader, NSUInteger rowIndex, StyleConfig *styleConfig, NSTextAlignment alignment)
{
NSString *backgroundColor = isHeader ? colorToCSS(styleConfig.tableHeaderBackgroundColor)
: (rowIndex % 2 == 0 ? colorToCSS(styleConfig.tableRowEvenBackgroundColor)
: colorToCSS(styleConfig.tableRowOddBackgroundColor));
NSString *textColor = isHeader ? colorToCSS(styleConfig.tableHeaderTextColor) : colorToCSS(styleConfig.tableColor);
return [NSString stringWithFormat:
@"padding: %.0fpx %.0fpx; "
"text-align: %@; "
"background-color: %@; "
"color: %@; "
"border: %.0fpx solid %@; "
"font-weight: %@;",
styleConfig.tableCellPaddingVertical, styleConfig.tableCellPaddingHorizontal,
alignmentToCSS(alignment), backgroundColor, textColor, styleConfig.tableBorderWidth,
colorToCSS(styleConfig.tableBorderColor), isHeader ? @"bold" : @"normal"];
}
static NSString *tableDirAttrFromRows(NSArray *> *rows)
{
for (NSArray *row in rows) {
for (NSDictionary *cell in row) {
NSAttributedString *cellText = cell[@"attributedText"];
if (cellText.length == 0) {
continue;
}
NSParagraphStyle *style = [cellText attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:NULL];
return dirAttrFromParagraphStyle(style);
}
}
return @"auto";
}
HTMLString _Nullable generateTableHTML(NSArray *> *rows, StyleConfig *styleConfig)
{
if (rows.count == 0)
return nil;
CachedStyles *cachedStyles = cacheStyles(styleConfig);
NSMutableString *htmlOutput = [NSMutableString stringWithCapacity:rows.count * 250];
NSString *dirAttr = tableDirAttrFromRows(rows);
[htmlOutput appendFormat:
@"",
dirAttr, styleConfig.tableBorderWidth, colorToCSS(styleConfig.tableBorderColor),
styleConfig.tableBorderRadius, styleConfig.tableFontSize];
BOOL hasOpenedBody = NO;
NSUInteger bodyRowIndex = 0;
for (NSArray *row in rows) {
if (row.count == 0)
continue;
BOOL isHeaderRow = [row.firstObject[@"isHeader"] boolValue];
if (isHeaderRow) {
[htmlOutput appendString:@""];
} else if (!hasOpenedBody) {
[htmlOutput appendString:@""];
hasOpenedBody = YES;
}
[htmlOutput appendString:@""];
for (NSDictionary *cellInfo in row) {
BOOL isHeaderCell = [cellInfo[@"isHeader"] boolValue];
NSTextAlignment alignment = (NSTextAlignment)[cellInfo[@"alignment"] integerValue];
NSAttributedString *attributedText = cellInfo[@"attributedText"];
if (attributedText)
attributedText = ENRMAttributedStringByExpandingLinkPills(attributedText, NULL);
NSString *htmlTag = isHeaderCell ? @"th" : @"td";
NSString *cellStyle = styleForCell(isHeaderCell, bodyRowIndex, styleConfig, alignment);
[htmlOutput appendFormat:@"<%@ style=\"%@\">", htmlTag, cellStyle];
if (attributedText.length > 0) {
generateInlineHTML(htmlOutput, attributedText, NSMakeRange(0, attributedText.length), cachedStyles, NO);
}
[htmlOutput appendFormat:@"%@>", htmlTag];
}
[htmlOutput appendString:@" "];
if (isHeaderRow) {
[htmlOutput appendString:@""];
} else {
bodyRowIndex++;
}
}
if (hasOpenedBody) {
[htmlOutput appendString:@""];
}
[htmlOutput appendString:@"
"];
return [htmlOutput copy];
}