-
Notifications
You must be signed in to change notification settings - Fork 161
/
Element.java
1612 lines (1494 loc) · 56.6 KB
/
Element.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2000-2018 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.dom;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.jsoup.nodes.Document;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.ComponentUtil;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.page.Page;
import com.vaadin.flow.dom.impl.BasicElementStateProvider;
import com.vaadin.flow.dom.impl.BasicTextElementStateProvider;
import com.vaadin.flow.dom.impl.CustomAttribute;
import com.vaadin.flow.dom.impl.ThemeListImpl;
import com.vaadin.flow.function.SerializableConsumer;
import com.vaadin.flow.internal.JavaScriptSemantics;
import com.vaadin.flow.internal.JsonCodec;
import com.vaadin.flow.internal.StateNode;
import com.vaadin.flow.internal.nodefeature.ElementData;
import com.vaadin.flow.internal.nodefeature.TextNodeMap;
import com.vaadin.flow.internal.nodefeature.VirtualChildrenList;
import com.vaadin.flow.server.AbstractStreamResource;
import com.vaadin.flow.server.Command;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.shared.Registration;
import elemental.json.Json;
import elemental.json.JsonValue;
/**
* A class representing an element in the DOM.
* <p>
* Contains methods for updating and querying various parts of the element, such
* as attributes.
*
* @author Vaadin Ltd
* @since 1.0
*/
public class Element extends Node<Element> {
private static final String EVENT_TYPE_MUST_NOT_BE_NULL = "Event type must not be null";
static final String ATTRIBUTE_NAME_CANNOT_BE_NULL = "The attribute name cannot be null";
// Can't set $name as a property, use $replacement instead.
private static final Map<String, String> illegalPropertyReplacements = new HashMap<>();
static {
illegalPropertyReplacements.put("textContent",
"setTextContent(String)");
illegalPropertyReplacements.put("classList", "getClassList()");
illegalPropertyReplacements.put("className", "getClassList()");
illegalPropertyReplacements.put("outerHTML",
"getParent().setProperty('innertHTML',value)");
}
/**
* Private constructor for initializing with an existing node and state
* provider.
*
* @param node
* the state node, not null
* @param stateProvider
* the state provider, not null
*/
protected Element(StateNode node, ElementStateProvider stateProvider) {
super(node, stateProvider);
}
/**
* Creates an element using the given tag name.
*
* @param tag
* the tag name of the element. Must be a non-empty string and
* can contain letters, numbers and dashes ({@literal -})
*/
public Element(String tag) {
super(createStateNode(tag), BasicElementStateProvider.get());
assert getNode() != null;
assert getStateProvider() != null;
}
/**
* Creates an element using the given tag name.
*
* @param tag
* tag name of the element. Must be a non-empty string and can
* contain letters, numbers and dashes ({@literal -})
* @param autocreate
* parameter is ignored, but retained in the API for backwards
* compatibility
* @deprecated The {@code autoCreate} parameter no longer has any effect.
* Use {@link #Element(String)} instead.
*/
@Deprecated
public Element(String tag, boolean autocreate) {
this(tag);
}
/**
* Gets the element mapped to the given state node.
*
* @param node
* the state node, not <code>null</code>
* @return the element for the node, not <code>null</code>
*/
public static Element get(StateNode node) {
assert node != null;
if (node.hasFeature(TextNodeMap.class)) {
return get(node, BasicTextElementStateProvider.get());
} else if (node.hasFeature(ElementData.class)) {
return get(node, BasicElementStateProvider.get());
} else {
throw new IllegalArgumentException(
"Node is not valid as an element");
}
}
/**
* Gets the element mapped to the given state node and element state
* provider.
*
* @param node
* the state node
* @param stateProvider
* the element state provider
* @return an element for the node and state provider, not <code>null</code>
*/
// Static builder instead of regular constructor to keep it slightly out of
// view
public static Element get(StateNode node,
ElementStateProvider stateProvider) {
return new Element(node, stateProvider);
}
/**
* Gets the number of child elements.
* <p>
* If the property "innerHTML" has been set explicitly then its value (the
* new element structure) won't be populated on the server side and this
* method will return <code>0</code>.
*
* @see #setProperty(String, String)
* @return the number of child elements
*/
@Override
public int getChildCount() {
return super.getChildCount();
}
/**
* Returns the child element at the given position.
* <p>
* If property "innerHTML" has been set explicitly then its value (the new
* element structure) won't be populated on the server side and this method
* will not work.
*
* @see #setProperty(String, String)
* @param index
* the index of the child element to return
* @return the child element
*/
@Override
public Element getChild(int index) {
return super.getChild(index);
}
/**
* Gets all the children of this element.
* <p>
* If property "innerHTML" has been set explicitly then its value (the new
* element structure) won't be populated on the server side and this method
* returns an empty stream.
*
* @see #setProperty(String, String)
*
* @return a stream of children
*/
@Override
public Stream<Element> getChildren() {
return super.getChildren();
}
/**
* Creates a text node with the given text.
*
* @param text
* the text in the node
* @return an element representing the text node
*/
public static Element createText(String text) {
if (text == null) {
throw new IllegalArgumentException("Text cannot be null");
}
return new Element(BasicTextElementStateProvider.createStateNode(text),
BasicTextElementStateProvider.get());
}
/**
* Creates a state node for an element using the given tag.
*
* @param tag
* the tag name of the element.
*/
private static StateNode createStateNode(String tag) {
if (!ElementUtil.isValidTagName(tag)) {
throw new IllegalArgumentException(
"Tag " + tag + " is not a valid tag name");
}
return BasicElementStateProvider.createStateNode(tag);
}
/**
* Gets the tag name for the element.
*
* @return the tag name
*/
public String getTag() {
return getStateProvider().getTag(getNode());
}
/**
* Sets the given attribute to the given value.
* <p>
* Attribute names are considered case insensitive and all names will be
* converted to lower case automatically.
* <p>
* An attribute always has a String key and a String value.
* <p>
* Note: An empty attribute value ({@literal ""}) will be rendered as
* {@literal <div something>} and not {@literal <div something="">}.
* <p>
* Note that setting the attribute <code>class</code> will override anything
* that has been set previously via {@link #getClassList()}.
* <p>
* Note that you cannot set the attribute <code>style</code> using this
* method. Instead you should use {@link #getStyle()} object.
* <p>
* Note that attribute changes made on the server are sent to the client but
* attribute changes made on the client side are not reflected back to the
* server.
*
* @param attribute
* the name of the attribute
* @param value
* the value of the attribute, not null
* @return this element
*/
public Element setAttribute(String attribute, String value) {
String lowerCaseAttribute = validateAttribute(attribute, value);
Optional<CustomAttribute> customAttribute = CustomAttribute
.get(lowerCaseAttribute);
if (customAttribute.isPresent()) {
customAttribute.get().setAttribute(this, value);
} else {
getStateProvider().setAttribute(getNode(), lowerCaseAttribute,
value);
}
return this;
}
/**
* Sets the given attribute to the given boolean value. Setting the value to
* <code>true</code> will internally set the value to <code>""</code>, which
* will be rendered as {@literal <div name>}, i.e. without any explicit
* value. Setting the value to <code>false</code> is a shorthand for
* removing the attribute.
* <p>
* Use {@link #hasAttribute(String)} to check whether a boolean attribute
* has been set.
* <p>
* Attribute names are considered case insensitive and all names will be
* converted to lower case automatically.
*
* @see #setAttribute(String, String)
*
* @param attribute
* the name of the attribute
* @param value
* the value of the attribute
* @return this element
*/
public Element setAttribute(String attribute, boolean value) {
if (value) {
return setAttribute(attribute, "");
} else {
return removeAttribute(attribute);
}
}
/**
* Sets the given attribute to the given {@link StreamResource} value.
* <p>
* Attribute names are considered case insensitive and all names will be
* converted to lower case automatically.
* <p>
* This is a convenience method to register a {@link StreamResource}
* instance into the session and use the registered resource URI as an
* element attribute.
* <p>
*
* @see #setAttribute(String, String)
*
* @param attribute
* the name of the attribute
* @param resource
* the resource value, not null
* @return this element
*/
public Element setAttribute(String attribute,
AbstractStreamResource resource) {
String lowerCaseAttribute = validateAttribute(attribute, resource);
Optional<CustomAttribute> customAttribute = CustomAttribute
.get(lowerCaseAttribute);
if (!customAttribute.isPresent()) {
getStateProvider().setAttribute(getNode(), attribute, resource);
} else {
throw new IllegalArgumentException("Can't set " + attribute
+ " to StreamResource value. This attribute has special semantic");
}
return this;
}
/**
* Gets the value of the given attribute.
* <p>
* Attribute names are considered case insensitive and all names will be
* converted to lower case automatically.
* <p>
* An attribute always has a String key and a String value.
* <p>
* Note that for attribute <code>class</code> the contents of the
* {@link #getClassList()} collection are returned as a single concatenated
* string.
* <p>
* Note that for attribute <code>style</code> the contents of the
* {@link #getStyle()} object are returned as a single concatenated string.
* <p>
* Note that attribute changes made on the server are sent to the client but
* attribute changes made on the client side are not reflected back to the
* server.
*
* @param attribute
* the name of the attribute
* @return the value of the attribute or null if the attribute has not been
* set
*/
public String getAttribute(String attribute) {
if (attribute == null) {
throw new IllegalArgumentException(ATTRIBUTE_NAME_CANNOT_BE_NULL);
}
String lowerCaseAttribute = attribute.toLowerCase(Locale.ENGLISH);
return CustomAttribute.get(lowerCaseAttribute)
.map(attr -> attr.getAttribute(this))
.orElseGet(() -> getStateProvider().getAttribute(getNode(),
lowerCaseAttribute));
}
/**
* Checks if the given attribute has been set.
* <p>
* Attribute names are considered case insensitive and all names will be
* converted to lower case automatically.
* <p>
* Note that attribute changes made on the server are sent to the client but
* attribute changes made on the client side are not reflected back to the
* server.
*
* @param attribute
* the name of the attribute
* @return true if the attribute has been set, false otherwise
*/
public boolean hasAttribute(String attribute) {
if (attribute == null) {
throw new IllegalArgumentException(ATTRIBUTE_NAME_CANNOT_BE_NULL);
}
String lowerCaseAttribute = attribute.toLowerCase(Locale.ENGLISH);
Optional<CustomAttribute> customAttribute = CustomAttribute
.get(lowerCaseAttribute);
if (customAttribute.isPresent()) {
return customAttribute.get().hasAttribute(this);
} else {
return getStateProvider().hasAttribute(getNode(),
lowerCaseAttribute);
}
}
/**
* Gets the defined attribute names.
* <p>
* Attribute names are considered case insensitive and all names will be
* converted to lower case automatically.
* <p>
* Note that attribute changes made on the server are sent to the client but
* attribute changes made on the client side are not reflected back to the
* server.
*
* @return a stream of defined attribute names
*/
public Stream<String> getAttributeNames() {
assert getStateProvider().getAttributeNames(getNode())
.map(CustomAttribute::get).filter(Optional::isPresent)
.filter(attr -> attr.get().hasAttribute(this))
.count() == 0 : "Overlap between stored attributes and existing custom attributes";
Stream<String> regularNames = getStateProvider()
.getAttributeNames(getNode());
Stream<String> customNames = CustomAttribute.getNames().stream().filter(
name -> CustomAttribute.get(name).get().hasAttribute(this));
return Stream.concat(regularNames, customNames);
}
/**
* Removes the given attribute.
* <p>
* Attribute names are considered case insensitive and all names will be
* converted to lower case automatically.
* <p>
* If the attribute has not been set, does nothing.
* <p>
* Note that attribute changes made on the server are sent to the client but
* attribute changes made on the client side are not reflected back to the
* server.
*
* @param attribute
* the name of the attribute
* @return this element
*/
public Element removeAttribute(String attribute) {
if (attribute == null) {
throw new IllegalArgumentException(ATTRIBUTE_NAME_CANNOT_BE_NULL);
}
String lowerCaseAttribute = attribute.toLowerCase(Locale.ENGLISH);
if (hasAttribute(lowerCaseAttribute)) {
Optional<CustomAttribute> customAttribute = CustomAttribute
.get(lowerCaseAttribute);
if (customAttribute.isPresent()) {
customAttribute.get().removeAttribute(this);
} else {
getStateProvider().removeAttribute(getNode(),
lowerCaseAttribute);
}
}
return this;
}
/**
* Adds an event listener for the given event type.
* <p>
* Event listeners are triggered in the order they are registered.
*
* @see DomListenerRegistration
*
* @param eventType
* the type of event to listen to, not <code>null</code>
* @param listener
* the listener to add, not <code>null</code>
* @return a handle that can be used for configuring or removing the
* listener
*/
public DomListenerRegistration addEventListener(String eventType,
DomEventListener listener) {
if (eventType == null) {
throw new IllegalArgumentException(EVENT_TYPE_MUST_NOT_BE_NULL);
}
if (listener == null) {
throw new IllegalArgumentException("Listener must not be null");
}
return getStateProvider().addEventListener(getNode(), eventType,
listener);
}
/**
* Adds an event listener and event data expressions for the given event
* type.
* <p>
* When an event is fired in the browser, custom JavaScript expressions
* defined in the <code>eventDataExpressions</code> parameter are evaluated
* to extract data that is sent back to the server. The expression is
* evaluated in a context where <code>element</code> refers to this element
* and <code>event</code> refers to the fired event. The result of the
* evaluation is available in {@link DomEvent#getEventData()} with the
* expression as the key in the JSON object. An expression might be e.g.
*
* <ul>
* <li><code>element.value</code> the get the value of an input element for
* a change event.
* <li><code>event.button === 0</code> to get true for click events
* triggered by the primary mouse button.
* </ul>
* <p>
* Event listeners are triggered in the order they are registered.
*
* @param eventType
* the type of event to listen to, not <code>null</code>
* @param listener
* the listener to add, not <code>null</code>
* @param eventDataExpressions
* definitions for data that should be passed back to the server
* together with the event
* @return a handle that can be used for configuring or removing the
* listener
*
* @deprecated Instead, use the returned registration instance for adding
* event data expressions
*/
@Deprecated
public DomListenerRegistration addEventListener(String eventType,
DomEventListener listener, String... eventDataExpressions) {
if (eventDataExpressions == null) {
throw new IllegalArgumentException(
"The event data expressions array must not be null");
}
DomListenerRegistration registration = addEventListener(eventType,
listener);
Stream.of(eventDataExpressions).forEach(registration::addEventData);
return registration;
}
/**
* Removes this element from its parent.
* <p>
* Has no effect if the element does not have a parent
*
* @return this element
*/
public Element removeFromParent() {
Node<?> parent = getParentNode();
if (parent != null) {
parent.removeChild(this);
}
return this;
}
/**
* Gets the parent element.
* <p>
* The method may return {@code null} if the parent is not an element but a
* {@link Node}.
*
* @see #getParentNode()
*
* @return the parent element or null if this element does not have a parent
* or the parent is not an element
*/
public Element getParent() {
Node<?> parent = getParentNode();
if (parent instanceof Element) {
return (Element) parent;
}
return null;
}
/**
* Sets the given property to the given string value.
* <p>
* Note in order to update the following properties, you need to use the
* specific API for that:
* <table>
* <caption>Properties with different API</caption>
* <tr>
* <th>Property</th>
* <th>Method</th>
* </tr>
* <tr>
* <td>classList / className</td>
* <td>{@link Element#getClassList()}</td>
* </tr>
* <tr>
* <td>style</td>
* <td>{@link Element#getStyle()}</td>
* </tr>
* <tr>
* <td>textContent</td>
* <td>{@link Element#getText()} and {@link Element#getTextRecursively()}
* </td>
* </tr>
* </table>
* <p>
* Note that properties changed on the server are updated on the client but
* changes made on the client side are not reflected back to the server
* unless configured using {@link #addSynchronizedProperty(String)} and
* {@link #addSynchronizedPropertyEvent(String)}.
* <p>
* The "innerHTML" property has an impact on the descendants structure of
* the element. So setting the "innerHTML" property removes all the
* children.
*
* @param name
* the property name, not <code>null</code>
* @param value
* the property value
* @return this element
*/
public Element setProperty(String name, String value) {
return setRawProperty(name, value);
}
/**
* Sets the given property to the given boolean value.
* <p>
* Note that properties changed on the server are updated on the client but
* changes made on the client side are not reflected back to the server
* unless configured using {@link #addSynchronizedProperty(String)} and
* {@link #addSynchronizedPropertyEvent(String)}.
*
* @param name
* the property name, not <code>null</code>
* @param value
* the property value
* @return this element
*/
public Element setProperty(String name, boolean value) {
return setRawProperty(name, Boolean.valueOf(value));
}
/**
* Sets the given property to the given numeric value.
* <p>
* Note that properties changed on the server are updated on the client but
* changes made on the client side are not reflected back to the server
* unless configured using {@link #addSynchronizedProperty(String)} and
* {@link #addSynchronizedPropertyEvent(String)}.
*
* @param name
* the property name, not <code>null</code>
* @param value
* the property value
* @return this element
*/
public Element setProperty(String name, double value) {
return setRawProperty(name, Double.valueOf(value));
}
/**
* Sets the given property to the given JSON value.
* <p>
* Please note that this method does not accept <code>null</code> as a
* value, since {@link Json#createNull()} should be used instead for JSON
* values.
* <p>
* Note that properties changed on the server are updated on the client but
* changes made on the client side are not reflected back to the server
* unless configured using {@link #addSynchronizedProperty(String)} and
* {@link #addSynchronizedPropertyEvent(String)}.
*
* @param name
* the property name, not <code>null</code>
* @param value
* the property value, not <code>null</code>
* @return this element
*/
// Distinct name so setProperty("foo", null) is not ambiguous
public Element setPropertyJson(String name, JsonValue value) {
if (value == null) {
throw new IllegalArgumentException(
"Json.createNull() must be used instead of null for JSON values");
}
setRawProperty(name, value);
return this;
}
/**
* Adds a property change listener.
* <p>
* Use either two way Polymer binding or synchronize property explicitly to
* be able to get property change events from the client.
*
* @see #synchronizeProperty(String, String)
* @param name
* the property name to add the listener for
* @param listener
* listener to get notifications about property value changes
* @return an event registration handle for removing the listener
*/
public Registration addPropertyChangeListener(String name,
PropertyChangeListener listener) {
return getStateProvider().addPropertyChangeListener(getNode(), name,
listener);
}
private Element setRawProperty(String name, Serializable value) {
verifySetPropertyName(name);
if ("innerHTML".equals(name)) {
removeAllChildren();
}
getStateProvider().setProperty(getNode(), name, value, true);
return this;
}
private static void verifySetPropertyName(String name) {
if (name == null) {
throw new IllegalArgumentException(
"A property name cannot be null");
}
String replacement = illegalPropertyReplacements.get(name);
if (replacement != null) {
throw new IllegalArgumentException("Can't set " + name
+ " as a property, use " + replacement + " instead.");
}
}
/**
* Gets the value of the given property as a string. The returned value is
* converted to a string if it has been set as some other type.
*
* @param name
* the property name, not <code>null</code>
* @param defaultValue
* the value to return if the property is not set, or if the
* value is <code>null</code>
* @return the property value
*/
public String getProperty(String name, String defaultValue) {
Object value = getPropertyRaw(name);
if (value == null) {
return defaultValue;
} else if (value instanceof JsonValue) {
return ((JsonValue) value).toJson();
} else if (value instanceof Number) {
double doubleValue = ((Number) value).doubleValue();
int intValue = (int) doubleValue;
// Special comparison to keep sonarqube happy
if (Double.doubleToRawLongBits(doubleValue - intValue) == 0) {
// Java adds ".0" at the end of integer-ish doubles
return Integer.toString(intValue);
} else {
return Double.toString(doubleValue);
}
} else {
return value.toString();
}
}
/**
* Gets the value of the given property as a string.
*
* @param name
* the property name, not <code>null</code>
* @return the property value, or <code>null</code> if no value is set
*/
public String getProperty(String name) {
return getProperty(name, null);
}
/**
* Gets the value of the given property as a boolean, or the given default
* value if the underlying value is <code>null</code>.
* <p>
* A value defined as some other type than boolean is converted according to
* JavaScript semantics:
* <ul>
* <li>String values are <code>true</code>, except for the empty string.
* <li>Numerical values are <code>true</code>, except for 0 and
* <code>NaN</code>.
* <li>JSON object and JSON array values are always <code>true</code>.
* </ul>
*
* @param name
* the property name, not <code>null</code>
* @param defaultValue
* the value to return if the property is not set, or if the
* value is <code>null</code>
* @return the property value
*/
public boolean getProperty(String name, boolean defaultValue) {
Object value = getPropertyRaw(name);
if (value == null) {
return defaultValue;
} else {
return JavaScriptSemantics.isTrueish(value);
}
}
/**
* Gets the value of the given property as a double, or the given default
* value if the underlying value is <code>null</code>
* <p>
* A value defined as some other type than double is converted according to
* JavaScript semantics:
* <ul>
* <li>String values are parsed to a number. <code>NaN</code> is returned if
* the string can't be parsed.
* <li>boolean <code>true</code> is 1, boolean <code>false</code> is 0.
* <li>JSON object and JSON array values are always <code>NaN</code>.
* </ul>
*
* @param name
* the property name, not <code>null</code>
* @param defaultValue
* the value to return if the property is not set, or if the
* value is <code>null</code>
* @return the property value
*/
public double getProperty(String name, double defaultValue) {
Object value = getPropertyRaw(name);
if (value == null) {
return defaultValue;
} else if (value instanceof Number) {
Number number = (Number) value;
return number.doubleValue();
} else if (value instanceof JsonValue) {
return ((JsonValue) value).asNumber();
} else if (value instanceof Boolean) {
return ((Boolean) value).booleanValue() ? 1 : 0;
} else if (value instanceof String) {
String string = (String) value;
if (string.isEmpty()) {
return 0;
} else {
try {
return Double.parseDouble(string);
} catch (NumberFormatException ignore) {
return Double.NaN;
}
}
} else {
throw new IllegalStateException(
"Unsupported property type: " + value.getClass());
}
}
/**
* Gets the value of the given property as an integer, or the given default
* value if the underlying value is <code>null</code>
* <p>
* The value is converted in the same way as for
* {@link #getProperty(String, double)}, and then truncated to
* <code>int</code>.
*
* @param name
* the property name, not <code>null</code>
* @param defaultValue
* the value to return if the property is not set, or if the
* value is <code>null</code>
* @return the property value
*/
public int getProperty(String name, int defaultValue) {
return (int) getProperty(name, (double) defaultValue);
}
/**
* Gets the raw property value without any value conversion. The type of the
* value is {@link String}, {@link Double}, {@link Boolean} or
* {@link JsonValue}. <code>null</code> is returned if there is no property
* with the given name or if the value is set to <code>null</code>.
*
* @param name
* the property name, not null
* @return the raw property value, or <code>null</code>
*/
public Serializable getPropertyRaw(String name) {
return getStateProvider().getProperty(getNode(), name);
}
/**
* Removes the given property.
* <p>
* Note that properties changed on the server are updated on the client but
* changes made on the client side are not reflected back to the server
* unless configured using {@link #addSynchronizedProperty(String)} and
* {@link #addSynchronizedPropertyEvent(String)}.
*
* @param name
* the property name, not <code>null</code>
* @return this element
*/
public Element removeProperty(String name) {
getStateProvider().removeProperty(getNode(), name);
return this;
}
/**
* Checks whether this element has a property with the given name.
* <p>
* Note that properties changed on the server are updated on the client but
* changes made on the client side are not reflected back to the server
* unless configured using {@link #addSynchronizedProperty(String)} and
* {@link #addSynchronizedPropertyEvent(String)}.
*
* @param name
* the property name, not <code>null</code>
* @return <code>true</code> if the property is present; otherwise
* <code>false</code>
*/
public boolean hasProperty(String name) {
return getStateProvider().hasProperty(getNode(), name);
}
/**
* Gets the defined property names.
* <p>
* Note that properties changed on the server are updated on the client but
* changes made on the client side are not reflected back to the server
* unless configured using {@link #addSynchronizedProperty(String)} and
* {@link #addSynchronizedPropertyEvent(String)}.
*
* @return a stream of defined property names
*/
public Stream<String> getPropertyNames() {
return getStateProvider().getPropertyNames(getNode());
}
/**
* Checks whether this element represents a text node.
*
* @return <code>true</code> if this element is a text node; otherwise
* <code>false</code>
*/
public boolean isTextNode() {
return getStateProvider().isTextNode(getNode());
}
/**
* Sets the text content of this element, replacing any existing children.
*
* @param textContent
* the text content to set, <code>null</code> is interpreted as
* an empty string
* @return this element
*/
public Element setText(String textContent) {
if (textContent == null) {
// Browsers work this way
textContent = "";
}
if (isTextNode()) {
getStateProvider().setTextContent(getNode(), textContent);
} else {
if (textContent.isEmpty()) {
removeAllChildren();
} else {
setTextContent(textContent);
}
}
return this;
}
private void setTextContent(String textContent) {
Element child;
if (getChildCount() == 1 && getChild(0).isTextNode()) {
child = getChild(0).setText(textContent);
} else {
child = createText(textContent);
}
removeAllChildren();
appendChild(child);
}
/**
* Gets the text content of this element. This includes only the text from
* any immediate child text nodes, but ignores text inside child elements.
* Use {@link #getTextRecursively()} to get the full text that recursively
* includes the text content of the entire element tree.
*