Menu

[r3166]: / trunk / Src / UHTMLUtils.pas  Maximize  Restore  History

Download this file

397 lines (352 with data), 12.5 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
 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
{
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/
*
* Copyright (C) 2005-2013, Peter Johnson (www.delphidabbler.com).
*
* $Rev$
* $Date$
*
* Helper interfaces and classes used to generate HTML.
}
unit UHTMLUtils;
interface
uses
// Delphi
Classes, Graphics, Generics.Collections,
// Project
UIStringList;
type
{
IHTMLAttributes:
Interface to object that can build a list of HTML tag attributes and render
them.
}
IHTMLAttributes = interface(IInterface)
['{2CE69ED2-9622-45A9-A800-5513443D1371}']
function IsEmpty: Boolean;
{Determines if attributes object is empty.
@return True if there are no attributes, False otherwise.
}
function Render: string;
{Renders attributes as plain text.
@return Text representation of attributes.
}
function RenderSafe: string;
{Renders attributes as HTML safe text.
@return HTML safe representation of attributes.
}
procedure Add(const Name, Value: string); overload;
{Adds a named attribute with its value.
@param Name [in] Name of attribute.
@param Value [in] Value of attribute. If '' attribute is not added.
}
procedure Add(const Name: string; Values: IStringList); overload;
{Adds a named attribute and spaced separated list of values.
@param Name [in] Name of attribute.
@param Values [in] String list of attribute values. If not assigned or
empty, attribute is not added.
}
procedure Append(Attrs: IHTMLAttributes);
{Appends all given attributes to these attributes. Any attributes with
same name as an existing attribute overwrite the existing one.
@param Attrs [in] Attributes to be appended.
}
end;
type
// Type that stores the name / value pairs of an HTML attribute
THTMLAttribute = TPair<string,string>;
{
THTMLAttributes:
Class that can build a list of HTML tag attributes and render them.
}
THTMLAttributes = class(TInterfacedObject, IHTMLAttributes)
strict private
fAttrs: TStringList;
{Maintains list of attributes as name=value pairs}
public
constructor Create; overload;
{Object constructor. Sets up empty object.
}
constructor Create(const Name, Value: string); overload;
{Object constructor. Sets up object containing a single named attribute.
@param Name [in] Name of attribute.
@param Value [in] Value of attribute. If '' attribute is not added.
}
constructor Create(Attrs: array of THTMLAttribute); overload;
{Object constructor. Sets up object containing zero or more named
attributes.
@param Attrs [in] Array of attributes represented by THTMLAttribute
records.
}
destructor Destroy; override;
{Object destructor. Tears down object.
}
{ IHTMLAttributes methods }
function IsEmpty: Boolean;
{Determines if attributes object is empty.
@return True if there are no attributes, False otherwise.
}
function Render: string;
{Renders attributes as plain text.
@return Text representation of attributes.
}
function RenderSafe: string;
{Renders attributes as HTML safe text.
@return HTML safe representation of attributes.
}
procedure Add(const Name, Value: string); overload;
{Adds a named attribute with its value.
@param Name [in] Name of attribute.
@param Value [in] Value of attribute. If '' attribute is not added.
}
procedure Add(const Name: string; Values: IStringList); overload;
{Adds a named attribute and spaced separated list of values.
@param Name [in] Name of attribute.
@param Values [in] String list of attribute values. If not assigned or
empty, attribute is not added.
}
procedure Append(Attrs: IHTMLAttributes);
{Appends all given attributes to these attributes. Any attributes with
same name as an existing attribute overwrite the existing one.
@param Attrs [in] Attributes to be appended.
}
end;
type
/// <summary>
/// Container for static methods that generate HTML tags and entities.
/// </summary>
THTML = record
strict private
/// <summary>Generates either an HTML start tag or a simple tag with given
/// name and attributes.</summary>
/// <param name="Name">string [in] Tag name.</param>
/// <param name="Attrs">IHTMLAttributes [in] Attributes to include in tag.
/// May be nil if no attributes are required.</param>
/// <param name="IsSimple">Boolean [in] Flag indicating whether tag is to
/// be simple (True) or the start of a compound tag (False).</param>
/// <returns>string. Required tag.</returns>
class function TagWithAttrs(const Name: string; Attrs: IHTMLAttributes;
const IsSimple: Boolean): string; static;
public
/// <summary>Generates an opening HTML tag.</summary>
/// <param name="Name">string [in] Name of tag.</param>
/// <param name="Attrs">IHTMLAttributes [in] Optional tag attributes. Omit
/// or set to nil if no attributes are required.</param>
/// <returns>String. Required tag.</returns>
/// <remarks>Example tag: &lt;p class=&quot;ident&quot;&gt;</remarks>
class function OpeningTag(const Name: string; Attrs: IHTMLAttributes = nil):
string; static;
/// <summary>Generates a closing HTML tag.</summary>
/// <param name="Name">string [in] Name of tag.</param>
/// <returns>String. Required tag.</returns>
/// <remarks>Example tag: &lt;/p&gt;</remarks>
class function ClosingTag(const Name: string): string; static;
/// <summary>Generates a simple HTML tag.</summary>
/// <param name="Name">string [in] Name of tag.</param>
/// <param name="Attrs">IHTMLAttributes [in] Optional tag attributes. Omit
/// or set to nil if no attributes are required.</param>
/// <returns>String. Required tag.</returns>
/// <remarks>Example tag: &lt;img class=&quot;glyph&quot; /&gt;</remarks>
class function SimpleTag(const Name: string; Attrs: IHTMLAttributes = nil):
string; static;
/// <summary>Surrounds the given HTML in a HTML tag pair.</summary>
/// <param name="Name">string [in] Name of tag.</param>
/// <param name="Attrs">IHTMLAttributes [in] Required attributes of tag.
/// </param>
/// <param name="InnerHTML">string [in] HTML that is to be enclosed within
/// the tag pair.</param>
/// <returns>String. Required tag.</returns>
class function CompoundTag(const Name: string; Attrs: IHTMLAttributes;
const InnerHTML: string): string; overload; static;
/// <summary>Surrounds the given HTML in a HTML tag pair. The opening tag
/// has no attributes.</summary>
/// <param name="Name">string [in] Name of tag.</param>
/// <param name="InnerHTML">string [in] HTML that is to be enclosed within
/// the tag pair.</param>
/// <returns>String. Required tag.</returns>
class function CompoundTag(const Name, InnerHTML: string): string; overload;
static;
/// <summary>Encodes the given string replacing any HTML-incompatible
/// characters with character entities.</summary>
class function Entities(const Text: string): string; static;
end;
implementation
uses
// Delphi
SysUtils, Windows,
// Project
UCSSUtils, UExceptions, UStrUtils, UURIEncode;
{ THTML }
class function THTML.ClosingTag(const Name: string): string;
begin
Result := '</' + StrToLower(Name) + '>';
end;
class function THTML.CompoundTag(const Name: string; Attrs: IHTMLAttributes;
const InnerHTML: string): string;
begin
Result := OpeningTag(Name, Attrs) + InnerHTML + ClosingTag(Name);
end;
class function THTML.CompoundTag(const Name, InnerHTML: string): string;
begin
Result := CompoundTag(Name, nil, InnerHTML);
end;
class function THTML.Entities(const Text: string): string;
var
Ch: Char; // each character in Text
SB: TStringBuilder; // used to build the result string
begin
SB := TStringBuilder.Create;
try
for Ch in Text do
begin
case Ch of
'<':
SB.Append('&lt;');
'>':
SB.Append('&gt;');
'&':
SB.Append('&amp;');
'"':
SB.Append('&quot;');
#0..#9, #11, #12, #14..#31:
SB.Append('&#' + IntToStr(Ord(Ch)) + ';')
else
SB.Append(Ch);
end;
end;
Result := SB.ToString;
finally
SB.Free;
end;
end;
class function THTML.OpeningTag(const Name: string;
Attrs: IHTMLAttributes): string;
begin
Result := TagWithAttrs(Name, Attrs, False);
end;
class function THTML.SimpleTag(const Name: string;
Attrs: IHTMLAttributes): string;
begin
Result := TagWithAttrs(Name, Attrs, True);
end;
class function THTML.TagWithAttrs(const Name: string; Attrs: IHTMLAttributes;
const IsSimple: Boolean): string;
begin
Result := '<' + StrToLower(Name);
if Assigned(Attrs) and (not Attrs.IsEmpty) then
Result := Result + ' ' + Attrs.RenderSafe;
if IsSimple then
Result := Result + ' />'
else
Result := Result + '>';
end;
{ THTMLAttributes }
procedure THTMLAttributes.Add(const Name, Value: string);
{Adds a named attribute with its value.
@param Name [in] Name of attribute.
@param Value [in] Value of attribute. If '' attribute is not added.
}
begin
fAttrs.Values[Name] := Value; // this deletes entry if Value is ''
end;
procedure THTMLAttributes.Add(const Name: string; Values: IStringList);
{Adds a named attribute and spaced separated list of values.
@param Name [in] Name of attribute.
@param Values [in] String list of attribute values. If not assigned or
empty, attribute is not added.
}
begin
if Assigned(Values) and (Values.Count > 0) then
Add(Name, Values.GetText(' ', False));
end;
procedure THTMLAttributes.Append(Attrs: IHTMLAttributes);
{Appends all given attributes to these attributes. Any attributes with
same name as an existing attribute overwrite the existing one.
@param Attrs [in] Attributes to be appended.
}
var
Idx: Integer;
AttrsObj: THTMLAttributes;
begin
if not Assigned(Attrs) or Attrs.IsEmpty then
Exit;
AttrsObj := Attrs as THTMLAttributes;
for Idx := 0 to Pred(AttrsObj.fAttrs.Count) do
Add(AttrsObj.fAttrs.Names[Idx], AttrsObj.fAttrs.ValueFromIndex[Idx]);
end;
constructor THTMLAttributes.Create;
{Object constructor. Sets up empty object.
}
begin
inherited Create;
fAttrs := TStringList.Create;
end;
constructor THTMLAttributes.Create(const Name, Value: string);
{Object constructor. Sets up object containing a single named attribute.
@param Name [in] Name of attribute.
@param Value [in] Value of attribute. If '' attribute is not added.
}
begin
Create;
Add(Name, Value);
end;
constructor THTMLAttributes.Create(Attrs: array of THTMLAttribute);
{Object constructor. Sets up object containing zero or more named attributes.
@param Attrs [in] Array of attributes represented by THTMLAttribute records.
}
var
Attr: THTMLAttribute; // each attribute
begin
Create;
for Attr in Attrs do
Add(Attr.Key, Attr.Value);
end;
destructor THTMLAttributes.Destroy;
{Object destructor. Tears down object.
}
begin
fAttrs.Free;
inherited;
end;
function THTMLAttributes.IsEmpty: Boolean;
{Determines if attributes object is empty.
@return True if there are no attributes, False otherwise.
}
begin
Result := fAttrs.Count = 0;
end;
function THTMLAttributes.Render: string;
{Renders attributes as plain text.
@return Text representation of attributes.
}
var
Idx: Integer; // loops thru each attribute
begin
Result := '';
for Idx := 0 to Pred(fAttrs.Count) do
Result := Result + Format(
' %0:s="%1:s"', [fAttrs.Names[Idx], fAttrs.ValueFromIndex[Idx]]
);
Result := StrTrimLeft(Result);
end;
function THTMLAttributes.RenderSafe: string;
{Renders attributes as HTML safe text.
@return HTML safe representation of attributes.
}
var
Idx: Integer;
begin
Result := '';
for Idx := 0 to Pred(fAttrs.Count) do
Result := Result + Format(
' %0:s="%1:s"',
[
THTML.Entities(fAttrs.Names[Idx]),
THTML.Entities(fAttrs.ValueFromIndex[Idx])
]
);
Result := StrTrimLeft(Result);
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.