use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::hash::Hasher;
use std::rc::Rc;
use waft_foundation::{App, Key, ValueKey};
use crate::framework::{BuildContext, IntoWidget, KeyRef, WidgetRef};
use crate::widgets::basic::{KeyedSubtree, RepaintBoundary};
pub type NullableIndexedWidgetBuilder =
Rc<dyn Fn(&mut App, BuildContext, i32) -> Option<WidgetRef>>;
pub type SemanticIndexCallback = Rc<dyn Fn(&WidgetRef, i32) -> Option<i32>>;
fn default_semantic_index_callback() -> SemanticIndexCallback {
Rc::new(|_widget, local_index| Some(local_index))
}
pub trait SliverChildDelegate: Debug + 'static {
fn build(&self, app: &mut App, context: BuildContext, index: i32) -> Option<WidgetRef>;
fn estimated_child_count(&self) -> Option<i32> {
None
}
fn estimate_max_scroll_offset(
&self,
first_index: i32,
last_index: i32,
leading_scroll_offset: f64,
trailing_scroll_offset: f64,
) -> Option<f64> {
let _ = (
first_index,
last_index,
leading_scroll_offset,
trailing_scroll_offset,
);
None
}
fn did_finish_layout(&self, first_index: i32, last_index: i32) {
let _ = (first_index, last_index);
}
fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool;
fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
let _ = key;
None
}
fn as_any(&self) -> &dyn Any;
fn delegate_type(&self) -> TypeId {
self.as_any().type_id()
}
fn debug_fill_description(&self, description: &mut Vec<String>) {
if let Some(children) = self.estimated_child_count() {
description.push(format!("estimated child count: {children}"));
}
}
}
pub type SliverChildDelegateRef = Rc<dyn SliverChildDelegate>;
pub fn same_delegate(a: &SliverChildDelegateRef, b: &SliverChildDelegateRef) -> bool {
Rc::ptr_eq(a, b)
}
#[derive(Clone, Debug)]
struct SaltedValueKey(ValueKey<KeyRef>);
impl SaltedValueKey {
fn new(value: KeyRef) -> SaltedValueKey {
SaltedValueKey(ValueKey::new(value))
}
}
impl Key for SaltedValueKey {
fn eq_key(&self, other: &dyn Key) -> bool {
(other as &dyn Any)
.downcast_ref::<SaltedValueKey>()
.is_some_and(|other| *other.0.value == *self.0.value)
}
fn hash_key(&self, mut state: &mut dyn Hasher) {
use std::hash::Hash;
TypeId::of::<SaltedValueKey>().hash(&mut state);
self.0.value.hash_key(state);
}
}
fn unsalt(key: &KeyRef) -> KeyRef {
match ((&**key) as &dyn Any).downcast_ref::<SaltedValueKey>() {
Some(salted) => Rc::clone(&salted.0.value),
None => Rc::clone(key),
}
}
fn wrap_child(child: WidgetRef, add_repaint_boundaries: bool) -> WidgetRef {
let key = child
.key()
.map(|key| Rc::new(SaltedValueKey::new(Rc::clone(key))) as KeyRef);
let child = if add_repaint_boundaries {
RepaintBoundary::new().child(child).into_widget()
} else {
child
};
let subtree = KeyedSubtree::new(child);
match key {
Some(key) => subtree.key(key).into_widget(),
None => subtree.into_widget(),
}
}
pub type ChildIndexGetter = Rc<dyn Fn(&KeyRef) -> Option<i32>>;
#[derive(Clone)]
pub struct SliverChildBuilderDelegate {
pub builder: NullableIndexedWidgetBuilder,
pub child_count: Option<i32>,
pub add_automatic_keep_alives: bool,
pub add_repaint_boundaries: bool,
pub add_semantic_indexes: bool,
pub semantic_index_offset: i32,
pub semantic_index_callback: SemanticIndexCallback,
pub find_child_index_callback: Option<ChildIndexGetter>,
}
impl SliverChildBuilderDelegate {
pub fn new(
builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
) -> SliverChildBuilderDelegate {
SliverChildBuilderDelegate::from_builder(Rc::new(builder))
}
pub fn from_builder(builder: NullableIndexedWidgetBuilder) -> SliverChildBuilderDelegate {
SliverChildBuilderDelegate {
builder,
child_count: None,
add_automatic_keep_alives: true,
add_repaint_boundaries: true,
add_semantic_indexes: true,
semantic_index_offset: 0,
semantic_index_callback: default_semantic_index_callback(),
find_child_index_callback: None,
}
}
pub fn child_count(mut self, child_count: i32) -> SliverChildBuilderDelegate {
self.child_count = Some(child_count);
self
}
pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverChildBuilderDelegate {
self.add_automatic_keep_alives = value;
self
}
pub fn add_repaint_boundaries(mut self, value: bool) -> SliverChildBuilderDelegate {
self.add_repaint_boundaries = value;
self
}
pub fn add_semantic_indexes(mut self, value: bool) -> SliverChildBuilderDelegate {
self.add_semantic_indexes = value;
self
}
pub fn semantic_index_offset(mut self, value: i32) -> SliverChildBuilderDelegate {
self.semantic_index_offset = value;
self
}
pub fn semantic_index_callback(
mut self,
value: SemanticIndexCallback,
) -> SliverChildBuilderDelegate {
self.semantic_index_callback = value;
self
}
pub fn find_child_index_callback(
mut self,
value: ChildIndexGetter,
) -> SliverChildBuilderDelegate {
self.find_child_index_callback = Some(value);
self
}
pub fn into_delegate(self) -> SliverChildDelegateRef {
Rc::new(self)
}
}
impl SliverChildDelegate for SliverChildBuilderDelegate {
fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
let find_child_index_callback = self.find_child_index_callback.as_ref()?;
find_child_index_callback(&unsalt(key))
}
fn build(&self, app: &mut App, context: BuildContext, index: i32) -> Option<WidgetRef> {
if index < 0 || self.child_count.is_some_and(|count| index >= count) {
return None;
}
let child = (self.builder)(app, context, index)?;
Some(wrap_child(child, self.add_repaint_boundaries))
}
fn estimated_child_count(&self) -> Option<i32> {
self.child_count
}
fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool {
let _ = old_delegate;
true
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Debug for SliverChildBuilderDelegate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
self.debug_fill_description(&mut description);
write!(f, "SliverChildBuilderDelegate({})", description.join(", "))
}
}
pub struct SliverChildListDelegate {
pub add_automatic_keep_alives: bool,
pub add_repaint_boundaries: bool,
pub add_semantic_indexes: bool,
pub semantic_index_offset: i32,
pub semantic_index_callback: SemanticIndexCallback,
pub children: Vec<WidgetRef>,
key_to_index: Option<RefCell<KeyToIndex>>,
}
#[derive(Default)]
struct KeyToIndex {
map: HashMap<KeyRef, i32>,
cursor: usize,
}
impl SliverChildListDelegate {
pub fn new(children: Vec<WidgetRef>) -> SliverChildListDelegate {
SliverChildListDelegate {
add_automatic_keep_alives: true,
add_repaint_boundaries: true,
add_semantic_indexes: true,
semantic_index_offset: 0,
semantic_index_callback: default_semantic_index_callback(),
children,
key_to_index: Some(RefCell::default()),
}
}
pub fn fixed(children: Vec<WidgetRef>) -> SliverChildListDelegate {
SliverChildListDelegate {
key_to_index: None,
..SliverChildListDelegate::new(children)
}
}
pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverChildListDelegate {
self.add_automatic_keep_alives = value;
self
}
pub fn add_repaint_boundaries(mut self, value: bool) -> SliverChildListDelegate {
self.add_repaint_boundaries = value;
self
}
pub fn add_semantic_indexes(mut self, value: bool) -> SliverChildListDelegate {
self.add_semantic_indexes = value;
self
}
pub fn semantic_index_offset(mut self, value: i32) -> SliverChildListDelegate {
self.semantic_index_offset = value;
self
}
pub fn semantic_index_callback(
mut self,
value: SemanticIndexCallback,
) -> SliverChildListDelegate {
self.semantic_index_callback = value;
self
}
pub fn into_delegate(self) -> SliverChildDelegateRef {
Rc::new(self)
}
fn find_child_index(&self, key: &KeyRef) -> Option<i32> {
let cache = self.key_to_index.as_ref()?;
let mut cache = cache.borrow_mut();
if let Some(index) = cache.map.get(key) {
return Some(*index);
}
let mut index = cache.cursor;
while index < self.children.len() {
let child = &self.children[index];
if let Some(child_key) = child.key() {
cache.map.insert(Rc::clone(child_key), index as i32);
if **child_key == **key {
cache.cursor = index + 1;
return Some(index as i32);
}
}
index += 1;
}
cache.cursor = index;
None
}
}
impl SliverChildDelegate for SliverChildListDelegate {
fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
self.find_child_index(&unsalt(key))
}
fn build(&self, _app: &mut App, _context: BuildContext, index: i32) -> Option<WidgetRef> {
let slot = usize::try_from(index).ok()?;
let child = self.children.get(slot)?.clone();
Some(wrap_child(child, self.add_repaint_boundaries))
}
fn estimated_child_count(&self) -> Option<i32> {
Some(self.children.len() as i32)
}
fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool {
let old = old_delegate
.as_any()
.downcast_ref::<SliverChildListDelegate>()
.expect("the caller compared the delegate types first");
self.children.len() != old.children.len()
|| std::iter::zip(&self.children, &old.children).any(|(a, b)| !Rc::ptr_eq(a, b))
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Debug for SliverChildListDelegate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
self.debug_fill_description(&mut description);
write!(f, "SliverChildListDelegate({})", description.join(", "))
}
}