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