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