Add a column cursor for the two-column page builder
This commit is contained in:
1 parent
f8dc31cae6
commit
9ae7353376
2 files changed
+84
No files matched your search
@@ -0,0 +1,83 @@
|
||||
//! Column/page cursor for two-column body layout.
|
||||
//!
|
||||
//! The cursor owns the vertical position inside a column and performs the
|
||||
//! column-then-page transitions. It is intentionally independent of block
|
||||
//! kinds so the page builder can share one transition rule for paragraphs,
|
||||
//! lists, equations, and tables.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct ColumnCursor {
|
||||
pub page: usize,
|
||||
pub column: usize,
|
||||
pub y: i64,
|
||||
pub columns: usize,
|
||||
pub column_top: i64,
|
||||
pub page_goal: i64,
|
||||
}
|
||||
|
||||
impl ColumnCursor {
|
||||
pub(crate) fn new(columns: usize, column_top: i64, page_goal: i64) -> Self {
|
||||
Self {
|
||||
page: 0,
|
||||
column: 0,
|
||||
y: column_top,
|
||||
columns: columns.max(1),
|
||||
column_top,
|
||||
page_goal,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true when the height no longer fits and the cursor moved to the
|
||||
/// next column or page. The caller is responsible for starting a new page
|
||||
/// when reports true.
|
||||
pub(crate) fn advance(&mut self, height: i64) -> bool {
|
||||
if self.y.saturating_add(height) <= self.page_goal {
|
||||
self.y = self.y.saturating_add(height);
|
||||
return false;
|
||||
}
|
||||
if self.column + 1 < self.columns {
|
||||
self.column += 1;
|
||||
self.y = self.column_top;
|
||||
} else {
|
||||
self.page += 1;
|
||||
self.column = 0;
|
||||
self.y = self.column_top;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn moved_to_page(&self, previous_page: usize) -> bool {
|
||||
self.page != previous_page
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ColumnCursor;
|
||||
|
||||
#[test]
|
||||
fn advance_keeps_the_cursor_in_the_current_column_while_it_fits() {
|
||||
let mut cursor = ColumnCursor::new(2, 25, 100);
|
||||
assert!(!cursor.advance(40));
|
||||
assert_eq!((cursor.page, cursor.column, cursor.y), (0, 0, 65));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advance_switches_to_the_second_column_on_overflow() {
|
||||
let mut cursor = ColumnCursor::new(2, 25, 100);
|
||||
assert!(!cursor.advance(60));
|
||||
assert!(cursor.advance(20));
|
||||
assert_eq!((cursor.page, cursor.column, cursor.y), (0, 1, 25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advance_starts_a_new_page_after_the_last_column() {
|
||||
let mut cursor = ColumnCursor::new(2, 25, 100);
|
||||
assert!(!cursor.advance(50));
|
||||
assert!(cursor.advance(60));
|
||||
assert!(cursor.advance(80));
|
||||
assert_eq!((cursor.page, cursor.column, cursor.y), (1, 0, 25));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user