ltk/layout/
row.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

use crate::types::{ Length, Rect };
use crate::render::Canvas;
use crate::widget::Element;

/// A horizontal layout container.
///
/// Children are arranged left-to-right. Use [`Row::align_right`] to
/// push the content block to the right edge of the available width.
///
/// ```rust,no_run
/// # use std::sync::Arc;
/// # use ltk::{ icon_button, row, Element };
/// # #[ derive( Clone ) ] enum Msg { A, B }
/// # fn _ex( a_rgba: Arc<Vec<u8>>, b_rgba: Arc<Vec<u8>>, w: u32, h: u32 ) -> Element<Msg> {
/// row()
///     .spacing( 16.0 )
///     .align_right()
///     .push( icon_button( a_rgba, w, h ).on_press( Msg::A ) )
///     .push( icon_button( b_rgba, w, h ).on_press( Msg::B ) )
/// .into()
/// # }
/// ```
///
/// `spacing` and `padding` accept any [`crate::Length`]:
///
/// ```rust,no_run
/// # use std::sync::Arc;
/// # use ltk::{ icon_button, row, Length, Element };
/// # #[ derive( Clone ) ] enum Msg { A, B }
/// # fn _ex( a_rgba: Arc<Vec<u8>>, b_rgba: Arc<Vec<u8>>, w: u32, h: u32 ) -> Element<Msg> {
/// row()
///     // 2 % of the viewport's smaller side, never below 8 px.
///     .spacing( Length::vmin( 2.0 ).at_least( 8.0 ) )
///     .push( icon_button( a_rgba, w, h ).on_press( Msg::A ) )
///     .push( icon_button( b_rgba, w, h ).on_press( Msg::B ) )
/// .into()
/// # }
/// ```
pub struct Row<Msg: Clone>
{
	pub children:    Vec<Element<Msg>>,
	/// Horizontal gap between children. [`Length`]; default `8.0` px.
	pub spacing:     Length,
	/// Padding on all sides. [`Length`]; default `0.0` px.
	pub padding:     Length,
	pub align_right: bool,
}

impl<Msg: Clone> Row<Msg>
{
	pub fn new() -> Self
	{
		Self
		{
			children:    Vec::new(),
			spacing:     Length::px( 8.0 ),
			padding:     Length::px( 0.0 ),
			align_right: false,
		}
	}

	/// Append a child widget or layout.
	pub fn push( mut self, e: impl Into<Element<Msg>> ) -> Self
	{
		self.children.push( e.into() );
		self
	}

	/// Set the horizontal gap between children. Default: `8.0` px. Accepts
	/// any [`Length`] so the gap can scale with the viewport.
	pub fn spacing( mut self, s: impl Into<Length> ) -> Self
	{
		self.spacing = s.into();
		self
	}

	/// Set the padding (all sides). Default: `0.0` px. Accepts any
	/// [`Length`].
	pub fn padding( mut self, p: impl Into<Length> ) -> Self
	{
		self.padding = p.into();
		self
	}

	#[ inline ]
	fn resolved_spacing( &self, canvas: &Canvas ) -> f32
	{
		self.spacing.resolve( canvas.viewport_layout(), Length::EM_BASE_DEFAULT )
	}

	#[ inline ]
	fn resolved_padding( &self, canvas: &Canvas ) -> f32
	{
		self.padding.resolve( canvas.viewport_layout(), Length::EM_BASE_DEFAULT )
	}

	/// Push the content block to the right edge of the available width.
	pub fn align_right( mut self ) -> Self
	{
		self.align_right = true;
		self
	}

	/// Return the preferred `(width, height)` given available `max_width`.
	pub fn preferred_size( &self, max_width: f32, canvas: &Canvas ) -> (f32, f32)
	{
		let pad     = self.resolved_padding( canvas );
		let spacing = self.resolved_spacing( canvas );
		// Width contribution of every fixed (non-flex, non-flex-spacer) child.
		// Used to compute the residual width that wrap-style children will
		// actually render in, so their reported height matches the layout.
		let inner_w = ( max_width - pad * 2.0 ).max( 0.0 );
		let gaps    = spacing * self.children.len().saturating_sub( 1 ) as f32;
		let fixed_w: f32 = self.children.iter()
			.filter( |c| match c
			{
				Element::Flex( _ )   => false,
				Element::Spacer( s ) => s.resolved_width( canvas ).is_some(),
				_                    => true,
			} )
			.map( |c| c.preferred_size( max_width, canvas ).0 )
			.sum();
		let residual = ( inner_w - fixed_w - gaps ).max( 0.0 );

		let max_h: f32 = self.children.iter()
			.map( |c| match c
			{
				Element::Flex( _ )   => c.preferred_size( residual, canvas ).1,
				Element::Spacer( _ ) => c.preferred_size( max_width, canvas ).1,
				_                    => c.preferred_size( max_width, canvas ).1,
			} )
			.fold( 0.0_f32, f32::max );

		// `align_right` and any flex / weight-only spacer child make the row
		// claim the full `max_width`: in those cases the row's rendered width
		// comes from leftover distribution (or the right-edge anchor), not
		// from the sum of children's preferred widths. Reporting only the
		// natural sum would leave the parent allocating a too-narrow rect and
		// the flex children would collapse to 0.
		let has_flex = self.children.iter().any( |c| match c
		{
			Element::Flex( _ )   => true,
			Element::Spacer( s ) => s.resolved_width( canvas ).is_none(),
			_                    => false,
		} );

		let w = if self.align_right || has_flex
		{
			max_width
		} else {
			let total_w: f32 = self.children.iter()
				.map( |c| c.preferred_size( max_width, canvas ).0 )
				.sum::<f32>()
				+ gaps
				+ pad * 2.0;
			total_w.min( max_width )
		};

		( w, max_h + pad * 2.0 )
	}

	pub fn draw( &self, _canvas: &mut Canvas, _rect: Rect, _focused: bool ) {}

	/// Layout children within rect and return `(rect, child_index)` pairs.
	///
	/// Flexible [`Spacer`](crate::layout::spacer::Spacer) children claim the
	/// leftover horizontal space: non-spacer widgets keep their preferred
	/// width, the remaining width (after subtracting spacing + padding) is
	/// distributed between spacers in proportion to their `weight`. When no
	/// spacers are present the cluster is centered (or right-aligned via
	/// [`Row::align_right`]).
	pub fn layout( &self, rect: Rect, canvas: &Canvas ) -> Vec<(Rect, usize)>
	{
		let pad     = self.resolved_padding( canvas );
		let spacing = self.resolved_spacing( canvas );
		let inner_h = rect.height - pad * 2.0;

		// Spacers and `Flex` wrappers report 0 width here; their real width
		// comes from the flex distribution below.
		let sizes: Vec<(f32, f32)> = self.children.iter()
			.map( |c| c.preferred_size( rect.width, canvas ) )
			.collect();

		let gaps = spacing * self.children.len().saturating_sub( 1 ) as f32;
		let fixed_w: f32 = self.children.iter().zip( sizes.iter() )
			.filter( |( c, _ )| match c
			{
				// Pure flex children (`Flex` and weight-only `Spacer`) take
				// width from the leftover pool; everything else, including
				// `Spacer::width(...)`-pinned spacers, contributes to the
				// fixed-width tally.
				Element::Flex( _ )   => false,
				Element::Spacer( s ) => s.resolved_width( canvas ).is_some(),
				_                    => true,
			} )
			.map( |( _, ( w, _ ) )| *w )
			.sum();

		let total_weight: u32 = self.children.iter()
			.filter_map( |c| match c {
				Element::Spacer( s ) if s.resolved_width( canvas ).is_none() => Some( s.weight ),
				Element::Flex( f )   => Some( f.weight ),
				_                    => None,
			} )
			.sum();

		let inner_w     = ( rect.width - pad * 2.0 ).max( 0.0 );
		let leftover    = ( inner_w - fixed_w - gaps ).max( 0.0 );
		let has_spacers = total_weight > 0;

		let ( start_x, flex_unit ) = if has_spacers
		{
			// Spacers and `Flex` wrappers claim the leftover; the cluster
			// sits flush to the left edge of the inner rect.
			( rect.x + pad, leftover / total_weight as f32 )
		}
		else if self.align_right
		{
			( rect.x + rect.width - ( fixed_w + gaps ) - pad, 0.0 )
		}
		else
		{
			( rect.x + ( rect.width - fixed_w - gaps ) / 2.0, 0.0 )
		};

		let mut x = start_x;
		let mut result = Vec::with_capacity( self.children.len() );
		for ( i, ( (w, h), child) ) in sizes.into_iter().zip( self.children.iter() ).enumerate()
		{
			let width = match child
			{
				Element::Spacer( s ) => match s.resolved_width( canvas )
				{
					Some( fw ) => fw,
					None       => flex_unit * s.weight as f32,
				},
				Element::Flex( f )   => flex_unit * f.weight as f32,
				_                    => w,
			};
			let y = rect.y + pad + ( inner_h - h ) / 2.0;
			result.push( ( Rect { x, y, width, height: h }, i ) );
			x += width + spacing;
		}
		result
	}

	pub( crate ) fn map_msg<U>( self, f: &crate::widget::MapFn<Msg, U> ) -> Row<U>
	where
		U: Clone + 'static,
		Msg: 'static,
	{
		Row
		{
			children:    self.children.into_iter().map( |c| c.map_arc( f ) ).collect(),
			spacing:     self.spacing,
			padding:     self.padding,
			align_right: self.align_right,
		}
	}
}

/// Create an empty row layout.
pub fn row<Msg: Clone>() -> Row<Msg>
{
	Row::new()
}

impl<Msg: Clone> Default for Row<Msg>
{
	fn default() -> Self
	{
		Self::new()
	}
}

#[ cfg( test ) ]
mod tests
{
	use super::*;
	use crate::render::Canvas;
	use crate::types::Rect;

	fn make_canvas() -> Canvas { Canvas::new( 800, 600 ) }

	#[ test ]
	fn align_right_returns_full_max_width()
	{
		let canvas = make_canvas();
		let r      = row::<()>().align_right();
		let ( w, _ ) = r.preferred_size( 500.0, &canvas );
		assert_eq!( w, 500.0 );
	}

	#[ test ]
	fn align_right_true_regardless_of_children()
	{
		let canvas = make_canvas();
		let r = row::<()>().align_right().spacing( 999.0 );
		let ( w, _ ) = r.preferred_size( 300.0, &canvas );
		assert_eq!( w, 300.0 );
	}

	#[ test ]
	fn centered_empty_row_returns_zero_width()
	{
		let canvas = make_canvas();
		let r      = row::<()>();
		let ( w, _ ) = r.preferred_size( 500.0, &canvas );
		assert_eq!( w, 0.0 );
	}

	#[ test ]
	fn centered_empty_row_returns_zero_height()
	{
		let canvas = make_canvas();
		let r      = row::<()>().padding( 0.0 );
		let ( _, h ) = r.preferred_size( 500.0, &canvas );
		assert_eq!( h, 0.0 );
	}

	#[ test ]
	fn padding_adds_to_height()
	{
		let canvas = make_canvas();
		let r      = row::<()>().padding( 8.0 );
		let ( _, h ) = r.preferred_size( 500.0, &canvas );
		assert_eq!( h, 16.0 );
	}

	#[ test ]
	fn layout_of_empty_row_is_empty()
	{
		let canvas = make_canvas();
		let r      = row::<()>().align_right();
		let rect   = Rect { x: 0., y: 0., width: 400., height: 48. };
		assert!( r.layout( rect, &canvas ).is_empty() );
	}

	#[ test ]
	fn vmin_padding_doubles_around_content()
	{
		// 800x600 canvas → vmin = 600. 4 % = 24 px each side → 48 px height.
		let canvas = make_canvas();
		let r      = row::<()>().padding( Length::vmin( 4.0 ) );
		let ( _, h ) = r.preferred_size( 500.0, &canvas );
		assert_eq!( h, 48.0 );
	}

	#[ test ]
	fn vmin_spacing_pins_visible_layout_gap()
	{
		// Two fixed-width spacers separated by a vmin spacing of 5 %.
		// Canvas vmin = 600 → 30 px between the inner edges. With both
		// spacers 10 px wide, the second one's `x` minus the first one's
		// `x + width` must equal the gap regardless of where the row chose
		// to anchor the cluster (centered, since there are no flex spacers).
		let canvas = make_canvas();
		let r = row::<()>()
			.padding( 0.0 )
			.spacing( Length::vmin( 5.0 ) )
			.push( crate::spacer().width( 10.0 ) )
			.push( crate::spacer().width( 10.0 ) );
		let rect = Rect { x: 0., y: 0., width: 200., height: 48. };
		let placed = r.layout( rect, &canvas );
		assert_eq!( placed.len(), 2 );
		let ( first_rect, _ )  = placed[ 0 ];
		let ( second_rect, _ ) = placed[ 1 ];
		let gap = second_rect.x - ( first_rect.x + first_rect.width );
		assert!( ( gap - 30.0 ).abs() < 1e-3, "expected ~30 px gap, got {gap}" );
	}
}