webview: Add bounds method to WebView to get container bounds. (#411)

<img width="1463" alt="image"
src="https://github.com/user-attachments/assets/f70c2d6b-cb26-4cf5-bd2e-9760ff54c524">
This commit is contained in:
ihavecoke 2024-11-12 19:31:48 +08:00 committed by GitHub
parent e77578a53f
commit 40345f1e42
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 51 additions and 2 deletions

View file

@ -17,7 +17,12 @@ use ui::{
list::{List, ListDelegate, ListItem},
notification::{Notification, NotificationType},
theme::ActiveTheme as _,
v_flex, ContextModal as _, Icon, IconName, Placement,
v_flex,
webview::WebView,
ContextModal as _,
Icon,
IconName,
Placement
};
actions!(modal_story, [TestAction]);
@ -482,6 +487,35 @@ impl Render for ModalStory {
.items_start()
.gap_3()
.flex_wrap()
.child(
Button::new("webview")
.label("Open WebView")
.on_click(cx.listener(|_, _, cx| {
let webview = cx.new_view(|cx| {
let webview = ui::wry::WebViewBuilder::new()
.build_as_child(&cx.raw_window_handle())
.unwrap();
WebView::new(cx, webview)
});
webview.update(cx, |webview, _| {
webview.load_url("https://github.com");
});
cx.open_drawer(move |drawer, cx| {
let height = cx.window_bounds().get_bounds().size.height;
let webview_bounds = webview.read(cx).bounds();
let buffer_height = px(12.);
drawer
.title("WebView Title")
.child(
div()
.h(height - webview_bounds.origin.y - buffer_height)
.child(webview.clone())
)
});
})),
)
.child(
Button::new("show-drawer-left")
.label("Left Drawer...")

View file

@ -6,7 +6,7 @@ use wry::{
};
use gpui::{
div, Bounds, ContentMask, DismissEvent, Element, ElementId, EventEmitter, FocusHandle,
canvas, div, Bounds, ContentMask, DismissEvent, Element, ElementId, EventEmitter, FocusHandle,
FocusableView, GlobalElementId, Hitbox, InteractiveElement, IntoElement, LayoutId,
MouseDownEvent, ParentElement as _, Pixels, Render, Size, Style, Styled as _, View,
WindowContext,
@ -16,6 +16,7 @@ pub struct WebView {
focus_handle: FocusHandle,
webview: Rc<wry::WebView>,
visible: bool,
bounds: Bounds<Pixels>,
}
impl Drop for WebView {
@ -31,6 +32,7 @@ impl WebView {
Self {
focus_handle: cx.focus_handle(),
visible: true,
bounds: Bounds::default(),
webview: Rc::new(webview),
}
}
@ -48,6 +50,10 @@ impl WebView {
self.visible
}
pub fn bounds(&self) -> Bounds<Pixels> {
self.bounds
}
/// Go back in the webview history.
pub fn back(&mut self) -> anyhow::Result<()> {
Ok(self.webview.evaluate_script("history.back();")?)
@ -81,6 +87,15 @@ impl Render for WebView {
div()
.track_focus(&self.focus_handle)
.size_full()
.child({
let view = cx.view().clone();
canvas(
move |bounds, cx| view.update(cx, |r, _| r.bounds = bounds),
|_, _, _| {},
)
.absolute()
.size_full()
})
.child(WebViewElement::new(self.webview.clone(), view, cx))
}
}