Skip to main content

script/dom/html/form_controls/
htmlprogresselement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Ref;
6
7use dom_struct::dom_struct;
8use html5ever::{LocalName, Prefix, local_name};
9use js::context::JSContext;
10use js::rust::HandleObject;
11use script_bindings::cell::DomRefCell;
12use style::selector_parser::PseudoElement;
13
14use crate::dom::bindings::codegen::Bindings::HTMLProgressElementBinding::HTMLProgressElementMethods;
15use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
16use crate::dom::bindings::inheritance::Castable;
17use crate::dom::bindings::num::Finite;
18use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
19use crate::dom::bindings::str::DOMString;
20use crate::dom::document::Document;
21use crate::dom::element::attributes::storage::AttrRef;
22use crate::dom::element::{AttributeMutation, Element};
23use crate::dom::html::htmlelement::HTMLElement;
24use crate::dom::node::virtualmethods::VirtualMethods;
25use crate::dom::node::{BindContext, Node};
26use crate::dom::nodelist::NodeList;
27use crate::dom::shadowroot::ShadowRoot;
28use crate::dom::shadowroot::ua_shadowroot::{CreateUAShadowRootForSelf, UAShadowRoot};
29
30#[dom_struct]
31pub(crate) struct HTMLProgressElement {
32    htmlelement: HTMLElement,
33    labels_node_list: MutNullableDom<NodeList>,
34    shadow_tree: DomRefCell<Option<ShadowTree>>,
35}
36
37/// Holds handles to all slots in the UA shadow tree
38#[derive(Clone, JSTraceable, MallocSizeOf)]
39#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
40struct ShadowTree {
41    progress_bar: Dom<Element>,
42}
43
44impl UAShadowRoot<ShadowTree> for HTMLProgressElement {
45    fn store_for_shadow_tree(&self, cx: &mut JSContext, shadow_root: DomRoot<ShadowRoot>) {
46        let progress_bar = self.create_element_in_ua_shadowroot(cx, local_name!("div"));
47        shadow_root
48            .upcast::<Node>()
49            .AppendChild(cx, progress_bar.upcast::<Node>())
50            .unwrap();
51        progress_bar
52            .upcast::<Node>()
53            .set_implemented_pseudo_element(PseudoElement::MozProgressBar);
54
55        let _ = self.shadow_tree.borrow_mut().insert(ShadowTree {
56            progress_bar: progress_bar.as_traced(),
57        });
58    }
59
60    fn borrow_for_shadow_tree(&self) -> Ref<'_, Option<ShadowTree>> {
61        self.shadow_tree.borrow()
62    }
63}
64
65impl HTMLProgressElement {
66    fn new_inherited(
67        local_name: LocalName,
68        prefix: Option<Prefix>,
69        document: &Document,
70    ) -> HTMLProgressElement {
71        HTMLProgressElement {
72            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
73            labels_node_list: MutNullableDom::new(None),
74            shadow_tree: Default::default(),
75        }
76    }
77
78    pub(crate) fn new(
79        cx: &mut js::context::JSContext,
80        local_name: LocalName,
81        prefix: Option<Prefix>,
82        document: &Document,
83        proto: Option<HandleObject>,
84    ) -> DomRoot<HTMLProgressElement> {
85        Node::reflect_node_with_proto(
86            cx,
87            Box::new(HTMLProgressElement::new_inherited(
88                local_name, prefix, document,
89            )),
90            document,
91            proto,
92        )
93    }
94
95    /// Update the visual width of bar
96    fn update_state(&self, cx: &mut JSContext) {
97        let shadow_tree = self.shadow_tree(cx);
98        let position = (*self.Value() / *self.Max()) * 100.0;
99        let style = format!("width: {}%", position);
100
101        shadow_tree
102            .progress_bar
103            .set_string_attribute(cx, &local_name!("style"), style.into());
104    }
105}
106
107impl HTMLProgressElementMethods<crate::DomTypeHolder> for HTMLProgressElement {
108    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
109    make_labels_getter!(Labels, labels_node_list);
110
111    /// <https://html.spec.whatwg.org/multipage/#dom-progress-value>
112    fn Value(&self) -> Finite<f64> {
113        // In case of missing `value`, parse error, or negative `value`, `value` should be
114        // interpreted as 0.  As `get_string_attribute` returns an empty string in case the
115        // attribute is missing, this case is handeled as the default of the `map_or` function.
116        //
117        // It is safe to wrap the number coming from `parse_floating_point_number` as it will
118        // return Err on inf and nan
119        self.upcast::<Element>()
120            .get_string_attribute(&local_name!("value"))
121            .parse_floating_point_number()
122            .map_or(Finite::wrap(0.0), |v| {
123                if v < 0.0 {
124                    Finite::wrap(0.0)
125                } else {
126                    Finite::wrap(v.min(*self.Max()))
127                }
128            })
129    }
130
131    /// <https://html.spec.whatwg.org/multipage/#dom-progress-value>
132    fn SetValue(&self, cx: &mut JSContext, new_val: Finite<f64>) {
133        if *new_val >= 0.0 {
134            let mut string_value = DOMString::from((*new_val).to_string());
135            string_value.set_best_representation_of_the_floating_point_number();
136            self.upcast::<Element>()
137                .set_string_attribute(cx, &local_name!("value"), string_value);
138        }
139    }
140
141    /// <https://html.spec.whatwg.org/multipage/#dom-progress-max>
142    fn Max(&self) -> Finite<f64> {
143        // In case of missing `max`, parse error, or negative `max`, `max` should be interpreted as
144        // 1.0. As `get_string_attribute` returns an empty string in case the attribute is missing,
145        // these cases are handeled by `map_or`
146        self.upcast::<Element>()
147            .get_string_attribute(&local_name!("max"))
148            .parse_floating_point_number()
149            .map_or(Finite::wrap(1.0), |m| {
150                if m <= 0.0 {
151                    Finite::wrap(1.0)
152                } else {
153                    Finite::wrap(m)
154                }
155            })
156    }
157
158    /// <https://html.spec.whatwg.org/multipage/#dom-progress-max>
159    fn SetMax(&self, cx: &mut JSContext, new_val: Finite<f64>) {
160        if *new_val > 0.0 {
161            let mut string_value = DOMString::from((*new_val).to_string());
162            string_value.set_best_representation_of_the_floating_point_number();
163            self.upcast::<Element>()
164                .set_string_attribute(cx, &local_name!("max"), string_value);
165        }
166    }
167
168    /// <https://html.spec.whatwg.org/multipage/#dom-progress-position>
169    fn Position(&self) -> Finite<f64> {
170        let value = self
171            .upcast::<Element>()
172            .get_string_attribute(&local_name!("value"));
173        if value.is_empty() {
174            Finite::wrap(-1.0)
175        } else {
176            let value = self.Value();
177            let max = self.Max();
178            // An unsafe Finite constructor might be nice here, as it's unlikely for the
179            // compiler to infer the following guarantees. It is probably premature
180            // optimization though.
181            //
182            // Safety: `ret` have to be a finite, defined number. This is the case since both
183            // value and max is finite, max > 0, and a value >> max cannot exist, as
184            // Self::Value(&self) enforces value <= max.
185            Finite::wrap(*value / *max)
186        }
187    }
188}
189
190impl VirtualMethods for HTMLProgressElement {
191    fn super_type(&self) -> Option<&dyn VirtualMethods> {
192        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
193    }
194
195    fn attribute_mutated(
196        &self,
197        cx: &mut js::context::JSContext,
198        attr: AttrRef<'_>,
199        mutation: AttributeMutation,
200    ) {
201        self.super_type()
202            .unwrap()
203            .attribute_mutated(cx, attr, mutation);
204
205        let is_important_attribute = matches!(
206            attr.local_name(),
207            &local_name!("value") | &local_name!("max")
208        );
209        if is_important_attribute {
210            self.update_state(cx);
211        }
212    }
213
214    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
215        self.super_type().unwrap().bind_to_tree(cx, context);
216
217        self.update_state(cx);
218    }
219}