use crate::geometry::Rect;
use strata_style::types::Clear;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExclusionKind {
FloatLeft,
FloatRight,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ExclusionRect {
pub bounds: Rect,
pub kind: ExclusionKind,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineOpportunity {
pub start_x: f32,
pub available_width: f32,
pub left_float_edge: f32,
pub right_float_edge: f32,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ExclusionSpace {
exclusions: Vec<ExclusionRect>,
}
impl ExclusionSpace {
pub fn new() -> Self {
Self {
exclusions: Vec::new(),
}
}
pub fn add_exclusion(&mut self, bounds: Rect, kind: ExclusionKind) {
self.exclusions.push(ExclusionRect { bounds, kind });
}
pub fn is_empty(&self) -> bool {
self.exclusions.is_empty()
}
pub fn exclusions(&self) -> &[ExclusionRect] {
&self.exclusions
}
pub fn line_opportunity(&self, y: f32, height: f32, container_width: f32) -> LineOpportunity {
if self.exclusions.is_empty() {
return LineOpportunity {
start_x: 0.0,
available_width: container_width.max(0.0),
left_float_edge: 0.0,
right_float_edge: container_width,
};
}
let line_top = y;
let line_bottom = y + height.max(0.001);
let mut left_edge: f32 = 0.0;
let mut right_edge: f32 = container_width;
for e in &self.exclusions {
let float_top = e.bounds.y;
let float_bottom = e.bounds.y + e.bounds.height;
if float_top < line_bottom && float_bottom > line_top {
match e.kind {
ExclusionKind::FloatLeft => {
let r = e.bounds.x + e.bounds.width;
if r > left_edge {
left_edge = r;
}
}
ExclusionKind::FloatRight => {
let l = e.bounds.x;
if l < right_edge {
right_edge = l;
}
}
}
}
}
let avail = if right_edge > left_edge {
right_edge - left_edge
} else {
0.0
};
LineOpportunity {
start_x: left_edge,
available_width: avail,
left_float_edge: left_edge,
right_float_edge: right_edge,
}
}
pub fn clearance_offset(&self, clear: Clear, current_y: f32) -> f32 {
if self.exclusions.is_empty() || clear == Clear::None {
return current_y;
}
let mut cleared_y = current_y;
for e in &self.exclusions {
let matches = match clear {
Clear::None => false,
Clear::Left | Clear::InlineStart => e.kind == ExclusionKind::FloatLeft,
Clear::Right | Clear::InlineEnd => e.kind == ExclusionKind::FloatRight,
Clear::Both => true,
};
if matches {
let bottom = e.bounds.y + e.bounds.height;
if bottom > cleared_y {
cleared_y = bottom;
}
}
}
cleared_y
}
pub fn max_float_bottom(&self) -> f32 {
self.exclusions
.iter()
.map(|e| e.bounds.y + e.bounds.height)
.fold(0.0, f32::max)
}
pub fn next_float_bottom_after(&self, y: f32) -> Option<f32> {
let mut best: Option<f32> = None;
for e in &self.exclusions {
let bottom = e.bounds.y + e.bounds.height;
if bottom > y + 0.01 {
match best {
Some(b) => {
if bottom < b {
best = Some(bottom);
}
}
None => best = Some(bottom),
}
}
}
best
}
pub fn translate(&mut self, dx: f32, dy: f32) {
for e in &mut self.exclusions {
e.bounds.x += dx;
e.bounds.y += dy;
}
}
}