forked from nolanw/HTMLReader
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHTMLElement.m
92 lines (73 loc) · 2.21 KB
/
HTMLElement.m
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// HTMLElement.m
//
// Public domain. https://github.com/nolanw/HTMLReader
#import "HTMLElement.h"
#import "HTMLOrderedDictionary.h"
#import "HTMLSelector.h"
NS_ASSUME_NONNULL_BEGIN
@implementation HTMLElement
{
HTMLOrderedDictionary *_attributes;
}
- (instancetype)initWithTagName:(NSString *)tagName attributes:(HTMLDictOf(NSString *, NSString *) * __nullable)attributes
{
NSParameterAssert(tagName);
if ((self = [super init])) {
_tagName = [tagName copy];
_attributes = [HTMLOrderedDictionary new];
if (attributes) {
[_attributes addEntriesFromDictionary:(NSDictionary * __nonnull)attributes];
}
}
return self;
}
- (instancetype)init
{
return [self initWithTagName:@"" attributes:nil];
}
- (HTMLDictOf(NSString *, NSString *) *)attributes
{
return [_attributes copy];
}
- (id __nullable)objectForKeyedSubscript:(id)attributeName
{
return _attributes[attributeName];
}
- (void)setObject:(NSString *)attributeValue forKeyedSubscript:(NSString *)attributeName
{
NSParameterAssert(attributeValue);
_attributes[attributeName] = attributeValue;
}
- (void)removeAttributeWithName:(NSString *)attributeName
{
[_attributes removeObjectForKey:attributeName];
}
- (BOOL)hasClass:(NSString *)className
{
NSParameterAssert(className);
NSArray *classes = [self[@"class"] componentsSeparatedByCharactersInSet:HTMLSelectorWhitespaceCharacterSet()];
return [classes containsObject:className];
}
- (void)toggleClass:(NSString *)className
{
NSParameterAssert(className);
NSString *classValue = self[@"class"] ?: @"";
NSMutableArray *classes = [[classValue componentsSeparatedByCharactersInSet:HTMLSelectorWhitespaceCharacterSet()] mutableCopy];
NSUInteger i = [classes indexOfObject:className];
if (i == NSNotFound) {
[classes addObject:className];
} else {
[classes removeObjectAtIndex:i];
}
self[@"class"] = [classes componentsJoinedByString:@" "];
}
#pragma mark NSCopying
- (id)copyWithZone:(NSZone * __nullable)zone
{
HTMLElement *copy = [super copyWithZone:zone];
copy->_tagName = self.tagName;
copy->_attributes = [_attributes copy];
return copy;
}
@end
NS_ASSUME_NONNULL_END