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

filter: Statementstmt 0.0% 0 / 114 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 6 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 27 totaltotal 0.0% 0 / 196 CC 8 SCAR 17.3
CC
8
Cov
0%
composedPath
20.0
setTimestamp
20.0
dispatch
6.0
CRAP 5.6
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/Event.pm
3 ## Version v0.2.1
4 ## Copyright(c) 2022 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/12/11
7 ## Modified 2023/11/06
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::Event;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTML::Object' );
20 use parent qw( Module::Generic );
21 use vars qw( @EXPORT_OK %EXPORT_TAGS $VERSION );
22 use Time::HiRes ();
23 use constant {
24 NONE => 0,
25 CAPTURING_PHASE => 1,
26 AT_TARGET => 2,
27 BUBBLING_PHASE => 3,
28
29 CANCEL_PROPAGATION => 1,
30 CANCEL_IMMEDIATE_PROPAGATION => 2,
31
32 ABORT => 1,
33 BLUR => 2,
34 CLICK => 4,
35 CHANGE => 16,
36 DBLCLICK => 32,
37 DRAGDDROP => 64,
38 ERROR => 128,
39 FOCUS => 256,
40 KEYDOWN => 512,
41 KEYPRESS => 1024,
42 KEYUP => 2048,
43 LOAD => 4096,
44 MOUSEDOWN => 8192,
45 MOUSEMOVE => 16384,
46 MOUSEOUT => 32768,
47 MOUSEOVER => 65536,
48 MOUSEUP => 131072,
49 MOVE => 262144,
50 RESET => 524288,
51 RESIZE => 1048576,
52 SELECT => 2097152,
53 SUBMIT => 4194304,
54 UNLOAD => 8388608,
55 };
56 our @EXPORT_OK = qw(
57 NONE CAPTURING_PHASE AT_TARGET BUBBLING_PHASE CANCEL_PROPAGATION CANCEL_IMMEDIATE_PROPAGATION
58 ABORT BLUR CLICK CHANGE DBLCLICK DRAGDDROP ERROR FOCUS KEYDOWN KEYPRESS KEYUP LOAD
59 MOUSEDOWN MOUSEMOVE MOUSEOUT MOUSEOVER MOUSEUP MOVE RESET RESIZE SELECT SUBMIT UNLOAD
60 );
61 our %EXPORT_TAGS = (
62 'all' => [qw(
63 NONE CAPTURING_PHASE AT_TARGET BUBBLING_PHASE
64 CANCEL_PROPAGATION CANCEL_IMMEDIATE_PROPAGATION
65 ABORT BLUR CLICK CHANGE DBLCLICK DRAGDDROP ERROR FOCUS KEYDOWN KEYPRESS KEYUP LOAD
66 MOUSEDOWN MOUSEMOVE MOUSEOUT MOUSEOVER MOUSEUP MOVE RESET RESIZE SELECT SUBMIT UNLOAD
67 )],
68 'events'=> [qw(
69 ABORT BLUR CLICK CHANGE DBLCLICK DRAGDDROP ERROR FOCUS KEYDOWN KEYPRESS KEYUP LOAD
70 MOUSEDOWN MOUSEMOVE MOUSEOUT MOUSEOVER MOUSEUP MOVE RESET RESIZE SELECT SUBMIT UNLOAD
71 )],
72 'phase' => [qw( NONE CAPTURING_PHASE AT_TARGET BUBBLING_PHASE )]
73 );
74 our $VERSION = 'v0.2.1';
75 };
76  
77 use strict;
78 use warnings;
79  
80 sub init
81 {
82 my $self = shift( @_ );
83 my $type = shift( @_ ) || return( $self->error( "No event type was provided." ) );
84 $self->{bubbles} = 1;
85 $self->{cancelable} = 1;
86 # Property that, if set to true, will be checked to stop events handlers and propagation
87 $self->{cancelled} = 0;
88 $self->{composed} = 0;
89 $self->{currentTarget} = undef;
90 $self->{defaultPrevented} = 0;
91 $self->{detail} = {};
92 $self->{eventPhase} = NONE;
93 $self->{isTrusted} = 1;
94 # array of html element for which their event handler will be called
95 $self->{path} = [];
96 $self->{target} = undef;
97 $self->{timeStamp} = Time::HiRes::time();
98 $self->{type} = $type;
99 $self->{_init_strict_use_sub} = 1;
100 $self->SUPER::init( @_ ) || return( $self->pass_error );
101 # Our immediate caller is new() in Module::Generic, so we skip that
102 my( $pack, $file, $line ) = caller(1);
103 my $sub = [caller(2)]->[3];
104 $self->{package} = $pack;
105 $self->{file} = $file;
106 $self->{line} = $line;
107 $self->{subroutine} = $sub;
108 return( $self );
109 }
110  
111 # Note: Property
112 sub bubbles : lvalue { return( shift->_set_get_boolean( 'bubbles', @_ ) ); }
113  
114 # Note: Property
115 sub cancelable : lvalue { return( shift->_set_get_boolean( 'cancelable', @_ ) ); }
116  
117 # Note: Property
118 sub cancellable : lvalue { return( shift->_set_get_boolean( 'cancelable', @_ ) ); }
119  
120 # Note: Property
121 sub canceled : lvalue { return( shift->_set_get_number( 'cancelled', @_ ) ); }
122  
123 # Note: Property
124 sub cancelled : lvalue { return( shift->_set_get_number( 'cancelled', @_ ) ); }
125  
126 # Note: Property
127 sub composed : lvalue { return( shift->_set_get_boolean( 'composed', @_ ) ); }
128  
129 sub composedPath
130 {
131 my $self = shift( @_ );
132 # already set
133 return( $self->path ) if( !$self->path->is_empty );
134 my $target = $self->target;
135 return( $self->error( "No target element is set yet!" ) ) if( !$target );
136 my $original_target = $target;
137 my $path = $self->path;
138 while( $target->parentNode )
139 {
140 $path->push( $target );
141 $target = $target->parentNode;
142 }
143 my $doc = $original_target->root;
144 $path->push( $doc ) if( $doc );
145 # Module::Generic::Array object
146 return( $path );
147 }
148  
149 # Note: Property
150 sub currentTarget : lvalue { return( shift->_set_get_lvalue( 'currentTarget', @_ ) ); }
151  
152 # Note: Property
153 sub defaultPrevented : lvalue { return( shift->_set_get_boolean( 'defaultPrevented', @_ ) ); }
154  
155 # Note : Property from CustomEvent, but we add it here as a standard
156 sub detail : lvalue { return( shift->_set_get_hash_as_mix_object( 'detail', @_ ) ); }
157  
158 sub dispatch
159 {
160 my $self = shift( @_ );
161 my $elem = shift( @_ ) || return( $self->error({
162 message => "No element was provided to dispatch this event to.",
163 class => 'HTML::Object::SyntaxError',
164 }) );
165 return( $self->error({
166 message => "Object provided is not a node object (HTML::Object::DOM::Node)",
167 class => 'HTML::Object::SyntaxError',
168 }) ) if( !$self->_is_a( $elem => 'HTML::Object::DOM::Node' ) );
169 return( $elem->dispatchEvent( $self ) );
170 }
171  
172 # Note: Property
173 sub eventPhase : lvalue { return( shift->_set_get_lvalue( 'eventPhase', @_ ) ); }
174  
175 sub file { return( shift->_set_get_scalar( 'file', @_ ) ); }
176  
177 # Note: Property
178 sub isTrusted : lvalue { return( shift->_set_get_boolean( 'isTrusted', @_ ) ); }
179  
180 sub line { return( shift->_set_get_scalar( 'line', @_ ) ); }
181  
182 sub package { return( shift->_set_get_scalar( 'package', @_ ) ); }
183  
184 sub path { return( shift->_set_get_array_as_object( 'path', @_ ) ); }
185  
186 # Note: preventDefault does nothing, except set defaultPrevented to true
187 sub preventDefault
188 {
189 my $self = shift( @_ );
190 $self->defaultPrevented(1);
191 return( $self );
192 }
193  
194 sub setTimestamp
195 {
196 my $self = shift( @_ );
197 my $now = scalar( @_ ) ? shift( @_ ) : Time::HiRes::time();
198 # try-catch
199 local $@;
200 my $rv = eval
201 {
202 my $dt;
203 unless( $self->_is_a( $now => 'DateTime' ) )
204 {
205 $dt = DateTime->from_epoch( epoch => $now );
206 }
207 return( $self->_set_get_datetime( timeStamp => $dt ) );
208 };
209 if( $@ )
210 {
211 return( $self->error( "Error setting event timestamp: $@" ) );
212 }
213 return( $rv );
214 }
215  
216 sub stopImmediatePropagation
217 {
218 my $self = shift( @_ );
219 $self->cancelled( CANCEL_IMMEDIATE_PROPAGATION );
220 return( $self );
221 }
222  
223 sub stopPropagation
224 {
225 my $self = shift( @_ );
226 $self->cancelled( CANCEL_PROPAGATION );
227 return( $self );
228 }
229  
230 sub subroutine { return( shift->_set_get_scalar( 'subroutine', @_ ) ); }
231  
232 # Note: Property
233 sub target { return( shift->_set_get_object_without_init( 'target', 'HTML::Object::Element', @_ ) ); }
234  
235 # Note: Property
236 sub timeStamp : lvalue { return( shift->_set_get_datetime( 'timeStamp', @_ ) ); }
237  
238 # Note: Property
239 sub type : lvalue { return( shift->_set_get_lvalue( 'type', @_ ) ); }
240  
241 1;
242 # NOTE: POD
243 __END__
244  
245 =encoding utf-8
246  
247 =head1 NAME
248  
249 HTML::Object::Event - HTML Object Event Class
250  
251 =head1 SYNOPSIS
252  
253 use HTML::Object::Event;
254 my $event = HTML::Object::Event->new ||
255 die( HTML::Object::Event->error, "\n" );
256  
257 =head1 VERSION
258  
259 v0.2.1
260  
261 =head1 DESCRIPTION
262  
263 This module represents an event which takes place in the DOM.
264  
265 Of course, unlike a web browser environment, there is no user interaction here, so all event "fired" are triggered programatically.
266  
267 Events are attached to L<HTML elements|HTML::Object::Element>
268  
269 One L<element|HTML::Object::Element> can have several such L<handlers|HTML::Object::EventTarget>, even for the exact same event
270  
271 =head1 CONSTRUCTOR
272  
273 =head2 new
274  
275 Provided with a type and an hash or hash reference of options and this creates a new L<HTML::Object::Event> object. An event created in this way is called a C<synthetic> event, as opposed to an event fired by the browser, and can be dispatched by a script.
276  
277 It returns the new event object upon success, or upon error, returns C<undef> and sets an L<error|HTML::Object::Exception>
278  
279 Parameters accepted:
280  
281 =over 4
282  
283 =item I<type>
284  
285 This is a string representing the type of the event.
286  
287 =item I<options hash or hash reference>
288  
289 The options can have the following properties. All of them are optional. Each of them can be accessed or modified by they equivalent method listed below.
290  
291 =over 8
292  
293 =item I<bubbles>
294  
295 A boolean value indicating whether the event bubbles. The default is true.
296  
297 When true, this means the event will be passed on from the element that triggered it on to its parent and its parent's parent and so on up to the top L<element|HTML::Object::DOM::Document>. This is the default behaviour. When set to false, the event will not bubble up.
298  
299 =item I<cancelable>
300  
301 A boolean value indicating whether the event can be cancelled. The default is true.
302  
303 It can also be called as C<cancellable> for non-American speakers.
304  
305 =item I<composed>
306  
307 Because this is a perl environment, this value is always false, and discarded.
308  
309 A boolean value indicating whether the event will trigger listeners outside of a shadow root (see L</composed> for more details). The default is C<false>.
310  
311 =item I<detail>
312  
313 An optional hash reference of arbitrary key-valu pairs that will be stored in the event object and can be later retrieved by the event handlers.
314  
315 =back
316  
317 =back
318  
319 For example:
320  
321 Create a look event that bubbles up and cannot be canceled
322  
323 my $evt = HTML::Object::Event->new( look => { bubbles => 1, cancelable => 0 } );
324 $doc->dispatchEvent( $evt );
325  
326 # event can be dispatched from any element, not only the document
327 $myDiv->dispatchEvent( $evt );
328  
329 =head1 PROPERTIES
330  
331 =head2 bubbles
332  
333 Read-only
334  
335 A boolean value indicating whether or not the event bubbles up through the DOM. Default to false
336  
337 When true, this means the event will be passed on from the element that triggered it on to its parent and its parent's parent and so on up to the top L<element|HTML::Object::DOM::Document>. This is the default behaviour. When set to false, the event will not bubble up.
338  
339 =head2 cancelable
340  
341 Read-only
342  
343 A boolean value indicating whether the event is cancelable. Default to true
344  
345 It can also be called as C<cancellable> for non-American speakers.
346  
347 =head2 canceled
348  
349 Read-only
350  
351 An integer value indicating whether the event has been canceled. Its value is 1 if it has been cancelled with L</stopPropagation> and 2 if it has been cancelled with L</stopImmediatePropagation>
352  
353 It can also be called as C<cancelled> for non-American speakers.
354  
355 =head2 cancellable
356  
357 Alias for L</cancelable>
358  
359 =head2 cancelled
360  
361 Alias for L</canceled>
362  
363 =head2 composed
364  
365 Read-only
366  
367 A boolean indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM. Default to false
368  
369 Since this is a perl environment, this is always false, and its value is ignored.
370  
371 =head2 currentTarget
372  
373 Read-only
374  
375 A reference to the currently registered L<target|HTML::Object::Element> for the event. This is the L<object|HTML::Object::Element> to which the event is currently slated to be sent. It's possible this has been changed along the way through retargeting.
376  
377 =head2 defaultPrevented
378  
379 Read-only
380  
381 Indicates whether or not the call to L</preventDefault> canceled the event. Default to false
382  
383 =head2 detail
384  
385 Set or get an hash reference of arbitrary key-value pairs that will be stored in this event.
386  
387 =head2 eventPhase
388  
389 Read-only
390  
391 Returns an integer value which specifies the current evaluation phase of the event flow. Possible values are: C<NONE> (0), C<CAPTURING_PHASE> (1), C<AT_TARGET> (2), C<BUBBLING_PHASE> (3).
392  
393 You can export those constants in your namespace by calling L<HTML::Object::Event> like this:
394  
395 use HTML::Object::Event qw( NONE CAPTURING_PHASE AT_TARGET BUBBLING_PHASE );
396  
397 or, more simply:
398  
399 use HTML::Object::Event ':phase';
400  
401 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase>
402  
403 =head2 isTrusted
404  
405 Read-only
406  
407 Obviously, since this is a perl environment, this is always true, because although it would be script-generated, it is fair to say your own script is trustworthy.
408  
409 Indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation method, for example).
410  
411 =head2 path
412  
413 Returns the computed elements path by L</composedPath>, as an L<array object|Module::Generic::Array>
414  
415 =head2 target
416  
417 Read-only
418  
419 A reference to the L<object|HTML::Object::Element> to which the event was originally dispatched.
420  
421 =head2 timeStamp
422  
423 Read-only
424  
425 The time at which the event was created (in milliseconds). By specification, this value is time since epoch using L<Time::HiRes>. This is actually a L<DateTime> object. L<DateTime> object supports nanoseconds.
426  
427 =head2 type
428  
429 Read-only
430  
431 The case-insensitive type indentifying the event.
432  
433 =head1 METHODS
434  
435 =head2 composedPath
436  
437 Returns the event's path (an array of objects on which listeners will be invoked).
438  
439 =head2 dispatch
440  
441 Provided with a L<node|HTML::Object::DOM::Node> and this will dispatch this event to the given C<node>.
442  
443 It returns the value returned by L</HTML::Object::EventTarget/dispatchEvent>
444  
445 =head2 file
446  
447 Returns the file path where this event was called from.
448  
449 =head2 line
450  
451 Returns the line at which this event was called from.
452  
453 =head2 package
454  
455 Returns the package name where this event was called from.
456  
457 =head2 preventDefault
458  
459 This does nothing under perl, except set the value of L</defaultPrevented> to true.
460  
461 Under JavaScript, this method is used to stop the browser’s default behavior when performing an action, such as checking a checkbox upon user click.
462  
463 =head2 setTimestamp
464  
465 Takes an optional unix timestamp or a L<DateTime> object, and this will set the event timestamp. If no argument is provided, this will resort to set the timestamp using L<Time::HiRes/time>, which provides a timestamp in milliseconds.
466  
467 It returns a L<DateTime> object.
468  
469 =head2 stopImmediatePropagation
470  
471 For this particular event, prevent all other listeners from being called. This includes listeners attached to the same element as well as those attached to elements that will be traversed later (during the capture phase, for instance).
472  
473 =head2 stopPropagation
474  
475 Stops the propagation of events further along in the DOM.
476  
477 =head2 subroutine
478  
479 Returns the subroutine where this event was called from.
480  
481 =head1 CONSTANTS
482  
483 =head2 NONE (0)
484  
485 The event is not being processed at this time.
486  
487 =head2 CAPTURING_PHASE (1)
488  
489 The event is being propagated through the target's ancestor objects. This process starts with the L<Document|HTML::Object::Document>, then the L<HTML html element|HTML::Object::Element>, and so on through the elements until the target's parent is reached. Event listeners registered for capture mode when L<HTML::Object::EventTarget/addEventListener> was called are triggered during this phase.
490  
491 =head2 AT_TARGET (2)
492  
493 The event has arrived at the event's target. Event listeners registered for this phase are called at this time. If L</bubbles> is false, processing the event is finished after this phase is complete.
494  
495 =head2 BUBBLING_PHASE (3)
496  
497 The event is propagating back up through the target's ancestors in reverse order, starting with the parent, and eventually reaching the containing L<document|HTML::Object::Document>. This is known as bubbling, and occurs only if L</bubbles> is true. Event listeners registered for this phase are triggered during this process.
498  
499 =head2 CANCEL_PROPAGATION (1)
500  
501 State of the propagation being cancelled.
502  
503 $event->stopPropagation();
504 $event->cancelled == CANCEL_PROPAGATION;
505  
506 =head2 CANCEL_IMMEDIATE_PROPAGATION (2)
507  
508 State of immediate propagation being cancelled.
509  
510 $event->stopImmediatePropagation();
511 $event->cancelled == CANCEL_IMMEDIATE_PROPAGATION;
512  
513 =head1 AUTHOR
514  
515 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
516  
517 =head1 SEE ALSO
518  
519 L<https://developer.mozilla.org/en-US/docs/Web/API/Event>
520  
521 L<https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events>
522  
523 L<https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events>
524  
525 L<https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent>
526  
527 =head1 COPYRIGHT & LICENSE
528  
529 Copyright(c) 2021 DEGUEST Pte. Ltd.
530  
531 All rights reserved
532  
533 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
534  
535 =cut