add: preload scripts (#6)

This commit is contained in:
elm
2025-08-19 19:54:19 +09:00
committed by GitHub
parent 1d3512c6b8
commit 6031e1c9d4
6 changed files with 182 additions and 52 deletions

View File

@@ -9,7 +9,9 @@ impl Plugin for WebviewCoreComponentsPlugin {
app.register_type::<WebviewSize>()
.register_type::<CefWebviewUri>()
.register_type::<HostWindow>()
.register_type::<ZoomLevel>();
.register_type::<ZoomLevel>()
.register_type::<AudioMuted>()
.register_type::<PreloadScripts>();
}
}
@@ -21,7 +23,7 @@ impl Plugin for WebviewCoreComponentsPlugin {
/// Alternatively, you can also use [`CefWebviewUri::local`].
#[derive(Component, Debug, Clone, PartialEq, Eq, Hash, Reflect)]
#[reflect(Component, Debug)]
#[require(WebviewSize, ZoomLevel, AudioMuted)]
#[require(WebviewSize, ZoomLevel, AudioMuted, PreloadScripts)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
pub struct CefWebviewUri(pub String);
@@ -78,3 +80,20 @@ pub struct ZoomLevel(pub f64);
#[derive(Reflect, Component, Debug, Copy, Clone, PartialEq, Default, Serialize, Deserialize)]
#[reflect(Component, Debug, Default, Serialize, Deserialize)]
pub struct AudioMuted(pub bool);
/// This component is used to preload scripts in the webview.
///
/// Scripts specified in this component are executed before the scripts in the HTML.
#[derive(Reflect, Component, Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[reflect(Component, Debug, Default, Serialize, Deserialize)]
pub struct PreloadScripts(pub Vec<String>);
impl<L, S> From<L> for PreloadScripts
where
L: IntoIterator<Item = S>,
S: Into<String>,
{
fn from(scripts: L) -> Self {
Self(scripts.into_iter().map(Into::into).collect())
}
}

View File

@@ -1,5 +1,6 @@
use crate::common::{CefWebviewUri, HostWindow, IpcEventRawSender, WebviewSize};
use crate::cursor_icon::SystemCursorIconSender;
use crate::prelude::PreloadScripts;
use crate::webview::mesh::MeshWebviewPlugin;
use bevy::ecs::component::HookContext;
use bevy::ecs::world::DeferredWorld;
@@ -104,13 +105,19 @@ fn create_webview(
cursor_icon_sender: Res<SystemCursorIconSender>,
winit_windows: NonSend<WinitWindows>,
webviews: Query<
(Entity, &CefWebviewUri, &WebviewSize, Option<&HostWindow>),
(
Entity,
&CefWebviewUri,
&WebviewSize,
&PreloadScripts,
Option<&HostWindow>,
),
Added<CefWebviewUri>,
>,
primary_window: Query<Entity, With<PrimaryWindow>>,
) {
for (entity, uri, size, parent) in webviews.iter() {
let host_window = parent
for (entity, uri, size, initialize_scripts, host_window) in webviews.iter() {
let host_window = host_window
.and_then(|w| winit_windows.get_window(w.0))
.or_else(|| winit_windows.get_window(primary_window.single().ok()?))
.and_then(|w| {
@@ -125,6 +132,7 @@ fn create_webview(
ipc_event_sender.0.clone(),
brp_sender.clone(),
cursor_icon_sender.clone(),
&initialize_scripts.0,
host_window,
);
}