script/dom/
messagechannel.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 http://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use js::rust::HandleObject;
7
8use crate::dom::bindings::codegen::Bindings::MessageChannelBinding::MessageChannelMethods;
9use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto};
10use crate::dom::bindings::root::{Dom, DomRoot};
11use crate::dom::globalscope::GlobalScope;
12use crate::dom::messageport::MessagePort;
13use crate::script_runtime::CanGc;
14
15#[dom_struct]
16pub(crate) struct MessageChannel {
17    reflector_: Reflector,
18    port1: Dom<MessagePort>,
19    port2: Dom<MessagePort>,
20}
21
22impl MessageChannel {
23    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel>
24    fn new(
25        incumbent: &GlobalScope,
26        proto: Option<HandleObject>,
27        can_gc: CanGc,
28    ) -> DomRoot<MessageChannel> {
29        // Step 1
30        let port1 = MessagePort::new(incumbent, can_gc);
31
32        // Step 2
33        let port2 = MessagePort::new(incumbent, can_gc);
34
35        incumbent.track_message_port(&port1, None);
36        incumbent.track_message_port(&port2, None);
37
38        // Step 3
39        incumbent.entangle_ports(*port1.message_port_id(), *port2.message_port_id());
40
41        // Steps 4-6
42        reflect_dom_object_with_proto(
43            Box::new(MessageChannel::new_inherited(&port1, &port2)),
44            incumbent,
45            proto,
46            can_gc,
47        )
48    }
49
50    pub(crate) fn new_inherited(port1: &MessagePort, port2: &MessagePort) -> MessageChannel {
51        MessageChannel {
52            reflector_: Reflector::new(),
53            port1: Dom::from_ref(port1),
54            port2: Dom::from_ref(port2),
55        }
56    }
57}
58
59impl MessageChannelMethods<crate::DomTypeHolder> for MessageChannel {
60    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel>
61    fn Constructor(
62        global: &GlobalScope,
63        proto: Option<HandleObject>,
64        can_gc: CanGc,
65    ) -> DomRoot<MessageChannel> {
66        MessageChannel::new(global, proto, can_gc)
67    }
68
69    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel-port1>
70    fn Port1(&self) -> DomRoot<MessagePort> {
71        DomRoot::from_ref(&*self.port1)
72    }
73
74    /// <https://html.spec.whatwg.org/multipage/#dom-messagechannel-port2>
75    fn Port2(&self) -> DomRoot<MessagePort> {
76        DomRoot::from_ref(&*self.port2)
77    }
78}