script/dom/html/
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, QualName, local_name, ns};
9use js::rust::HandleObject;
10
11use crate::dom::attr::Attr;
12use crate::dom::bindings::cell::DomRefCell;
13use crate::dom::bindings::codegen::Bindings::ElementBinding::Element_Binding::ElementMethods;
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::{AttributeMutation, CustomElementCreationMode, Element, ElementCreator};
22use crate::dom::html::htmlelement::HTMLElement;
23use crate::dom::node::{BindContext, Node, NodeTraits};
24use crate::dom::nodelist::NodeList;
25use crate::dom::virtualmethods::VirtualMethods;
26use crate::script_runtime::CanGc;
27
28#[dom_struct]
29pub(crate) struct HTMLProgressElement {
30    htmlelement: HTMLElement,
31    labels_node_list: MutNullableDom<NodeList>,
32    shadow_tree: DomRefCell<Option<ShadowTree>>,
33}
34
35/// Holds handles to all slots in the UA shadow tree
36#[derive(Clone, JSTraceable, MallocSizeOf)]
37#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
38struct ShadowTree {
39    progress_bar: Dom<Element>,
40}
41
42impl HTMLProgressElement {
43    fn new_inherited(
44        local_name: LocalName,
45        prefix: Option<Prefix>,
46        document: &Document,
47    ) -> HTMLProgressElement {
48        HTMLProgressElement {
49            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
50            labels_node_list: MutNullableDom::new(None),
51            shadow_tree: Default::default(),
52        }
53    }
54
55    pub(crate) fn new(
56        local_name: LocalName,
57        prefix: Option<Prefix>,
58        document: &Document,
59        proto: Option<HandleObject>,
60        can_gc: CanGc,
61    ) -> DomRoot<HTMLProgressElement> {
62        Node::reflect_node_with_proto(
63            Box::new(HTMLProgressElement::new_inherited(
64                local_name, prefix, document,
65            )),
66            document,
67            proto,
68            can_gc,
69        )
70    }
71
72    fn create_shadow_tree(&self, can_gc: CanGc) {
73        let document = self.owner_document();
74        let root = self.upcast::<Element>().attach_ua_shadow_root(true, can_gc);
75
76        let progress_bar = Element::create(
77            QualName::new(None, ns!(html), local_name!("div")),
78            None,
79            &document,
80            ElementCreator::ScriptCreated,
81            CustomElementCreationMode::Asynchronous,
82            None,
83            can_gc,
84        );
85
86        // FIXME: This should use ::-moz-progress-bar
87        progress_bar.SetId("-servo-progress-bar".into(), can_gc);
88        root.upcast::<Node>()
89            .AppendChild(progress_bar.upcast::<Node>(), can_gc)
90            .unwrap();
91
92        let _ = self.shadow_tree.borrow_mut().insert(ShadowTree {
93            progress_bar: progress_bar.as_traced(),
94        });
95        self.upcast::<Node>()
96            .dirty(crate::dom::node::NodeDamage::Other);
97    }
98
99    fn shadow_tree(&self, can_gc: CanGc) -> Ref<'_, ShadowTree> {
100        if !self.upcast::<Element>().is_shadow_host() {
101            self.create_shadow_tree(can_gc);
102        }
103
104        Ref::filter_map(self.shadow_tree.borrow(), Option::as_ref)
105            .ok()
106            .expect("UA shadow tree was not created")
107    }
108
109    /// Update the visual width of bar
110    fn update_state(&self, can_gc: CanGc) {
111        let shadow_tree = self.shadow_tree(can_gc);
112        let position = (*self.Value() / *self.Max()) * 100.0;
113        let style = format!("width: {}%", position);
114
115        shadow_tree
116            .progress_bar
117            .set_string_attribute(&local_name!("style"), style.into(), can_gc);
118    }
119}
120
121impl HTMLProgressElementMethods<crate::DomTypeHolder> for HTMLProgressElement {
122    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
123    make_labels_getter!(Labels, labels_node_list);
124
125    /// <https://html.spec.whatwg.org/multipage/#dom-progress-value>
126    fn Value(&self) -> Finite<f64> {
127        // In case of missing `value`, parse error, or negative `value`, `value` should be
128        // interpreted as 0.  As `get_string_attribute` returns an empty string in case the
129        // attribute is missing, this case is handeled as the default of the `map_or` function.
130        //
131        // It is safe to wrap the number coming from `parse_floating_point_number` as it will
132        // return Err on inf and nan
133        self.upcast::<Element>()
134            .get_string_attribute(&local_name!("value"))
135            .parse_floating_point_number()
136            .map_or(Finite::wrap(0.0), |v| {
137                if v < 0.0 {
138                    Finite::wrap(0.0)
139                } else {
140                    Finite::wrap(v.min(*self.Max()))
141                }
142            })
143    }
144
145    /// <https://html.spec.whatwg.org/multipage/#dom-progress-value>
146    fn SetValue(&self, new_val: Finite<f64>, can_gc: CanGc) {
147        if *new_val >= 0.0 {
148            let mut string_value = DOMString::from_string((*new_val).to_string());
149
150            string_value.set_best_representation_of_the_floating_point_number();
151
152            self.upcast::<Element>().set_string_attribute(
153                &local_name!("value"),
154                string_value,
155                can_gc,
156            );
157        }
158    }
159
160    /// <https://html.spec.whatwg.org/multipage/#dom-progress-max>
161    fn Max(&self) -> Finite<f64> {
162        // In case of missing `max`, parse error, or negative `max`, `max` should be interpreted as
163        // 1.0. As `get_string_attribute` returns an empty string in case the attribute is missing,
164        // these cases are handeled by `map_or`
165        self.upcast::<Element>()
166            .get_string_attribute(&local_name!("max"))
167            .parse_floating_point_number()
168            .map_or(Finite::wrap(1.0), |m| {
169                if m <= 0.0 {
170                    Finite::wrap(1.0)
171                } else {
172                    Finite::wrap(m)
173                }
174            })
175    }
176
177    /// <https://html.spec.whatwg.org/multipage/#dom-progress-max>
178    fn SetMax(&self, new_val: Finite<f64>, can_gc: CanGc) {
179        if *new_val > 0.0 {
180            let mut string_value = DOMString::from_string((*new_val).to_string());
181
182            string_value.set_best_representation_of_the_floating_point_number();
183
184            self.upcast::<Element>().set_string_attribute(
185                &local_name!("max"),
186                string_value,
187                can_gc,
188            );
189        }
190    }
191
192    /// <https://html.spec.whatwg.org/multipage/#dom-progress-position>
193    fn Position(&self) -> Finite<f64> {
194        let value = self
195            .upcast::<Element>()
196            .get_string_attribute(&local_name!("value"));
197        if value.is_empty() {
198            Finite::wrap(-1.0)
199        } else {
200            let value = self.Value();
201            let max = self.Max();
202            // An unsafe Finite constructor might be nice here, as it's unlikely for the
203            // compiler to infer the following guarantees. It is probably premature
204            // optimization though.
205            //
206            // Safety: `ret` have to be a finite, defined number. This is the case since both
207            // value and max is finite, max > 0, and a value >> max cannot exist, as
208            // Self::Value(&self) enforces value <= max.
209            Finite::wrap(*value / *max)
210        }
211    }
212}
213
214impl VirtualMethods for HTMLProgressElement {
215    fn super_type(&self) -> Option<&dyn VirtualMethods> {
216        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
217    }
218
219    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
220        self.super_type()
221            .unwrap()
222            .attribute_mutated(attr, mutation, can_gc);
223
224        let is_important_attribute = matches!(
225            attr.local_name(),
226            &local_name!("value") | &local_name!("max")
227        );
228        if is_important_attribute {
229            self.update_state(CanGc::note());
230        }
231    }
232
233    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
234        self.super_type().unwrap().bind_to_tree(context, can_gc);
235
236        self.update_state(CanGc::note());
237    }
238}