View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html;
16  
17  import java.math.BigDecimal;
18  import java.math.RoundingMode;
19  import java.util.Map;
20  
21  import org.htmlunit.SgmlPage;
22  import org.htmlunit.util.StringUtils;
23  
24  /**
25   * Wrapper for the HTML element "input" where type is "range".
26   *
27   * @author Ahmed Ashour
28   * @author Ronald Brill
29   * @author Frank Danek
30   * @author Anton Demydenko
31   */
32  public class HtmlRangeInput extends HtmlInput implements LabelableElement {
33  
34      /**
35       * Creates an instance.
36       *
37       * @param qualifiedName the qualified name of the element type to instantiate
38       * @param page the page that contains this element
39       * @param attributes the initial attributes
40       */
41      HtmlRangeInput(final String qualifiedName, final SgmlPage page,
42              final Map<String, DomAttr> attributes) {
43          super(qualifiedName, page, attributes);
44  
45          final String value = getValueAttribute();
46          if (value == ATTRIBUTE_NOT_DEFINED) {
47              final double min = getMinNumeric();
48              final double max = getMaxNumeric();
49              if (max < min) {
50                  setValue(min);
51                  unmarkValueDirty();
52                  return;
53              }
54  
55              final double val = min + ((max - min) / 2);
56              setValue(val);
57              unmarkValueDirty();
58          }
59          else {
60              setValue(value);
61              unmarkValueDirty();
62          }
63      }
64  
65      /**
66       * Returns the numeric value of the {@code min} attribute.
67       *
68       * @return the value of the {@code min} attribute as a {@code double}, or
69       *         {@code 0} if the attribute is not defined or cannot be parsed
70       */
71      public double getMinNumeric() {
72          final String min = getAttributeDirect("min");
73          if (min == ATTRIBUTE_NOT_DEFINED) {
74              return 0;
75          }
76          try {
77              return Double.parseDouble(min);
78          }
79          catch (final NumberFormatException e) {
80              return 0;
81          }
82      }
83  
84      /**
85       * Returns the numeric value of the {@code max} attribute.
86       *
87       * @return the value of the {@code max} attribute as a {@code double}, or
88       *         {@code 100} if the attribute is not defined or cannot be parsed
89       */
90      public double getMaxNumeric() {
91          final String max = getAttributeDirect("max");
92          if (max == ATTRIBUTE_NOT_DEFINED) {
93              return 100;
94          }
95          try {
96              return Double.parseDouble(max);
97          }
98          catch (final NumberFormatException e) {
99              return 100;
100         }
101     }
102 
103     /**
104      * Returns the numeric value of the {@code step} attribute.
105      *
106      * @return the value of the {@code step} attribute as a {@code double}, or
107      *         {@code 1} if the attribute is not defined or cannot be parsed
108      */
109     public double getStepNumeric() {
110         final String step = getAttributeDirect("step");
111         if (step == ATTRIBUTE_NOT_DEFINED) {
112             return 1;
113         }
114         try {
115             return Double.parseDouble(step);
116         }
117         catch (final NumberFormatException e) {
118             return 1;
119         }
120     }
121 
122     /**
123      * {@inheritDoc}
124      */
125     @Override
126     public void setDefaultChecked(final boolean defaultChecked) {
127         // Empty.
128     }
129 
130     /**
131      * {@inheritDoc}
132      */
133     @Override
134     public void setValue(final String newValue) {
135         try {
136             if (!StringUtils.isEmptyOrNull(newValue)) {
137                 setValue(Double.parseDouble(newValue));
138             }
139             else {
140                 final double min = getMinNumeric();
141                 final double max = getMaxNumeric();
142 
143                 // place in the middle
144                 setValue(min + ((max - min) / 2));
145             }
146         }
147         catch (final NumberFormatException ignored) {
148             // ignore
149         }
150     }
151 
152     private void setValue(final double newValue) {
153         super.setValue(toValueString(newValue));
154     }
155 
156     @Override
157     protected void valueAttributeChanged(final String attributeValue, final boolean isValueDirty) {
158         if (isValueDirty) {
159             return;
160         }
161 
162         try {
163             if (!org.htmlunit.util.StringUtils.isEmptyOrNull(attributeValue)) {
164                 setRawValue(Double.parseDouble(attributeValue));
165             }
166             else {
167                 final double min = getMinNumeric();
168                 final double max = getMaxNumeric();
169 
170                 // place in the middle
171                 setRawValue(min + ((max - min) / 2));
172             }
173         }
174         catch (final NumberFormatException ignored) {
175             // ignore
176         }
177     }
178 
179     private void setRawValue(final double newValue) {
180         setRawValue(toValueString(newValue));
181     }
182 
183     /**
184      * Clamps the given value to min/max, aligns it to the step and converts it into the string
185      * representation used as value.
186      *
187      * @param newValue the value
188      * @return the value string
189      */
190     private String toValueString(final double newValue) {
191         double value = newValue;
192 
193         final double min = getMinNumeric();
194         final double max = getMaxNumeric();
195 
196         if (value > max) {
197             value = max;
198         }
199         else {
200             if (value < min) {
201                 value = min;
202             }
203         }
204 
205         final double step = getStepNumeric();
206         if (Double.isFinite(value) && Double.isFinite(min) && Double.isFinite(step) && step > 0) {
207             // decimal arithmetic; with doubles step 0.1 results in values like 0.30000000000000004
208             // and the rounding of 0.25 to the step is wrong (0.2 instead of 0.3)
209             final BigDecimal decimalMin = BigDecimal.valueOf(min);
210             final BigDecimal decimalStep = BigDecimal.valueOf(step);
211             final BigDecimal diff = BigDecimal.valueOf(value).subtract(decimalMin);
212             // round to the nearest step (ties up); below min (max < min) truncate like before
213             final BigDecimal steps = diff.divide(decimalStep, 0,
214                     diff.signum() < 0 ? RoundingMode.DOWN : RoundingMode.HALF_UP);
215             BigDecimal result = decimalMin.add(decimalStep.multiply(steps));
216             if (Double.isFinite(max) && result.compareTo(BigDecimal.valueOf(max)) > 0 && steps.signum() > 0) {
217                 // the largest value matching the step that is not greater than max
218                 result = result.subtract(decimalStep);
219             }
220             return format(result.doubleValue());
221         }
222 
223         value = value - min;
224         long fact = (long) (value / step);
225         final double rest = value % step;
226         if (rest >= step / 2) {
227             fact++;
228         }
229         value = min + step * fact;
230 
231         return format(value);
232     }
233 
234     /**
235      * Formats the given number; integral values are formatted without fraction digits
236      * (also outside of the int range).
237      *
238      * @param value the number
239      * @return the string representation
240      */
241     private static String format(final double value) {
242         if (Double.isFinite(value)) {
243             final BigDecimal decimal = BigDecimal.valueOf(value).stripTrailingZeros();
244             if (decimal.scale() <= 0) {
245                 return decimal.toPlainString();
246             }
247         }
248         return Double.toString(value);
249     }
250 
251     /**
252      * {@inheritDoc}
253      */
254     @Override
255     protected boolean isRequiredSupported() {
256         return false;
257     }
258 
259     /**
260      * {@inheritDoc}
261      */
262     @Override
263     public boolean isValid() {
264         return super.isValid() && isMaxValid() && isMinValid();
265     }
266 
267     /**
268      * Returns if the input element has a valid min value. Refer to the
269      * <a href="https://www.w3.org/TR/html5/sec-forms.html">HTML 5</a>
270      * documentation for details.
271      *
272      * @return if the input element has a valid min value
273      */
274     private boolean isMinValid() {
275         if (!getRawValue().isEmpty() && !getMin().isEmpty()) {
276             try {
277                 final double value = Double.parseDouble(getRawValue());
278                 return getMinNumeric() <= value;
279             }
280             catch (final NumberFormatException ignored) {
281                 // ignore
282             }
283         }
284         return true;
285     }
286 
287     /**
288      * Returns if the input element has a valid max value. Refer to the
289      * <a href="https://www.w3.org/TR/html5/sec-forms.html">HTML 5</a>
290      * documentation for details.
291      *
292      * @return if the input element has a valid max value
293      */
294     private boolean isMaxValid() {
295         if (!getRawValue().isEmpty() && !getMax().isEmpty()) {
296             try {
297                 final int value = Integer.parseInt(getRawValue());
298                 return getMaxNumeric() >= value;
299             }
300             catch (final NumberFormatException ignored) {
301                 // ignore
302             }
303         }
304         return true;
305     }
306 }