1 | package Mojo::DOM::HTML;
|
---|
2 | use Mojo::Base -base;
|
---|
3 |
|
---|
4 | use Exporter 'import';
|
---|
5 | use Mojo::Util qw(html_attr_unescape html_unescape xml_escape);
|
---|
6 | use Scalar::Util 'weaken';
|
---|
7 |
|
---|
8 | our @EXPORT_OK = ('tag_to_html');
|
---|
9 |
|
---|
10 | has tree => sub { ['root'] };
|
---|
11 | has 'xml';
|
---|
12 |
|
---|
13 | my $ATTR_RE = qr/
|
---|
14 | ([^<>=\s\/]+|\/) # Key
|
---|
15 | (?:
|
---|
16 | \s*=\s*
|
---|
17 | (?s:(["'])(.*?)\g{-2}|([^>\s]*)) # Value
|
---|
18 | )?
|
---|
19 | \s*
|
---|
20 | /x;
|
---|
21 | my $TOKEN_RE = qr/
|
---|
22 | ([^<]+)? # Text
|
---|
23 | (?:
|
---|
24 | <(?:
|
---|
25 | !(?:
|
---|
26 | DOCTYPE(
|
---|
27 | \s+\w+ # Doctype
|
---|
28 | (?:(?:\s+\w+)?(?:\s+(?:"[^"]*"|'[^']*'))+)? # External ID
|
---|
29 | (?:\s+\[.+?\])? # Int Subset
|
---|
30 | \s*)
|
---|
31 | |
|
---|
32 | --(.*?)--\s* # Comment
|
---|
33 | |
|
---|
34 | \[CDATA\[(.*?)\]\] # CDATA
|
---|
35 | )
|
---|
36 | |
|
---|
37 | \?(.*?)\? # Processing Instruction
|
---|
38 | |
|
---|
39 | \s*([^<>\s]+\s*(?:(?:$ATTR_RE){0,32766})*+) # Tag
|
---|
40 | )>
|
---|
41 | |
|
---|
42 | (<) # Runaway "<"
|
---|
43 | )??
|
---|
44 | /xis;
|
---|
45 |
|
---|
46 | # HTML elements that only contain raw text
|
---|
47 | my %RAW = map { $_ => 1 } qw(script style);
|
---|
48 |
|
---|
49 | # HTML elements that only contain raw text and entities
|
---|
50 | my %RCDATA = map { $_ => 1 } qw(title textarea);
|
---|
51 |
|
---|
52 | # HTML elements with optional end tags
|
---|
53 | my %END = (body => 'head', optgroup => 'optgroup', option => 'option');
|
---|
54 |
|
---|
55 | # HTML elements that break paragraphs
|
---|
56 | map { $END{$_} = 'p' } (
|
---|
57 | qw(address article aside blockquote details div dl fieldset figcaption),
|
---|
58 | qw(figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p),
|
---|
59 | qw(pre section table ul)
|
---|
60 | );
|
---|
61 |
|
---|
62 | # HTML table elements with optional end tags
|
---|
63 | my %TABLE = map { $_ => 1 } qw(colgroup tbody td tfoot th thead tr);
|
---|
64 |
|
---|
65 | # HTML elements with optional end tags and scoping rules
|
---|
66 | my %CLOSE
|
---|
67 | = (li => [{li => 1}, {ul => 1, ol => 1}], tr => [{tr => 1}, {table => 1}]);
|
---|
68 | $CLOSE{$_} = [\%TABLE, {table => 1}] for qw(colgroup tbody tfoot thead);
|
---|
69 | $CLOSE{$_} = [{dd => 1, dt => 1}, {dl => 1}] for qw(dd dt);
|
---|
70 | $CLOSE{$_} = [{rp => 1, rt => 1}, {ruby => 1}] for qw(rp rt);
|
---|
71 | $CLOSE{$_} = [{th => 1, td => 1}, {table => 1}] for qw(td th);
|
---|
72 |
|
---|
73 | # HTML elements without end tags
|
---|
74 | my %EMPTY = map { $_ => 1 } (
|
---|
75 | qw(area base br col embed hr img input keygen link menuitem meta param),
|
---|
76 | qw(source track wbr)
|
---|
77 | );
|
---|
78 |
|
---|
79 | # HTML elements categorized as phrasing content (and obsolete inline elements)
|
---|
80 | my @PHRASING = (
|
---|
81 | qw(a abbr area audio b bdi bdo br button canvas cite code data datalist),
|
---|
82 | qw(del dfn em embed i iframe img input ins kbd keygen label link map mark),
|
---|
83 | qw(math meta meter noscript object output picture progress q ruby s samp),
|
---|
84 | qw(script select slot small span strong sub sup svg template textarea time u),
|
---|
85 | qw(var video wbr)
|
---|
86 | );
|
---|
87 | my @OBSOLETE = qw(acronym applet basefont big font strike tt);
|
---|
88 | my %PHRASING = map { $_ => 1 } @OBSOLETE, @PHRASING;
|
---|
89 |
|
---|
90 | # HTML elements that don't get their self-closing flag acknowledged
|
---|
91 | my %BLOCK = map { $_ => 1 } (
|
---|
92 | qw(a address applet article aside b big blockquote body button caption),
|
---|
93 | qw(center code col colgroup dd details dialog dir div dl dt em fieldset),
|
---|
94 | qw(figcaption figure font footer form frameset h1 h2 h3 h4 h5 h6 head),
|
---|
95 | qw(header hgroup html i iframe li listing main marquee menu nav nobr),
|
---|
96 | qw(noembed noframes noscript object ol optgroup option p plaintext pre rp),
|
---|
97 | qw(rt s script section select small strike strong style summary table),
|
---|
98 | qw(tbody td template textarea tfoot th thead title tr tt u ul xmp)
|
---|
99 | );
|
---|
100 |
|
---|
101 | sub parse {
|
---|
102 | my ($self, $html) = (shift, "$_[0]");
|
---|
103 |
|
---|
104 | my $xml = $self->xml;
|
---|
105 | my $current = my $tree = ['root'];
|
---|
106 | while ($html =~ /\G$TOKEN_RE/gcso) {
|
---|
107 | my ($text, $doctype, $comment, $cdata, $pi, $tag, $runaway)
|
---|
108 | = ($1, $2, $3, $4, $5, $6, $11);
|
---|
109 |
|
---|
110 | # Text (and runaway "<")
|
---|
111 | $text .= '<' if defined $runaway;
|
---|
112 | _node($current, 'text', html_unescape $text) if defined $text;
|
---|
113 |
|
---|
114 | # Tag
|
---|
115 | if (defined $tag) {
|
---|
116 |
|
---|
117 | # End
|
---|
118 | if ($tag =~ /^\/\s*(\S+)/) { _end($xml ? $1 : lc $1, $xml, \$current) }
|
---|
119 |
|
---|
120 | # Start
|
---|
121 | elsif ($tag =~ m!^([^\s/]+)([\s\S]*)!) {
|
---|
122 | my ($start, $attr) = ($xml ? $1 : lc $1, $2);
|
---|
123 |
|
---|
124 | # Attributes
|
---|
125 | my (%attrs, $closing);
|
---|
126 | while ($attr =~ /$ATTR_RE/go) {
|
---|
127 | my ($key, $value) = ($xml ? $1 : lc $1, $3 // $4);
|
---|
128 |
|
---|
129 | # Empty tag
|
---|
130 | ++$closing and next if $key eq '/';
|
---|
131 |
|
---|
132 | $attrs{$key} = defined $value ? html_attr_unescape $value : $value;
|
---|
133 | }
|
---|
134 |
|
---|
135 | # "image" is an alias for "img"
|
---|
136 | $start = 'img' if !$xml && $start eq 'image';
|
---|
137 | _start($start, \%attrs, $xml, \$current);
|
---|
138 |
|
---|
139 | # Element without end tag (self-closing)
|
---|
140 | _end($start, $xml, \$current)
|
---|
141 | if !$xml && $EMPTY{$start} || ($xml || !$BLOCK{$start}) && $closing;
|
---|
142 |
|
---|
143 | # Raw text elements
|
---|
144 | next if $xml || !$RAW{$start} && !$RCDATA{$start};
|
---|
145 | next unless $html =~ m!\G(.*?)<\s*/\s*\Q$start\E\s*>!gcsi;
|
---|
146 | _node($current, 'raw', $RCDATA{$start} ? html_unescape $1 : $1);
|
---|
147 | _end($start, 0, \$current);
|
---|
148 | }
|
---|
149 | }
|
---|
150 |
|
---|
151 | # DOCTYPE
|
---|
152 | elsif (defined $doctype) { _node($current, 'doctype', $doctype) }
|
---|
153 |
|
---|
154 | # Comment
|
---|
155 | elsif (defined $comment) { _node($current, 'comment', $comment) }
|
---|
156 |
|
---|
157 | # CDATA
|
---|
158 | elsif (defined $cdata) { _node($current, 'cdata', $cdata) }
|
---|
159 |
|
---|
160 | # Processing instruction (try to detect XML)
|
---|
161 | elsif (defined $pi) {
|
---|
162 | $self->xml($xml = 1) if !exists $self->{xml} && $pi =~ /xml/i;
|
---|
163 | _node($current, 'pi', $pi);
|
---|
164 | }
|
---|
165 | }
|
---|
166 |
|
---|
167 | return $self->tree($tree);
|
---|
168 | }
|
---|
169 |
|
---|
170 | sub render { _render($_[0]->tree, $_[0]->xml) }
|
---|
171 |
|
---|
172 | sub tag { shift->tree(['root', _tag(@_)]) }
|
---|
173 |
|
---|
174 | sub tag_to_html { _render(_tag(@_), undef) }
|
---|
175 |
|
---|
176 | sub _end {
|
---|
177 | my ($end, $xml, $current) = @_;
|
---|
178 |
|
---|
179 | # Search stack for start tag
|
---|
180 | my $next = $$current;
|
---|
181 | do {
|
---|
182 |
|
---|
183 | # Ignore useless end tag
|
---|
184 | return if $next->[0] eq 'root';
|
---|
185 |
|
---|
186 | # Right tag
|
---|
187 | return $$current = $next->[3] if $next->[1] eq $end;
|
---|
188 |
|
---|
189 | # Phrasing content can only cross phrasing content
|
---|
190 | return if !$xml && $PHRASING{$end} && !$PHRASING{$next->[1]};
|
---|
191 |
|
---|
192 | } while $next = $next->[3];
|
---|
193 | }
|
---|
194 |
|
---|
195 | sub _node {
|
---|
196 | my ($current, $type, $content) = @_;
|
---|
197 | push @$current, my $new = [$type, $content, $current];
|
---|
198 | weaken $new->[2];
|
---|
199 | }
|
---|
200 |
|
---|
201 | sub _render {
|
---|
202 | my ($tree, $xml) = @_;
|
---|
203 |
|
---|
204 | # Tag
|
---|
205 | my $type = $tree->[0];
|
---|
206 | if ($type eq 'tag') {
|
---|
207 |
|
---|
208 | # Start tag
|
---|
209 | my $tag = $tree->[1];
|
---|
210 | my $result = "<$tag";
|
---|
211 |
|
---|
212 | # Attributes
|
---|
213 | for my $key (sort keys %{$tree->[2]}) {
|
---|
214 | my $value = $tree->[2]{$key};
|
---|
215 | $result .= $xml ? qq{ $key="$key"} : " $key" and next
|
---|
216 | unless defined $value;
|
---|
217 | $result .= qq{ $key="} . xml_escape($value) . '"';
|
---|
218 | }
|
---|
219 |
|
---|
220 | # No children
|
---|
221 | return $xml ? "$result />" : $EMPTY{$tag} ? "$result>" : "$result></$tag>"
|
---|
222 | unless $tree->[4];
|
---|
223 |
|
---|
224 | # Children
|
---|
225 | no warnings 'recursion';
|
---|
226 | $result .= '>' . join '', map { _render($_, $xml) } @$tree[4 .. $#$tree];
|
---|
227 |
|
---|
228 | # End tag
|
---|
229 | return "$result</$tag>";
|
---|
230 | }
|
---|
231 |
|
---|
232 | # Text (escaped)
|
---|
233 | return xml_escape $tree->[1] if $type eq 'text';
|
---|
234 |
|
---|
235 | # Raw text
|
---|
236 | return $tree->[1] if $type eq 'raw';
|
---|
237 |
|
---|
238 | # Root
|
---|
239 | return join '', map { _render($_, $xml) } @$tree[1 .. $#$tree]
|
---|
240 | if $type eq 'root';
|
---|
241 |
|
---|
242 | # DOCTYPE
|
---|
243 | return '<!DOCTYPE' . $tree->[1] . '>' if $type eq 'doctype';
|
---|
244 |
|
---|
245 | # Comment
|
---|
246 | return '<!--' . $tree->[1] . '-->' if $type eq 'comment';
|
---|
247 |
|
---|
248 | # CDATA
|
---|
249 | return '<![CDATA[' . $tree->[1] . ']]>' if $type eq 'cdata';
|
---|
250 |
|
---|
251 | # Processing instruction
|
---|
252 | return '<?' . $tree->[1] . '?>' if $type eq 'pi';
|
---|
253 |
|
---|
254 | # Everything else
|
---|
255 | return '';
|
---|
256 | }
|
---|
257 |
|
---|
258 | sub _start {
|
---|
259 | my ($start, $attrs, $xml, $current) = @_;
|
---|
260 |
|
---|
261 | # Autoclose optional HTML elements
|
---|
262 | if (!$xml && $$current->[0] ne 'root') {
|
---|
263 | if (my $end = $END{$start}) { _end($end, 0, $current) }
|
---|
264 |
|
---|
265 | elsif (my $close = $CLOSE{$start}) {
|
---|
266 | my ($allowed, $scope) = @$close;
|
---|
267 |
|
---|
268 | # Close allowed parent elements in scope
|
---|
269 | my $parent = $$current;
|
---|
270 | while ($parent->[0] ne 'root' && !$scope->{$parent->[1]}) {
|
---|
271 | _end($parent->[1], 0, $current) if $allowed->{$parent->[1]};
|
---|
272 | $parent = $parent->[3];
|
---|
273 | }
|
---|
274 | }
|
---|
275 | }
|
---|
276 |
|
---|
277 | # New tag
|
---|
278 | push @$$current, my $new = ['tag', $start, $attrs, $$current];
|
---|
279 | weaken $new->[3];
|
---|
280 | $$current = $new;
|
---|
281 | }
|
---|
282 |
|
---|
283 | sub _tag {
|
---|
284 | my $tree = ['tag', shift, undef, undef];
|
---|
285 |
|
---|
286 | # Content
|
---|
287 | push @$tree, ref $_[-1] eq 'CODE' ? ['raw', pop->()] : ['text', pop]
|
---|
288 | if @_ % 2;
|
---|
289 |
|
---|
290 | # Attributes
|
---|
291 | my $attrs = $tree->[2] = {@_};
|
---|
292 | return $tree unless exists $attrs->{data} && ref $attrs->{data} eq 'HASH';
|
---|
293 | my $data = delete $attrs->{data};
|
---|
294 | @$attrs{map { y/_/-/; lc "data-$_" } keys %$data} = values %$data;
|
---|
295 | return $tree;
|
---|
296 | }
|
---|
297 |
|
---|
298 | 1;
|
---|
299 |
|
---|
300 | =encoding utf8
|
---|
301 |
|
---|
302 | =head1 NAME
|
---|
303 |
|
---|
304 | Mojo::DOM::HTML - HTML/XML engine
|
---|
305 |
|
---|
306 | =head1 SYNOPSIS
|
---|
307 |
|
---|
308 | use Mojo::DOM::HTML;
|
---|
309 |
|
---|
310 | # Turn HTML into DOM tree
|
---|
311 | my $html = Mojo::DOM::HTML->new;
|
---|
312 | $html->parse('<div><p id="a">Test</p><p id="b">123</p></div>');
|
---|
313 | my $tree = $html->tree;
|
---|
314 |
|
---|
315 | =head1 DESCRIPTION
|
---|
316 |
|
---|
317 | L<Mojo::DOM::HTML> is the HTML/XML engine used by L<Mojo::DOM>, based on the
|
---|
318 | L<HTML Living Standard|https://html.spec.whatwg.org> and the
|
---|
319 | L<Extensible Markup Language (XML) 1.0|http://www.w3.org/TR/xml/>.
|
---|
320 |
|
---|
321 | =head1 FUNCTIONS
|
---|
322 |
|
---|
323 | L<Mojo::DOM::HTML> implements the following functions, which can be imported
|
---|
324 | individually.
|
---|
325 |
|
---|
326 | =head2 tag_to_html
|
---|
327 |
|
---|
328 | my $str = tag_to_html 'div', id => 'foo', 'safe content';
|
---|
329 |
|
---|
330 | Generate HTML/XML tag and render it right away. This is a significantly faster
|
---|
331 | alternative to L</"tag"> for template systems that have to generate a lot of
|
---|
332 | tags. Note that this function is EXPERIMENTAL and might change without warning!
|
---|
333 |
|
---|
334 | =head1 ATTRIBUTES
|
---|
335 |
|
---|
336 | L<Mojo::DOM::HTML> implements the following attributes.
|
---|
337 |
|
---|
338 | =head2 tree
|
---|
339 |
|
---|
340 | my $tree = $html->tree;
|
---|
341 | $html = $html->tree(['root']);
|
---|
342 |
|
---|
343 | Document Object Model. Note that this structure should only be used very
|
---|
344 | carefully since it is very dynamic.
|
---|
345 |
|
---|
346 | =head2 xml
|
---|
347 |
|
---|
348 | my $bool = $html->xml;
|
---|
349 | $html = $html->xml($bool);
|
---|
350 |
|
---|
351 | Disable HTML semantics in parser and activate case-sensitivity, defaults to
|
---|
352 | auto-detection based on XML declarations.
|
---|
353 |
|
---|
354 | =head1 METHODS
|
---|
355 |
|
---|
356 | L<Mojo::DOM::HTML> inherits all methods from L<Mojo::Base> and implements the
|
---|
357 | following new ones.
|
---|
358 |
|
---|
359 | =head2 parse
|
---|
360 |
|
---|
361 | $html = $html->parse('<foo bar="baz">I ⥠Mojolicious!</foo>');
|
---|
362 |
|
---|
363 | Parse HTML/XML fragment.
|
---|
364 |
|
---|
365 | =head2 render
|
---|
366 |
|
---|
367 | my $str = $html->render;
|
---|
368 |
|
---|
369 | Render DOM to HTML/XML.
|
---|
370 |
|
---|
371 | =head2 tag
|
---|
372 |
|
---|
373 | $html = $html->tag('div', id => 'foo', 'safe content');
|
---|
374 |
|
---|
375 | Generate HTML/XML tag. Note that this method is EXPERIMENTAL and might change
|
---|
376 | without warning!
|
---|
377 |
|
---|
378 | =head1 SEE ALSO
|
---|
379 |
|
---|
380 | L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
|
---|
381 |
|
---|
382 | =cut
|
---|