-
Notifications
You must be signed in to change notification settings - Fork 13
/
KSHTMLWriter.m
583 lines (482 loc) · 17.8 KB
/
KSHTMLWriter.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//
// KSHTMLWriter.m
//
// Created by Mike Abdullah
// Copyright © 2010 Karelia Software
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#import "KSHTMLWriter.h"
#import "KSXMLAttributes.h"
NSString *KSHTMLDoctypeHTML_4_01_Strict = @"HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"";
NSString *KSHTMLDoctypeHTML_4_01_Transitional = @"HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"";
NSString *KSHTMLDoctypeHTML_4_01_Frameset = @"HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\"";
NSString *KSHTMLDoctypeXHTML_1_0_Strict = @"html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"";
NSString *KSHTMLDoctypeXHTML_1_0_Transitional = @"html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"";
NSString *KSHTMLDoctypeXHTML_1_0_Frameset = @"html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\"";
NSString *KSHTMLDoctypeXHTML_1_1 = @"html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\"";
NSString *KSHTMLDoctypeHTML_5 = @"html";
@implementation KSHTMLWriter
#pragma mark Creating an HTML Writer
- initWithOutputWriter:(KSWriter *)output;
{
if (self = [super initWithOutputWriter:output])
{
self.doctype = KSHTMLDoctypeHTML_5;
self.prettyPrint = YES;
_classNames = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc
{
[_classNames release];
[super dealloc];
}
#pragma mark DTD
- (void)setDoctype:(NSString *)doctype;
{
[super setDoctype:doctype];
_isXHTML = [self.class isDoctypeXHTML:doctype];
}
+ (BOOL)isDoctypeXHTML:(NSString *)docType;
{
return ([docType isEqualToString:KSHTMLDoctypeXHTML_1_0_Strict] ||
[docType isEqualToString:KSHTMLDoctypeXHTML_1_0_Transitional] ||
[docType isEqualToString:KSHTMLDoctypeXHTML_1_0_Frameset] ||
[docType isEqualToString:KSHTMLDoctypeXHTML_1_1]);
}
- (void)writeDoctypeDeclaration {
[self writeString:@"<!doctype "];
[self writeString:self.doctype];
[self writeString:@">"];
[self startNewline];
}
#pragma mark CSS Class Name
- (NSString *)currentElementClassName;
{
NSString *result = nil;
if ([_classNames count])
{
result = [_classNames componentsJoinedByString:@" "];
}
return result;
}
- (void)pushClassName:(NSString *)className;
{
#ifdef DEBUG
if ([_classNames containsObject:className])
{
NSLog(@"Adding class \"%@\" to an element twice", className);
}
#endif
[_classNames addObject:className];
}
- (void)pushClassNames:(NSArray *)classNames;
{
// TODO: Check for duplicates while debugging
[_classNames addObjectsFromArray:classNames];
}
- (void)pushAttribute:(NSString *)attribute value:(id)value;
{
id newValue = [[value copy] autorelease]; // in case value was mutable and cleared later
if ([attribute isEqualToString:@"class"])
{
return [self pushClassName:newValue];
}
[super pushAttribute:attribute value:newValue];
}
- (KSXMLAttributes *)currentAttributes;
{
KSXMLAttributes *result = [super currentAttributes];
// Add in buffered class info
NSString *class = [self currentElementClassName];
if (class) [result addAttribute:@"class" value:class];
return result;
}
- (BOOL)hasCurrentAttributes;
{
return ([super hasCurrentAttributes] || [_classNames count]);
}
#pragma mark HTML Fragments
- (void)writeHTMLString:(NSString *)html withTerminatingNewline:(BOOL)terminatingNewline;
{
if (terminatingNewline)
{
if (![html hasSuffix:@"\n"]) html = [html stringByAppendingString:@"\n"];
}
else
{
if ([html hasSuffix:@"\n"]) html = [html substringToIndex:[html length] - 1];
}
[self writeHTMLString:html];
}
- (void)writeHTMLString:(NSString *)html; { [self writeHTMLString:html range:NSMakeRange(0, html.length)]; }
- (void)writeHTMLString:(NSString *)html range:(NSRange)range; // high-performance variant
{
NSUInteger indent = self.indentationLevel;
if (!indent) return [self writeString:html range:range]; // no need for work
// Write line-by-line, injecting tabs as needed
while (range.length)
{
NSRange newlineRange = [html rangeOfString:@"\n" options:0 range:range];
if (newlineRange.location == NSNotFound)
{
// Write the whole thing and be done with it!
[self writeString:html range:range];
return;
}
else
{
// Write the text up to and including the newline
NSRange toWrite = NSMakeRange(range.location, NSMaxRange(newlineRange) - range.location);
[self writeString:html range:toWrite];
// Insert tabs
for (NSUInteger i=0; i<indent; i++)
{
[self writeString:@"\t"];
}
// Carry on searching
range.location = NSMaxRange(newlineRange);
range.length -= toWrite.length;
}
}
}
#pragma mark General
- (void)writeElement:(NSString *)name idName:(NSString *)idName className:(NSString *)className content:(void (^)(void))content;
{
if (idName) [self pushAttribute:@"id" value:idName];
if (className) [self pushAttribute:@"class" value:className];
[self writeElement:name content:content];
}
- (void)startElement:(NSString *)tagName className:(NSString *)className;
{
[self startElement:tagName idName:nil className:className];
}
- (void)startElement:(NSString *)tagName idName:(NSString *)idName className:(NSString *)className;
{
if (idName) [self pushAttribute:@"id" value:idName];
if (className) [self pushAttribute:@"class" value:className];
[self startElement:tagName];
}
#pragma mark Document
- (void)writeDocumentWithHead:(void (^)(void))headBlock body:(void (^)(void))bodyBlock {
[self writeDoctypeDeclaration];
[self writeElement:@"html" content:^{
if (headBlock) [self writeElement:@"head" content:headBlock];
[self writeElement:@"body" content:bodyBlock];
}];
}
#pragma mark Line Break
- (void)writeLineBreak;
{
[self startElement:@"br"];
[self endElement];
}
#pragma mark Anchors
- (void)startAnchorElementWithHref:(NSString *)href title:(NSString *)titleString target:(NSString *)targetString rel:(NSString *)relString;
{
// TODO: Remove this method once Sandvox no longer needs it
[self startElement:@"a"];
if (href) [self addAttribute:@"href" value:href];
if (targetString) [self addAttribute:@"target" value:targetString];
if (titleString) [self addAttribute:@"title" value:titleString];
if (relString) [self addAttribute:@"rel" value:relString];
}
- (void)writeAnchorElementWithHref:(NSString *)href title:(NSString *)titleString target:(NSString *)targetString rel:(NSString *)relString content:(void (^)(void))content;
{
NSParameterAssert(content);
[self startAnchorElementWithHref:href title:titleString target:targetString rel:relString];
content();
[self endElement];
}
#pragma mark Images
- (void)writeImageWithSrc:(NSString *)src
alt:(NSString *)alt
width:(id)width
height:(id)height;
{
[self writeElement:@"img" content:^{
[self addAttribute:@"src" value:src];
[self addAttribute:@"alt" value:alt];
if (width) [self addAttribute:@"width" value:width];
if (height) [self addAttribute:@"height" value:height];
}];
}
#pragma mark Link
- (void)writeLinkWithHref:(NSString *)href
type:(NSString *)type
rel:(NSString *)rel
title:(NSString *)title
media:(NSString *)media;
{
[self writeElement:@"link" content:^{
if (rel) [self addAttribute:@"rel" value:rel];
if (type) [self addAttribute:@"type" value:type];
[self addAttribute:@"href" value:href];
if (title) [self addAttribute:@"title" value:title];
if (media) [self addAttribute:@"media" value:media];
}];
}
- (void)writeLinkToStylesheet:(NSString *)href
title:(NSString *)title
media:(NSString *)media;
{
[self writeLinkWithHref:href type:@"text/css" rel:@"stylesheet" title:title media:media];
}
#pragma mark Scripts
- (void)writeJavascriptWithSrc:(NSString *)src encoding:(NSStringEncoding)encoding;
{
// According to the HTML spec, charset only needs to be specified if the script is a different encoding to the document
NSString *charset = nil;
if (encoding != [self encoding])
{
charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding));
}
[self writeJavascriptWithSrc:src charset:charset];
}
- (void)writeJavascriptWithSrc:(NSString *)src charset:(NSString *)charset; // src may be nil
{
[self startJavascriptElementWithSrc:src];
if (charset) [self addAttribute:@"charset" value:charset];
if (!src) [self increaseIndentationLevel]; // compensate for -decreaseIndentationLevel
[self endElement];
}
- (void)writeJavascript:(NSString *)script useCDATA:(BOOL)useCDATA;
{
[self writeJavascriptWithContent:^{
if (useCDATA) [self startJavascriptCDATA];
[self writeHTMLString:script];
if (useCDATA) [self endJavascriptCDATA];
}];
}
- (void)writeJavascriptWithContent:(void (^)(void))content;
{
[self startJavascriptElementWithSrc:nil];
content();
[self increaseIndentationLevel]; // compensate for -decreaseIndentationLevel
[self endElement];
}
- (void)startJavascriptElementWithSrc:(NSString *)src; // src may be nil
{
[self startElement:@"script"];
// HTML5 doesn't need the script type specified, but older doc types do for standards-compliance
if (![self.doctype isEqualToString:KSHTMLDoctypeHTML_5])
{
[self addAttribute:@"type" value:@"text/javascript"];
}
// Script
if (src)
{
[self addAttribute:@"src" value:src];
}
else
{
// Outdent the script compared to what's normal. Context will take care of placing on a
// new line for us
[self decreaseIndentationLevel];
[self startNewline];
}
}
- (void)startJavascriptCDATA;
{
[self writeString:@"\n/* "];
[self startCDATA];
[self writeString:@" */"];
}
- (void)endJavascriptCDATA;
{
[self writeString:@"\n/* "];
[self endCDATA];
[self writeString:@" */\n"];
}
#pragma mark Param
- (void)writeParamElementWithName:(NSString *)name value:(NSString *)value;
{
[self writeElement:@"param" content:^{
if (name) [self addAttribute:@"name" value:name];
if (value) [self addAttribute:@"value" value:value];
}];
}
#pragma mark Style
- (void)writeStyleElementWithCSSString:(NSString *)css;
{
[self startStyleElementWithType:@"text/css"];
[self writeString:css]; // browsers don't expect styles to be XML escaped
[self endElement];
}
- (void)startStyleElementWithType:(NSString *)type;
{
[self startElement:@"style"];
if (type) [self addAttribute:@"type" value:type];
}
#pragma mark Elements Stack
- (BOOL)hasListOpen;
{
return ([self hasOpenElement:@"ul"] || [self hasOpenElement:@"ol"]);
}
- (BOOL)topElementIsList;
{
return [[self class] elementIsList:[self topElement]];
}
+ (BOOL)elementIsList:(NSString *)element;
{
BOOL result = ([element isEqualToString:@"ul"] ||
[element isEqualToString:@"ol"]);
return result;
}
#pragma mark (X)HTML
- (BOOL)isVoidElement:(NSString *)tagName;
{
static NSSet *voidElements;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements
voidElements = [[NSSet alloc] initWithObjects:
@"area",
@"base",
@"br",
@"col",
@"embed",
@"hr",
@"img",
@"input",
@"keygen",
@"link",
@"menuitem",
@"meta",
@"param",
@"source",
@"track",
@"wbr", nil];
});
return [voidElements containsObject:tagName];
}
+ (BOOL)shouldPrettyPrintElementInline:(NSString *)elementName;
{
switch ([elementName length])
{
case 1:
if ([elementName isEqualToString:@"a"] ||
[elementName isEqualToString:@"b"] ||
[elementName isEqualToString:@"i"] ||
[elementName isEqualToString:@"s"] ||
[elementName isEqualToString:@"u"] ||
[elementName isEqualToString:@"q"]) return YES;
break;
case 2:
if ([elementName isEqualToString:@"br"] ||
[elementName isEqualToString:@"em"] ||
[elementName isEqualToString:@"tt"]) return YES;
break;
case 3:
if ([elementName isEqualToString:@"img"] ||
[elementName isEqualToString:@"sup"] ||
[elementName isEqualToString:@"sub"] ||
[elementName isEqualToString:@"big"] ||
[elementName isEqualToString:@"del"] ||
[elementName isEqualToString:@"ins"] ||
[elementName isEqualToString:@"dfn"] ||
[elementName isEqualToString:@"map"] ||
[elementName isEqualToString:@"var"] ||
[elementName isEqualToString:@"bdo"] ||
[elementName isEqualToString:@"kbd"]) return YES;
break;
case 4:
if ([elementName isEqualToString:@"span"] ||
[elementName isEqualToString:@"font"] ||
[elementName isEqualToString:@"abbr"] ||
[elementName isEqualToString:@"cite"] ||
[elementName isEqualToString:@"code"] ||
[elementName isEqualToString:@"samp"]) return YES;
break;
case 5:
if ([elementName isEqualToString:@"small"] ||
[elementName isEqualToString:@"input"] ||
[elementName isEqualToString:@"label"]) return YES;
break;
case 6:
if ([elementName isEqualToString:@"strong"] ||
[elementName isEqualToString:@"select"] ||
[elementName isEqualToString:@"button"] ||
[elementName isEqualToString:@"object"] ||
[elementName isEqualToString:@"applet"] ||
[elementName isEqualToString:@"script"] ||
[elementName isEqualToString:@"strike"]) return YES;
break;
case 7:
if ([elementName isEqualToString:@"acronym"]) return YES;
break;
case 8:
if ([elementName isEqualToString:@"textarea"]) return YES;
break;
}
return [super shouldPrettyPrintElementInline:elementName];
}
- (BOOL)validateElement:(NSString *)element;
{
if (![super validateElement:element]) return NO;
// Lists can only contain list items
if ([self topElementIsList])
{
return [element isEqualToString:@"li"];
}
else
{
return YES;
}
}
- (NSString *)validateAttribute:(NSString *)name value:(NSString *)value ofElement:(NSString *)element;
{
NSString *result = [super validateAttribute:name value:value ofElement:element];
if (!result) return nil;
// value is only allowed as a list item attribute when in an ordered list
if ([element isEqualToString:@"li"] && [name isEqualToString:@"value"])
{
if (![[self topElement] isEqualToString:@"ol"]) result = nil;
}
return result;
}
#pragma mark Element Primitives
- (void)startElement:(NSString *)elementName {
#ifdef DEBUG
NSAssert1([elementName isEqualToString:[elementName lowercaseString]], @"Attempt to start non-lowercase element: %@", elementName);
#endif
[super startElement:elementName];
// Add in any pre-written classes
NSString *class = [self currentElementClassName];
if (class)
{
[_classNames removeAllObjects];
[self addAttribute:@"class" value:class];
}
}
- (void)closeEmptyElementTag; // /> OR > depending on -isXHTML
{
if ([self isXHTML])
{
// http://dev.w3.org/html5/html-author/#tags tells us a space before the slash isn't needed
[self writeString:@"/>"];
}
else
{
[self writeString:@">"];
}
}
@end