-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathENRMImageRenderer.m
More file actions
77 lines (62 loc) · 2.17 KB
/
ENRMImageRenderer.m
File metadata and controls
77 lines (62 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#import "ENRMImageRenderer.h"
#import "ENRMImageAttachment.h"
#import "MarkdownASTNode.h"
#import "RenderContext.h"
#import "RendererFactory.h"
#import "StyleConfig.h"
static const unichar kLineBreak = '\n';
static const unichar kZeroWidthSpace = 0x200B;
@implementation ENRMImageRenderer {
__weak RendererFactory *_rendererFactory;
StyleConfig *_config;
}
- (instancetype)initWithRendererFactory:(id)rendererFactory config:(id)config
{
if (self = [super init]) {
_rendererFactory = rendererFactory;
_config = (StyleConfig *)config;
}
return self;
}
- (void)renderNode:(MarkdownASTNode *)node into:(NSMutableAttributedString *)output context:(RenderContext *)context
{
NSString *imageURL = node.attributes[@"url"];
if (!imageURL || imageURL.length == 0) {
return;
}
BOOL isInline = [self isInlineImageInOutput:output];
ENRMImageAttachment *attachment = [ENRMImageAttachment attachmentForURL:imageURL config:_config isInline:isInline];
NSUInteger startIndex = output.length;
NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attachment];
[output appendAttributedString:imageString];
// Extract alt text from children ( - "alt text" is in children)
NSString *altText = [self extractTextFromNode:node];
NSRange imageRange = NSMakeRange(startIndex, output.length - startIndex);
[context registerImageRange:imageRange altText:altText url:imageURL];
}
- (NSString *)extractTextFromNode:(MarkdownASTNode *)node
{
if (!node)
return @"";
NSMutableString *buffer = [NSMutableString string];
[self _appendChildTextFromNode:node toBuffer:buffer];
return [buffer copy];
}
- (void)_appendChildTextFromNode:(MarkdownASTNode *)node toBuffer:(NSMutableString *)buffer
{
if (node.content.length > 0) {
[buffer appendString:node.content];
}
for (MarkdownASTNode *child in node.children) {
[self _appendChildTextFromNode:child toBuffer:buffer];
}
}
- (BOOL)isInlineImageInOutput:(NSAttributedString *)output
{
if (output.length == 0) {
return NO;
}
unichar lastChar = [output.string characterAtIndex:output.length - 1];
return (lastChar != kLineBreak && lastChar != kZeroWidthSpace);
}
@end