Implement ThemeChanged for web target. (#1462)
* Implement ThemeChanged for web target. * Add TODO upstream to stdweb. Co-authored-by: Ryan G <ryanisaacg@users.noreply.github.com>
This commit is contained in:
parent
e88e8bc194
commit
d1073dcecb
9 changed files with 92 additions and 2 deletions
|
|
@ -8,7 +8,10 @@ use std::cell::RefCell;
|
|||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::{closure::Closure, JsCast};
|
||||
use web_sys::{Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, PointerEvent, WheelEvent};
|
||||
use web_sys::{
|
||||
Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, MediaQueryListEvent, PointerEvent,
|
||||
WheelEvent,
|
||||
};
|
||||
|
||||
pub struct Canvas {
|
||||
/// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained.
|
||||
|
|
@ -26,6 +29,7 @@ pub struct Canvas {
|
|||
on_mouse_wheel: Option<Closure<dyn FnMut(WheelEvent)>>,
|
||||
on_fullscreen_change: Option<Closure<dyn FnMut(Event)>>,
|
||||
wants_fullscreen: Rc<RefCell<bool>>,
|
||||
on_dark_mode: Option<Closure<dyn FnMut(MediaQueryListEvent)>>,
|
||||
}
|
||||
|
||||
impl Drop for Canvas {
|
||||
|
|
@ -77,6 +81,7 @@ impl Canvas {
|
|||
on_mouse_wheel: None,
|
||||
on_fullscreen_change: None,
|
||||
wants_fullscreen: Rc::new(RefCell::new(false)),
|
||||
on_dark_mode: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -251,6 +256,28 @@ impl Canvas {
|
|||
Some(self.add_event("fullscreenchange", move |_: Event| handler()));
|
||||
}
|
||||
|
||||
pub fn on_dark_mode<F>(&mut self, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(bool),
|
||||
{
|
||||
let window = web_sys::window().expect("Failed to obtain window");
|
||||
|
||||
self.on_dark_mode = window
|
||||
.match_media("(prefers-color-scheme: dark)")
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|media| {
|
||||
let closure = Closure::wrap(Box::new(move |event: MediaQueryListEvent| {
|
||||
handler(event.matches())
|
||||
}) as Box<dyn FnMut(_)>);
|
||||
|
||||
media
|
||||
.add_listener_with_opt_callback(Some(&closure.as_ref().unchecked_ref()))
|
||||
.map(|_| closure)
|
||||
.ok()
|
||||
});
|
||||
}
|
||||
|
||||
fn add_event<E, F>(&self, event_name: &str, mut handler: F) -> Closure<dyn FnMut(E)>
|
||||
where
|
||||
E: 'static + AsRef<web_sys::Event> + wasm_bindgen::convert::FromWasmAbi,
|
||||
|
|
|
|||
|
|
@ -38,6 +38,17 @@ impl WindowExtWebSys for Window {
|
|||
fn canvas(&self) -> HtmlCanvasElement {
|
||||
self.window.canvas().raw().clone()
|
||||
}
|
||||
|
||||
fn is_dark_mode(&self) -> bool {
|
||||
let window = web_sys::window().expect("Failed to obtain window");
|
||||
|
||||
window
|
||||
.match_media("(prefers-color-scheme: dark)")
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|media| media.matches())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn window_size() -> LogicalSize<f64> {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue