script/dom/closewatcher/internalclosewatcher.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::Cell;
6use std::ptr;
7use std::rc::Rc;
8
9use js::context::{JSContext, NoGC};
10use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
11use script_bindings::inheritance::Castable;
12use script_bindings::root::Dom;
13
14use crate::dom::CloseWatcher;
15use crate::dom::bindings::reflector::DomGlobal;
16use crate::dom::event::{Event, EventBubbles, EventCancelable};
17use crate::dom::eventtarget::EventTarget;
18use crate::dom::html::htmlelement::HTMLElement;
19use crate::dom::htmldialogelement::HTMLDialogElement;
20use crate::dom::window::Window;
21
22/// <https://html.spec.whatwg.org/multipage/#close-watcher>
23#[derive(JSTraceable, MallocSizeOf, PartialEq)]
24#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
25#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
26pub(crate) struct InternalCloseWatcher {
27 /// <https://html.spec.whatwg.org/multipage/#close-watcher-window>
28 window: Dom<Window>,
29 /// <https://html.spec.whatwg.org/multipage/#close-watcher-is-running-cancel>
30 is_running_cancel_action: Cell<bool>,
31
32 /// <https://html.spec.whatwg.org/multipage/#close-watcher-cancel-action>
33 /// <https://html.spec.whatwg.org/multipage/#close-watcher-close-action>
34 /// <https://html.spec.whatwg.org/multipage/#close-watcher-get-enabled-state>
35 owner: InternalCloseWatcherOwner,
36}
37
38impl InternalCloseWatcher {
39 pub(crate) fn new(window: &Window, owner: &InternalCloseWatcherOwner) -> Self {
40 Self {
41 window: Dom::from_ref(window),
42 is_running_cancel_action: Cell::new(false),
43 owner: owner.clone(),
44 }
45 }
46
47 /// <https://html.spec.whatwg.org/multipage/#close-watcher-active>
48 pub(crate) fn is_active(&self) -> bool {
49 // > A close watcher closeWatcher is active if closeWatcher's window's close watcher manager
50 // > contains any list which contains closeWatcher.
51 self.window
52 .close_watcher_manager()
53 .groups()
54 .iter()
55 .flatten()
56 .any(|watcher| ptr::eq(Rc::as_ptr(watcher), self))
57 }
58
59 /// <https://html.spec.whatwg.org/multipage/#establish-a-close-watcher>
60 pub(crate) fn establish(
61 no_gc: &NoGC,
62 window: &Window,
63 owner: &InternalCloseWatcherOwner,
64 ) -> Rc<InternalCloseWatcher> {
65 // Step 1. Assert: window's associated Document is fully active.
66 assert!(window.Document().is_fully_active());
67
68 // Step 2. Let closeWatcher be a new close watcher, with
69 // - window: window
70 // - cancel action: cancelAction
71 // - close action: closeAction
72 // - is running cancel action: false
73 // - get enabled state: getEnabledState
74 let close_watcher = Rc::new(Self::new(window, owner));
75
76 // Step 3. Let manager be window's close watcher manager.
77 let manager = window.close_watcher_manager();
78 let mut groups = manager.groups_mut(no_gc);
79
80 // Step 4. If manager's groups's size is less than manager's allowed number of groups, then
81 // append « closeWatcher » to manager's groups.
82 if groups.len() < manager.allowed_number_of_groups() {
83 groups.push(vec![close_watcher.clone()])
84 }
85 // Step 5. Otherwise:
86 else {
87 // Step 5.1. Assert: manager's groups's size is at least 1 in this branch, since
88 // manager's allowed number of groups is always at least 1.
89 assert!(!groups.is_empty());
90
91 // Step 5.2. Append closeWatcher to manager's groups's last item.
92 groups
93 .last_mut()
94 .expect("There is at least one group at this point")
95 .push(close_watcher.clone());
96 }
97
98 // Step 6. Set manager's next user interaction allows a new group to true.
99 manager.set_next_user_interaction_allows_a_new_group(true);
100
101 // Step 7. Return closeWatcher.
102 close_watcher
103 }
104
105 /// <https://html.spec.whatwg.org/multipage/#close-watcher-request-close>
106 pub(crate) fn request_to_close(
107 &self,
108 cx: &mut JSContext,
109 require_history_action_activation: bool,
110 ) -> bool {
111 // Step 1. If closeWatcher is not active, then return true.
112 if !self.is_active() {
113 return true;
114 }
115
116 // Step 2. If the result of running closeWatcher's get enabled state is false, then return
117 // true.
118 if !self.get_enabled_state() {
119 return true;
120 }
121
122 // Step 3. If closeWatcher's is running cancel action is true, then return true.
123 if self.is_running_cancel_action.get() {
124 return true;
125 }
126
127 // Step 4. Let window be closeWatcher's window.
128 let window = &self.window;
129
130 // Step 5. If window's associated Document is not fully active, then return true.
131 if !window.Document().is_fully_active() {
132 return true;
133 }
134
135 // Step 6. Let canPreventClose be true if requireHistoryActionActivation is false, or if
136 // window's close watcher manager's groups's size is less than window's close watcher
137 // manager's allowed number of groups, and window has history-action activation;
138 // otherwise false.
139 let can_prevent_close = !require_history_action_activation || {
140 let manager = window.close_watcher_manager();
141 manager.groups().len() < manager.allowed_number_of_groups() &&
142 window.has_history_action_activation()
143 };
144
145 // Step 7. Set closeWatcher's is running cancel action to true.
146 self.is_running_cancel_action.set(true);
147
148 // Step 8. Let shouldContinue be the result of running closeWatcher's cancel action given
149 // canPreventClose.
150 let should_continue = self.cancel_action(cx, can_prevent_close);
151
152 // Step 9. Set closeWatcher's is running cancel action to false.
153 self.is_running_cancel_action.set(false);
154
155 // Step 10. If shouldContinue is false, then:
156 if !should_continue {
157 // Step 10.1. Assert: canPreventClose is true.
158 assert!(can_prevent_close);
159
160 // Step 10.2. Consume history-action user activation given window.
161 window.consume_history_action_user_activation();
162
163 // Step 10.3. Return false.
164 return false;
165 }
166
167 // Step 11. Close closeWatcher.
168 self.close(cx);
169
170 // Step 12. Return true.
171 true
172 }
173
174 /// <https://html.spec.whatwg.org/multipage/#close-watcher-close>
175 pub(crate) fn close(&self, cx: &mut JSContext) {
176 // Step 1. If closeWatcher is not active, then return.
177 if !self.is_active() {
178 return;
179 }
180
181 // Step 2. If the result of running closeWatcher's get enabled state is false, then return.
182 if !self.get_enabled_state() {
183 return;
184 }
185
186 // Step 3. If closeWatcher's window's associated Document is not fully active, then return.
187 if !self.window.Document().is_fully_active() {
188 return;
189 }
190
191 // Step 4. Destroy closeWatcher.
192 self.destroy(cx.no_gc());
193
194 // Step 5. Run closeWatcher's close action.
195 self.close_action(cx)
196 }
197
198 /// <https://html.spec.whatwg.org/multipage/#close-watcher-destroy>
199 pub(crate) fn destroy(&self, no_gc: &NoGC) {
200 // Step 1. Let manager be closeWatcher's window's close watcher manager.
201 let manager = self.window.close_watcher_manager();
202 let mut groups = manager.groups_mut(no_gc);
203
204 // Step 2. For each group of manager's groups: remove closeWatcher from group.
205 for group in groups.iter_mut() {
206 group.retain(|watcher| !ptr::eq(Rc::as_ptr(watcher), self))
207 }
208
209 // Step 3. Remove any item from manager's groups that is empty.
210 groups.retain(|group| !group.is_empty())
211 }
212
213 /// <https://html.spec.whatwg.org/multipage/#create-close-watcher-cancelaction>
214 pub(crate) fn cancel_action(&self, cx: &mut JSContext, can_prevent_close: bool) -> bool {
215 match &self.owner {
216 InternalCloseWatcherOwner::CloseWatcher(close_watcher) => {
217 // https://html.spec.whatwg.org/multipage/#the-closewatcher-interface:create-close-watcher-cancelaction
218 // > cancelAction given canPreventClose being to return the result of firing an event
219 // > named cancel at this, with the cancelable attribute initialized to
220 // > canPreventClose
221 let event = Event::new(
222 cx,
223 &self.window.global(),
224 atom!("cancel"),
225 EventBubbles::DoesNotBubble,
226 if can_prevent_close {
227 EventCancelable::Cancelable
228 } else {
229 EventCancelable::NotCancelable
230 },
231 );
232 event.fire(cx, close_watcher.upcast::<EventTarget>())
233 },
234 InternalCloseWatcherOwner::Dialog(dialog) => {
235 // https://html.spec.whatwg.org/multipage/#the-dialog-element:create-close-watcher-cancelaction
236 // > cancelAction given canPreventClose being to return the result of firing an event
237 // > named cancel at dialog, with the cancelable attribute initialized to
238 // > canPreventClose.
239 let event = Event::new(
240 cx,
241 &self.window.global(),
242 atom!("cancel"),
243 EventBubbles::DoesNotBubble,
244 if can_prevent_close {
245 EventCancelable::Cancelable
246 } else {
247 EventCancelable::NotCancelable
248 },
249 );
250 event.fire(cx, dialog.upcast::<EventTarget>())
251 },
252 // https://html.spec.whatwg.org/multipage/#show-popover
253 // > cancelAction being to return true.
254 InternalCloseWatcherOwner::Popover(_) => true,
255 }
256 }
257
258 /// <https://html.spec.whatwg.org/multipage/#create-close-watcher-closeaction>
259 pub(crate) fn close_action(&self, cx: &mut JSContext) {
260 match &self.owner {
261 InternalCloseWatcherOwner::CloseWatcher(close_watcher) => {
262 // https://html.spec.whatwg.org/multipage/#the-closewatcher-interface:create-close-watcher-closeaction
263 // > closeAction being to fire an event named close at this.
264 let event = Event::new(
265 cx,
266 &self.window.global(),
267 atom!("close"),
268 EventBubbles::DoesNotBubble,
269 EventCancelable::NotCancelable,
270 );
271 event.fire(cx, close_watcher.upcast::<EventTarget>());
272 },
273 InternalCloseWatcherOwner::Dialog(dialog) => {
274 // https://html.spec.whatwg.org/multipage/#the-dialog-element:create-close-watcher-closeaction
275 // > closeAction being to close the dialog given dialog, dialog's request close
276 // > return value, and dialog's request close source element.
277 dialog.close_watcher_close(cx)
278 },
279 InternalCloseWatcherOwner::Popover(popover) => {
280 // https://html.spec.whatwg.org/multipage/#show-popover
281 // > closeAction being to hide a popover given element, true, true, false, and null.
282 let _ = popover.hide_popover(cx, true, true, false, None);
283 },
284 }
285 }
286
287 /// <https://html.spec.whatwg.org/multipage/#close-watcher-get-enabled-state>
288 pub(crate) fn get_enabled_state(&self) -> bool {
289 match &self.owner {
290 // https://html.spec.whatwg.org/multipage/#the-dialog-element:create-close-watcher-getenabledstate
291 // > getEnabledState being to return true if dialog's enable close watcher
292 // > for request close is true or dialog's computed closed-by state is not None; otherwise false.
293 InternalCloseWatcherOwner::Dialog(dialog) => dialog.close_watcher_enabled_state(),
294 // https://html.spec.whatwg.org/multipage/#the-closewatcher-interface:close-watcher-get-enabled-state
295 // > getEnabledState being to return true.
296 InternalCloseWatcherOwner::CloseWatcher(_) => true,
297 // https://html.spec.whatwg.org/multipage/#show-popover
298 // > getEnabledState being to return true.
299 InternalCloseWatcherOwner::Popover(_) => true,
300 }
301 }
302}
303
304#[derive(Clone, JSTraceable, MallocSizeOf, PartialEq)]
305#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
306pub(crate) enum InternalCloseWatcherOwner {
307 /// <https://html.spec.whatwg.org/multipage/#dom-closewatcher>
308 CloseWatcher(Dom<CloseWatcher>),
309 /// <https://html.spec.whatwg.org/multipage/#set-the-dialog-close-watcher>
310 Dialog(Dom<HTMLDialogElement>),
311 /// <https://html.spec.whatwg.org/multipage/#popover-close-watcher>
312 Popover(Dom<HTMLElement>),
313}