use crate::ThemeResources;
use crate::ThemeScope;
use std::{fmt, rc::Rc};
use waft_embedder::{Offset, Rect, TextDirection, ViewId};
use waft_foundation::{App, Handle, Listener, Ref};
use waft_painting::transform_rect;
use waft_scheduler::{FrameCallback, SchedulerBinding};
use waft_widgets::*;
pub struct RetainedFlyoutHost {
builder: WidgetBuilder,
entry: Option<Ref<OverlayEntry>>,
overlay: Option<Handle<OverlayState>>,
state: Option<Handle<RetainedFlyoutState>>,
target: Option<Handle<FlyoutTargetState>>,
resources: Option<Rc<ThemeResources>>,
direction: TextDirection,
open: bool,
take_focus: bool,
previous_focus: Option<AnyFocusNode>,
pub(crate) return_focus: Option<AnyFocusNode>,
disposed: bool,
rebuild_pending: bool,
epoch: u64,
pub(crate) opened: Option<Listener>,
pub(crate) closed: Option<Listener>,
pub(crate) on_dispose: Option<Listener>,
pub(crate) target_removed: Option<Listener>,
pub(crate) on_key_event: Option<FocusOnKeyEventCallback>,
}
impl fmt::Debug for RetainedFlyoutHost {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RetainedFlyoutHost")
.field("open", &self.open)
.field("disposed", &self.disposed)
.finish_non_exhaustive()
}
}
impl RetainedFlyoutHost {
pub fn new(app: &mut App, builder: WidgetBuilder) -> Ref<Self> {
app.create(Self {
builder,
entry: None,
overlay: None,
state: None,
target: None,
resources: None,
direction: TextDirection::Ltr,
open: false,
take_focus: true,
previous_focus: None,
return_focus: None,
disposed: false,
epoch: 0,
rebuild_pending: false,
opened: None,
closed: None,
target_removed: None,
on_dispose: None,
on_key_event: None,
})
}
pub fn is_open(self: Handle<Self>, app: &App) -> bool {
app.get(self).open
}
pub fn target_bounds(self: Handle<Self>, app: &App) -> Option<Rect> {
let target = app.get(self).target?;
if !target.mounted(app) {
return None;
}
let target_box = target.context(app).find_render_object(app)?.as_box()?;
let overlay = app.get(self).overlay?;
let root = overlay.context(app).find_render_object(app)?;
let transform = target_box.as_object().get_transform_to(app, Some(root));
Some(transform_rect(
&transform,
Offset::ZERO & target_box.size(app),
))
}
fn view(self: Handle<Self>, app: &App) -> Option<ViewId> {
let overlay = app.get(self).overlay?;
View::maybe_id_of(app, overlay.context(app))
}
pub fn rebuild(self: Handle<Self>, app: &mut App) {
if app.get(self).disposed {
return;
}
if SchedulerBinding::scheduler_phase(app)
== waft_scheduler::SchedulerPhase::PersistentCallbacks
{
if app.get(self).rebuild_pending {
return;
}
app.get_mut(self).rebuild_pending = true;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if app.contains(self) {
app.get_mut(self).rebuild_pending = false;
self.rebuild(app);
}
}),
self.view(app),
);
} else if let Some(state) = app.get(self).state {
state.set_state(app, |_| {});
}
}
pub fn show_at(self: Handle<Self>, app: &mut App, context: BuildContext, take_focus: bool) {
assert!(
!app.get(self).disposed,
"cannot show a disposed flyout host"
);
let target = context
.find_ancestor_state_of_type::<FlyoutTargetState>(app)
.expect("show_at requires a context beneath FlyoutTarget");
let overlay = Overlay::of(app, context, true);
if let Some(previous_overlay) = app.get(self).overlay {
assert_eq!(
previous_overlay, overlay,
"a retained flyout belongs to one root overlay"
);
}
let resources = app
.get(target)
.resources
.clone()
.expect("a built target has a theme");
let direction = app.get(target).direction;
if let Some(previous_target) = app.get(self).target
&& previous_target != target
&& app.contains(previous_target)
{
app.get_mut(previous_target)
.hosts
.retain(|host| *host != self);
}
let previous_focus = app.get(self).return_focus.or_else(|| primary_focus(app));
let already_owns_focus = app.get(self).state.is_some_and(|state| {
app.get(state)
.focus
.clone()
.unwrap()
.as_node()
.has_focus(app)
});
let host = app.get_mut(self);
host.target = Some(target);
host.resources = Some(resources);
host.direction = direction;
host.open = true;
host.take_focus = take_focus;
host.epoch += 1;
if !already_owns_focus {
host.previous_focus = previous_focus;
}
if !app.get(target).hosts.contains(&self) {
app.get_mut(target).hosts.push(self);
}
if let Some(state) = app.get(self).state {
let entry = app.get(self).entry.clone().unwrap();
overlay.rearrange(app, vec![entry.clone()], Some(entry.handle()), None);
state.set_state(app, |_| {});
state.focus_after_frame(app);
} else if app.get(self).entry.is_none() {
let entry = OverlayEntry::new(
app,
Rc::new(move |_, _| RetainedFlyoutRoot { host: self }.into_widget()),
false,
true,
false,
);
app.get_mut(self).entry = Some(entry.clone());
app.get_mut(self).overlay = Some(overlay);
overlay.insert(app, entry, None, None);
}
}
pub fn hide(self: Handle<Self>, app: &mut App) {
if app.get(self).disposed || !app.get(self).open {
return;
}
if let Some(state) = app.get(self).state {
state.restore_focus(app);
}
if let Some(target) = app.get(self).target
&& app.contains(target)
{
app.get_mut(target).hosts.retain(|host| *host != self);
}
let host = app.get_mut(self);
host.open = false;
host.target = None;
host.previous_focus = None;
host.epoch += 1;
let epoch = host.epoch;
self.rebuild(app);
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if app.contains(self)
&& !app.get(self).disposed
&& !app.get(self).open
&& app.get(self).epoch == epoch
&& let Some(closed) = app.get(self).closed.clone()
{
closed.call(app);
}
}),
self.view(app),
);
}
pub fn dispose(self: Handle<Self>, app: &mut App) {
if app.get(self).disposed {
return;
}
self.hide(app);
app.get_mut(self).disposed = true;
if let Some(entry) = app.get_mut(self).entry.take() {
entry.remove(app);
entry.dispose(app);
}
if let Some(disposed) = app.get(self).on_dispose.clone() {
disposed.call(app);
}
}
}
#[derive(Clone, Debug)]
pub struct FlyoutTarget {
pub child: WidgetRef,
pub key: Option<KeyRef>,
}
impl FlyoutTarget {
pub fn new<K>(child: impl IntoWidget<K>) -> Self {
Self {
child: child.into_widget(),
key: None,
}
}
pub fn key(mut self, key: KeyRef) -> Self {
self.key = Some(key);
self
}
}
pub struct FlyoutTargetState {
state: StateData<FlyoutTarget>,
hosts: Vec<Handle<RetainedFlyoutHost>>,
resources: Option<Rc<ThemeResources>>,
direction: TextDirection,
}
impl StatefulWidget for FlyoutTarget {
type State = FlyoutTargetState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> Self::State {
FlyoutTargetState {
state: StateData::new(),
hosts: Vec::new(),
resources: None,
direction: TextDirection::Ltr,
}
}
}
impl State for FlyoutTargetState {
type Widget = FlyoutTarget;
waft_widgets::state_accessors!();
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
let resources = ThemeResources::of(app, self.context(app));
let direction = Directionality::of(app, self.context(app));
app.get_mut(self).resources = Some(resources.clone());
app.get_mut(self).direction = direction;
let hosts = app.get(self).hosts.clone();
for host in hosts {
if app.contains(host) && !app.get(host).disposed && app.get(host).target == Some(self) {
app.get_mut(host).resources = Some(resources.clone());
app.get_mut(host).direction = direction;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if app.contains(host)
&& !app.get(host).disposed
&& let Some(state) = app.get(host).state
{
state.set_state(app, |_| {});
}
}),
View::maybe_id_of(app, self.context(app)),
);
}
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
let hosts = app.get(self).hosts.clone();
for host in hosts {
if app.contains(host) && !app.get(host).disposed && app.get(host).target == Some(self) {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if app.contains(host)
&& !app.get(host).disposed
&& app.get(host).target == Some(self)
{
if let Some(removed) = app.get(host).target_removed.clone() {
removed.call(app);
} else {
host.hide(app);
}
}
}),
None,
);
}
}
}
fn build(self: Handle<Self>, app: &mut App, _: BuildContext) -> WidgetRef {
self.widget(app).child.clone()
}
}
#[derive(Debug)]
struct RetainedFlyoutRoot {
host: Handle<RetainedFlyoutHost>,
}
struct RetainedFlyoutState {
state: StateData<RetainedFlyoutRoot>,
focus: Option<Ref<FocusScopeNode>>,
}
impl StatefulWidget for RetainedFlyoutRoot {
type State = RetainedFlyoutState;
fn create_state(&self) -> Self::State {
RetainedFlyoutState {
state: StateData::new(),
focus: None,
}
}
}
impl RetainedFlyoutState {
fn focus_after_frame(self: Handle<Self>, app: &mut App) {
let host = self.widget(app).host;
let epoch = app.get(host).epoch;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if !self.mounted(app)
|| !app.contains(host)
|| app.get(host).disposed
|| !app.get(host).open
|| app.get(host).epoch != epoch
{
return;
}
if app.get(host).take_focus {
let scope = app.get(self).focus.clone().unwrap().as_node();
let first = scope
.traversal_descendants(app)
.into_iter()
.find(|node| node.can_request_focus(app));
first.unwrap_or(scope).request_focus(app, None);
}
if let Some(opened) = app.get(host).opened.clone() {
opened.call(app);
}
}),
View::maybe_id_of(app, self.context(app)),
);
}
fn restore_focus(self: Handle<Self>, app: &mut App) {
let host = self.widget(app).host;
let previous = app.get(host).previous_focus;
if app
.get(self)
.focus
.clone()
.unwrap()
.as_node()
.has_focus(app)
&& let Some(previous) = previous.filter(|node| {
app.contains(node.id())
&& !app.is_disposed(node.id())
&& node.context(app).is_some()
&& node.can_request_focus(app)
})
{
previous.request_focus(app, None);
}
}
}
impl State for RetainedFlyoutState {
type Widget = RetainedFlyoutRoot;
waft_widgets::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let host = self.widget(app).host;
let focus = FocusScopeNode::new(app);
focus.set_traversal_edge_behavior(app, TraversalEdgeBehavior::ClosedLoop);
app.get_mut(self).focus = Some(focus);
app.get_mut(host).state = Some(self);
self.focus_after_frame(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let focus = app.get(self).focus.clone().unwrap();
focus.as_node().dispose(app);
let host = self.widget(app).host;
if app.contains(host) {
app.get_mut(host).state = None;
host.dispose(app);
}
}
fn build(self: Handle<Self>, app: &mut App, _: BuildContext) -> WidgetRef {
let host = self.widget(app).host;
let data = app.get(host);
let open = data.open;
let resources = data
.resources
.clone()
.expect("a shown flyout has a target theme");
let direction = data.direction;
let builder = data.builder.clone();
let on_key_event = data.on_key_event.clone();
let themed_content = ThemeScope::with_resources(
resources,
Directionality::new(
direction,
Builder::new(move |app, context| builder(app, context)),
),
);
let mut scope = FocusScope::new(themed_content).node(app.get(self).focus.clone().unwrap());
if let Some(handler) = on_key_event {
scope = scope.on_key_event(handler);
}
Offstage::new()
.offstage(!open)
.child(TickerMode::new(
open,
ExcludeFocus::new(scope).excluding(!open),
))
.into_widget()
}
}