blib/lib/HTML/Object/XQuery.pm untested

filter: Statementstmt 0.0% 0 / 2554 Branchbran 0.0% 0 / 1398 Conditioncond 0.0% 0 / 848 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 155 Podpod 0.0% 0 / 123 totaltotal 0.0% 0 / 5078 CC 700 SCAR 69.2
CC
700
Cov
0%
ajax
7310.0
load
992.0
_before_after
992.0
CRAP 1009.1
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/m
3 ## Version v0.4.1
4 ## Copyright(c) 2024 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/05/01
7 ## Modified 2026/06/27
8 ## All rights reserved.
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTML::Object::XQuery;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTML::Object' );
20 use parent qw( HTML::Object::DOM );
21 use vars qw( @EXPORT $DEBUG $VERSION );
22 our @EXPORT = qw( xq );
23 our $DEBUG = 0;
24 our $VERSION = 'v0.4.1';
25 };
26  
27 use strict;
28 use warnings;
29  
30 {
31 no warnings 'once';
32 *xq = \&HTML::Object::DOM::Element::xq;
33 }
34  
35 # NOTE: DateTimeFormat class
36 # package
37 # DateTimeFormat;
38 # BEGIN
39 # {
40 # use strict;
41 # use warnings;
42 # use parent qw( HTML::Object::DateTime::Format );
43 # };
44 #
45 # use strict;
46 # use warnings;
47  
48 # NOTE: xQuery class
49 package xQuery;
50 BEGIN
51 {
52 use strict;
53 use warnings;
54 use parent qw( Module::Generic );
55 };
56 use strict;
57 use warnings;
58  
59 {
60 no warnings 'once';
61 # NOTE: clearQueue
62 *clearQueue = \&HTML::Object::DOM::Element::clearQueue;
63 # NOTE: contains
64 *contains = \&HTML::Object::DOM::Element::contains;
65 }
66  
67 sub data
68 {
69 my $self = shift( @_ );
70 my $elem = shift( @_ ) || return( $self->error( "No element was provided to set/get data on it." ) );
71 return( $self->error( "Element value provided is not an HTML::Object::DOM::Element" ) ) if( !$self->_is_a( $elem => 'HTML::Object::DOM::Element' ) );
72 my $rv = $elem->data( @_ );
73 return( $self->pass_error( $elem->error ) ) if( !defined( $rv ) && $elem->error );
74 return( $rv );
75 }
76  
77 {
78 no warnings 'once';
79 # NOTE: dequeue
80 *dequeue = \&HTML::Object::DOM::Element::dequeue;
81 }
82  
83 sub each
84 {
85 my $self = shift( @_ );
86 my( $data, $cb ) = @_;
87 my $obj;
88 if( $self->_is_array( $data ) )
89 {
90 $obj = $self->new_array( $data );
91 }
92 elsif( $self->_is_hash( $data ) )
93 {
94 $obj = $self->new_hash( $data );
95 }
96 else
97 {
98 return( $self->error( "Unsupported data type (", overload::StrVal( $data // 'undef' ), ")" ) );
99 }
100 return( $self->error( "Callback value provided is not a code reference." ) ) if( !$self->_is_code( $cb ) );
101 return( $obj->each($cb) );
102 }
103  
104 sub extend
105 {
106 my $self = shift( @_ );
107 my $deep = 0;
108 if( scalar( @_ ) && !$self->_is_hash( $_[0] ) )
109 {
110 my $bool = shift( @_ );
111 $deep = $bool ? 1 : 0;
112 }
113 # Clean up the arguments
114 my @args = ();
115 for( my $i = 0; $i < scalar( @_ ); $i++ )
116 {
117 if( $self->_is_hash( $_[$i] ) )
118 {
119 push( @args, $_[$i] );
120 }
121 }
122 return( {} ) if( !scalar( @args ) );
123 return( { map( %$_, @args ) } ) unless( $deep );
124 # Credits: Hash::Merge::Simple
125 my $merge;
126 $merge = sub
127 {
128 my( $left, @right ) = @_;
129 return( $left ) unless( @right );
130 return( $merge->( $left, $merge->( @right ) ) ) if( @right > 1 );
131 my( $right ) = @right;
132 my $merged = { %$left };
133 foreach my $key ( keys( %$right ) )
134 {
135 my( $hr, $hl ) = map{ ref( $_->{ $key } ) eq 'HASH' } $right, $left;
136 # Both hash have the same key pointing to an hash
137 if( $hr and $hl )
138 {
139 $merged->{ $key } = $merge->( $left->{ $key }, $right->{ $key } );
140 }
141 else
142 {
143 $merged->{ $key } = $right->{ $key };
144 }
145 }
146 return( $merged );
147 };
148 return( $merge->( @args ) );
149 }
150  
151 sub grep
152 {
153 my $self = shift( @_ );
154 my( $ref, $cb, $invert ) = @_;
155 return( $self->error( "Value provided is not an array reference." ) ) if( !$self->_is_array( $ref ) );
156 return( $self->error( "Callback value provided is not a code reference." ) ) if( !$self->_is_code( $cb ) );
157 $invert //= 0;
158 $ref = $self->new_array( $ref );
159 return( $ref->grep( $cb, $invert ) );
160 }
161  
162 sub inArray
163 {
164 my $self = shift( @_ );
165 my( $val, $array, $fromIndex ) = @_;
166 return( $self->error( "Array value provided is not an array." ) ) if( !$self->_is_array( $array ) );
167 return( $self->error( "fromIndex value provided is not an integer." ) ) if( defined( $fromIndex ) && !$self->_is_integer( $fromIndex ) );
168 $fromIndex //= 0;
169 my $isRe = ( ref( $val ) eq 'Regexp' ? 1 : 0 );
170 for( my $i = 0; $i < scalar( @$array ); $i++ )
171 {
172 next unless( $i >= $fromIndex );
173 if( $isRe )
174 {
175 return( $i ) if( $array->[$i] =~ /$val/ );
176 }
177 else
178 {
179 return( $i ) if( $array->[$i] eq $val );
180 }
181 }
182 return(-1);
183 }
184  
185 sub isArray { return( shift->_is_array( @_ ) ); }
186  
187 sub isEmptyObject
188 {
189 my $self = shift( @_ );
190 my $this = shift( @_ );
191 return(0) if( !$self->_is_hash( $this, 'strict' ) );
192 return( scalar( keys( %$this ) ) ? 0 : 1 );
193 }
194  
195 sub isFunction
196 {
197 my $self = shift( @_ );
198 my $this = shift( @_ );
199 return(0) if( $self->_is_empty( $this ) );
200 return(1) if( $self->_is_code( $this ) );
201 my $pkg = caller;
202 if( $self->_has_symbol( $pkg => "\&${this}" ) &&
203 defined( &{"${pkg}\::${this}"} ) )
204 {
205 return(1);
206 }
207 return(0);
208 }
209  
210 sub isNumeric { return( shift->_look_like_number( @_ ) ); }
211  
212 sub isPlainObject { return( shift->_is_hash( shift( @_ ), 'strict' ) ); }
213  
214 sub isWindow { return( shift->_is_a( shift( @_ ) => 'HTML::Object::DOM::Window' ) ); }
215  
216 sub makeArray
217 {
218 my $self = shift( @_ );
219 my $ref = shift( @_ );
220 if( $self->_is_a( $ref => 'HTML::Object::Collection' ) )
221 {
222 $ref = $ref->children;
223 }
224 return( $self->error( "Value provided is not an array reference or an array object." ) ) if( !$self->_is_array( $ref ) );
225 my $new = [];
226 @$new = @$ref;
227 return( $new );
228 }
229  
230 sub map
231 {
232 my $self = shift( @_ );
233 my $ref = shift( @_ ) || return( $self->error( "No data was provided." ) );
234 my $code = shift( @_ ) || return( $self->error( "No code reference was provided." ) );
235 return( $self->error( "I was expecting a code reference, but instead I was provided with this: \"", overload::StrVal( $code ), "\"." ) ) if( ref( $code ) ne 'CODE' );
236 my $type;
237 if( $self->_is_array( $ref ) )
238 {
239 $type = 'array';
240 }
241 elsif( $self->_is_hash( $ref => 'strict' ) )
242 {
243 $type = 'hash';
244 }
245 my $new = $self->new_array;
246 local $@;
247 if( defined( $type ) )
248 {
249 my $each = sub
250 {
251 if( $type eq 'hash' )
252 {
253 return( CORE::each( %$ref ) );
254 }
255 else
256 {
257 return( CORE::each( @$ref ) );
258 }
259 };
260  
261 # We use a callback, because perl does not accept: each( $type eq 'array' ? @$ref : %$ref )
262 while( my( $key, $value ) = $each->() )
263 {
264 # try-catch
265 my @rv = eval
266 {
267 $code->( $value, $key );
268 };
269 if( $@ )
270 {
271 warn( "An error occured while executing callback for key ${key}: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
272 next;
273 }
274 # User returned an empty array or undef
275 if( !scalar( @rv ) || ( scalar( @rv ) == 1 && !defined( $rv[0] ) ) )
276 {
277 next;
278 }
279 if( scalar( @rv ) == 1 )
280 {
281 # User returned an array reference, such as:
282 # my @rv = $.map( $array, sub{ return( [1, 2, 3] ) } );
283 if( $self->_is_array( $rv[0] ) )
284 {
285 $new->push( @{$rv[0]} );
286 }
287 else
288 {
289 # warn( "Warning only: value returned from the \$.map callback for key ${key} did not return either undef or an array reference: ", join( ', ', map( overload::StrVal( $_ // 'undef' ), @rv ) ) ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
290 $new->push( $rv[0] );
291 }
292 }
293 # User returned an array of more than 1 item, such as:
294 # my @rv = $.map( $array, sub{ return( 1, 2, 3 ) } );
295 else
296 {
297 $new->push( @rv );
298 }
299 }
300 return( $new );
301 }
302 else
303 {
304 return( $self->error( "The data provided is neither an array reference, an array object or an hash reference." ) );
305 }
306 }
307  
308 sub merge
309 {
310 my $self = shift( @_ );
311 my( $first, $second ) = @_;
312 return( $self->error( "First value provided is not an array reference." ) ) if( !$self->_is_array( $first ) );
313 return( $self->error( "Second value provided is not an array reference." ) ) if( !$self->_is_array( $second ) );
314 CORE::push( @$first, @$second );
315 return( $first );
316 }
317  
318 sub noop { return }
319  
320 sub now
321 {
322 my $self = shift( @_ );
323 $self->_load_class( 'DateTime::Lite' ) || return( $self->pass_error );
324 $self->_load_class( 'DateTime::Format::Lite' ) || return( $self->pass_error );
325 my $fmt = DateTime::Format::Lite->new(
326 pattern => '%s',
327 );
328 my $dt = DateTime::Lite->now(
329 formatter => $fmt,
330 );
331 return( $dt );
332 }
333  
334 sub parseHTML
335 {
336 my( $self, $str ) = @_;
337 my $res = $self->new_array;
338 return( $res ) if( $self->_is_empty( $str ) );
339 my $parser = HTML::Object::DOM->new( debug => $self->debug );
340 my $doc = $parser->parse_data( "$str" ) ||
341 return( $self->pass_error( $parser->error ) );
342 $res->push( $doc->children->list );
343 return( $res );
344 }
345  
346 sub parseJSON
347 {
348 my( $self, $str ) = @_;
349 return( $self->error( "No JSON data was provided to parse" ) ) if( $self->_is_empty( $str ) );
350 my $j = $self->new_json( allow_tags => 0 );
351 # try-catch
352 local $@;
353 my $rv = eval
354 {
355 return( $j->decode( "$str" ) );
356 };
357 if( $@ )
358 {
359 return( $self->error( "An error occurred while parsing ", CORE::length( "$str" ), " bytes of JSON data: $@" ) );
360 }
361 return( $rv );
362 }
363  
364 sub parseXML
365 {
366 my( $self, $str ) = @_;
367 return( $self->error( "No XML data was provided to parse" ) ) if( $self->_is_empty( $str ) );
368 if( !$self->_load_class( 'XML::LibXML' ) )
369 {
370 return( $self->pass_error );
371 }
372 # try-catch
373 local $@;
374 my $doc = eval
375 {
376 XML::LibXML->load_xml( string => $str );
377 };
378 if( $@ )
379 {
380 return( $self->error( "Error while parsing XML data with XML::LibXML: $@" ) );
381 }
382 return( $doc );
383 }
384  
385 # NOTE: $.proxy() is deprecated
386 # <https://api.jquery.com/jQuery.proxy/>
387  
388 # NOTE: $.queue() is unsupported as it has no meaning under perl
389 # <https://api.jquery.com/jQuery.queue/>
390  
391 sub removeData
392 {
393 my $self = shift( @_ );
394 my $elem = shift( @_ ) || return( $self->error( "No element was provided." ) );
395 return( $self->error( "Element object provided is not an HTML::Object::DOM::Element" ) ) if( !$self->_is_a( $elem => 'HTML::Object::DOM::Element' ) );
396 $elem->removeData( scalar( @_ ) ? @_ : () );
397 return( $self->pass_error( $elem->error ) ) if( $elem->error );
398 return;
399 }
400  
401 # NOTE: support() is not supported
402 # <https://api.jquery.com/jQuery.support/>
403  
404 sub trim
405 {
406 my $self = shift( @_ );
407 my $this = shift( @_ );
408 return( $this ) if( $self->_is_empty( $this ) );
409 if( ref( $this ) &&
410 !$self->_can_overload( $this => '""' ) )
411 {
412 return( $self->error( "Value provided is not a string nor a stringifyable object." ) );
413 }
414 my $str = "$this";
415 $str =~ s/^[[:blank:]\h\v]+|[[:blank:]\h\v]+$//gs;
416 return( $str );
417 }
418  
419 sub type
420 {
421 my $self = shift( @_ );
422 my $this = shift( @_ );
423 if( !defined( $this ) )
424 {
425 return( 'undef' );
426 }
427 elsif( $self->_is_hash( $this => 'strict' ) )
428 {
429 return( 'hash' );
430 }
431 elsif( $self->_is_array( $this ) )
432 {
433 return( 'array' );
434 }
435 elsif( $self->_is_a( $this => [qw( DateTime DateTime::Lite Module::Generic::DateTime )] ) )
436 {
437 return( 'date' );
438 }
439 elsif( $self->_is_a( $this => [qw( Module::Generic::Boolean JSON::PP::Boolean )] ) )
440 {
441 return( 'boolean' );
442 }
443 elsif( $self->_is_a( $this => 'Regexp' ) )
444 {
445 return( 'regexp' );
446 }
447 elsif( $self->_is_a( $this => [qw( Module::Generic::Exception Error Throwable::Error )] ) )
448 {
449 return( 'error' );
450 }
451 elsif( $self->_is_number( $this ) )
452 {
453 return( 'number' );
454 }
455 elsif( $self->_look_like_number( $this ) )
456 {
457 return( 'number' );
458 }
459 else
460 {
461 return( 'string' );
462 }
463 }
464  
465 sub unique
466 {
467 my $self = shift( @_ );
468 my $arr = shift( @_ ) || return( $self->error( "No array was provided to make unique." ) );
469 return( $self->error( "Value provided is not an array reference or an array object." ) ) if( !$self->_is_array( $arr ) );
470 my $res = $self->new_array( $arr )->unique;
471 return( $res );
472 }
473  
474 sub uniqueSort
475 {
476 my $self = shift( @_ );
477 my $new = $self->unique( @_ ) || return( $self->pass_error );
478 return( $new ) if( $new->is_empty );
479 my $root = $new->first->getRootNode;
480 # <https://stackoverflow.com/questions/63575333/javascript-replacement-of-sourceindex-in-chromium-browsers>
481 # <https://developer.mozilla.org/en-US/docs/Web/API/Document/all>
482 # <https://johnresig.com/blog/comparing-document-position/#postcomment>
483 # Compare Position - MIT Licensed, John Resig
484 # function comparePosition(a, b)
485 # {
486 # return a.compareDocumentPosition
487 # ? a.compareDocumentPosition(b)
488 # : a.contains
489 # ? ( a != b && a.contains(b) && 16 ) +
490 # ( a != b && b.contains(a) && 8 ) +
491 # ( a.sourceIndex >= 0 && b.sourceIndex >= 0
492 # ? ( a.sourceIndex < b.sourceIndex && 4 ) + ( a.sourceIndex > b.sourceIndex && 2 )
493 # : 1
494 # ) + 0
495 # : 0;
496 # }
497 my $all = $root->querySelectorAll('*');
498 for( my $i = 0; $i < scalar( @$all ); $i++ )
499 {
500 my $e = $all->[$i];
501 $e->sourceIndex( $i );
502 }
503 $new = $new->sort(sub
504 {
505 my( $a, $b ) = @_;
506 return(
507 $a->can( 'compareDocumentPosition' )
508 ? $a->compareDocumentPosition( $b )
509 : $a->can( 'contains' )
510 ? ( $a !=$ b && $a->contains($b) && 16 ) +
511 ( $a != $b && $b->contains($a) && 8 ) +
512 ( ( $a->sourceIndex // -1 ) >= 0 && ( $b->sourceIndex // -1 ) >= 0
513 ? ( $a->sourceIndex < $b->sourceIndex && 4 ) + ( $a->sourceIndex > $b->sourceIndex && 2 )
514 : 1
515 ) + 0
516 : 0
517 );
518 });
519 return( $new );
520 }
521  
522 # NOTE: HTML::Object::DOM::Element class
523 package HTML::Object::DOM::Element;
524 BEGIN
525 {
526 use strict;
527 use warnings;
528 use vars qw( $XP $LOOK_LIKE_HTML $VERSION );
529 use CSS::Object;
530 use HTML::Object::Collection;
531 use HTML::Object::DOM::Attribute;
532 use HTML::Object::DOM::Boolean;
533 use HTML::Object::DOM::Document;
534 use HTML::Object::DOM::Number;
535 use HTML::Object::DOM::Root;
536 # use HTML::Object::DOM::Text;
537 use HTML::Selector::XPath 0.20 qw( selector_to_xpath );
538 use List::Util ();
539 # use Promise::XS ();
540 # use Promise::Me;
541 use HTML::Object::XPath;
542 use overload (
543 'eq' => \&_same_as,
544 '==' => \&_same_as,
545 fallback => 1,
546 );
547 our $XP;
548 # As perl jQuery documentation
549 our $LOOK_LIKE_HTML = qr/^[[:blank:]\h\v]*\<\w+.*?\>/;
550 };
551  
552 use strict;
553 use warnings;
554 no warnings 'redefine';
555  
556 # Takes a selector (e.g. '.some-class'); or
557 # a collection (i.e. one or more elements resulting from a find or equivalent query); or
558 # "HTML fragment to add to the set of matched elements."; or
559 # a selector and a context (i.e. an element object); or
560 # a element object
561 # $self->add( $selector );
562 # $self->add( $elements );
563 # $self->add( $html );
564 # $self->add( $selector, $context );
565 sub add
566 {
567 my $self = shift( @_ );
568 my( $this, $context ) = @_;
569 # Compliant with what jQuery does, i.e. when no argument is provide this just returns a collection of the collecting object
570 my $collection = $self->new_collection( end => $self );
571 # if( $self->isa_element && !$self->isa_collection )
572 if( $self->isa_collection )
573 {
574 $collection->children( $self->children );
575 }
576 elsif( $self->isa_element )
577 {
578 $collection->children->push( $self );
579 }
580  
581 if( !defined( $this ) )
582 {
583 return( $collection )
584 }
585 # e.g.: $( "p" ).add( "div" )
586 # $( "li" ).add( "<p id='new'>new paragraph</p>" )
587 # elsif( !ref( $this ) || ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
588 elsif( !ref( $this ) || overload::Method( $this, '""' ) )
589 {
590 # https://api.jquery.com/Types/#htmlString
591 # $( "li" ).add( "<p id='new'>new paragraph</p>" )
592 if( "$this" =~ /$LOOK_LIKE_HTML/ )
593 {
594 my $p = $self->new_parser;
595 $this = $p->parse_data( "$this" ) || return( $self->pass_error( $p->error ) );
596 }
597 # selector
598 # $( "p" ).add( "div" )
599 else
600 {
601 # $self->add( $selector, $context );
602 if( defined( $context ) )
603 {
604 return( $self->error( "A context has been provided, but it is not an HTML::Object::DOM::Element." ) ) if( !$self->_is_object( $context ) || !$context->isa( 'HTML::Object::DOM::Element' ) );
605 $this = $context->find( "$this" ) || return( $self->pass_error( $context->error ) );
606 }
607 # $self->add( $selector );
608 elsif( defined( $HTML::Object::DOM::GLOBAL_DOM ) )
609 {
610 my $selector = "$this";
611 $this = $HTML::Object::DOM::GLOBAL_DOM->find( "$selector" ) || return( $self->pass_error( $HTML::Object::DOM::GLOBAL_DOM->error ) );
612 }
613 else
614 {
615 return( $self->error( "You need to provide some context to the selector by supplying an HTML::Object::DOM::Element object." ) );
616 }
617 }
618 }
619 # Some array or hash ref provided maybe ?
620 elsif( !$self->_is_object( $this ) )
621 {
622 return( $self->error( "I was expecting an HTML::Object::DOM::Element, an HTML::Object::Collection, an html string or a selector., but instead I got '$this'." ) );
623 }
624  
625 # We now have either an element object or a collection of them
626 # We return a new collection either way
627 if( $self->isa_collection( $this ) )
628 {
629 $collection->children->merge( $this->children->unique );
630 }
631 elsif( $this->isa( 'HTML::Object::DOM::Element' ) )
632 {
633 $collection->children->push( $this );
634 }
635 else
636 {
637 return( $self->error( "An object of class \"", ref( $this ), "\" was provided, but I do not know what to do with it. I was expecting an HTML::Object::DOM::Element, or an HTML::Object::Collection." ) );
638 }
639 return( $collection );
640 }
641  
642 # To make it look like really like jQuery
643 sub addClass
644 {
645 my( $self, $class ) = @_;
646 return( $self->error( "I received a reference to add as a class, but was expecting a string or a code reference." ) ) if( ref( $class ) && ref( $class ) ne 'CODE' && !( overload::Overloaded( $class ) && overload::Method( $class, '""' ) ) );
647 $class = "${class}" unless( ref( $class ) CORE::eq 'CODE' );
648 my $set_attr;
649 $set_attr = sub
650 {
651 my( $i, $e ) = @_;
652 my $v = $e->attr( 'class' ) // '';
653 local $_ = $e;
654 my $classes = ref( $class ) CORE::eq 'CODE'
655 ? $class->({ element => $e, pos => $i, value => $v })
656 : $class;
657 my $cl_ref = $self->new_array(
658 $self->_is_array( $classes )
659 ? $classes
660 : CORE::length( "$classes" )
661 ? [split( /[[:blank:]\h]+/, "${classes}" )]
662 : []
663 );
664 my $curr;
665 if( CORE::length( "${v}" ) )
666 {
667 $curr = $self->_is_a( $v, 'Module::Generic::Array' ) ? $v : $self->new_array( [split( /[[:blank:]\h]+/, $v )] );
668 my $new = $self->new_array;
669 $cl_ref->foreach(sub
670 {
671 # <http://www.w3.org/TR/CSS21/grammar.html#scanner>
672 # <https://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors#449000>
673 $new->push( $_ ) if( !$curr->exists( $_ ) );
674 });
675 $curr->push( $new->list ) if( $new->length );
676 }
677 else
678 {
679 $curr = $cl_ref;
680 }
681 $e->attr( class => $curr->join( ' ' )->scalar );
682 $e->reset(1);
683 };
684  
685 if( $self->isa_collection )
686 {
687 $self->children->for( $set_attr );
688 }
689 else
690 {
691 my $v = $self->attr( 'class' ) // '';
692 # Here 0 is a dummy number to satisfy the code ref required by for()
693 $set_attr->( 0, $self );
694 }
695 }
696  
697 # <https://api.jquery.com/after/>
698 sub after { return( shift->_before_after( @_, { action => 'after' } ) ); }
699  
700 sub ajax
701 {
702 my $self = shift( @_ );
703 my $url = shift( @_ ) ||
704 return( $self->error( "No URL was provided." ) );
705 my $opts = $self->_get_args_as_hash( @_ );
706 $opts->{async} //= 1;
707 $opts->{cache} = 0;
708 $opts->{processData} //= 1;
709 $opts->{debug} //= 0;
710 $self->_load_class( 'HTTP::Promise', { version => 'v0.5.0' } ) ||
711 return( $self->pass_error );
712 $self->_load_class( 'HTTP::Promise::Request' ) ||
713 return( $self->pass_error );
714 $self->_load_class( 'URI', { version => '5.21' } ) ||
715 return( $self->pass_error );
716 if( !$self->_is_empty( $opts->{url} ) )
717 {
718 $url = $opts->{url};
719 }
720 my $uri = URI->new( "$url" );
721 # Contextual URL that requires a base URL.
722 # We check for documentURI of the root element, if any
723 my( $doc_root, $doc_uri );
724 if( ( substr( $url, 0, 1 ) eq '/' ||
725 substr( $url, 0, 2 ) eq './' ||
726 substr( $url, 0, 3 ) eq '../' ) &&
727 ( $doc_root = $self->getRootNode ) &&
728 $doc_root->isa( 'HTML::Object::DOM::Document' ) &&
729 ( $doc_uri = $doc_root->documentURI ) )
730 {
731 $uri = $doc_uri->clone;
732 $uri->path( $url );
733 }
734 # !contents
735 # !context
736 # converters
737 # !crossDomain
738 # NOTE dataType
739 my $dataType;
740 $dataType = $opts->{dataType} if( !$self->_is_empty( $opts->{dataType} ) );
741 # NOTE error
742 my $error;
743 if( $self->_is_code( $opts->{error} ) )
744 {
745 $error = [$opts->{error}];
746 }
747 elsif( $self->_is_array( $opts->{error} ) )
748 {
749 for( my $i = 0; $i < scalar( @{$opts->{error}} ); $i++ )
750 {
751 my $this = $opts->{error}->[$i];
752 if( !$self->_is_code( $opts->{error}->[$i] ) )
753 {
754 return( $self->error( "Value provided at offset $i with the 'error' argument to ajax method, is not a code reference." ) );
755 }
756 }
757 $error = $opts->{error};
758 }
759 # NOTE headers
760 my $headers = ( ( exists( $opts->{headers} ) && ref( $opts->{headers} // '' ) eq 'HASH' ) ? $opts->{headers} : {} );
761 unless( exists( $headers->{X_Requested_With} ) || exists( $headers->{ 'X-Requested-With' } ) )
762 {
763 $headers->{X_Requested_With} = 'XMLHttpRequest';
764 }
765 # !global
766 # !isLocal
767 # !jsonp
768 # !jsonpCallback
769 my $params =
770 {
771 use_promise => ( $opts->{async} ? 1 : 0 ),
772 # NOTE timeout
773 ( $self->_is_integer( $opts->{timeout} ) ? ( timeout => $opts->{timeout} ) : () ),
774 ( ( $self->_is_integer( $opts->{debug} ) && $opts->{debug} ) ? ( debug => $opts->{debug} ) : () ),
775 };
776 # NOTE accepts
777 if( !$self->_is_empty( $opts->{accepts} ) )
778 {
779 $headers->{accept} = $opts->{accepts};
780 }
781 elsif( !$self->_is_empty( $opts->{accept} ) )
782 {
783 $headers->{accept} = $opts->{accept};
784 }
785 # NOTE contentType
786 if( !$self->_is_empty( $opts->{contentType} ) )
787 {
788 $headers->{Content_Type} = $opts->{contentType};
789 }
790 # NOTE ifModified
791 if( exists( $opts->{ifModified} ) &&
792 ref( $opts->{ifModified} ) eq 'HASH' )
793 {
794 my $ifmod = $opts->{ifModified};
795 if( exists( $ifmod->{since} ) &&
796 defined( $ifmod->{since} ) &&
797 CORE::length( $ifmod->{since} ) )
798 {
799 my $dt;
800 if( $ifmod->{since} =~ /^\d{10}$/ )
801 {
802 $self->_load_class( 'DateTime::Lite' ) || return( $self->pass_error );
803 # try-catch
804 local $@;
805 $dt = eval
806 {
807 DateTime::Lite->from_epoch( epoch => $ifmod->{since} );
808 };
809 if( $@ )
810 {
811 return( $self->error( "Error with the timestamp provided for the option ifModified: $@" ) );
812 }
813 }
814 elsif( $self->_is_a( $ifmod->{since} => [qw( DateTime DateTime::Lite Module::Generic::DateTime )] ) )
815 {
816 $dt = $ifmod->{since};
817 }
818 else
819 {
820 return( $self->error( "Unsupported value provided to option ifModified->since: '", ( $ifmod->{since} // 'undef' ), "'" ) );
821 }
822  
823 $self->_load_class( 'DateTime::Format::Lite' ) ||
824 return( $self->pass_error );
825 $dt->set_time_zone( 'GMT' );
826 my $fmt = DateTime::Format::Lite->new(
827 pattern => '%a, %d %b %Y %H:%M:%S GMT',
828 locale => 'en_GB',
829 time_zone => 'GMT',
830 );
831 $dt->set_formatter( $fmt );
832 $headers->{If_Modified_Since} = $dt;
833 }
834 if( exists( $ifmod->{etag} ) &&
835 defined( $ifmod->{etag} ) &&
836 CORE::length( $ifmod->{etag} ) )
837 {
838 if( $ifmod->{etag} =~ /^[\w\-]+$/ )
839 {
840 $headers->{If_None_Match} = '"' . $ifmod->{etag} . '"';
841 }
842 # Useless to use the weak prefix since If-None-Match only uses the weak algorithm
843 elsif( $ifmod->{etag} =~ m,W/"^[\w\-]+"$, )
844 {
845 $headers->{If_None_Match} = $ifmod->{etag};
846 }
847 else
848 {
849 return( $self->error( "The etag provided for the option ifModified->etag contains illegal characters." ) );
850 }
851 }
852 }
853 # !isLocal
854 # !jsonp
855 # NOTE method, type
856 my $method = 'get';
857 $opts->{method} = $opts->{type} if( !$self->_is_empty( $opts->{method} ) && !$self->_is_empty( $opts->{type} ) );
858 if( exists( $opts->{method} ) &&
859 defined( $opts->{method} ) &&
860 CORE::length( $opts->{method} // '' ) )
861 {
862 if( $opts->{method} =~ /^(get|head|options|patch|post|put)$/i )
863 {
864 $method = lc( $1 );
865 }
866 else
867 {
868 return( $self->error( "Unsupported HTTP method '$opts->{method}'" ) );
869 }
870 }
871 # NOTE data, processData
872 my $data;
873 if( $opts->{data} )
874 {
875 if( $opts->{processData} )
876 {
877 $headers->{Content} = $data;
878 }
879 else
880 {
881 $headers->{Content} = "$data";
882 }
883 }
884 else
885 {
886 }
887  
888 # NOTE mimeType
889 if( !$self->_is_empty( $opts->{mimeType} ) )
890 {
891 $headers->{Content_Type} = $opts->{mimeType};
892 }
893 # !scriptAttrs
894 # !scriptCharset
895 # NOTE statusCode
896 my $statusCode;
897 if( exists( $opts->{statusCode} ) &&
898 defined( $opts->{statusCode} ) &&
899 ref( $opts->{statusCode} // '' ) eq 'HASH' )
900 {
901 foreach my $c ( sort( keys( %{$opts->{statusCode}} ) ) )
902 {
903 if( !defined( $c ) || !CORE::length( "$c" // '' ) )
904 {
905 return( $self->error( "The code value provided in the option statusCode is empty!" ) );
906 }
907 elsif( "$c" !~ /^\d{3}$/ )
908 {
909 return( $self->error( "The code value provided (${c}) is invalid. It should be a 3 digits code, such as 200" ) );
910 }
911  
912 my $code_ref = $opts->{statusCode}->{ $c };
913 if( !$self->_is_code( $code_ref ) )
914 {
915 return( $self->error( "The value provided for status code '${c}' is not a code reference." ) );
916 }
917 }
918 $statusCode = $opts->{statusCode};
919 }
920 # NOTE success
921 my $success;
922 if( exists( $opts->{success} ) )
923 {
924 if( $self->_is_code( $opts->{success} ) )
925 {
926 $success = $opts->{success};
927 }
928 else
929 {
930 return( $self->error( "The success callback provided is not a code reference." ) );
931 }
932 }
933 # !traditional
934  
935 my $http = HTTP::Promise->new( %$params ) ||
936 return( $self->pass_error( HTTP::Promise->error ) );
937 my $req = $http->prepare( $method => $uri, %$headers ) ||
938 return( $self->pass_error( $http->error ) );
939 if( exists( $opts->{xhr} ) && defined( $opts->{xhr} ) )
940 {
941 if( $self->_is_code( $opts->{xhr} ) )
942 {
943 my $code_ref = $opts->{xhr};
944 # try-catch
945 local $@;
946 my $this = eval
947 {
948 $code_ref->( $req );
949 };
950 if( $@ )
951 {
952 return( $self->error( "An error occurred while calling the callback code reference for xhr: $@" ) ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
953 }
954 if( $self->_is_a( $this => 'HTTP::Promise::Request' ) )
955 {
956 $req = $this;
957 }
958 else
959 {
960 return( $self->error( "The value returned by the callback (", overload::StrVal( $this // '' ), ") is not an HTTP::Promise::Request object." ) );
961 }
962 }
963 else
964 {
965 return( $self->error( "The value provided for the xhr callback is not a code reference." ) );
966 }
967 }
968  
969 # NOTE password & username
970 if( !$self->_is_empty( $opts->{password} ) ||
971 !$self->_is_empty( $opts->{username} ) )
972 {
973 $req->headers->authorization_basic( ( $opts->{username} // '' ), ( $opts->{password} // '' ) );
974 }
975 # NOTE beforeSend
976 my $beforeSend = ( $self->_is_code( $opts->{beforeSend} ) ? $opts->{beforeSend} : sub{ $_[0] } );
977 my $complete;
978 if( $self->_is_code( $opts->{complete} ) )
979 {
980 $complete = [$opts->{complete}];
981 }
982 elsif( $self->_is_array( $opts->{complete} ) )
983 {
984 for( my $i = 0; $i < scalar( @{$opts->{complete}} ); $i++ )
985 {
986 my $this = $opts->{complete}->[$i];
987 if( !$self->_is_code( $opts->{complete}->[$i] ) )
988 {
989 return( $self->error( "Value provided at offset $i with the 'complete' argument to ajax method, is not a code reference." ) );
990 }
991 }
992 $complete = $opts->{complete};
993 }
994  
995 # NOTE dataFilter
996 my $dataFilter = ( $self->_is_code( $opts->{dataFilter} ) ? $opts->{dataFilter} : sub{ $_[0] } );
997 my $code2status = sub
998 {
999 my $resp = shift( @_ );
1000 my $code = $resp->code;
1001 if( $code == 200 )
1002 {
1003 return( 'success' );
1004 }
1005 elsif( $code == 204 )
1006 {
1007 return( 'nocontent' );
1008 }
1009 elsif( $code == 304 )
1010 {
1011 return( 'notmodified' );
1012 }
1013 elsif( $code == 408 )
1014 {
1015 return( 'timeout' );
1016 }
1017 elsif( $code >= 400 && $code <= 599 )
1018 {
1019 return( 'error' );
1020 }
1021 else
1022 {
1023 return( 'success' );
1024 }
1025 };
1026  
1027 my $process = sub
1028 {
1029 my $resp = shift( @_ );
1030 my( $resolve, $reject ) = @_;
1031 my $status = $code2status->( $resp );
1032 my $code = $resp->code;
1033 # TODO: converters
1034 my $content = $resp->decoded_content;
1035 $content = $dataFilter->( $content );
1036 my $decoded;
1037 unless( defined( $dataType ) )
1038 {
1039 my $type = $resp->headers->type;
1040 if( defined( $type ) )
1041 {
1042 if( $type =~ m,^application/json,i )
1043 {
1044 $dataType = 'json';
1045 }
1046 elsif( $type =~ m,^text/html,i )
1047 {
1048 $dataType = 'html';
1049 }
1050 elsif( $type =~ m,^text/xml,i )
1051 {
1052 $dataType = 'xml';
1053 }
1054 elsif( $type =~ m,^text/plain,i )
1055 {
1056 $dataType = 'text';
1057 }
1058 else
1059 {
1060 $dataType = 'application/octet-stream';
1061 }
1062 }
1063 }
1064  
1065 if( defined( $dataType ) )
1066 {
1067 if( ( $dataType eq 'json' ||
1068 $dataType eq 'jsonp' ) &&
1069 defined( $content ) )
1070 {
1071 my $j = $self->new_json->relaxed->utf8;
1072 # try-catch
1073 local $@;
1074 $decoded = eval
1075 {
1076 $j->decode( "$content" );
1077 };
1078 if( $@ )
1079 {
1080 $self->error( "Error decoding ", CORE::length( $content ), " bytes of JSON data: $@" );
1081 if( defined( $reject ) )
1082 {
1083 return({ error => $self->error });
1084 }
1085 else
1086 {
1087 return( $self->pass_error );
1088 }
1089 }
1090 else
1091 {
1092 # $resolve->( $decoded );
1093 $content = $decoded;
1094 }
1095 }
1096 }
1097 else
1098 {
1099 # Hmm, dataType is still undefined
1100 }
1101  
1102 if( defined( $statusCode ) )
1103 {
1104 my $code_ref = $statusCode->{ $code };
1105 # try-catch
1106 local $@;
1107 eval
1108 {
1109 $code_ref->( $content, $status, $resp, $http );
1110 };
1111 if( $@ )
1112 {
1113 warn( "Error calling statusCode callback for code '${code}': $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1114 }
1115 }
1116  
1117 if( defined( $complete ) )
1118 {
1119 foreach my $coderef ( @$complete )
1120 {
1121 $coderef->( $resp, $status, $http );
1122 }
1123 }
1124  
1125 if( defined( $success ) )
1126 {
1127 # try-catch
1128 local $@;
1129 eval
1130 {
1131 $success->( $content, $status, $resp, $http );
1132 };
1133 if( $@ )
1134 {
1135 warn( "Error calling success callback: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1136 }
1137 }
1138 if( defined( $error ) && ( $code >= 400 && $code < 600 ) )
1139 {
1140 my $status = $resp->status;
1141 for( my $i = 0; $i < scalar( @$error ); $i++ )
1142 {
1143 my $code_ref = $error->[$i];
1144 # try-catch
1145 local $@;
1146 eval
1147 {
1148 # No exception object, because this is just a regular HTTP error
1149 $code_ref->( $req, $status );
1150 };
1151 if( $@ )
1152 {
1153 warn( "An error occurred while calling the error callback at offset $i: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1154 }
1155 }
1156 }
1157 return({
1158 content => $content,
1159 status => $status,
1160 resp => $resp,
1161 http => $http,
1162 });
1163 };
1164  
1165 if( $params->{use_promise} )
1166 {
1167 my $p;
1168 $p = Promise::Me->new(sub
1169 {
1170 my( $resolve_main, $reject_main ) = @$_;
1171 # NOTE: Process beforeSend for asynchronous process
1172 my $this = $beforeSend->( $req );
1173 if( !defined( $this ) || !CORE::length( $this // '' ) )
1174 {
1175 return( $resolve_main->( '', 'abort', undef, $http ) );
1176 }
1177 elsif( !$self->_is_a( $this => 'HTTP::Promise::Request' ) )
1178 {
1179 $self->error( "Value returned by the beforeSend callback is not an HTTP::Promise::Request object." );
1180 my $err = $self->error;
1181 return( $reject_main->( $err ) );
1182 }
1183 $req = $this;
1184 my $prom = $http->request( $req,
1185 ( defined( $opts->{promise_debug} ) ? ( promise_debug => $opts->{promise_debug} ) : () ),
1186 )->then(sub
1187 {
1188 my( $resolve, $reject ) = @$_;
1189 my $resp = shift( @_ );
1190 if( !$resp )
1191 {
1192 return( $reject_main->( $http->error ) );
1193 }
1194 my $res = $process->( $resp, $resolve_main, $reject_main );
1195 if( $res->{error} )
1196 {
1197 return( $reject_main->( $res->{error} ) );
1198 }
1199 return( $resolve_main->( @$res{qw( content status resp http )} ) );
1200 })->catch(sub
1201 {
1202 my $err = shift( @_ );
1203 if( defined( $error ) )
1204 {
1205 my $status = 'error';
1206 for( my $i = 0; $i < scalar( @$error ); $i++ )
1207 {
1208 my $code_ref = $error->[$i];
1209 # try-catch
1210 local $@;
1211 eval
1212 {
1213 $code_ref->( $req, $status, $err );
1214 };
1215 if( $@ )
1216 {
1217 warn( "An error occurred while calling the error callback at offset $i: $@" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1218 }
1219 }
1220 }
1221 return( $reject_main->( $err ) );
1222 });
1223 return( $reject_main->( $http->error ) ) if( !$prom );
1224 # return(1);
1225 return( $prom );
1226 },
1227 {
1228 ( defined( $opts->{promise_debug} ) ? ( debug => $opts->{promise_debug} ) : () ),
1229 });
1230 return( $p );
1231 }
1232 # No promise
1233 else
1234 {
1235 # NOTE: Process beforeSend for synchronous process
1236 my $this = $beforeSend->( $req );
1237 if( !defined( $this ) || !CORE::length( $this // '' ) )
1238 {
1239 return( '', 'abort', undef, $http );
1240 }
1241 elsif( !$self->_is_a( $this => 'HTTP::Promise::Request' ) )
1242 {
1243 return( $self->error( "Value returned by the beforeSend callback is not an HTTP::Promise::Request object." ) );
1244 }
1245 $req = $this;
1246 my $resp = $http->request( $req );
1247 my $res = $process->( $resp );
1248 return( $self->pass_error ) if( $res->{error} );
1249 return( @$res{qw( content status resp http )} );
1250 }
1251 }
1252  
1253 # Takes html string (start with <tag...), text object (HTML::Object::DOM::Text), array or element object
1254 # or alternatively a code reference that returns the above
1255 # <https://api.jquery.com/append/>
1256 sub append { return( shift->_append_prepend( @_, { action => 'append' } ) ); }
1257  
1258 sub appendTo { return( shift->_append_prepend_to( @_, { action => 'append' } ) ); }
1259  
1260 # $e->attr( attribute );
1261 # $collection->attribute( attribute );
1262 # $e->attr( attribute1 => value1, attribute2 => value2 );
1263 # $collection->attr( attribute1 => value1, attribute2 => value2 );
1264 # $e->attr( attribute1 => $sub_routine1, attribute2 => $string );
1265 # $collection->attr( attribute1 => $sub_routine1, attribute2 => $string );
1266 sub attr
1267 {
1268 my $self = shift( @_ );
1269 my @classes = @_;
1270 return if( !scalar( @classes ) );
1271 if( scalar( @classes ) > 1 )
1272 {
1273 my $ref = {};
1274 %$ref = @classes;
1275 my $set_attributes;
1276 $set_attributes = sub
1277 {
1278 my $e = shift( @_ );
1279 while( my( $a, $v ) = each( %$ref ) )
1280 {
1281 local $_ = $e;
1282 my $val = ref( $v ) CORE::eq 'CODE'
1283 ? $v->({ element => $e, attribute => $a, current => $e->attributes->get( $a ) })
1284 : $v;
1285 return( $self->error( "I was expecting a string value for the attribute \"${a}\", but instead got \"", overload::StrVal( $val ), "\"." ) ) if( ref( $val ) && !( overload::Overloaded( $val ) && overload::Method( $val, '""' ) ) );
1286 if( defined( $val ) )
1287 {
1288 $val = "$val";
1289 $val =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//g;
1290 $e->attributes->set( $a => $val );
1291 }
1292 else
1293 {
1294 $e->attributes->delete( $a );
1295 }
1296 }
1297 return(1);
1298 };
1299  
1300 if( $self->isa_collection )
1301 {
1302 $self->children->foreach(sub
1303 {
1304 my $e = shift( @_ );
1305 $e->reset(1);
1306 # $e->attributes->merge( $ref );
1307 $set_attributes->( $e ) || return( $self->pass_error );
1308 });
1309 }
1310 else
1311 {
1312 $self->reset(1);
1313 $set_attributes->( $self ) || return( $self->pass_error );
1314 }
1315 return( $self );
1316 }
1317 # Get mode
1318 else
1319 {
1320 # return( $self->children->map(sub{ $_->attributes->get( $classes[0] ) }) );
1321 # Get the value of an attribute for the first element in the set of matched elements.
1322 if( $self->isa_collection )
1323 {
1324 return( $self->children->first->attributes->get( $classes[0] ) );
1325 }
1326 else
1327 {
1328 return( $self->attributes->get( $classes[0] ) );
1329 }
1330 }
1331 }
1332  
1333 sub before { return( shift->_before_after( @_, { action => 'before' } ) ); }
1334  
1335 sub clearQueue { return( $_[0] ) }
1336  
1337 # Takes a selector; or
1338 # a selector and an HTML::Object::DOM::Element as a context; or
1339 # a HTML::Object::DOM::Element object
1340 # "Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements."
1341 sub closest
1342 {
1343 my $self = shift( @_ );
1344 my $this = shift( @_ );
1345 my $context = shift( @_ );
1346 my $collection = $self->new_collection;
1347 return $collection if( !defined( $this ) );
1348 if( defined( $context ) &&
1349 ( !$self->_is_object( $context ) ||
1350 ( $self->_is_object( $context ) &&
1351 !$context->isa( 'HTML::Object::DOM::Element' )
1352 )
1353 ) )
1354 {
1355 return( $self->error( "Context provided (", overload::StrVal( $context ), ") is not an HTML::Object::DOM::Element." ) );
1356 }
1357 elsif( ref( $this ) &&
1358 $self->_is_object( $this ) &&
1359 ( !$this->isa( 'HTML::Object::DOM::Element' ) ||
1360 ( overload::Overloaded( $this ) && !overload::Method( $this, '""' ) )
1361 ) )
1362 {
1363 return( $self->error( "I was expecting a selector or an HTML::Object::DOM::Element, but instead received '$this'" ) );
1364 }
1365 else
1366 {
1367 return( $self->error( "I was expecting a selector or an HTML::Object::DOM::Element, but instead received '$this'" ) );
1368 }
1369  
1370 my $xpath;
1371 if( !ref( $this ) )
1372 {
1373 $xpath = $self->_xpath_value( $this );
1374 }
1375 my $process;
1376 $process = sub
1377 {
1378 my $elem = shift( @_ );
1379 # We reach the limit of our upward search
1380 return if( defined( $context ) && $elem->eid CORE::eq $context->eid );
1381 my $parent = $elem->parent;
1382 if( defined( $xpath ) )
1383 {
1384 if( $elem->matches( $xpath ) )
1385 {
1386 $collection->push( $elem );
1387 }
1388 }
1389 else
1390 {
1391 if( $elem->eid CORE::eq $this->eid )
1392 {
1393 $collection->push( $elem );
1394 }
1395 }
1396 return if( !$parent );
1397 return( $process->( $parent ) );
1398 };
1399 $process->( $self );
1400 return( $collection );
1401 }
1402  
1403 sub contains
1404 {
1405 my $self = shift( @_ );
1406 my( $container, $contained );
1407 if( scalar( @_ ) > 1 )
1408 {
1409 return( $self->error( "Wrong number of argument: \$el->contains( \$container, \$contained )" ) ) if( scalar( @_ ) > 2 );
1410 ( $container, $contained ) = @_;
1411 }
1412 elsif( scalar( @_ ) )
1413 {
1414 $container = $self;
1415 $contained = shift( @_ );
1416 }
1417 elsif( !ref( $self ) && scalar( @_ ) < 2 )
1418 {
1419 return( $self->error( "You need to provide 2 arguments when using contains() as a class function: xQuery->contains( \$container, \$contained )" ) );
1420 }
1421 else
1422 {
1423 return( $self->error( "No contained object provided to check." ) );
1424 }
1425 # We need an object to access certain methods
1426 my $this = ref( $self ) ? $self : HTML::Object::DOM->new;
1427 return( $self->error( "Container value provided is undefined." ) ) if( !defined( $container ) );
1428 return( $self->error( "Contained value provided is undefined." ) ) if( !defined( $contained ) );
1429 return( $this->false ) if( $this->_is_a( $contained => [qw( HTML::Object::DOM::Text HTML::Object::DOM::Comment )] ) );
1430 return( $self->error( "Container object provided is not an HTML::Object::DOM::Element" ) ) if( !$this->_is_a( $container => 'HTML::Object::DOM::Element' ) );
1431 return( $self->error( "Contained object provided is not an HTML::Object::DOM::Element" ) ) if( !$this->_is_a( $contained => 'HTML::Object::DOM::Element' ) );
1432 my $crawl;
1433 my $seen = {};
1434 $crawl = sub
1435 {
1436 my $kids = shift( @_ );
1437 my $grand_kids = $this->new_array;
1438 for( my $i = 0; $i < scalar( @$kids ); $i++ )
1439 {
1440 my $e = $kids->[$i];
1441 # Avoid recursion
1442 next if( ++$seen->{ $e->eid } > 1 );
1443 next unless( $this->_is_a( $e => 'HTML::Object::DOM::Element' ) );
1444 return( $this->true ) if( $e == $contained );
1445 $grand_kids->push( $e->children->list ) if( !$e->children->is_empty );
1446 }
1447 return( $this->false ) if( $grand_kids->is_empty );
1448 return( $crawl->( $grand_kids ) );
1449 };
1450 return( $crawl->( $container->children ) );
1451 }
1452  
1453 sub contents
1454 {
1455 my $self = shift( @_ );
1456 my $collection = $self->new_collection;
1457 my $children = $collection->children;
1458 if( $self->isa_collection )
1459 {
1460 $self->children->foreach(sub
1461 {
1462 $children->push( $_->children->list );
1463 });
1464 }
1465 else
1466 {
1467 $children->push( $self->children->list );
1468 }
1469 return( $collection );
1470 }
1471  
1472 # Takes a property name; or
1473 # an array reference of one or more css properties; or
1474 # a property name and a value; or
1475 # a property name and a function; or
1476 # an hash reference of property name-value pairs
1477 # <https://api.jquery.com/css/>
1478 # $e->css( $property_name );
1479 # $e->css( [$property_name1, $property_name2, $property_name3] );
1480 # $e->css( $property_name, $value );
1481 # $e->css( $property_name, $code_reference );
1482 # $e->css({ $property_name1 => $value1, $property_name2 => $value2 });
1483 # <https://api.jquery.com/css/>
1484 sub css
1485 {
1486 my $self = shift( @_ );
1487 # "An element should be connected to the DOM when calling .css()"
1488 return( $self->error( "Method css() must be called on an HTML::Object::DOM::Element." ) ) if( ( !$self->isa_element && !$self->isa_collection ) || $self->tag->substr( 0, 1 ) CORE::eq '_' );
1489 my( $name, $more ) = @_;
1490 return( $self->error( "No css property was provided." ) ) if( !defined( $name ) || !CORE::length( $name ) );
1491  
1492 my $process;
1493 $process = sub
1494 {
1495 my $elem = shift( @_ );
1496 my $style = $elem->attributes->get( 'style' );
1497 # return if( !defined( $style ) );
1498 my $css = CSS::Object->new( format => 'CSS::Object::Format::Inline', debug => $self->debug );
1499 my $cached;
1500 $cached = $elem->css_cache_check( $style ) if( defined( $style ) );
1501 if( $cached )
1502 {
1503 $css = $cached;
1504 }
1505 elsif( defined( $style ) )
1506 {
1507 # 'inline' here is just a fake selector to serve as a container rule for the inline properties,
1508 # because CSS::Object requires properties to be within a rule
1509 $css->read_string( 'inline {' . $style . ' }' ) ||
1510 return( $self->error( "Unable to parse existing style for tag name \"", $elem->prop( 'tagName' ), "\":", $css->error ) );
1511 }
1512 else
1513 {
1514 }
1515 my $main = $css->rules->first;
1516 # my $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
1517 my $rule;
1518  
1519 # Get the requested property values
1520 # $e->css( $property_name );
1521 # $e->css( [$property_name1, $property_name2, $property_name3] );
1522 # $e->css({ $property_name1 => $value1, $property_name2 => $value2 });
1523 if( $self->_is_array( $name ) ||
1524 $self->_is_hash( $name ) ||
1525 ( ( !ref( $name ) || overload::Method( $name, '""' ) ) && !defined( $more ) ) )
1526 {
1527 # If this is just 1 css property, we encapsulate it into an array to standardise our processing
1528 # $e->css( $property_name );
1529 $name = [ "$name" ] if( !defined( $more ) && ( !ref( $name ) || overload::Method( $name, '""' ) ) );
1530 # $e->css( [$property_name1, $property_name2, $property_name3] );
1531 # "assing an array of style properties to .css() will result in an object of property-value pairs."
1532 # <https://api.jquery.com/css/#css-propertyName>
1533 if( $self->_is_array( $name ) )
1534 {
1535 my $res = $self->new_hash;
1536 $self->new_array( $name )->foreach(sub
1537 {
1538 my $prop = shift( @_ );
1539 $prop =~ tr/_/-/;
1540 my $obj = $main->get_property_by_name( $prop );
1541 # next
1542 return(1) if( !defined( $obj ) );
1543 $res->{ $prop } = $obj->value->as_string;
1544 return(1);
1545 });
1546 return( $res );
1547 }
1548 # $e->css({ $property_name1 => $value1, $property_name2 => $value2 });
1549 elsif( $self->_is_hash( $name ) )
1550 {
1551 $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
1552 $self->new_hash( $name )->each(sub
1553 {
1554 my( $prop, $value ) = @_;
1555 my $obj = $main->get_property_by_name( $prop );
1556 # if the value is undef, remove the property from the set of css properties
1557 # "Setting the value of a style property to an empty string - e.g. $( "#mydiv" ).css( "color", "" ) - removes that property from an element if it has already been directly applied,"
1558 # <https://api.jquery.com/css/#css-propertyName-value>
1559 if( !defined( $value ) || !CORE::length( $value ) )
1560 {
1561 $main->element->remove( $obj ) if( $obj );
1562 }
1563 elsif( defined( $obj ) )
1564 {
1565 $obj->value( "$value" );
1566 }
1567 else
1568 {
1569 $main->$prop( "$value" );
1570 }
1571 });
1572 if( $rule->elements->length > 0 )
1573 {
1574 my $style = $rule->as_string;
1575 $elem->css_cache_store( $style, $css ) || return( $self->pass_error( $elem->error ) );
1576 $elem->attributes->set( style => $style );
1577 }
1578 else
1579 {
1580 }
1581 return( $self );
1582 }
1583 else
1584 {
1585 return( $self->error( "I was expecting a css property, or an array reference of css property, but instead I received '$name'." ) );
1586 }
1587 }
1588 else
1589 {
1590 # Set css property values
1591 # $e->css( $property_name, $value );
1592 # $e->css( $property_name, $code_reference );
1593 if( defined( $more ) )
1594 {
1595 return( $self->error( "More than 2 arguments were provided. I was expecting a property and its value or a function." ) ) if( scalar( @_ ) > 2 );
1596 $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
1597 # $e->css( $property_name, $code_reference );
1598 if( ref( $more ) CORE::eq 'CODE' )
1599 {
1600 my $pos = $elem->parent ? $elem->parent->children->pos( $elem ) : 0;
1601 $name =~ tr/_/-/;
1602 my $obj = $main->get_property_by_name( $name );
1603 my $val;
1604 if( defined( $obj ) )
1605 {
1606 $val = $obj->value->as_string;
1607 }
1608 local $_ = $elem;
1609 my $ret = $more->( $pos, $val );
1610 # "If nothing is returned in the setter function (ie. function( index, style ){} ), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met."
1611 # <https://api.jquery.com/css/#css-propertyName-function>
1612 return( $elem ) if( !defined( $ret ) || !CORE::length( $ret ) );
1613 if( defined( $obj ) )
1614 {
1615 $obj->value( "$val" );
1616 }
1617 else
1618 {
1619 $rule->$name( "$val" );
1620 }
1621 }
1622 # $e->css( $property_name, $value );
1623 else
1624 {
1625 return( $self->error( "I was expecting a value as a string, but instead got '$more'." ) ) if( ref( $more ) && !( overload::Overloaded( $more ) && overload::Method( $more, '""' ) ) );
1626 $name =~ tr/_/-/;
1627 my $obj = $rule->get_property_by_name( $name );
1628 if( defined( $obj ) )
1629 {
1630 $obj->value( "$more" );
1631 }
1632 else
1633 {
1634 $rule->$name( "$more" );
1635 }
1636 }
1637 }
1638  
1639 if( defined( $rule ) && $rule->elements->length > 0 )
1640 {
1641 my $style = $rule->as_string;
1642 $elem->css_cache_store( $style, $css ) || return( $self->pass_error( $elem->error ) );
1643 $elem->attributes->set( style => $style );
1644 }
1645 else
1646 {
1647 }
1648 return( $elem );
1649 }
1650 };
1651  
1652 if( $self->isa_collection )
1653 {
1654 $self->children->foreach(sub
1655 {
1656 $_->reset(1);
1657 $process->( $_ );
1658 });
1659 return( $self );
1660 }
1661 else
1662 {
1663 $self->reset(1);
1664 return( $process->( $self ) );
1665 }
1666 }
1667  
1668 sub css_cache_check
1669 {
1670 my $self = shift( @_ );
1671 # my $data = shift( @_ );
1672 # return if( !defined( $data ) );
1673 return( $self->error( "css_cache_check() must be called on an HTML element, not a collection." ) ) if( $self->isa_collection );
1674 my $internal = $self->internal;
1675 $internal->{css_cache} //= {};
1676 if( exists( $internal->{css_cache} ) )
1677 {
1678 my $css = $internal->{css_cache}->{object} ||
1679 return( $self->error( "CSS object could not be found in cache!" ) );
1680 # return( $css->clone );
1681 # my $clone = $css->clone;
1682 # return( $clone );
1683 return( $css );
1684 }
1685 return( '' );
1686 }
1687  
1688 sub css_cache_store
1689 {
1690 my $self = shift( @_ );
1691 my $data = shift( @_ );
1692 return if( !defined( $data ) );
1693 return( $self->error( "css_cache_store() must be called on an HTML element, not a collection." ) ) if( $self->isa_collection );
1694 my $css = shift( @_ );
1695 return( $self->error( "No css object provided to store in the element cache." ) ) if( !$self->_is_object( $css ) );
1696 my $trace = $self->_get_stack_trace;
1697 my $internal = $self->internal;
1698 $internal->{css_cache} =
1699 {
1700 timestamp => time(),
1701 # object => $css->clone,
1702 object => $css,
1703 };
1704 return( $self );
1705 }
1706  
1707 # sub data { return( shift->attr( join( '-', 'data', shift( @_ ) ) => shift( @_ ) ) ) }
1708 # nothing which returns everything as a hash; or
1709 # a key-value pair; or
1710 # a hash reference
1711 sub data
1712 {
1713 my $self = shift( @_ );
1714 my( $this, $val ) = @_;
1715 my $elem;
1716 if( $self->isa_collection )
1717 {
1718 $elem = $self->children->first;
1719 }
1720 # elsif( $self->tag->substr( 0, 1 ) eq '_' )
1721 elsif( !$self->_is_a( $self => 'HTML::Object::DOM::Element' ) )
1722 {
1723 return( $self->error( "You can only call the data method on HTML elements." ) );
1724 }
1725 else
1726 {
1727 $elem = $self;
1728 }
1729  
1730 if( $self->_is_hash( $this ) )
1731 {
1732 my $changed = 0;
1733 $this = $self->new_hash( $this )->each(sub
1734 {
1735 my( $k, $v ) = @_;
1736 # Remove leading and trailing spaces if this is not a reference
1737 $v =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//g if( !ref( $v ) );
1738 # $attr->set( 'data-' . $k, $v );
1739 if( $elem->setAttribute( 'data-' . $k, $v ) )
1740 {
1741 $changed++;
1742 }
1743 });
1744 $elem->reset(1) if( $changed );
1745 return( $elem );
1746 }
1747 elsif( defined( $this ) && scalar( @_ ) > 1 )
1748 {
1749 # From jQuery documentation: "undefined is not recognized as a data value. Calls such as .data( "name", undefined ) will return the jQuery object that it was called on, allowing for chaining."
1750 return( $self ) if( !defined( $val ) );
1751 return( $self->error( "I was provided data name '$this', but I was expcting a regular string." ) ) if( ref( $this ) && ( !overload::Overloaded( $this ) || ( overload::Overloaded( $this ) && !overload::Method( $this, '""' ) ) ) );
1752 # $attr->set( 'data-' . $this => $val );
1753 if( $elem->setAttribute( 'data-' . $this => $val ) )
1754 {
1755 $elem->reset(1);
1756 }
1757 return( $elem );
1758 }
1759 elsif( defined( $this ) && scalar( @_ ) == 1 )
1760 {
1761 # return( $attr->get( $this ) );
1762 return( $elem->getAttribute( 'data-' . $this ) );
1763 }
1764 else
1765 {
1766 $self->_load_class( 'Module::Generic::Dynamic' ) || return( $self->pass_error );
1767 my $ref = {};
1768 my $attr = $elem->attributes;
1769 $attr->each(sub
1770 {
1771 my( $k, $v ) = @_;
1772 if( substr( $k, 0, 5 ) CORE::eq 'data-' && CORE::length( $k ) > 5 )
1773 {
1774 $ref->{ substr( $k, 5 ) } = $v;
1775 }
1776 });
1777 my $obj = Module::Generic::Dynamic->new( $ref ) ||
1778 return( $self->pass_error( Module::Generic::Dynamic->error ) );
1779 return( $obj );
1780 }
1781 }
1782  
1783 sub debug
1784 {
1785 my $self = shift( @_ );
1786 if( @_ )
1787 {
1788 my $val = $self->SUPER::debug( @_ );
1789 if( $self->isa_collection )
1790 {
1791 $self->children->foreach(sub
1792 {
1793 $_->debug( $val );
1794 });
1795 }
1796 return( $val );
1797 }
1798 return( $self->SUPER::debug );
1799 }
1800  
1801 sub dequeue { return( $_[0] ) }
1802  
1803 # TODO: Instead of adding this method, maybe we should change the one in HTML::Object::DOM::Element to have it return $self instead of $parent, because otherwise there is no difference
1804 sub detach
1805 {
1806 my $self = shift( @_ );
1807 # If this is a collection, walk through its children
1808 if( $self->isa_collection )
1809 {
1810 $self->children->foreach(sub
1811 {
1812 my $e = shift( @_ );
1813 my $parent = $e->parent;
1814 return(1) if( !$parent );
1815 my $pos = $parent->children->pos( $e );
1816 $parent->children->splice( $pos, 1 );
1817 $e->parent( undef() );
1818 $parent->reset(1);
1819 });
1820 }
1821 # otherwise, process this one element individually
1822 else
1823 {
1824 my $parent = $self->parent;
1825 return( $self ) if( !$parent );
1826 my $pos = $parent->children->pos( $self );
1827 if( defined( $pos ) )
1828 {
1829 $parent->children->splice( $pos, 1 );
1830 $self->parent( undef() );
1831 $parent->reset(1);
1832 }
1833 }
1834 return( $self );
1835 }
1836  
1837 # Takes a code reference which receives the element position and element object as parameter
1838 # It returns the current object it was called with
1839 sub each
1840 {
1841 my( $self, $code ) = @_;
1842 return( $self->error( "I was expecting a code reference to pass it the element position and element object, but instead I got \"", overload::StrVal( $code ), "\"." ) ) if( ref( $code ) ne 'CODE' );
1843 # Make a copy of the array so that call to code ref that may remove a child element does not alter our looping operation through all the children
1844 $self->children->clone->for(sub
1845 {
1846 my( $i, $e ) = @_;
1847 $code->( $i, $e );
1848 });
1849 return( $self );
1850 }
1851  
1852 sub empty
1853 {
1854 my $self = shift( @_ );
1855 # Element object of Collection object, it does not matter
1856 $self->children->reset;
1857 $self->reset(1);
1858 return( $self );
1859 }
1860  
1861 sub end { return( shift->_set_get_object({
1862 field => 'end',
1863 weaken => 1,
1864 }, 'HTML::Object::DOM::Element', @_ ) ); }
1865  
1866 sub eq { return( shift->children->index( shift( @_ ) ) ); }
1867  
1868 # Returns a new collection of elements whose position is an even number
1869 sub even
1870 {
1871 my $self = shift( @_ );
1872 return( $self ) unless( $self->isa_collection );
1873 my $even = $self->children->even;
1874 my $collection = $self->new_collection;
1875 $collection->children( $even );
1876 return( $collection );
1877 }
1878  
1879 sub exists
1880 {
1881 my( $self, $path ) = @_;
1882 return( $self->xp->exists( $path, $self ) );
1883 }
1884  
1885 # Takes a selector; or
1886 # function with arguments are element position (starting from 0) and the element itself, expecting a true value in return; or
1887 # an array of element objects; or
1888 # an element object;
1889 sub filter
1890 {
1891 my $self = shift( @_ );
1892 my $this = shift( @_ );
1893 my $collection = $self->new_collection( end => $self );
1894 return( $collection ) if( !defined( $this ) );
1895 if( !ref( $this ) ||
1896 ( ref( $this ) &&
1897 overload::Overloaded( $this ) &&
1898 overload::Method( $this, '""' )
1899 ) )
1900 {
1901 my $xpath = $self->_xpath_value( "$this" ) || return;
1902 if( $self->isa_collection )
1903 {
1904 $self->children->foreach(sub
1905 {
1906 # $_->debug( $self->debug );
1907 if( $_->tag->substr( 0, 1 ) ne '_' &&
1908 $_->matches( $xpath ) )
1909 {
1910 $collection->children->push( $_ );
1911 }
1912 else
1913 {
1914 # No match
1915 }
1916 });
1917 }
1918 elsif( $self->tag->substr( 0, 1 ) ne '_' && $self->matches( $xpath ) )
1919 {
1920 $collection->children->push( $self );
1921 }
1922 }
1923 elsif( ref( $this ) eq 'CODE' )
1924 {
1925 if( $self->isa_collection )
1926 {
1927 $self->children->for(sub
1928 {
1929 my( $i, $e ) = @_;
1930 local $_ = $e;
1931 if( $this->( $i, $e ) )
1932 {
1933 $collection->children->push( $e );
1934 }
1935 });
1936 }
1937 elsif( $self->isa( 'HTML::Object::DOM::Element' ) )
1938 {
1939 return( $collection ) if( $self->tag->substr( 0, 1 ) eq '_' );
1940 local $_ = $self;
1941 $collection->children->push( $self ) if( $this->( 0, $self ) );
1942 }
1943 }
1944 elsif( $self->_is_array( $this ) || $self->_is_object( $this ) )
1945 {
1946 if( $self->_is_object( $this ) &&
1947 ( !$this->isa( 'HTML::Object::DOM::Element' ) ||
1948 (
1949 # Probably need to change this to HTML::Object::DOM::Node
1950 $this->isa( 'HTML::Object::Element' ) &&
1951 $this->tag->substr( 0, 1 ) eq '_' &&
1952 !$this->isa( 'HTML::Object::Collection' )
1953 )
1954 ) )
1955 {
1956 return( $self->error( "Object of class \"", ref( $this ), "\", but you can only provide an HTML::Object::DOM::Element or an HTML::Object::Collection object." ) );
1957 }
1958 my $a = $self->new_array( $self->_is_array( $this ) ? $this : [ $this ] );
1959 $a->foreach(sub
1960 {
1961 my $xpath = $_->getNodePath();
1962 if( $self->isa_collection )
1963 {
1964 $self->children->foreach(sub
1965 {
1966 my $e = shift( @_ );
1967 if( $e->matches( $xpath ) )
1968 {
1969 $collection->children->push( $e );
1970 }
1971 });
1972 }
1973 elsif( $self->matches( $xpath ) )
1974 {
1975 $collection->children->push( $self );
1976 }
1977 });
1978 }
1979 else
1980 {
1981 return( $self->error( "I was expecting a selector, a code reference, an array of elements or an element to use in filter(), but instead I got '$this', and I do not know what to do with it." ) );
1982 }
1983 return( $collection );
1984 }
1985  
1986 # Takes a selector; or
1987 # Element object
1988 sub find
1989 {
1990 my( $self, $this ) = @_;
1991 my $collection = $self->new_collection;
1992 return( $collection ) if( !defined( $this ) );
1993  
1994 if( ref( $this ) && $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
1995 {
1996 my $a = $self->new_array( $self->isa_collection( $this ) ? $this->children : [ $this ] );
1997 my $lookup;
1998 $lookup = sub
1999 {
2000 my $kids = shift( @_ );
2001 $kids->foreach(sub
2002 {
2003 my $child = shift( @_ );
2004 $a->foreach(sub
2005 {
2006 my $candidate = shift( @_ );
2007 if( $child->eid eq $candidate->eid )
2008 {
2009 $collection->children->push( $child );
2010 # We've added this child. Move to next child.
2011 return(1);
2012 }
2013 });
2014 if( $child->children->length > 0 )
2015 {
2016 $lookup->( $child->children );
2017 }
2018 });
2019 };
2020 # Wether this is a collection or just an element object, we check our children
2021 $lookup->( $self->children );
2022 }
2023 # I am expecting an xpath value
2024 else
2025 {
2026 if( ref( $this ) &&
2027 (
2028 !overload::Overloaded( $this ) ||
2029 ( overload::Overloaded( $this ) && !overload::Method( $this, '\"\"' ) )
2030 ) )
2031 {
2032 return( $self->error( "I was expecting an xpath string, but instead I got '$this'." ) );
2033 }
2034  
2035 # Fast paths pour les sélecteurs simples - évite le pipeline XPath complet
2036 my $str = "$this";
2037  
2038 # Fast path: #id
2039 if( $str =~ /\A#([\w][\w-]*)\z/ )
2040 {
2041 my $id = $1;
2042 my $found = $self->_fast_find_by(sub
2043 {
2044 my $e = shift( @_ );
2045 my $v = $e->attributes->get( 'id' );
2046 return( defined( $v ) && $v eq $id );
2047 });
2048 $collection->children->push( $found->list );
2049 return( $collection );
2050 }
2051 # Fast path: .class (une seule classe, pas de combinaison)
2052 elsif( $str =~ /\A\.([\w][\w-]*)\z/ )
2053 {
2054 my $class = $1;
2055 my $found = $self->_fast_find_by(sub
2056 {
2057 my $e = shift( @_ );
2058 my $v = $e->attributes->get( 'class' );
2059 return( defined( $v ) && $v =~ /(?:\A|[[:blank:]\h]+)\Q${class}\E(?:[[:blank:]\h]+|\Z)/ );
2060 });
2061 $collection->children->push( $found->list );
2062 return( $collection );
2063 }
2064 # Fast path: tag simple (lettres uniquement, pas de combinaison)
2065 elsif( $str =~ /\A([a-zA-Z][a-zA-Z0-9]*)\z/ )
2066 {
2067 my $tag = lc( $1 );
2068 my $found = $self->_fast_find_by(sub
2069 {
2070 my $e = shift( @_ );
2071 return( lc( "$e->{tag}" ) eq $tag );
2072 });
2073 $collection->children->push( $found->list );
2074 return( $collection );
2075 }
2076  
2077 # Fallback : pipeline XPath complet
2078 my $xpath = $self->_xpath_value( $str ) || return( $self->pass_error );
2079 # $self->children->foreach(sub
2080 # {
2081 # my $child = shift( @_ );
2082 # # Propagate debug value
2083 # $child->debug( $self->debug );
2084 # try
2085 # {
2086 # my @nodes = $child->findnodes( $xpath );
2087 # $collection->children->push( @nodes );
2088 # }
2089 # catch( $e )
2090 # {
2091 # warn( "Error while calling findnodes on element id \"", $_->id, "\" and tag \"", $_->tag, "\": $e\n" );
2092 # }
2093 # });
2094 # try-catch
2095 local $@;
2096 eval
2097 {
2098 my @nodes = $self->findnodes( $xpath );
2099 $collection->children->push( @nodes );
2100 };
2101 if( $@ )
2102 {
2103 warn( "Error while calling findnodes on element id \"", $self->id, "\" and tag \"", $self->tag, "\": $@\n" );
2104 }
2105 }
2106 return( $collection );
2107 }
2108  
2109 sub find_xpath
2110 {
2111 my( $self, $path ) = @_;
2112 return( $self->xp->find( $path, $self ) );
2113 }
2114  
2115 sub findnodes
2116 {
2117 my( $self, $path ) = @_;
2118 # xp()->debug( $self->debug );
2119 return( $self->xp->findnodes( $path, $self ) );
2120 }
2121  
2122 sub findnodes_as_string
2123 {
2124 my( $self, $path ) = @_;
2125 return( $self->xp->findnodes_as_string( $path, $self ) );
2126 }
2127  
2128 sub findnodes_as_strings
2129 {
2130 my( $self, $path ) = @_;
2131 return( $self->xp->findnodes_as_strings( $path, $self ) );
2132 }
2133  
2134 sub findvalue
2135 {
2136 my( $self, $path ) = @_;
2137 return( $self->xp->findvalue( $path, $self ) );
2138 }
2139  
2140 sub findvalues
2141 {
2142 my( $self, $path ) = @_;
2143 return( $self->xp->findvalues( $path, $self ) );
2144 }
2145  
2146 sub first
2147 {
2148 my $self = shift( @_ );
2149 my $collection = $self->new_collection;
2150 if( $self->isa_collection )
2151 {
2152 return( $self->children->first );
2153 }
2154 else
2155 {
2156 return( $self );
2157 }
2158 }
2159  
2160 # <https://api.jquery.com/get/>
2161 sub get
2162 {
2163 my $self = shift( @_ );
2164 my $idx = shift( @_ );
2165 if( $self->isa_collection )
2166 {
2167 if( defined( $idx ) )
2168 {
2169 return( $self->error( "Index value provided is not an integer." ) ) if( !$self->_is_integer( $idx ) );
2170 return( $self->children->[ $idx ] );
2171 }
2172 else
2173 {
2174 my $arr = $self->new_array;
2175 $arr->push( $self->children->list );
2176 return( $arr );
2177 }
2178 }
2179 else
2180 {
2181 if( defined( $idx ) )
2182 {
2183 return( $self );
2184 }
2185 else
2186 {
2187 return( $self->new_array( $self ) );
2188 }
2189 }
2190 }
2191  
2192 sub getDataJson
2193 {
2194 my $self = shift( @_ );
2195 my $dataName = shift( @_ ) ||
2196 return( $self->error( "No data name was provided to get its JSON object" ) );
2197 my $el;
2198 if( $self->isa_collection )
2199 {
2200 $el = $self->children->first;
2201 return({}) if( !$el );
2202 }
2203 else
2204 {
2205 $el = $self;
2206 }
2207 my $json;
2208 my $shortName = $dataName;
2209 if( substr( $dataName, 0, 5 ) eq 'data-' )
2210 {
2211 $shortName = substr( $dataName, 5, length( $dataName ) );
2212 }
2213 my $data = $self->data( $shortName );
2214 return({}) if( !defined( $data ) || !length( $data // '' ) );
2215 if( ref( $data ) eq 'HASH' )
2216 {
2217 $json = $data;
2218 }
2219 else
2220 {
2221 # Taken from URI::Escape
2222 my $decodeURIComponent = sub
2223 {
2224 my $str = shift( @_ );
2225 if( @_ && wantarray )
2226 {
2227 # not executed for the common case of a single argument
2228 # need to copy
2229 my @str = ( $str, @_ );
2230 for( @str )
2231 {
2232 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
2233 }
2234 return( @str );
2235 }
2236 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if( defined( $str ) );
2237 return( $str );
2238 };
2239 # try-catch
2240 local $@;
2241 eval
2242 {
2243 my $j = $self->new_json;
2244 if( index( $data, '{' ) != -1 )
2245 {
2246 $json = $j->decode( $data );
2247 }
2248 else
2249 {
2250 $json = $j->decode( $decodeURIComponent->( $data ) );
2251 }
2252 };
2253 if( $@ )
2254 {
2255 return( $self->error( "An error occurred while trying to decode the json data: $@" ) );
2256 }
2257 # Replace parsed json string by its object representation
2258 $self->data( $shortName => $json );
2259 }
2260 return( $json );
2261 }
2262  
2263 sub getJSON
2264 {
2265 my $self = shift( @_ );
2266 my $url = shift( @_ ) || return( $self->error( "No URL was provided." ) );
2267 my @args = @_;
2268 my( $data, $success );
2269 for( my $i = 0; $i < scalar( @args ); $i++ )
2270 {
2271 if( !defined( $data ) && ref( $args[$i] // '' ) eq 'HASH' )
2272 {
2273 $data = $args[$i];
2274 }
2275 elsif( !defined( $success ) && ref( $args[$i] // '' ) eq 'CODE' )
2276 {
2277 $success = $args[$i];
2278 }
2279 }
2280  
2281 $self->_load_class( 'Promise::Me' ) || return( $self->pass_error );
2282 if( lc( substr( "$url", 0, 7 ) ) eq 'file://' )
2283 {
2284 $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error );
2285 return( Promise::Me->new(sub
2286 {
2287 my( $resolve, $reject ) = @$_;
2288 my $f = $self->new_file( $url ) || return( $reject->( $self->error ) );
2289 if( $f->exists )
2290 {
2291 my $ref = $f->load_json || return( $reject->( $f->error ) );
2292 my $resp2 = HTTP::Promise::Response->new( 200 => 'OK' );
2293 if( defined( $success ) )
2294 {
2295 my $ua = HTTP::Promise->new;
2296 $success->( $ref, 'success', $resp2, $ua );
2297 }
2298 return( $resolve->( $ref, 'success', $resp2 ) );
2299 }
2300 else
2301 {
2302 my $resp2 = HTTP::Promise::Response->new( 404 => 'Not found' );
2303 my $err = "File $url is not found.";
2304 if( defined( $success ) )
2305 {
2306 my $ua = HTTP::Promise->new;
2307 $success->( $err, 'error', $resp2, $ua );
2308 }
2309 $self->error({
2310 code => 404,
2311 message => $err,
2312 });
2313 my $ex = $self->error;
2314 return( $reject->( $ex ) );
2315 }
2316 }) );
2317 }
2318 else
2319 {
2320 return( Promise::Me->new(sub
2321 {
2322 my( $resolve, $reject ) = @$_;
2323 my( $uri, $doc_root, $doc_uri );
2324 if( lc( substr( $url, 0, 7 ) ) eq 'http://' ||
2325 lc( substr( $url, 0, 7 ) ) eq 'http://' )
2326 {
2327 $uri = $url;
2328 }
2329 # Contextual URL that requires a base URL.
2330 # We check for documentURI of the root element, if any
2331 elsif( ( substr( $url, 0, 1 ) eq '/' ||
2332 substr( $url, 0, 2 ) eq './' ||
2333 substr( $url, 0, 3 ) eq '../' ) &&
2334 ( $doc_root = $self->getRootNode ) &&
2335 $doc_root->isa( 'HTML::Object::DOM::Document' ) &&
2336 ( $doc_uri = $doc_root->documentURI ) )
2337 {
2338 $uri = $doc_uri->clone;
2339 $uri->path( $url );
2340 }
2341 else
2342 {
2343 $self->error( "Unsupported URL '${url}'" );
2344 return( $reject->( $self->error ) );
2345 }
2346 $self->ajax( $uri,
2347 dataType => 'json',
2348 ( defined( $data ) ? ( data => $data ) : () ),
2349 ( defined( $success ) ? ( success => $success ) : () ),
2350 )->catch(sub
2351 {
2352 return( $reject->( @_ ) );
2353 });
2354 }) );
2355 }
2356 }
2357  
2358 sub has
2359 {
2360 my $self = shift( @_ );
2361 my $this = shift( @_ );
2362 my $collection = $self->new_collection;
2363 return( $collection ) if( !defined( $this ) );
2364 if( ref( $this ) && $self->_is_object( $this ) && $self->isa( 'HTML::Object::DOM::Element' ) )
2365 {
2366 my $lookup;
2367 $lookup = sub
2368 {
2369 my $kids = shift( @_ );
2370 my $found;
2371 $kids->foreach(sub
2372 {
2373 my $child = shift( @_ );
2374 $this->children->foreach(sub
2375 {
2376 my $candidate = shift( @_ );
2377 # Found a match, no need to look down further
2378 if( $child->eid eq $candidate->eid )
2379 {
2380 $found = $child;
2381 return( $kids->return( undef() ) );
2382 }
2383 });
2384 if( $child->children->length )
2385 {
2386 my $rc = $lookup->( $child->children );
2387 if( $rc )
2388 {
2389 $found = $rc;
2390 return( $kids->return( undef() ) );
2391 }
2392 }
2393 });
2394 return( $found );
2395 };
2396 $self->children->foreach(sub
2397 {
2398 $collection->children->push( $_ ) if( $lookup->( $_->children ) );
2399 });
2400 }
2401 # An xpath then?
2402 else
2403 {
2404 if( ref( $this ) &&
2405 (
2406 !overload::Overloaded( $this ) ||
2407 ( overload::Overloaded( $this ) && !overload::Method( $this, '""' ) )
2408 ) )
2409 {
2410 return( $self->error( "I was expecting an xpath value, but got '$this' instead." ) );
2411 }
2412 my $xpath = $self->_xpath_value( "$this" ) || return;
2413  
2414 my $lookup;
2415 $lookup = sub
2416 {
2417 my $kids = shift( @_ );
2418 my $found;
2419 $kids->foreach(sub
2420 {
2421 my $child = shift( @_ );
2422 if( $child->matches( $xpath ) )
2423 {
2424 $found = $child;
2425 # No need to look further, we found a match
2426 return(1);
2427 }
2428 if( $child->children->length > 0 )
2429 {
2430 my $rc = $lookup->( $child->children );
2431 if( $rc )
2432 {
2433 $found = $rc;
2434 return(1);
2435 }
2436 }
2437 });
2438 return( $found );
2439 };
2440  
2441 $self->children->foreach(sub
2442 {
2443 $collection->children->push( $_ ) if( $lookup->( $_->children ) );
2444 });
2445 }
2446 return( $collection );
2447 }
2448  
2449 sub hasClass
2450 {
2451 my $self = shift( @_ );
2452 my $class = shift( @_ );
2453 return(0) if( !CORE::length( $class ) );
2454 my $found = 0;
2455 if( $self->isa_collection )
2456 {
2457 $self->children->foreach(sub
2458 {
2459 my $e = shift( @_ );
2460 my $classes = $e->attributes->get( 'class' );
2461 # No class attribute, skip to next element
2462 return(1) if( !defined( $classes ) );
2463 # Found a match, no need to go further since we only need to return true or false
2464 if( $classes =~ /(?:\A|[[:blank:]\h]+)${class}(?:[[:blank:]\h]+|\Z)/ )
2465 {
2466 $found++;
2467 return(0);
2468 }
2469 return(1);
2470 });
2471 }
2472 else
2473 {
2474 my $classes = $self->attributes->get( 'class' );
2475 return(0) if( !defined( $classes ) );
2476 return(1) if( $classes =~ /(?:\A|[[:blank:]\h]+)${class}(?:[[:blank:]\h]+|\Z)/ );
2477 return(0);
2478 }
2479 }
2480  
2481 # Since this is a perl context, this only set the inline css to "display: none" like jQuery actually does
2482 # Any parameter provided will be ignored
2483 # See the show() method for its alter ego
2484 sub hide
2485 {
2486 my $self = shift( @_ );
2487 my( $this, $code ) = @_;
2488 $code = $this if( ref( $this ) eq 'CODE' && !defined( $code ) );
2489 my $process;
2490 $process = sub
2491 {
2492 my $e = shift( @_ );
2493 my $internal = $e->internal;
2494 my $rule = $self->_css_object();
2495 if( defined( $rule ) )
2496 {
2497 my $display = $rule->get_property_by_name( 'display' );
2498 my $val = $display->value;
2499 # $val may be undefined if it was not set in the first place, and that's ok
2500 # when we'll restore it with show(), we'll see the original value was empty and
2501 # we'll just remove the "display: none"
2502 # Here we check what the current value is, because, if it is already set to none, we just ignore it
2503 if( $val ne 'none' )
2504 {
2505 $internal->{css_display_value} = $val;
2506 }
2507 $display->value( 'none' );
2508 }
2509 else
2510 {
2511 $rule = $self->_css_builder;
2512 $rule->display( 'none' );
2513 }
2514 if( $rule->elements->length > 0 )
2515 {
2516 $e->_css_object( $rule );
2517 }
2518 };
2519  
2520 if( $self->isa_collection )
2521 {
2522 $self->children->foreach(sub
2523 {
2524 $process->( $_ );
2525 });
2526 }
2527 elsif( $self->tag->substr( 0, 1 ) eq '_' )
2528 {
2529 return( $self->error( "You can only use the hide() or show() method on html object elements. The element you are calling hide() with is an object of class \"", ref( $self ), "\"." ) );
2530 }
2531 else
2532 {
2533 $process->( $self );
2534 }
2535 }
2536  
2537 # This takes either no arguments and it returns the inner html; or
2538 # it takes an html string to replace its content; or
2539 # it takes a code reference that is called with the index position in the set of element and
2540 # the current html data. It returns the new html data
2541 # See also text() method
2542 sub html
2543 {
2544 my $self = shift( @_ );
2545 my $this = shift( @_ );
2546 if( defined( $this ) )
2547 {
2548 if( !ref( $this ) ||
2549 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
2550 {
2551 my $p = $self->new_parser;
2552 my $res = $p->parse_data( "$this" ) ||
2553 return( $self->error( "Error while parsing html data provided: ", $p->error ) );
2554 $this = $res;
2555 }
2556 elsif( ref( $this ) ne 'CODE' )
2557 {
2558 return( $self->error( "I was expecting some html data or a code reference in replacement of html for this element \"", $self->tag, "\", but instead got '$this'." ) );
2559 }
2560  
2561 my $is_code = ref( $this ) eq 'CODE' ? 1 : 0;
2562 my $process = sub
2563 {
2564 my( $e, $i ) = @_;
2565 if( $is_code )
2566 {
2567 my $current_html = $e->as_string;
2568 my $html = $this->( $i, $current_html );
2569 if( !defined( $html ) || !CORE::length( $html ) )
2570 {
2571 $e->empty();
2572 # Next please
2573 return(1);
2574 }
2575 # We were provided with an HTML::Object::DOM::Element in response, we use its children as the new content
2576 elsif( ref( $html ) && $self->_is_object( $html ) && $html->isa( 'HTML::Object::DOM::Element' ) )
2577 {
2578 if( $html->tag->substr( 0, 1 ) eq '_' && !$html->isa_collection )
2579 {
2580 warn( "You cannot use this object of class ", ref( $html ), " to set its children as the new html. You can only use html element objects.\n" );
2581 return(1);
2582 }
2583 $e->children( $html->children );
2584 $html->children->foreach(sub
2585 {
2586 $_->parent( $e );
2587 });
2588 $e->reset(1);
2589 return(1);
2590 }
2591 elsif( ref( $html ) &&
2592 !( overload::Overloaded( $html ) && overload::Method( $html, '""' ) ) )
2593 {
2594 warn( "I was provided a reference '$html' as a result from calling this code reference to get the replacement html for tag \"", $e->tag, "\", but I do not know what to do with it.\n" );
2595 return(1);
2596 }
2597 my $p = $self->new_parser;
2598 my $doc = $p->parse_data( "$html" ) || do
2599 {
2600 warn( "Error while trying to parse html data returned by code reference supplied: ", $p->error );
2601 # Switch to next element
2602 return(1);
2603 };
2604 # Replace the children element by the new ones found in parsing.
2605 $e->children( $doc->children );
2606 $doc->children->foreach(sub
2607 {
2608 $_->parent( $e );
2609 });
2610 $e->reset(1);
2611 }
2612 # It's an HTML::Object::DOM::Document object
2613 else
2614 {
2615 my $a = $self->new_array;
2616 $this->children->foreach(sub
2617 {
2618 $a->push( $_->clone );
2619 });
2620 $e->children( $a );
2621 $e->reset(1);
2622 }
2623 };
2624  
2625 if( $self->isa_collection )
2626 {
2627 $self->children->for(sub
2628 {
2629 my( $i, $e ) = @_;
2630 $process->( $e, $i );
2631 # Return true at the end to satisfy Module::Generic::Array->for
2632 return(1);
2633 });
2634 }
2635 else
2636 {
2637 $process->( $self, 0 );
2638 }
2639 }
2640 else
2641 {
2642 # "Get the HTML contents of the first element in the set of matched elements."
2643 my $elem = $self->isa_collection ? $self->children->first : $self;
2644 return( '' ) unless( $self );
2645 # Create a new document, because we want to use the document object as_string function which produce a string of its children, and no need to reproduce it here
2646 my $doc = $elem->new_document;
2647 $doc->children( $elem->children );
2648 return( $doc->as_string );
2649 }
2650 }
2651  
2652 sub id
2653 {
2654 my $self = shift( @_ );
2655 if( @_ )
2656 {
2657 if( $self->isa_collection )
2658 {
2659 return( $self->error( "Cannot set an id on a collection" ) );
2660 }
2661 else
2662 {
2663 # Method in HTML::Object::DOM::Element
2664 return( $self->_set_get_id( @_ ) );
2665 }
2666 }
2667 else
2668 {
2669 my $e = $self;
2670 if( $self->isa_collection )
2671 {
2672 my $first = $self->children->first;
2673 return if( !$first || !$self->isa_element( $first ) );
2674 $e = $first;
2675 }
2676 my $id = $e->attributes->get( 'id' );
2677 return( $e->new_scalar( $id ) );
2678 }
2679 }
2680  
2681 # Takes either nothing; or
2682 # a selector; or
2683 # an element object
2684 sub index
2685 {
2686 my $self = shift( @_ );
2687 my $this = shift( @_ );
2688 if( defined( $this ) )
2689 {
2690 if( !ref( $this ) ||
2691 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
2692 {
2693 my $xpath = $self->_xpath_value( "$this" );
2694 if( $self->isa_collection() )
2695 {
2696 my $found;
2697 $self->children->for(sub
2698 {
2699 my( $i, $e ) = @_;
2700 if( $e->matches( $xpath ) )
2701 {
2702 $found = $i;
2703 # Exit the for loop
2704 return(1);
2705 }
2706 });
2707 return( $self->new_number(-1) ) if( !defined( $found ) );
2708 return( $self->new_number( $found ) );
2709 }
2710 else
2711 {
2712 if( $self->matches( $xpath ) )
2713 {
2714 return( $self->new_number(0) ) if( !$self->parent );
2715 my $pos = $self->parent->children->pos( $self );
2716 return( $self->new_number( defined( $pos ) ? $pos : -1 ) );
2717 }
2718 else
2719 {
2720 return( $self->new_number(-1) );
2721 }
2722 }
2723 }
2724 elsif( ref( $this ) && $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
2725 {
2726 my $elem = $this->isa_collection() ? $this->children->first : $this;
2727 my $found;
2728 if( $self->isa_collection() )
2729 {
2730 $self->children->for(sub
2731 {
2732 my( $i, $e ) = @_;
2733 if( $e->eid eq $elem->eid )
2734 {
2735 $found = $i;
2736 return;
2737 }
2738 });
2739 }
2740 else
2741 {
2742 return( $self->new_number( $self->eid eq $elem->eid ? 0 : -1 ) );
2743 }
2744 }
2745 }
2746 # Return the position of the element or if this is a collection, the position of the first element in the collection
2747 else
2748 {
2749 my $elem = ( $self->isa_collection ? $self->children->first : $self );
2750 return( $self->new_number(-1) ) if( !defined( $elem ) || !CORE::length( $elem ) );
2751 return( $self->new_number(0) ) if( !$elem->parent );
2752 my $pos = $elem->parent->children->pos( $elem );
2753 return( $self->new_number( defined( $pos ) ? $pos : -1 ) );
2754 }
2755 }
2756  
2757 sub insertAfter { return( shift->_insert_before_after( @_, { action => 'after' }) ); }
2758  
2759 sub insertBefore { return( shift->_insert_before_after( @_, { action => 'before' }) ); }
2760  
2761 # Takes a selector; or
2762 # an element object; or
2763 # a collection object; or
2764 # a code reference and
2765 # return true or false object
2766 # "Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments."
2767 # <https://api.jquery.com/is/#is-selector>
2768 sub is
2769 {
2770 my $self = shift( @_ );
2771 my $this = shift( @_ );
2772 my $found = $self->false;
2773 if( ref( $this ) CORE::eq 'CODE' )
2774 {
2775 if( $self->isa_collection() )
2776 {
2777 $self->children->for(sub
2778 {
2779 my( $i, $e ) = @_;
2780 local $_ = $e;
2781 if( $this->( $i, $e ) )
2782 {
2783 $found = $self->true;
2784 return(1);
2785 }
2786 });
2787 }
2788 else
2789 {
2790 my $pos = ( $self->parent ? $self->parent->children->pos( $self ) : 0 );
2791 if( $this->( $pos, $self ) )
2792 {
2793 $found = $self->true;
2794 }
2795 }
2796 return( $found );
2797 }
2798 elsif( ref( $this ) && $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
2799 {
2800 my $a = $this->isa_collection() ? $this->children() : $self->new_array( [ $this ] );
2801 if( $self->isa_collection() )
2802 {
2803 my $kids = $self->children;
2804 $kids->foreach(sub
2805 {
2806 my $e = shift( @_ );
2807 $a->foreach(sub
2808 {
2809 my $other = shift( @_ );
2810 if( $e->eid CORE::eq $other->eid )
2811 {
2812 $found = $self->true;
2813 # Exit this loop and tell the upper loop to exit as well
2814 return( $kids->return( undef() ) );
2815 }
2816 });
2817 });
2818 }
2819 else
2820 {
2821 $a->foreach(sub
2822 {
2823 if( $_->eid CORE::eq $self->eid )
2824 {
2825 $found = $self->true;
2826 return(1);
2827 }
2828 });
2829 }
2830 return( $found );
2831 }
2832 # Works for xpath, but also need to account for special keywords starting with ':'
2833 # e.g.:
2834 # is( ":first-child" )
2835 # is( ":contains('Peter')" )
2836 # is( ":checked" )
2837 elsif( !ref( $this ) ||
2838 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
2839 {
2840 my $xpath = $self->_xpath_value( $this );
2841 # false() method is inherited from Module::Generic module.
2842 if( $self->isa_collection() )
2843 {
2844 $self->children->foreach(sub
2845 {
2846 if( $_->matches( $xpath ) )
2847 {
2848 $found = $self->true;
2849 return(1);
2850 }
2851 });
2852 }
2853 else
2854 {
2855 $found = $self->true if( $self->matches( $xpath ) );
2856 }
2857 return( $found );
2858 }
2859 else
2860 {
2861 return( $self->error( "I was expecting a selector, an element object, a collection object or a code reference, but got '$this'." ) );
2862 }
2863 }
2864  
2865 sub isArray { return( shift->_is_array( @_ ) ); }
2866  
2867 sub isa_collection
2868 {
2869 my $self = shift( @_ );
2870 if( scalar( @_ ) )
2871 {
2872 return( $_[0]->isa( 'HTML::Object::Collection' ) );
2873 }
2874 return( $self->isa( 'HTML::Object::Collection' ) );
2875 }
2876  
2877 sub isa_element
2878 {
2879 my $self = shift( @_ );
2880 my $e = scalar( @_ ) ? shift( @_ ) : $self;
2881 return( $self->_is_a( $e, 'HTML::Object::DOM::Element' ) );
2882 }
2883  
2884 sub length
2885 {
2886 my $self = shift( @_ );
2887 if( $self->isa_collection )
2888 {
2889 return( $self->children->length );
2890 }
2891 else
2892 {
2893 return( $self->new_number(1) );
2894 }
2895 }
2896  
2897 # $e->load( 'https://example.org/some/where' );
2898 # $e->load( 'https://example.org/some/where', { param1 => value1, param2 => value2 } );
2899 # $e->load( 'https://example.org/some/where', { param1 => value1, param2 => value2 }, sub
2900 # {
2901 # my( $responseText, $responseStatus, $responseObject ) = @_;
2902 # # do something
2903 # });
2904 # <https://api.jquery.com/load/#load-url-data-complete>
2905 # $e->load( 'https://example.org/some/where', sub
2906 # {
2907 # my( $responseText, $responseStatus, $responseObject ) = @_;
2908 # # do something
2909 # });
2910 # $e->load({
2911 # url => 'https://example.org/some/where',
2912 # data => { param1 => value1, param2 => value2 },
2913 # callback => sub
2914 # {
2915 # my( $responseText, $responseStatus, $responseObject ) = @_;
2916 # # do something
2917 # }
2918 # });
2919 # <https://api.jquery.com/load/#load-url-data-complete>
2920 sub load
2921 {
2922 my $self = shift( @_ );
2923 my( $url, $data, $complete ) = @_;
2924 my $opts = {};
2925 if( scalar( @_ ) == 1 && ref( $_[0] ) eq 'HASH' )
2926 {
2927 $opts = shift( @_ );
2928 ( $url, $data, $complete ) = @$opts{qw( url data callback )};
2929 }
2930 # e.g. $e->load( $url, $data, $complete, $options );
2931 elsif( scalar( @_ ) > 2 && ref( $_[-1] ) eq 'HASH' )
2932 {
2933 $opts = pop( @_ );
2934 }
2935  
2936 return( $self->error( "No url was provided to load data" ) ) if( !defined( $url ) || !CORE::length( "$url" ) );
2937 if( !defined( $complete ) && defined( $data ) && ref( $data ) eq 'CODE' )
2938 {
2939 $complete = $data;
2940 undef( $data );
2941 }
2942 if( defined( $data ) && ref( $data ) ne 'HASH' )
2943 {
2944 warn( "Data to be submitted to $url was provided, but I was expecting an hash reference and I got '", overload::StrVal( $data ), "'" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
2945 return( $self->error( "Data to be submitted to $url was provided, but I was expecting an hash reference and I got '", overload::StrVal( $data ), "'" ) );
2946 }
2947 if( defined( $complete ) && ref( $complete ) ne 'CODE' )
2948 {
2949 return( $self->error( "A callback parameter was provided, and I was expecting a code reference, such as an anonymous subroutine, but instead I got '", overload::StrVal( $complete ), "'" ) );
2950 }
2951  
2952 # No need to go further if there is nothing in our collection
2953 my $children = $self->isa_collection ? $self->children : $self->new_array( $self );
2954 return( $self ) if( !$children->length );
2955 # if( !$children->length )
2956 # {
2957 # if( defined( $complete ) )
2958 # {
2959 # my $resp = HTTP::Response->new( 204, 'No content', [] );
2960 # $children->foreach(sub
2961 # {
2962 # $complete->( '', 'nocontent', $resp );
2963 # });
2964 # }
2965 # return( $self );
2966 # }
2967  
2968 # Ultimately, if the callback is not set, we set a dummy one instead
2969 $complete = sub{1} if( !defined( $complete ) );
2970  
2971 if( !$self->_load_class( 'HTTP::Promise', { version => 'v0.5.0' } ) )
2972 {
2973 return( $self->error( "HTTP::Promise version v0.5.0 or higher is required to use load()" ) );
2974 }
2975 if( !$self->_load_class( 'URI', { version => '1.74' } ) )
2976 {
2977 return( $self->error( "URI version 1.74 or higher is required to use load()" ) );
2978 }
2979 $opts->{timeout} //= 10;
2980 $opts->{agent} ||= "HTML::Object/$VERSION";
2981 # "If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded."
2982 # e.g.: $( "#new-projects" )->load( "/resources/load.html #projects li" );
2983 # <https://api.jquery.com/load/#load-url-data-complete>
2984 ( $url, my $target ) = split( /[[:blank:]\h]+/, $url, 2 );
2985  
2986 my $uri;
2987 # try-catch
2988 local $@;
2989 eval
2990 {
2991 $uri = URI->new( "$url" );
2992 };
2993 if( $@ )
2994 {
2995 return( $self->error( "Bad url provided \"$url\": $@" ) );
2996 }
2997  
2998 my $content;
2999 my $resp;
3000 my @http_options = qw(
3001 accept_encoding accept_language auto_switch_https cookie_jar dnt max_redirect
3002 proxy
3003 );
3004 my $params = {};
3005 foreach my $k ( @http_options )
3006 {
3007 if( exists( $opts->{ $k } ) &&
3008 defined( $opts->{ $k } ) &&
3009 CORE::length( $opts->{ $k } ) )
3010 {
3011 $params->{ $k } = $opts->{ $k };
3012 }
3013 }
3014 $params->{use_promise} = 0;
3015 # try-catch
3016 my $ua = HTTP::Promise->new( %$params );
3017 return( $self->pass_error( HTTP::Promise->error ) ) if( !defined( $ua ) );
3018  
3019 # Contextual URL that requires a base URL.
3020 # We check for documentURI of the root element, if any
3021 my( $doc_root, $doc_uri );
3022 if( ( substr( $uri, 0, 1 ) eq '/' ||
3023 substr( $uri, 0, 2 ) eq './' ||
3024 substr( $uri, 0, 3 ) eq '../' ) &&
3025 ( $doc_root = $self->getRootNode ) &&
3026 $doc_root->isa( 'HTML::Object::DOM::Document' ) &&
3027 ( $doc_uri = $doc_root->documentURI ) )
3028 {
3029 my $clone = $doc_uri->clone;
3030 $clone->path( $uri );
3031 $uri = $clone;
3032 }
3033  
3034 if( $uri->scheme eq 'http' || $uri->scheme eq 'https' )
3035 {
3036 # "The POST method is used if data is provided as an object; otherwise, GET is assumed."
3037 # <https://api.jquery.com/load/#load-url-data-complete>
3038 if( defined( $data ) )
3039 {
3040 $resp = $ua->post( $uri, $data, ( ref( $opts->{headers} ) eq 'HASH' && scalar( keys( %{$opts->{headers}} ) ) ) ? %{$opts->{headers}} : () );
3041 }
3042 else
3043 {
3044 $resp = $ua->get( $uri, ( ref( $opts->{headers} ) eq 'HASH' && scalar( keys( %{$opts->{headers}} ) ) ) ? %{$opts->{headers}} : () );
3045 }
3046  
3047 if( !$resp )
3048 {
3049 $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error );
3050 my $err = "Error trying to get url \"${url}\": " . ( $ua->error ? $ua->error->message : 'unknown' );
3051 my $resp2 = HTTP::Promise::Response->new( 500, "Unexpected error", [], $err );
3052 $complete->( $err, 'error', $resp2, $ua );
3053 return( $self->error({
3054 code => 500,
3055 message => $err,
3056 }) );
3057 }
3058 $content = $resp->decoded_content;
3059  
3060 if( $resp->header( 'Client-Warning' ) || !$resp->is_success )
3061 {
3062 $complete->( $content, 'error', $resp, $ua );
3063 return( $self->error({
3064 code => $resp->code,
3065 message => $resp->message,
3066 }) );
3067 }
3068 }
3069 elsif( $uri->scheme eq 'file' )
3070 {
3071 $self->_load_class( 'HTTP::Promise::Response' ) || return( $self->pass_error );
3072 my $f = $self->new_file( $uri ) || return( $self->pass_error );
3073 if( $f->exists )
3074 {
3075 $resp = HTTP::Promise::Response->new( 200 => 'OK' );
3076 $content = $f->load;
3077 }
3078 else
3079 {
3080 my $resp2 = HTTP::Promise::Response->new( 404 => 'Not found' );
3081 my $err = "File $uri is not found.";
3082 $complete->( $err, 'error', $resp2, $ua );
3083 return( $self->error({
3084 code => 404,
3085 message => $err,
3086 }) );
3087 }
3088 }
3089 else
3090 {
3091 my $resp2 = HTTP::Promise::Response->new( 400 => 'Bad request' );
3092 my $err = "The URL provided is unsupported.";
3093 $complete->( $err, 'error', $resp2, $ua );
3094 return( $self->error({
3095 code => 400,
3096 message => $err,
3097 }) );
3098 }
3099  
3100 my $new;
3101 if( defined( $content ) && CORE::length( $content // '' ) )
3102 {
3103 my $parser = $self->new_parser;
3104 # HTML::Object::DOM::Document
3105 my $doc = $parser->parse_data( $content ) ||
3106 return( $self->pass_error( $parser->error ) );
3107 $new = $doc->children;
3108 # "When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded."
3109 if( defined( $target ) )
3110 {
3111 $doc->debug( $self->debug );
3112 my $elem = $doc->find( $target ) || return( $self->pass_error( $doc->error ) );
3113 # $new = $self->new_array( $elem );
3114 $new = $elem->children;
3115 }
3116 }
3117 # The content returned is empty, so we cannot parse it, and instead we provide a HTML::Object::DOM::Text element with an empty value inside.
3118 else
3119 {
3120 my $txt = $self->new_text( value => '' ) || return( $self->pass_error );
3121 $new = $self->new_array( $txt );
3122 }
3123  
3124 # "If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the collection, and $_ is set to each DOM element in turn."
3125 $children->foreach(sub
3126 {
3127 my $child = shift( @_ );
3128 # Make a deep copy for each child element and set each child element's children
3129 my $clone = $new->map(sub{ $_->clone });
3130 $child->children( $clone );
3131 $child->reset(1);
3132 my $status = 'error';
3133 if( $resp->code >= 200 && $resp->code < 300 )
3134 {
3135 $status = 'success';
3136 }
3137 elsif( $resp->code == 304 )
3138 {
3139 $status = 'notmodified';
3140 }
3141 elsif( $resp->is_error )
3142 {
3143 $status = 'error';
3144 }
3145 $complete->( $content, $status, $resp );
3146 });
3147 return( $self );
3148 }
3149  
3150 sub map
3151 {
3152 my $self = shift( @_ );
3153 my $code = shift( @_ ) || return( $self->error( "No code reference was provided." ) );
3154 return( $self->error( "I was expecting a code reference, but instead I was provided with this: \"", overload::StrVal( $code ), "\"." ) ) if( ref( $code ) ne 'CODE' );
3155 return( $self->children->for( $code ) );
3156 }
3157  
3158 sub matches
3159 {
3160 my( $self, $path ) = @_;
3161 return( $self->xp->matches( $self, $path, $self ) );
3162 }
3163  
3164 sub name { return( shift->attr( name => shift( @_ ) ) ); }
3165  
3166 sub new_attribute
3167 {
3168 my $self = shift( @_ );
3169 my $opts = $self->_get_args_as_hash( @_ );
3170 $opts->{debug} = $self->debug unless( exists( $opts->{debug} ) );
3171 my $e = HTML::Object::DOM::Attribute->new( $opts ) ||
3172 return( $self->pass_error( HTML::Object::DOM::Attribute->error ) );
3173 return( $e );
3174 }
3175  
3176 sub new_parser { HTML::Object::DOM->new }
3177  
3178 sub new_collection
3179 {
3180 my $self = shift( @_ );
3181 my $opts = $self->_get_args_as_hash( @_ );
3182 $opts->{debug} = $self->debug unless( exists( $opts->{debug} ) );
3183 $opts->{end} = $self unless( exists( $opts->{end} ) );
3184 my $e = HTML::Object::Collection->new( $opts ) ||
3185 return( $self->pass_error( HTML::Object::Collection->error ) );
3186 return( $e );
3187 }
3188  
3189 sub new_root
3190 {
3191 my $self = shift( @_ );
3192 my $opts = $self->_get_args_as_hash( @_ );
3193 $opts->{debug} = $self->debug unless( exists( $opts->{debug} ) );
3194 my $e = HTML::Object::DOM::Root->new( $opts ) ||
3195 return( $self->pass_error( HTML::Object::DOM::Root->error ) );
3196 return( $e );
3197 }
3198  
3199 sub normalize_content
3200 {
3201 my $self = shift( @_ );
3202 if( $self->isa_collection )
3203 {
3204 $self->children->foreach(sub
3205 {
3206 $_->normalize_content;
3207 });
3208 return( $self );
3209 }
3210 else
3211 {
3212 $self->SUPER::normalize_content;
3213 }
3214 }
3215  
3216 # Takes a selector expression; or
3217 # a element object; or
3218 # a collection of elements; or
3219 # an array of element objects to match against the set.
3220 sub not
3221 {
3222 my $self = shift( @_ );
3223 my $this;
3224 $this = shift( @_ ) if( scalar( @_ ) );
3225 my $collection = $self->new_collection( end => $self );
3226 # Process array of elements
3227 my $process;
3228 $process = sub
3229 {
3230 my( $kids, $to_exclude ) = @_;
3231 my $exclude = $self->new_array;
3232 $kids->foreach(sub
3233 {
3234 my $elem = shift( @_ );
3235 my $path = $elem->getNodePath();
3236 $to_exclude->foreach(sub
3237 {
3238 my $e = shift( @_ );
3239 return(1) if( !$self->_is_object( $e ) || !$e->isa( 'HTML::Object::DOM::Element' ) );
3240 return(1) if( !$e->isa( 'HTML::Object::DOM::Comment' ) || $e->isa( 'HTML::Object::DOM::Text' ) || $e->isa( 'HTML::Object::DOM::Declaration' ) || $e->isa( 'HTML::Object::DOM::Space' ) );
3241 # This element matches the xpath of one of the collection element, so we exclude it from the result
3242 if( $e->matches( $path ) )
3243 {
3244 $exclude->push( $elem );
3245 return(1);
3246 }
3247 });
3248 });
3249 return( $kids->clone->remove( $exclude ) );
3250 };
3251  
3252 # No parameter provided, thus we return an empty collection
3253 if( !defined( $this ) )
3254 {
3255 return( $collection );
3256 }
3257 elsif( !ref( $this ) || ( $self->_is_object( $this ) && overload::Overloaded( $this ) && overload::Method( '""' ) ) )
3258 {
3259 my $xpath = $self->_xpath_value( "$this" );
3260 my $doc = $self->filter(sub
3261 {
3262 my $elem = shift( @_ );
3263 # try-catch
3264 my $rv = eval
3265 {
3266 return( !$elem->matches( $xpath ) );
3267 };
3268 if( $@ )
3269 {
3270 return( $self->error( "Caught an exception while calling matches with xpath '$xpath' for element of class ", ref( $elem ), " and tag '", $elem->tag, "': $@" ) );
3271 }
3272 return( $rv );
3273 });
3274 $collection->children( $doc->children );
3275 }
3276 elsif( $self->_is_array( $this ) )
3277 {
3278 $this = $self->new_array( $this );
3279 #my $new = $self->children->clone->remove( $this );
3280 #$collection->children( $new );
3281 $this->unique(1);
3282 my $new = $process->( $self->children, $this );
3283 $collection->children( $new );
3284 }
3285 elsif( $self->_is_object( $this ) && $self->isa_collection( $this ) )
3286 {
3287 my $kids = $this->children;
3288 my $new = $process->( $self->children, $kids );
3289 $collection->children( $new );
3290 }
3291 elsif( $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
3292 {
3293 $this = $self->new_array( [ $this ] );
3294 my $new = $process->( $self->children, $this );
3295 $collection->children( $new );
3296 }
3297 else
3298 {
3299 return( $self->error( "I receive an object \"", ref( $this ), "\", but I do not know what to do with it." ) );
3300 }
3301 return( $collection );
3302 }
3303  
3304 # Returns a new collection of elements whose position is an even number
3305 sub odd
3306 {
3307 my $self = shift( @_ );
3308 return( $self ) unless( $self->isa_collection );
3309 my $odd = $self->children->odd;
3310 my $collection = $self->new_collection;
3311 $collection->children( $odd );
3312 return( $collection );
3313 }
3314  
3315 # Takes html string (start with <tag...), text object (HTML::Object::DOM::Text), array or element object
3316 # or alternatively a code reference that returns the above
3317 sub prepend { return( shift->_append_prepend( @_, { action => 'prepend' } ) ); }
3318  
3319 sub prependTo { return( shift->_append_prepend_to( @_, { action => 'prepend' } ) ); }
3320  
3321 # TODO: prop(), e.g. $e->prop('outerHTML') or $e->prop('tagName')
3322 sub prop
3323 {
3324 my $self = shift( @_ );
3325 # In get mode, this only affects the first element of the set
3326 # In set mode, this affect all elements of the set
3327 # <https://api.jquery.com/prop/#prop-propertyName>
3328 # <https://developer.mozilla.org/en-US/docs/Web/API/Element#properties>
3329 my $map =
3330 {
3331 checked => sub{ return( shift->attr( 'checked' ) ); },
3332 # Returns the number of child elements of this element.
3333 childElementCount => sub{ return( shift->children->length ); },
3334 # Returns the child elements of this element.
3335 children => sub{ return( shift->children ); },
3336 # Is a DOMString representing the class of the element.
3337 className => sub{ return( shift->attr( 'class' ) ); },
3338 disabled => sub{ return( shift->attr( 'disabled' ) ); },
3339 # Returns the first child element of this element.
3340 firstElementChild => sub{ return( shift->children->first ); },
3341 # Is a DOMString representing the id of the element.
3342 id => sub{ return( shift->attr( 'id' ) ); },
3343 # Is a DOMString representing the markup of the element's content.
3344 innerHTML => sub
3345 {
3346 my $e = shift( @_ );
3347 my $a = $self->new_array;
3348 $self->children->foreach(sub
3349 {
3350 my $e = shift( @_ );
3351 my $v = $e->as_string;
3352 $a->push( defined( $v ) ? $v->scalar : $v );
3353 });
3354 return( $a->join( '' ) );
3355 },
3356 # Returns the last child element of this element.
3357 lastElementChild => sub{ return( shift->children->last ); },
3358 # A DOMString representing the local part of the qualified name of the element.
3359 localName => sub{ return( shift->tag ); },
3360 # Is an Element, the element immediately following the given one in the tree, or null if there's no sibling node.
3361 nextElementSibling => sub
3362 {
3363 my $e = shift( @_ );
3364 my $parent = $e->parent || return;
3365 my $pos = $parent->children->pos( $e );
3366 return( $parent->children->index( $pos + 1 ) );
3367 },
3368 # Is a DOMString representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
3369 outerHTML => sub{ return( shift->as_string ); },
3370 # Is a Element, the element immediately preceding the given one in the tree, or null if there is no sibling element.
3371 previousElementSibling => sub
3372 {
3373 my $e = shift( @_ );
3374 my $parent = $e->parent || return;
3375 my $pos = $parent->children->pos( $e );
3376 return( $parent->children->index( $pos - 1 ) );
3377 },
3378 readonly => sub{ return( shift->attr( 'readonly' ) ); },
3379 # Returns a String with the name of the tag for the given element.
3380 tagName => sub{ return( shift->tag ); },
3381 };
3382 my $ro = $self->new_array( [qw(
3383 childelementcount children firstelementchild
3384 )] );
3385  
3386 # Get
3387 if( scalar( @_ ) == 1 )
3388 {
3389 my $e = $self->isa_collection ? $self->children->first : $self;
3390 return if( !$e );
3391 my $prop = lc( shift( @_ ) );
3392 return( $self->error( "No such property \"$prop\"." ) ) if( !CORE::exists( $map->{ $prop } ) );
3393 my $code = $map->{ $prop };
3394 return( $code->( $e ) );
3395 }
3396 # Set
3397 elsif( scalar( @_ ) > 1 )
3398 {
3399 my $all = $self->new_array( $self->isa_collection ? $self->children : [ $self ] );
3400 my @props = @_;
3401 while( scalar( @props ) )
3402 {
3403 my( $prop, $val ) = CORE::splice( @props, 0, 2 );
3404 $prop = lc( $prop );
3405 if( defined( $val ) && CORE::length( $val ) && $ro->exists( $prop ) )
3406 {
3407 next;
3408 }
3409  
3410 # process the html
3411 if( $prop eq 'innerHTML' )
3412 {
3413 if( defined( $val ) )
3414 {
3415 my $p = HTML::Object::DOM->new;
3416 my $doc = $p->parse_data( $val ) || do
3417 {
3418 $! = $p->error;
3419 return;
3420 };
3421 $all->foreach(sub
3422 {
3423 my $e = shift( @_ );
3424 $e->children( $doc->children );
3425 $e->reset(1);
3426 });
3427 }
3428 else
3429 {
3430 $all->foreach(sub
3431 {
3432 my $e = shift( @_ );
3433 $e->children->empty;
3434 $e->reset(1);
3435 });
3436 }
3437 next;
3438 }
3439 elsif( $prop eq 'outerHTML' )
3440 {
3441 if( defined( $val ) )
3442 {
3443 my $p = HTML::Object::DOM->new;
3444 my $doc = $p->parse_data( $val ) || do
3445 {
3446 $! = $p->error;
3447 return;
3448 };
3449 $all->foreach(sub
3450 {
3451 my $e = shift( @_ );
3452 my $parent = $e->parent;
3453 return(1) if( !$parent );
3454 my $pos = $parent->children->pos( $e );
3455 my @new = ();
3456 $doc->children->foreach(sub
3457 {
3458 my $kid = shift( @_ );
3459 my $clone = $kid->clone;
3460 $clone->parent( $parent );
3461 push( @new, $clone );
3462 });
3463 $parent->children->splice( $pos, 1, @new );
3464 $parent->reset(1);
3465 });
3466 }
3467 else
3468 {
3469 $all->foreach(sub
3470 {
3471 my $e = shift( @_ );
3472 my $parent = $e->parent;
3473 return(1) if( !$parent );
3474 my $pos = $parent->children->pos( $e );
3475 $e->children->splice( $pos, 1 );
3476 $e->reset(1);
3477 });
3478 }
3479 next;
3480 }
3481  
3482 $all->foreach(sub
3483 {
3484 my $e = shift( @_ );
3485 if( $prop eq 'checked' )
3486 {
3487 if( $val )
3488 {
3489 $e->attr( checked => 'checked' );
3490 }
3491 else
3492 {
3493 $e->attributes->delete( $prop );
3494 }
3495 $e->reset(1);
3496 }
3497 elsif( $prop eq 'className' )
3498 {
3499 if( defined( $val ) )
3500 {
3501 $e->attr( class => $val );
3502 }
3503 else
3504 {
3505 $e->attributes->delete( 'class' );
3506 }
3507 $e->reset(1);
3508 }
3509 elsif( $prop eq 'disabled' )
3510 {
3511 if( $val )
3512 {
3513 $e->attr( disabled => 'disabled' );
3514 }
3515 else
3516 {
3517 $e->attributes->delete( $prop );
3518 }
3519 $e->reset(1);
3520 }
3521 elsif( $prop eq 'id' )
3522 {
3523 if( defined( $val ) )
3524 {
3525 $e->attr( id => $val );
3526 }
3527 else
3528 {
3529 $e->attributes->delete( $prop );
3530 }
3531 $e->reset(1);
3532 }
3533 elsif( $prop eq 'readonly' )
3534 {
3535 if( $val )
3536 {
3537 $e->attr( readonly => 'readonly' );
3538 }
3539 else
3540 {
3541 $e->attributes->delete( $prop );
3542 }
3543 $e->reset(1);
3544 }
3545 });
3546 }
3547 }
3548 }
3549  
3550 sub promise
3551 {
3552 my $self = shift( @_ );
3553 return( Promise::Me->new( @_ ) );
3554 # my $deferred = Promise::XS::deferred();
3555 # return( $deferred->promise() );
3556 }
3557  
3558 # NOTE: queue is not implemented
3559 # <https://api.jquery.com/queue/>
3560  
3561 sub rank { return( shift->_set_get_number_as_object( 'rank', @_ ) ); }
3562  
3563 # <https://api.jquery.com/remove/>
3564 # TODO: Need to check again and do some test to ensure this api is compliant
3565 sub remove
3566 {
3567 my $self = shift( @_ );
3568 if( $self->isa_collection )
3569 {
3570 $self->children->foreach(sub
3571 {
3572 my $e = shift( @_ );
3573 my $pos = $e->pos;
3574 my $parent = $e->parent;
3575 $e->delete;
3576 });
3577 }
3578 # xpath provided
3579 elsif( @_ )
3580 {
3581 my $xpath = $self->_xpath_value( shift( @_ ) ) || return;
3582 $self->find( $xpath )->remove;
3583 }
3584 # Equivalent to delete
3585 else
3586 {
3587 $self->delete;
3588 }
3589 return( $self );
3590 }
3591  
3592 sub removeAttr
3593 {
3594 my $self = shift( @_ );
3595 my $attr = shift( @_ );
3596 return( $self ) if( !defined( $attr ) );
3597 if( $self->isa_collection )
3598 {
3599 $self->children->foreach(sub
3600 {
3601 $_->attributes->delete( $attr );
3602 $_->reset(1);
3603 });
3604 }
3605 else
3606 {
3607 $self->attributes->delete( $attr );
3608 $self->reset(1);
3609 }
3610 return( $self );
3611 }
3612  
3613 # class name, array of class name or a code reference
3614 # If parameter is a code reference it must return a class name or an array of class name
3615 # It receives "the index position of the element in the set and the old class value as arguments"
3616 sub removeClass
3617 {
3618 my $self = shift( @_ );
3619 my $this;
3620 $this = shift( @_ ) if( @_ );
3621 my $a;
3622 if( $self->_is_array( $this ) )
3623 {
3624 $a = $self->new_array( $this );
3625 my $failed = 0;
3626 $a->foreach(sub
3627 {
3628 if( ref( $_ ) && !( overload::Overloaded( $_ ) && overload::Method( $_, '""' ) ) )
3629 {
3630 $failed++;
3631 $self->error( "Class provided to be removed \"$_\" is not a string nor an overloaded object." );
3632 return(0);
3633 }
3634 });
3635 return( $self ) if( $failed );
3636 }
3637 elsif( defined( $this ) )
3638 {
3639 $a = $self->new_array( "$this" );
3640 }
3641  
3642 # No class provided, so we will remove all existing class
3643 if( !defined( $a ) )
3644 {
3645 $a = $self->new_array;
3646 }
3647  
3648 my $process;
3649 $process = sub
3650 {
3651 my $e = shift( @_ );
3652 return( $e ) unless( $e->attributes->exists( 'class' ) );
3653 my $c = $self->new_array( [split( /[[:blank:]\h]+/, $e->attributes->get( 'class' ) )] );
3654 my $new = $self->new_array;
3655 # Loop through the element classes
3656 $c->for(sub
3657 {
3658 my( $i, $v ) = @_;
3659 if( ref( $this ) CORE::eq 'CODE' )
3660 {
3661 local $_ = $self;
3662 my $res = $this->( $i, $v );
3663 if( $self->_is_array( $res ) )
3664 {
3665 $a = $self->new_array( $res );
3666 }
3667 else
3668 {
3669 $a = $self->new_array( [ $res ] );
3670 }
3671 }
3672 my $need_to_remove = 0;
3673 $a->foreach(sub
3674 {
3675 my $to_remove = shift( @_ );
3676 if( $v CORE::eq "$to_remove" )
3677 {
3678 $need_to_remove++;
3679 return(1);
3680 }
3681 });
3682 if( !$need_to_remove )
3683 {
3684 $new->push( $v );
3685 }
3686 });
3687 if( $c->length )
3688 {
3689 if( !$e->setAttribute( class => $new->join( ' ' )->scalar ) )
3690 {
3691 warn( "Error trying to set the class attribute for element '", $self->_str_val( $e ), "': ", $e->error ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
3692 }
3693 }
3694 else
3695 {
3696 if( !$e->removeAttribute( 'class' ) )
3697 {
3698 warn( "Error trying to remove the class attribute from element '", $self->_str_val( $e ), "': ", $e->error ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
3699 }
3700 }
3701 $e->reset(1);
3702 return(1);
3703 };
3704 if( $self->isa_collection )
3705 {
3706 $self->children->foreach( $process );
3707 }
3708 else
3709 {
3710 $process->( $self );
3711 }
3712 return( $self );
3713 }
3714  
3715 sub removeData
3716 {
3717 my $self = shift( @_ );
3718 my $elem;
3719 if( $self->isa_collection )
3720 {
3721 $elem = $self->children->first;
3722 }
3723 elsif( !$self->_is_a( $self => 'HTML::Object::DOM::Element' ) )
3724 {
3725 return( $self->error( "You can only call the removeData() method on html elements." ) );
3726 }
3727 else
3728 {
3729 $elem = $self;
3730 }
3731  
3732 my $keys;
3733 # If no @_ is provided this is undef and it is ok, we would remove all data attributes then
3734 if( @_ )
3735 {
3736 my $this = shift( @_ );
3737 if( $self->_is_empty( $this ) )
3738 {
3739 return( $self->error( "Data name value provided is empty. If you want to remove all data attributes, simply call removeData() without argument." ) );
3740 }
3741 elsif( !ref( $this ) ||
3742 ( ref( $this ) && $self->_can_overload( $this => '""' ) ) )
3743 {
3744 $this = "$this";
3745 if( CORE::index( $this, ' ' ) != -1 )
3746 {
3747 $keys = [CORE::split( /[[:blank:]\h]+/, $this )];
3748 }
3749 else
3750 {
3751 $keys = [$this];
3752 }
3753 }
3754 elsif( $self->_is_array( $this ) )
3755 {
3756 $keys = $this;
3757 }
3758 else
3759 {
3760 return( $self->error( "Data name value to remove is unsupported. You can only provide a string, a space-separated string of names, or an array reference." ) );
3761 }
3762 }
3763 else
3764 {
3765 $keys = $elem->attributes_sequence;
3766 }
3767  
3768 my $changed = 0;
3769 foreach my $k ( @$keys )
3770 {
3771 if( $elem->hasAttribute( 'data-' . $k ) )
3772 {
3773 $elem->removeAttribute( 'data-' . $k );
3774 $changed++;
3775 }
3776 }
3777 $elem->reset(1) if( $changed );
3778 # Return undef
3779 return;
3780 }
3781  
3782 # Takes html string, array of elements, an element (including a collection object) or a code reference
3783 sub replaceWith
3784 {
3785 my $self = shift( @_ );
3786 my $this = shift( @_ ) || return( $self->error( "Nothing was provided to replace." ) );
3787 my $a;
3788 if( !ref( $this ) )
3789 {
3790 my $p = $self->new_parser;
3791 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
3792 $a = $self->new_array( [ $this ] );
3793 }
3794 elsif( $self->_is_array( $this ) )
3795 {
3796 # Make sure this is a Module::Generic::Array object
3797 $a = $self->new_array( $this );
3798 }
3799 elsif( $self->_is_object( $this ) )
3800 {
3801 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
3802 $a = $self->new_array( [ $this ] );
3803 }
3804 elsif( ref( $this ) ne 'CODE' )
3805 {
3806 return( $self->error( "I do not know what to do with '$this'. I was expecing an html string, or an HTML::Object::DOM::Element or an array of element objects or a collection object (HTML::Object::Collection) or a code reference." ) );
3807 }
3808  
3809 if( $self->isa_collection )
3810 {
3811 my $failed = 0;
3812 $self->children->foreach(sub
3813 {
3814 my $elem = shift( @_ );
3815 if( ref( $this ) CORE::eq 'CODE' )
3816 {
3817 local $_ = $elem;
3818 my $res = $this->( $elem );
3819 if( !defined( $res ) )
3820 {
3821 $failed++;
3822 $self->error( "An error occurred while executing code reference to replace html element(s). Code reference returned undef." );
3823 return(0);
3824 }
3825 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
3826 {
3827 $a = $self->new_array( [ $res ] );
3828 }
3829 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
3830 {
3831 my $elem = $self->new_parser( "$res" );
3832 if( !defined( $elem ) )
3833 {
3834 $failed++;
3835 return(0);
3836 }
3837 $a = $self->new_array( [ $elem ] );
3838 }
3839 else
3840 {
3841 $failed++;
3842 $self->error( "Value returned from code reference to be used in replaceWith is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." );
3843 return(0);
3844 }
3845 }
3846 if( !$elem->parent )
3847 {
3848 $self->error( "Found an element within a collection that has no parent! Element has tag \"", $elem->tag, "\"." );
3849 return(0);
3850 }
3851 my $pos = $elem->parent->pos( $elem );
3852 if( !defined( $pos ) )
3853 {
3854 $self->error( "This element with tag \"", $self->tag, "\" has a parent and yet I could not find its position." );
3855 return(0);
3856 }
3857 my $new = $self->new_array;
3858 $a->foreach(sub
3859 {
3860 my $e = $_->detach->clone();
3861 $e->parent( $elem->parent );
3862 $new->push( $e );
3863 });
3864 $elem->parent->children->splice( $pos, 1, $a->list );
3865 $elem->parent->reset(1);
3866 });
3867 # Now that the element have been copied to their replacement location, we remove them
3868 $a->foreach(sub
3869 {
3870 $_->delete;
3871 });
3872 return if( $failed );
3873 }
3874 else
3875 {
3876 if( ref( $this ) CORE::eq 'CODE' )
3877 {
3878 local $_ = $self;
3879 my $res = $this->( $self );
3880 return( $self->error( "An error occurred while executing code reference to replace html element(s). Code reference returned undef." ) ) if( !defined( $res ) );
3881 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
3882 {
3883 $a = $self->new_array( [ $res ] );
3884 }
3885 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
3886 {
3887 my $elem = $self->new_parser( "$res" );
3888 return if( !defined( $elem ) );
3889 $a = $self->new_array( [ $elem ] );
3890 }
3891 else
3892 {
3893 return( $self->error( "Value returned from code reference to be used in replaceWith is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." ) );
3894 }
3895 }
3896  
3897 # Object has no parent, so we are essentially replace 1 element for one or more others with no attachment to the dom
3898 if( !$self->parent )
3899 {
3900 # Basically swapping one element for another
3901 if( $a->length == 1 )
3902 {
3903 my $e = $a->first;
3904 $e->detach;
3905 return( $e );
3906 }
3907 # There are multiple element, create a document element
3908 else
3909 {
3910 my $doc = HTML::Object::DOM::Document->new;
3911 $doc->children( $a );
3912 $a->foreach(sub
3913 {
3914 $_->detach;
3915 $_->parent( $doc );
3916 $_->parent->reset(1);
3917 });
3918 return( $doc );
3919 }
3920 }
3921 else
3922 {
3923 my $pos = $self->parent->pos( $self );
3924 return( $self->error( "This element with tag \"", $self->tag, "\" has a parent and yet I could not find its position." ) ) if( !defined( $pos ) );
3925 $a->foreach(sub
3926 {
3927 $_->detach->parent( $self->parent );
3928 });
3929 $self->parent->children->splice( $pos, 1, $a->list );
3930 $self->parent->reset(1);
3931 }
3932 }
3933 return( $self );
3934 }
3935  
3936 sub set_namespace
3937 {
3938 my $self = shift( @_ );
3939 return( $self->xp->new->set_namespace( @_ ) );
3940 }
3941  
3942 # Since this is a perl context, this only set the inline css 1) back to its previous value,
3943 # if any; or 2) remove the display property if there was no previous value set.
3944 # Any parameter provided will be ignored
3945 # See the hide() method for its alter ego.
3946 sub show
3947 {
3948 my $self = shift( @_ );
3949 my( $this, $code ) = @_;
3950 $code = $this if( ref( $this ) eq 'CODE' && !defined( $code ) );
3951 my $process;
3952 $process = sub
3953 {
3954 my $e = shift( @_ );
3955 my $internal = $e->internal;
3956 my $rule = $self->_css_object();
3957 if( defined( $rule ) )
3958 {
3959 my $display = $rule->get_property_by_name( 'display' );
3960 my $val = $display->value;
3961 # if display current value is 'none', we check if there was a previous value we kept
3962 # and if there is we restore it, otherwise we simply just remove the property
3963 if( $val eq 'none' )
3964 {
3965 my $previous_val = $internal->{css_display_value};
3966 if( defined( $previous_val ) && CORE::length( $previous_val ) )
3967 {
3968 $display->value( $previous_val );
3969 }
3970 else
3971 {
3972 $display->remove_from( $rule );
3973 }
3974 }
3975 }
3976 # otherwise, there is no rule inline defined, and thus, nothing to do.
3977  
3978 # Is there any rule and properties to save back?
3979 if( defined( $rule ) && $rule->elements->length > 0 )
3980 {
3981 $e->_css_object( $rule );
3982 }
3983 };
3984  
3985 if( $self->isa_collection )
3986 {
3987 $self->children->foreach(sub
3988 {
3989 $process->( $_ );
3990 $_->reset(1);
3991 });
3992 }
3993 elsif( $self->tag->substr( 0, 1 ) eq '_' )
3994 {
3995 return( $self->error( "You can only use the hide() or show() method on html object elements. The element you are calling hide() with is an object of class \"", ref( $self ), "\"." ) );
3996 }
3997 else
3998 {
3999 $process->( $self );
4000 $self->reset(1);
4001 }
4002 }
4003  
4004 # This is here and although it has been deprecated, so that $.uniqueSort() works
4005 # <https://stackoverflow.com/questions/63575333/javascript-replacement-of-sourceindex-in-chromium-browsers>
4006 # <https://developer.mozilla.org/en-US/docs/Web/API/Document/all>
4007 sub sourceIndex : lvalue { return( shift->_set_get_lvalue( 'sourceIndex', @_ ) ); }
4008  
4009 sub string_value
4010 {
4011 my $self = shift( @_ );
4012 return( $self->value ) if( $self->isCommentNode );
4013 return( $self->as_text );
4014 }
4015  
4016 # This is normally a HTML::Object::DOM::Element property and it should not be used equally
4017 # by a collection object, because of its nature, so we created it here to catch calls to it
4018 # while still allowing HTML::Object::DOM::Element to use it normally
4019 sub tag
4020 {
4021 my $self = shift( @_ );
4022 if( @_ )
4023 {
4024 if( $self->isa_collection )
4025 {
4026 return( $self->error( "tag is a read-only property" ) );
4027 }
4028 else
4029 {
4030 return( $self->_set_get_scalar_as_object( 'tag', @_ ) );
4031 }
4032 }
4033 else
4034 {
4035 if( $self->isa_collection )
4036 {
4037 my $first = $self->children->first;
4038 return unless( $first && $self->_is_a( $first, 'HTML::Object::DOM::Element' ) );
4039 return( $first->_set_get_scalar_as_object( 'tag' ) );
4040 }
4041 else
4042 {
4043 return( $self->_set_get_scalar_as_object( 'tag' ) );
4044 }
4045 }
4046 }
4047  
4048 sub tagname
4049 {
4050 my $self = shift( @_ );
4051 my @args = @_;
4052 my $map =
4053 {
4054 Comment => '#comment',
4055 Text => '#text'
4056 };
4057 my $a = $self->new_array;
4058 $self->children->foreach(sub
4059 {
4060 my $e = shift( @_ );
4061 my $type = [split( /::/, ref( $e ) )]->[-1];
4062 $a->push( exists( $map->{ $type } ) ? $map->{ $type } : $e->tag( @args ) );
4063 });
4064 return( $a );
4065 }
4066  
4067 # This method work for absolutely any element, including the root element (html)
4068 sub text
4069 {
4070 my $self = shift( @_ );
4071 my $this = shift( @_ );
4072 # Mutator
4073 if( defined( $this ) )
4074 {
4075 if( !ref( $this ) ||
4076 ( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) )
4077 {
4078 $this = "$this";
4079 }
4080 elsif( ref( $this ) ne 'CODE' )
4081 {
4082 return( $self->error( "I was expecting some text data or a code reference in replacement of text for this element \"", $self->tag, "\", but instead got '$this'." ) );
4083 }
4084  
4085 my $is_code = ref( $this ) eq 'CODE' ? 1 : 0;
4086 my $process = sub
4087 {
4088 my( $e, $i ) = @_;
4089 if( $is_code )
4090 {
4091 my $current_text = $e->as_text( unescape => 1 );
4092 my $text = $this->( $i, $current_text );
4093 if( !defined( $text ) || !CORE::length( $text ) )
4094 {
4095 $e->empty();
4096 # Next please
4097 return(1);
4098 }
4099 elsif( ref( $text ) &&
4100 !( overload::Overloaded( $text ) && overload::Method( $text, '""' ) ) )
4101 {
4102 warn( "I was provided a reference '$text' as a result from calling this code reference to get the replacement text for tag \"", $e->tag, "\", but I do not know what to do with it.\n" );
4103 return(1);
4104 }
4105 $text = "$text";
4106 $text =~ s/</\&lt;/gs;
4107 $text =~ s/>/\&gt;/gs;
4108 $text =~ s,\n,<br />\n,gs;
4109 if( $self->isa( 'HTML::Object::DOM::Comment' ) ||
4110 $self->isa( 'HTML::Object::DOM::Text' ) )
4111 {
4112 $self->value( $text );
4113 }
4114 else
4115 {
4116 my $new = $self->new_text( value => $text, parent => $self );
4117 # If this is an empty tag, such as <input /> or <img />, the text cannot be added to it.
4118 # jQuery actually accepts the text and attach it to the element as a child, but the web browser does not show it, because it is an empty element.
4119 # Since this is not a web browser interface, we need to silently ignore it, so it does not end up in the DOM and turn an empty tag into a tag with children and a closing tag, which would be an heresy.
4120 if( !$e->is_empty )
4121 {
4122 $e->children->set( $new );
4123 }
4124 }
4125 }
4126 else
4127 {
4128 my $new = $self->new_text( value => $this, parent => $e );
4129 # See comment just above
4130 if( !$e->is_empty )
4131 {
4132 $e->children->set( $new );
4133 }
4134 }
4135 };
4136  
4137 if( $self->isa_collection )
4138 {
4139 $self->children->for(sub
4140 {
4141 my( $i, $e ) = @_;
4142 $process->( $e, $i );
4143 $e->reset(1);
4144 # Return true at the end to satisfy Module::Generic::Array->for
4145 return(1);
4146 });
4147 }
4148 else
4149 {
4150 $process->( $self, 0 );
4151 $self->reset(1);
4152 }
4153 }
4154 # Accessor
4155 else
4156 {
4157 return( $self->as_text( unescape => 1 ) );
4158 }
4159 }
4160  
4161 # Takes a class name; or
4162 # class name and state (true or false); or
4163 # array of class names; or
4164 # array of class names and a state; or
4165 # a code reference called with the index position of the current class and its name. Returns a space separated list of classes or an array
4166 # <https://api.jquery.com/toggleClass/>
4167 sub toggleClass
4168 {
4169 my $self = shift( @_ );
4170 my $this;
4171 $this = shift( @_ ) if( @_ );
4172 my $state;
4173 $state = scalar( @_ ) ? shift( @_ ) : 1;
4174 my $a = $self->new_array;
4175 my $has_code = 0;
4176 if( defined( $this ) )
4177 {
4178 if( $self->_is_array( $this ) )
4179 {
4180 $a = $self->new_array( $this );
4181 }
4182 elsif( ref( $this ) CORE::eq 'CODE' )
4183 {
4184 # ok
4185 $has_code++;
4186 }
4187 elsif( ref( $this ) && overload::Overloaded( $this ) && overload::Method( $this, '""' ) )
4188 {
4189 $a = $self->new_array( [split( /[[:blank:]\h]+/, "$this" )] );
4190 }
4191 else
4192 {
4193 return( $self->error( "I was expecting an array reference of classes, or class string or a code reference, but instead I got '$this', and I do not know what to do with it." ) );
4194 }
4195 # Make sure the classes we are provided are unique
4196 $a->unique(1);
4197 }
4198  
4199 my $process;
4200 $process = sub
4201 {
4202 my( $i, $e ) = @_;
4203 my $ref = $e->internal->{class};
4204 $ref //= {};
4205 $ref->{toggle_status} //= 0;
4206 my $classes;
4207 if( $e->attributes->exists( 'class' ) )
4208 {
4209 $classes = $self->new_array( [split( /[[:blank:]\h]+/, $e->attributes->get( 'class' ) )] );
4210 $ref->{original_classes} //= $classes;
4211 }
4212 # No class on this element yet
4213  
4214 if( $has_code )
4215 {
4216 local $_ = $e;
4217 my $res = $this->( $i, $classes, $ref->{toggle_status} );
4218 if( $self->_is_array( $res ) )
4219 {
4220 $a = $self->new_array( $res );
4221 }
4222 elsif( !ref( $res ) || ( overload::Overloaded( $res ) && overload::Method( $res, '""' ) ) )
4223 {
4224 $a = $self->new_array( [ split( /[[:blank:]\h]+/, "$res" ) ] );
4225 }
4226 else
4227 {
4228 warn( "Code reference for class of element with tag \"", $e->tag, "\" returned '$this', but I do not know what to do with it.\n" );
4229 return( 1 );
4230 }
4231 $a->unique(1);
4232 }
4233  
4234 # No class set yet on this element
4235 if( !defined( $classes ) )
4236 {
4237 # and we have no class either, so we skip to the next element. Nothing to do here
4238 if( !$a->length )
4239 {
4240 return(1);
4241 }
4242 # we activate our classes
4243 else
4244 {
4245 $ref->{toggle_status} = 1;
4246 $e->attributes->set( class => $a->join( ' ' ) );
4247 $e->reset(1);
4248 }
4249 }
4250 else
4251 {
4252 # we found existing class, and we toggled without specifying any
4253 # which mean we switch them all on/off
4254 if( !$a->length )
4255 {
4256 $e->attributes->set( class => ( $ref->{toggle_status} ? $ref->{original_classes} : '' ) );
4257 }
4258 # Specific were provided. We toggle them on/off
4259 else
4260 {
4261 if( $ref->{toggle_status} )
4262 {
4263 $classes->remove( $a );
4264 }
4265 else
4266 {
4267 $classes->push( $a->list )->unique;
4268 }
4269 $e->attributes->set( class => $classes->join( ' ' ) );
4270 $e->reset(1);
4271 $ref->{toggle_status} = !$ref->{toggle_status};
4272 }
4273 }
4274 };
4275  
4276 if( $self->isa_collection )
4277 {
4278 $self->children->for( $process );
4279 }
4280 else
4281 {
4282 $process->( 0, $self );
4283 }
4284 }
4285  
4286 sub to_number { return( HTML::Object::DOM::Number->new( shift->getValue ) ); }
4287  
4288 sub toString { return( shift->as_xml( @_ ) ); }
4289  
4290 sub uniqueSort
4291 {
4292 my $self = shift( @_ );
4293 my $collection = $self->new_collection;
4294 if( $self->isa_collection )
4295 {
4296 my $elems = xQuery->uniqueSort( $self->children ) ||
4297 return( $self->pass_error( xQuery->error ) );
4298 $collection->children->push( $elems->list );
4299 }
4300 else
4301 {
4302 $collection->children->push( $self );
4303 }
4304 return( $collection );
4305 }
4306  
4307 sub wrap
4308 {
4309 my $self = shift( @_ );
4310 my @args = @_;
4311 my( $this, $more ) = @args;
4312 return( $self->error( "Nothing was provided to wrap elements." ) ) if( !$this );
4313 my( $wrapper, $elems, $is_code );
4314 # "When you pass a collection object containing more than one element, or a selector matching more than one element, the first element will be used."
4315 if( $self->_is_a( $this => 'HTML::Object::Collection' ) )
4316 {
4317 return( $self->error( "Collection provided as wrapper is actually empty!" ) ) if( $this->children->is_empty );
4318 $wrapper = $this->children->first;
4319 return( $self->error( "The first element of the collection provided did not yield an element object." ) ) if( !$self->_is_a( $wrapper => 'HTML::Object::DOM::Element' ) );
4320 }
4321 elsif( $self->_is_a( $this => 'HTML::Object::DOM::Element' ) )
4322 {
4323 $wrapper = $this;
4324 }
4325 elsif( $self->_is_code( $this ) )
4326 {
4327 $is_code = 1;
4328 $wrapper = $this;
4329 }
4330 # selector, html to parse
4331 else
4332 {
4333 my $tmp = xq( @args ) || return( $self->pass_error );
4334 return( $self->error( "Selector or HTML provided as wrapper did not yield any wrapping element." ) ) if( $tmp->children->is_empty );
4335 $wrapper = $tmp->children->first ||
4336 return( $self->error( "Collection returned from selector or HTML provided is empty." ) );
4337 return( $self->error( "Collection returned from selector or HTML provided did not yield an element object." ) ) if( !$self->_is_a( $wrapper => 'HTML::Object::DOM::Element' ) );
4338 }
4339  
4340 if( $self->isa_collection )
4341 {
4342 $elems = $self->children;
4343 }
4344 else
4345 {
4346 $elems = $self->new_array( $self );
4347 }
4348  
4349 my $find_nested;
4350 $find_nested = sub
4351 {
4352 my( $el, $kids ) = @_;
4353 my $n = $kids->length;
4354 if( !$n )
4355 {
4356 return( $el );
4357 }
4358 elsif( $n == 1 )
4359 {
4360 return( $find_nested->( $kids->[0] => $kids->[0]->children ) );
4361 }
4362 else
4363 {
4364 return( '' );
4365 }
4366 };
4367  
4368 local $@;
4369 for( my $i = 0; $i < scalar( @$elems ); $i++ )
4370 {
4371 my $e = $elems->[$i];
4372 my $parent = $e->parent;
4373 my $pos = $parent->children->pos( $e );
4374 return( $self->error( "Unable to find element No $i position in its parent." ) ) if( !defined( $pos ) );
4375 my $wrap;
4376 if( $is_code )
4377 {
4378 # try-catch
4379 my $rv = eval
4380 {
4381 local $_ = $e;
4382 $wrapper->( $i );
4383 };
4384 if( $@ )
4385 {
4386 return( $self->error( "An error occurred executing the wrapper callback code reference for element at offset $i: $@" ) );
4387 }
4388 my $thingy;
4389 if( $self->_is_a( $rv => 'HTML::Object::Collection' ) )
4390 {
4391 return( $self->error( "Collection provided as wrapper is actually empty!" ) ) if( $rv->children->is_empty );
4392 $thingy = $rv->children->first;
4393 return( $self->error( "The first element of the collection provided did not yield an element object." ) ) if( !$self->_is_a( $thingy => 'HTML::Object::DOM::Element' ) );
4394 }
4395 elsif( $self->_is_a( $rv => 'HTML::Object::DOM::Element' ) )
4396 {
4397 $thingy = $rv;
4398 }
4399 # selector, html to parse
4400 else
4401 {
4402 my $tmp = xq( $rv, ( defined( $more ) ? $more : () ) ) || return( $self->pass_error );
4403 return( $self->error( "Selector or HTML returned from callback as wrapper did not yield any wrapping element." ) ) if( $tmp->children->is_empty );
4404 $thingy = $tmp->children->first ||
4405 return( $self->error( "Collection returned from selector or HTML provided is empty." ) );
4406 return( $self->error( "Collection returned from selector or HTML provided did not yield an element object." ) ) if( !$self->_is_a( $thingy => 'HTML::Object::DOM::Element' ) );
4407 }
4408 $wrap = $thingy->clone;
4409 }
4410 else
4411 {
4412 $wrap = $wrapper->clone;
4413 }
4414 my $nested = $find_nested->( $wrap => $wrap->children );
4415 # $e->detach;
4416 $wrap->parent( $parent );
4417 $parent->children->splice( $pos, 1, $wrap );
4418 $nested->children->set( $e );
4419 $e->parent( $nested );
4420 }
4421 return( $self );
4422 }
4423  
4424 sub xp
4425 {
4426 my $self = shift( @_ );
4427 unless( $XP )
4428 {
4429 $XP = HTML::Object::XPath->new;
4430 }
4431 # $XP->debug( $self->debug );
4432 return( $XP );
4433 }
4434  
4435 # Ref: <https://api.jquery.com/Types/#jQuery>
4436 # xq( '#myId', $document )
4437 # xq( '<div />', { id => 'Pouec', class => 'Hello' } );
4438 # xq( '<html><head><title>Hello world</title></head><body>Hello!</body></html>' );
4439 # xq();
4440 sub xq
4441 {
4442 my( @args ) = @_;
4443 # Check if this might be all some HTML::Object::DOM::Element objects passed to form a collection
4444 my $is_all_objects = 1;
4445 no warnings 'once';
4446 my $opts =
4447 {
4448 xq_debug => $HTML::Object::xQuery::DEBUG,
4449 };
4450 if( scalar( @args ) > 1 &&
4451 defined( $args[-1] ) &&
4452 ref( $args[-1] ) eq 'HASH' &&
4453 CORE::exists( $args[-1]->{xq_debug} ) )
4454 {
4455 $opts = CORE::pop( @args );
4456 }
4457 # A dummy accessor
4458 my $self = HTML::Object::DOM::Element->new( debug => $opts->{xq_debug} );
4459 # We check if xq was not called with a bunch of HTML::Object::DOM::Element objects, such as:
4460 # $(@elements) or maybe xq(@elements), which would return a new collection.
4461 for( my $i = 0; $i < scalar( @args ); $i++ )
4462 {
4463 unless( $self->_is_a( $args[$i] => 'HTML::Object::DOM::Element' ) )
4464 {
4465 $is_all_objects = 0;
4466 last;
4467 }
4468 }
4469 # Shortcut
4470 if( $is_all_objects )
4471 {
4472 my $collection = $self->new_collection( debug => $opts->{xq_debug} );
4473 $collection->children->set( @args );
4474 return( $collection );
4475 }
4476 my( $this, $more ) = @args;
4477 # e.g. $('<div />', { id => 'pouec', class => 'hello' });
4478 if( $this =~ /^$LOOK_LIKE_HTML/ )
4479 {
4480 my $p = HTML::Object::DOM->new;
4481 $this = "$this";
4482 # We trim the string, so that leading and trailing space do not get counted
4483 $this =~ s/^[[:blank:]\h\v]+|[[:blank:]\h\v]+$//gs;
4484 my $doc = $p->parse_data( $this ) || do
4485 {
4486 $! = $p->error;
4487 return;
4488 };
4489 # $doc is a HTML::Object::DOM::Document, which is not suitable, so we change it to a
4490 # collection object
4491 my $collection = $doc->new_collection;
4492 $collection->children( $doc->children );
4493 if( $doc->children->length == 1 )
4494 {
4495 my $e = $doc->children->first;
4496 # I do not use Module::Generic::_is_hash on purpose because I do not want to catch objects inadvertently
4497 # We found attributes, so we set them up now
4498 if( ref( $more ) CORE::eq 'HASH' )
4499 {
4500 my $debug = CORE::delete( $more->{_debug} ) if( CORE::exists( $more->{_debug} ) );
4501 $e->attributes->merge( $more );
4502 $e->debug( $debug );
4503 $collection->debug( $debug );
4504 }
4505 # We correct a situation where the user called for example $('<div />', { class => 'hello', id => 'pouec' });
4506 # And this would lead the parser to flag it to be empty, respecting the user decision,
4507 # but in this case, this is merely a short-hand notation to create a tag, and is not a
4508 # reflexion that this tag should indeed be treated as empty when it is not by standard
4509 # hus, we correct it here.
4510 if( $e->children->length == 0 && $e->is_empty )
4511 {
4512 my $def = $p->get_definition( $e->tag );
4513 $e->is_empty(0) if( !$def->{is_empty} );
4514 $e->close;
4515 }
4516 }
4517 return( $collection );
4518 }
4519 # Hmmm, I wanted to support $.parseXML and consequently allow $($xmlDoc), but our interface is really just tailored for HTML::Object::Element and not for XML::libXML, so all of the HTML::Object::XQuery methods would not work.
4520 # elsif( $self->_is_a( $this => 'XML::LibXML::Node' ) )
4521 # {
4522 # my $collection = $self->new_collection;
4523 # my @childnodes = $this->childNodes;
4524 # $collection->children->push( @childNodes );
4525 # return( $collection );
4526 # }
4527 elsif( ( !ref( $this ) || ( overload::Overloaded( $this ) && overload::Method( $this, '""' ) ) ) && CORE::index( "$this", "\n" ) == -1 )
4528 {
4529 # e.g. $('div')
4530 if( !defined( $more ) )
4531 {
4532 # e.g. $('body')
4533 if( defined( $HTML::Object::DOM::GLOBAL_DOM ) )
4534 {
4535 my $collection = $HTML::Object::DOM::GLOBAL_DOM->find( $this ) || return;
4536 $collection->debug( $self->debug );
4537 return( $collection );
4538 }
4539 else
4540 {
4541 warn( "No context was specified for '$this'. You need to provide some context to the selector by supplying an HTML::Object::DOM::Element object." ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
4542 return( HTML::Object::DOM->error( "You need to provide some context to the selector by supplying an HTML::Object::DOM::Element object." ) );
4543 }
4544 }
4545 # e.g., with context: $('div', $element);
4546 elsif( !ref( $more ) || ( ref( $more ) && !$more->isa( 'HTML::Object::DOM::Element' ) ) )
4547 {
4548 return( HTML::Object::DOM->error( "Context provided selector must be an element object. Got '", overload::StrVal( $more ), "'" ) );
4549 }
4550 my $collection = $more->find( $this ) || return( HTML::Object::DOM->pass_error( $more->error ) );
4551 $collection->debug( $more->debug );
4552 return( $collection );
4553 }
4554 else
4555 {
4556 return( HTML::Object::DOM->error( "I do not know what to do with '$this'." ) );
4557 }
4558 }
4559  
4560 sub _append_prepend
4561 {
4562 my $self = shift( @_ );
4563 my $this = shift( @_ ) || return( $self->error( "Nothing was provided to append or prepend." ) );
4564 my $opts = $self->_get_args_as_hash( @_ );
4565 if( !exists( $opts->{action} ) )
4566 {
4567 my @caller_info = caller(1);
4568 my $caller = [split( /::/, $caller_info[3])]->[-1];
4569 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(append|prepend)$/ );
4570 $opts->{action} = $caller;
4571 }
4572 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(append|prepend)$/ );
4573 my $a;
4574 if( !ref( $this ) )
4575 {
4576 my $p = $self->new_parser;
4577 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
4578 $a = $self->new_array( [ $this ] );
4579 }
4580 elsif( $self->_is_array( $this ) )
4581 {
4582 # Make sure this is a Module::Generic::Array object
4583 $a = $self->new_array( $this );
4584 }
4585 elsif( $self->_is_object( $this ) )
4586 {
4587 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
4588 $a = $self->new_array( [ $this ] );
4589 }
4590 elsif( ref( $this ) ne 'CODE' )
4591 {
4592 return( $self->error( "I do not know what to do with '$this'. I was expecing an html string, or an HTML::Object::DOM::Element or an array of element objects or a collection object (HTML::Object::Collection) or a code reference." ) );
4593 }
4594  
4595 if( $self->isa_collection )
4596 {
4597 my $failed = 0;
4598 # Going through each object in the collection
4599 $self->children->for(sub
4600 {
4601 my( $i, $e ) = @_;
4602 $e->reset(1);
4603 # will silently fail just like jQuery does
4604 my $parent = $e->parent;
4605 my $pos = $parent ? $parent->children->pos( $e ) : $i;
4606 if( ref( $this ) CORE::eq 'CODE' )
4607 {
4608 local $_ = $e;
4609 my $res = $this->( $pos, $e->as_string );
4610 if( !defined( $res ) )
4611 {
4612 $failed++;
4613 $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." );
4614 return(0);
4615 }
4616 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4617 {
4618 $a = $self->new_array( [ $res ] );
4619 }
4620 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4621 {
4622 my $elem = $self->new_parser( "$res" );
4623 if( !defined( $elem ) )
4624 {
4625 $failed++;
4626 return(0);
4627 }
4628 $a = $self->new_array( [ $elem ] );
4629 }
4630 else
4631 {
4632 $failed++;
4633 $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." );
4634 return(0);
4635 }
4636 }
4637 $a->foreach(sub
4638 {
4639 my $elem = $_->detach->clone;
4640 $elem->parent( $e );
4641 if( $opts->{action} CORE::eq 'append' )
4642 {
4643 $e->children->push( $elem );
4644 }
4645 elsif( $opts->{action} CORE::eq 'prepend' )
4646 {
4647 $e->children->unshift( $elem );
4648 }
4649 });
4650 });
4651 return if( $failed );
4652 }
4653 else
4654 {
4655 $self->reset(1);
4656 # will silently fail just like jQuery does
4657 my $parent = $self->parent;
4658 my $pos = $parent ? $parent->children->pos( $self ) : 0;
4659 if( ref( $this ) CORE::eq 'CODE' )
4660 {
4661 local $_ = $self;
4662 my $res = $this->( $pos, $self->as_string );
4663 return( $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." ) ) if( !defined( $res ) );
4664 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4665 {
4666 $a = $self->new_array( [ $res ] );
4667 }
4668 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4669 {
4670 my $elem = $self->new_parser( "$res" );
4671 return if( !defined( $elem ) );
4672 $a = $self->new_array( [ $elem ] );
4673 }
4674 else
4675 {
4676 return( $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." ) );
4677 }
4678 }
4679 $a->foreach(sub
4680 {
4681 $_->detach();
4682 $_->parent( $self );
4683 if( $opts->{action} CORE::eq 'append' )
4684 {
4685 $self->children->push( $_ );
4686 }
4687 elsif( $opts->{action} CORE::eq 'prepend' )
4688 {
4689 $self->children->unshift( $_ );
4690 }
4691 });
4692 }
4693 return( $self );
4694 }
4695  
4696 # Takes html string; or
4697 # selector; or
4698 # element object; or
4699 # array of objects; or
4700 # collection
4701 # "If there is more than one target element, however, cloned copies of the inserted element will be created for each target except the last, and that new set (the original element plus clones) is returned."
4702 sub _append_prepend_to
4703 {
4704 my $self = shift( @_ );
4705 my $this = shift( @_ ) || return( $self->error( "No target was provided to insert element." ) );
4706 # For example: $sel->appendTo( 'body', $doc );
4707 my $context = shift( @_ ) if( $self->_is_a( $_[0] => 'HTML::Object::DOM::Element' ) );
4708 my $opts = $self->_get_args_as_hash( @_ );
4709 if( !exists( $opts->{action} ) )
4710 {
4711 my @caller_info = caller(1);
4712 my $caller = [split( /::/, $caller_info[3])]->[-1];
4713 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(appendTo|prependTo|append_to|prepend_to)$/ );
4714 $opts->{action} = ( $caller =~ /^(append|prepend)(?:To|_to)$/ )[0];
4715 }
4716 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(append|prepend)$/ );
4717 my( $src, $dst );
4718 # A collection to be returned if there is more than 1 target
4719 my $collection = $self->new_collection;
4720 if( !ref( $this ) )
4721 {
4722 if( $self->_is_html( $this ) )
4723 {
4724 my $p = $self->new_parser;
4725 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
4726 $dst = $self->new_array( [ $this ] );
4727 }
4728 # otherwise this has to be a selector
4729 # TODO: Need to correct this and adjust the object used as a base for the find
4730 # since $self could very well be a dynamically created dom object
4731 else
4732 {
4733 if( !defined( $context ) &&
4734 defined( $HTML::Object::DOM::GLOBAL_DOM ) )
4735 {
4736 $context = $HTML::Object::DOM::GLOBAL_DOM;
4737 }
4738 elsif( !defined( $context ) &&
4739 $self->isa_collection &&
4740 !$self->children->is_empty )
4741 {
4742 $context = $self->children->first->getRootNode;
4743 }
4744 $this = defined( $context ) ? $context->find( $this ) : $self->find( $this );
4745 return( $self->pass_error ) unless( $this );
4746 # $dst = $self->new_array( [ $this ] );
4747 $dst = $this->children;
4748 }
4749 }
4750 elsif( $self->_is_array( $this ) )
4751 {
4752 # Make sure this is a Module::Generic::Array object
4753 $dst = $self->new_array( $this );
4754 }
4755 elsif( $self->_is_object( $this ) )
4756 {
4757 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
4758 $dst = $self->new_array( [ $this ] );
4759 }
4760 else
4761 {
4762 return( $self->error( "I do not know what to do with \"$this\". I was expecting a selector, html data, an element object or an array." ) );
4763 }
4764  
4765 # If the content to be inserted is a collection, we loop through it, duplicate each element and insert them
4766 if( $self->isa_collection )
4767 {
4768 $src = $self->children;
4769 }
4770 else
4771 {
4772 $src = $self->new_array( $self );
4773 }
4774  
4775 # If the target is just one element, we do not duplicate them, but simply move them
4776 if( $dst->length == 1 )
4777 {
4778 my $elem = $dst->first;
4779 my $parent = $elem->parent;
4780 return( 1 ) if( !$parent );
4781 $elem->reset(1);
4782 my $pos = $parent->children->pos( $elem );
4783 return( $self->error( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements." ) ) if( !defined( $pos ) );
4784 $src->foreach(sub
4785 {
4786 my $e = shift( @_ );
4787 # Making sure the content element is detached from its original parent
4788 $e->detach;
4789 $e->parent( $elem );
4790 $e->reset(1);
4791 if( $opts->{action} CORE::eq 'prepend' )
4792 {
4793 $elem->children->unshift( $e );
4794 }
4795 elsif( $opts->{action} CORE::eq 'append' )
4796 {
4797 $elem->children->push( $e );
4798 }
4799 $collection->children->push( $e );
4800 });
4801 }
4802 # However, if the target contain multiple element, we clone the content element
4803 else
4804 {
4805 $dst->foreach(sub
4806 {
4807 my $elem = $_;
4808 my $parent = $elem->parent;
4809 return(1) if( !$parent );
4810 $elem->reset(1);
4811 my $pos = $parent->children->pos( $elem );
4812 warn( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements.\n" ) if( !defined( $pos ) );
4813 return(1) if( !defined( $pos ) );
4814 $src->foreach(sub
4815 {
4816 my $e = shift( @_ );
4817 # Making sure the content element is detached from its original parent
4818 my $clone = $e->detach->clone;
4819 $clone->parent( $elem );
4820 $clone->reset(1);
4821 if( $opts->{action} CORE::eq 'prepend' )
4822 {
4823 $elem->children->unshift( $clone );
4824 }
4825 elsif( $opts->{action} CORE::eq 'append' )
4826 {
4827 $elem->children->push( $clone );
4828 }
4829 $collection->children->push( $clone );
4830 });
4831 });
4832 }
4833 return( $collection );
4834 }
4835  
4836 # Takes html string (start with <tag...), text object (HTML::Object::DOM::Text), array or element object
4837 # or alternatively a code reference that returns the above
4838 sub _before_after
4839 {
4840 my $self = shift( @_ );
4841 my $this = shift( @_ ) || return( $self->error( "Nothing was provided to insert before or after." ) );
4842 my $opts = $self->_get_args_as_hash( @_ );
4843 if( !exists( $opts->{action} ) )
4844 {
4845 my @caller_info = caller(1);
4846 my $caller = [split( /::/, $caller_info[3])]->[-1];
4847 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(before|after)$/ );
4848 $opts->{action} = $caller;
4849 }
4850 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(before|after)$/ );
4851 my $a;
4852 if( !ref( $this ) )
4853 {
4854 my $p = $self->new_parser;
4855 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
4856 # $a = $self->new_array( [ $this ] );
4857 # $this is a HTML::Document; we take its children
4858 $a = $this->children;
4859 }
4860 elsif( $self->_is_array( $this ) )
4861 {
4862 # Make sure this is a Module::Generic::Array object
4863 $a = $self->new_array( $this );
4864 }
4865 elsif( $self->_is_object( $this ) )
4866 {
4867 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
4868 $a = $self->new_array( [ $this ] );
4869 }
4870 elsif( ref( $this ) ne 'CODE' )
4871 {
4872 return( $self->error( "I do not know what to do with '$this'. I was expecing an html string, or an HTML::Object::DOM::Element or an array of element objects or a collection object (HTML::Object::Collection) or a code reference." ) );
4873 }
4874  
4875 if( $self->isa_collection )
4876 {
4877 my $failed = 0;
4878 # Going through each object in the collection
4879 $self->children->for(sub
4880 {
4881 my( $i, $e ) = @_;
4882 $e->reset(1);
4883 # will silently fail just like jQuery does
4884 my $parent = $e->parent;
4885 return( 1 ) if( !$parent );
4886 my $pos;
4887 if( $opts->{action} CORE::eq 'before' )
4888 {
4889 $pos = $parent->children->pos( $e );
4890 }
4891 elsif( $opts->{action} CORE::eq 'after' )
4892 {
4893 # $pos = $parent->children->pos( $e->close_tag ? $e->close_tag : $e );
4894 $pos = $parent->children->pos( $e );
4895 }
4896 if( !defined( $pos ) )
4897 {
4898 $failed++;
4899 $self->error( "Element with tag \"", $e->tag, "\" has a parent, but I could not find it among its children elements." );
4900 return(0);
4901 }
4902 if( ref( $this ) CORE::eq 'CODE' )
4903 {
4904 local $_ = $e;
4905 my $res = $this->( $pos, $e->as_string );
4906 if( !defined( $res ) )
4907 {
4908 $failed++;
4909 $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." );
4910 return(0);
4911 }
4912 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4913 {
4914 $a = $self->new_array( [ $res ] );
4915 }
4916 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4917 {
4918 my $elem = $self->new_parser( "$res" );
4919 if( !defined( $elem ) )
4920 {
4921 $failed++;
4922 return(0);
4923 }
4924 $a = $self->new_array( [ $elem ] );
4925 }
4926 else
4927 {
4928 $failed++;
4929 $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." );
4930 return(0);
4931 }
4932 }
4933 $a->foreach(sub
4934 {
4935 my $elem = $_->clone;
4936 $elem->parent( $e );
4937 if( $opts->{action} CORE::eq 'before' )
4938 {
4939 $parent->children->splice( $pos, 0, $_ );
4940 }
4941 elsif( $opts->{action} CORE::eq 'after' )
4942 {
4943 $parent->children->splice( $pos + 1, 0, $_ );
4944 }
4945 $pos++;
4946 });
4947 });
4948 return( $self->pass_error ) if( $failed );
4949 }
4950 else
4951 {
4952 # will silently fail just like jQuery does
4953 my $parent = $self->parent;
4954 return(1) if( !$parent );
4955 my $pos = $parent->children->pos( $self );
4956 return( $self->error( "Element with tag \"", $self->tag, "\" has a parent, but I could not find it among its children elements." ) ) if( !defined( $pos ) );
4957 if( ref( $this ) CORE::eq 'CODE' )
4958 {
4959 local $_ = $self;
4960 my $res = $this->( $pos, $self->as_string );
4961 return( $self->error( "An error occurred while executing code reference to $opts->{action} html element(s). Code reference returned undef." ) ) if( !defined( $res ) );
4962 if( $self->_is_object( $res ) && $res->isa( 'HTML::Object::DOM::Element' ) )
4963 {
4964 $a = $self->new_array( [ $res ] );
4965 }
4966 elsif( overload::Overloaded( $res ) && overload::Method( $res, '""' ) )
4967 {
4968 my $elem = $self->new_parser( "$res" );
4969 return if( !defined( $elem ) );
4970 $a = $self->new_array( [ $elem ] );
4971 }
4972 else
4973 {
4974 return( $self->error( "Value returned from code reference to be used in $opts->{action}\(\) is neither a string nor a HTML::Object::DOM::Element, so I do not know what to do with it." ) );
4975 }
4976 }
4977 $a->foreach(sub
4978 {
4979 $_->detach();
4980 $_->parent( $self );
4981 $_->reset(1);
4982 if( $opts->{action} CORE::eq 'before' )
4983 {
4984 $parent->children->splice( $pos, 0, $_ );
4985 }
4986 elsif( $opts->{action} CORE::eq 'after' )
4987 {
4988 $parent->children->splice( $pos + 1, 0, $_ );
4989 }
4990 });
4991 }
4992 return( $self );
4993 }
4994  
4995 sub _same_as
4996 {
4997 my $self = shift( @_ );
4998 my $this = shift( @_ );
4999 return(0) if( !defined( $this ) || !$self->_is_object( $this ) || !$this->isa( 'HTML::Object::DOM::Element' ) );
5000 if( $this->isa_collection )
5001 {
5002 # We are not a collection, but the other is
5003 if( !$self->isa_collection )
5004 {
5005 return(0);
5006 }
5007 # https://css-tricks.com/snippets/jquery/compare-jquery-objects/
5008 elsif( $self->length == $this->length &&
5009 $self->length == $self->filter( $this )->length )
5010 {
5011 return(1);
5012 }
5013 else
5014 {
5015 return(0);
5016 }
5017 }
5018 else
5019 {
5020 return(0) if( $self->tag CORE::ne $this->tag );
5021 return( $self->eid CORE::eq $this->eid ? 1: 0 );
5022 }
5023 }
5024  
5025 # If argument is provided, pass a CSS::Object::Builder::Rule object
5026 # If no argument is provided, get a CSS::Object::Builder::Rule of the inline css, if any at all.
5027 # Returns undef if no css attribute is set yet.
5028 sub _css_object
5029 {
5030 my $self = shift( @_ );
5031 if( @_ )
5032 {
5033 my $rule = shift( @_ );
5034 my $css = $rule->css;
5035 my $style = $rule->as_string;
5036 $self->css_cache_store( $style, $css );
5037 $self->attributes->set( css => $style );
5038 return( $rule );
5039 }
5040 else
5041 {
5042 my $style = $self->attributes->get( 'css' );
5043 return if( !defined( $style ) );
5044 my $css = CSS::Object->new( format => 'CSS::Object::Format::Inline', debug => $self->debug );
5045 my $cached = $self->css_cache_check( $style );
5046 if( $cached )
5047 {
5048 $css = $cached;
5049 }
5050 else
5051 {
5052 ## 'inline' here is just a fake selector to serve as a container rule for the inline properties,
5053 ## because CSS::Object requires properties to be within a rule
5054 $css->read_string( 'inline {' . $style . ' }' ) ||
5055 return( $self->error( "Unable to parse existing style for tag name \"", $self->prop( 'tagName' ), "\":", $css->error ) );
5056 }
5057 my $main = $css->rules->first;
5058 my $rule = defined( $main ) ? $css->builder->select( $main ) : $css->builder->select( 'inline' );
5059 return( $rule );
5060 }
5061 }
5062  
5063 sub _css_builder
5064 {
5065 my $self = shift( @_ );
5066 my $css = CSS::Object->new( format => 'CSS::Object::Format::Inline', debug => $self->debug );
5067 return( $css->builder->select( 'inline' ) );
5068 }
5069  
5070 # Private method : BFS (Breadth-First Search) on the sub-tree of $self, returns an array
5071 # of all the elements for which $test->($elem) is true. Ignores the nodes text/space/comment.
5072 sub _fast_find_by
5073 {
5074 my( $self, $test ) = @_;
5075 my $result = $self->new_array;
5076 # Racine(s) à parcourir
5077 my @roots;
5078 if( $self->isa_collection )
5079 {
5080 @roots = $self->children->list;
5081 }
5082 else
5083 {
5084 @roots = ( $self );
5085 }
5086 my @queue = @roots;
5087 while( @queue )
5088 {
5089 my $node = shift( @queue );
5090 # We only test on the true elements, no on Text, Space, or Comment
5091 if( $node->isa( 'HTML::Object::DOM::Element' ) &&
5092 $node->{tag} &&
5093 substr( "$node->{tag}", 0, 1 ) ne '_' )
5094 {
5095 $result->push( $node ) if( $test->( $node ) );
5096 }
5097 # Crawl down in te children if the method exists.
5098 if( $node->can( 'children' ) && $node->children->length )
5099 {
5100 push( @queue, $node->children->list );
5101 }
5102 }
5103 return( $result );
5104 }
5105  
5106 # Takes selector, html, element or array
5107 # xq( '<p>Test</p>' )->insertBefore( xq( '.inner', $doc ) );
5108 # $elem->insertBefore( '.inner' );
5109 sub _insert_before_after
5110 {
5111 my $self = shift( @_ );
5112 my $this = shift( @_ ) || return( $self->error( "No target was provided to insert element." ) );
5113 my $opts = $self->_get_args_as_hash( @_ );
5114 if( !exists( $opts->{action} ) )
5115 {
5116 my @caller_info = caller(1);
5117 my $caller = [split( /::/, $caller_info[3])]->[-1];
5118 return( $self->error( "No action argument was provided and I am unable to guess it." ) ) if( $caller !~ /^(?:insert|insert_)(?:Before|After)$/i );
5119 $opts->{action} = lc( ( $caller =~ /^(?:insert|insert_)(?:Before|After)$/i )[0] );
5120 }
5121 return( $self->error( "Invalid value for argument \"action\": '$opts->{action}'" ) ) if( $opts->{action} !~ /^(?:before|after)$/ );
5122 my $a;
5123 if( !ref( $this ) )
5124 {
5125 if( $self->_is_html( $this ) )
5126 {
5127 my $p = $self->new_parser;
5128 $this = $p->parse_data( $this ) || return( $self->pass_error( $p->error ) );
5129 $a = $self->new_array( [ $this ] );
5130 }
5131 # otherwise this has to be a selector
5132 # TODO: Need to correct this and adjust the object used as a base for the find
5133 # since $self could very well be a dynamically created dom object
5134 else
5135 {
5136 $this = $self->find( $this ) || return;
5137 $a = $self->new_array( [ $this ] );
5138 }
5139 }
5140 elsif( $self->_is_array( $this ) )
5141 {
5142 # Make sure this is a Module::Generic::Array object
5143 $a = $self->new_array( $this );
5144 }
5145 elsif( $self->_is_object( $this ) )
5146 {
5147 return( $self->error( "Object provided '$this' (", overload::StrVal( $this ), ") is not an HTML::Object::DOM::Element object." ) ) if( !$this->isa( 'HTML::Object::DOM::Element' ) );
5148 $a = $self->new_array( [ $this ] );
5149 }
5150 else
5151 {
5152 return( $self->error( "I do not know what to do with \"$this\". I was expecting a selector, html data, an element object or an array." ) );
5153 }
5154  
5155 # If the content to be inserted is a collection, we loop through it, duplicate each element and insert them
5156 if( $self->isa_collection )
5157 {
5158 $a->foreach(sub
5159 {
5160 my $elem = $_;
5161 my $parent = $elem->parent;
5162 return(1) if( !$parent );
5163 $elem->reset(1);
5164 my $pos = $parent->children->pos( $elem );
5165 warn( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements.\n" ) if( !defined( $pos ) );
5166 return(1) if( !defined( $pos ) );
5167 $self->children->foreach(sub
5168 {
5169 my $e = shift( @_ );
5170 # Making sure the content element is detached from its original parent
5171 my $clone = $e->detach->clone;
5172 $clone->parent( $elem );
5173 if( $opts->{action} CORE::eq 'before' )
5174 {
5175 $parent->children->splice( $pos, 0, $clone );
5176 }
5177 elsif( $opts->{action} CORE::eq 'after' )
5178 {
5179 $parent->children->splice( $pos + 1, 0, $clone );
5180 }
5181 });
5182 });
5183 }
5184 else
5185 {
5186 # If the target is just one element, we do not duplicate them, but simply move them
5187 if( $a->length == 1 )
5188 {
5189 my $elem = $a->first;
5190 my $parent = $elem->parent;
5191 return(1) if( !$parent );
5192 $elem->reset(1);
5193 my $pos = $parent->children->pos( $elem );
5194 return( $self->error( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements." ) ) if( !defined( $pos ) );
5195 $self->detach;
5196 $self->parent( $elem );
5197 if( $opts->{action} CORE::eq 'before' )
5198 {
5199 $parent->children->splice( $pos, 0, $self );
5200 }
5201 elsif( $opts->{action} CORE::eq 'after' )
5202 {
5203 $parent->children->splice( $pos + 1, 0, $self );
5204 }
5205 }
5206 # However, if the target contain multiple element, we clone the content element
5207 else
5208 {
5209 $a->foreach(sub
5210 {
5211 my $elem = $_;
5212 my $parent = $elem->parent;
5213 return(1) if( !$parent );
5214 $elem->reset(1);
5215 my $pos = $parent->children->pos( $elem );
5216 warn( "Found a parent for tag \"", $elem->tag, "\", but somehow I could not find its position among its children elements.\n" ) if( !defined( $pos ) );
5217 return(1) if( !defined( $pos ) );
5218 my $clone = $self->detach->clone;
5219 $clone->parent( $elem );
5220 if( $opts->{action} CORE::eq 'before' )
5221 {
5222 $parent->children->splice( $pos, 0, $clone );
5223 }
5224 elsif( $opts->{action} CORE::eq 'after' )
5225 {
5226 $parent->children->splice( $pos + 1, 0, $clone );
5227 }
5228 });
5229 }
5230 }
5231 return( $self );
5232 }
5233  
5234 sub _is_html { return( $_[1] =~ /^[[:blank:]\h]*<\w+/ ? 1 : 0 ); }
5235  
5236 sub _is_same_node { shift( @_ ); return( shift->eid CORE::eq shift->eid ); }
5237  
5238 sub _xpath_value { shift( @_ ); return( ref( $_[0] ) ? ${$_[0]} : HTML::Selector::XPath::selector_to_xpath( $_[0] ) ); }
5239  
5240 1;
5241 # NOTE: POD
5242 __END__