1use iced::advanced::layout;
26use iced::advanced::mouse;
27use iced::advanced::renderer;
28use iced::advanced::text::{self, paragraph, Paragraph, Text};
29use iced::advanced::widget::{tree, Tree};
30use iced::advanced::{Layout, Widget};
31use iced::alignment;
32use iced::widget::text::{LineHeight, Shaping, Wrapping};
33use iced::{Color, Element, Length, Pixels, Rectangle, Size};
34use std::borrow::Cow;
35use unicode_segmentation::UnicodeSegmentation;
36
37pub const ELLIPSIS: &str = "\u{2026}";
39
40pub fn clamped_text<'a>(content: impl Into<Cow<'a, str>>, lines: usize) -> ClampedText<'a> {
45 ClampedText {
46 content: content.into(),
47 lines: lines.max(1),
48 size: None,
49 line_height: LineHeight::default(),
50 font: None,
51 width: Length::Shrink,
52 align_x: text::Alignment::Default,
53 wrapping: Wrapping::WordOrGlyph,
54 shaping: Shaping::default(),
55 color: None,
56 _theme: std::marker::PhantomData,
57 }
58}
59
60pub struct ClampedText<'a, Theme = iced::Theme, Renderer = iced::Renderer>
62where
63 Renderer: text::Renderer,
64{
65 content: Cow<'a, str>,
66 lines: usize,
67 size: Option<Pixels>,
68 line_height: LineHeight,
69 font: Option<Renderer::Font>,
70 width: Length,
71 align_x: text::Alignment,
72 wrapping: Wrapping,
73 shaping: Shaping,
74 color: Option<Color>,
75 _theme: std::marker::PhantomData<Theme>,
76}
77
78impl<'a, Theme, Renderer> ClampedText<'a, Theme, Renderer>
79where
80 Renderer: text::Renderer,
81{
82 pub fn size(mut self, size: impl Into<Pixels>) -> Self {
83 self.size = Some(size.into());
84 self
85 }
86
87 pub fn line_height(mut self, line_height: impl Into<LineHeight>) -> Self {
88 self.line_height = line_height.into();
89 self
90 }
91
92 pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self {
93 self.font = Some(font.into());
94 self
95 }
96
97 pub fn width(mut self, width: impl Into<Length>) -> Self {
98 self.width = width.into();
99 self
100 }
101
102 pub fn align_x(mut self, align: impl Into<text::Alignment>) -> Self {
103 self.align_x = align.into();
104 self
105 }
106
107 pub fn wrapping(mut self, wrapping: Wrapping) -> Self {
112 self.wrapping = wrapping;
113 self
114 }
115
116 pub fn shaping(mut self, shaping: Shaping) -> Self {
117 self.shaping = shaping;
118 self
119 }
120
121 pub fn color(mut self, color: impl Into<Color>) -> Self {
123 self.color = Some(color.into());
124 self
125 }
126}
127
128#[derive(Debug, Clone, PartialEq)]
131struct Asked {
132 content: String,
133 width: f32,
134 size: f32,
135 lines: usize,
136}
137
138struct State<P: Paragraph> {
139 paragraph: paragraph::Plain<P>,
140 asked: Option<Asked>,
141 shown: String,
142}
143
144impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for ClampedText<'_, Theme, Renderer>
145where
146 Renderer: text::Renderer,
147{
148 fn tag(&self) -> tree::Tag {
149 tree::Tag::of::<State<Renderer::Paragraph>>()
150 }
151
152 fn state(&self) -> tree::State {
153 tree::State::new(State::<Renderer::Paragraph> {
154 paragraph: paragraph::Plain::default(),
155 asked: None,
156 shown: String::new(),
157 })
158 }
159
160 fn size(&self) -> Size<Length> {
161 Size { width: self.width, height: Length::Shrink }
162 }
163
164 fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
165 let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
166 let limits = limits.width(self.width);
167 let width = limits.max().width;
168 let size = self.size.unwrap_or_else(|| renderer.default_size());
169 let font = self.font.unwrap_or_else(|| renderer.default_font());
170 let template = Text {
171 content: "",
172 bounds: Size::new(width, f32::INFINITY),
173 size,
174 line_height: self.line_height,
175 font,
176 align_x: self.align_x,
177 align_y: alignment::Vertical::Top,
178 shaping: self.shaping,
179 wrapping: self.wrapping,
180 };
181 let asked = Asked { content: self.content.to_string(), width, size: size.0, lines: self.lines };
182 if state.asked.as_ref() != Some(&asked) {
183 state.shown = clamp::<Renderer::Paragraph>(Text { content: &self.content, ..template }, self.lines).into_owned();
184 state.asked = Some(asked);
185 }
186 let _ = state.paragraph.update(Text { content: &state.shown, ..template });
187 let measured = state.paragraph.min_bounds();
188 layout::Node::new(limits.resolve(self.width, Length::Shrink, measured))
189 }
190
191 fn draw(
192 &self,
193 tree: &Tree,
194 renderer: &mut Renderer,
195 _theme: &Theme,
196 style: &renderer::Style,
197 layout: Layout<'_>,
198 _cursor: mouse::Cursor,
199 viewport: &Rectangle,
200 ) {
201 let state = tree.state.downcast_ref::<State<Renderer::Paragraph>>();
202 let paragraph = state.paragraph.raw();
203 let anchor = layout.bounds().anchor(paragraph.min_bounds(), paragraph.align_x(), paragraph.align_y());
204 renderer.fill_paragraph(paragraph, anchor, self.color.unwrap_or(style.text_color), *viewport);
205 }
206}
207
208pub fn clamp<'t, P: Paragraph>(text: Text<&'t str, P::Font>, lines: usize) -> Cow<'t, str> {
215 if lines == usize::MAX {
216 return Cow::Borrowed(text.content);
217 }
218 let line = text.line_height.to_absolute(text.size).0;
219 let tallest = line * lines as f32 + 0.5;
222 let widest = text.bounds.width + 0.5;
223 let fits = |content: &str| {
224 let bounds = P::with_text(Text { content, ..text }).min_bounds();
225 bounds.height <= tallest && bounds.width <= widest
226 };
227 if fits(text.content) {
228 return Cow::Borrowed(text.content);
229 }
230 let cuts: Vec<usize> = text.content.grapheme_indices(true).map(|(at, _)| at).collect();
231 let with_ellipsis = |at: usize| format!("{}{ELLIPSIS}", text.content[..at].trim_end());
232 let (mut lo, mut hi) = (0usize, cuts.len());
236 while lo + 1 < hi {
237 let mid = (lo + hi) / 2;
238 if fits(&with_ellipsis(cuts[mid])) {
239 lo = mid;
240 } else {
241 hi = mid;
242 }
243 }
244 Cow::Owned(with_ellipsis(cuts.get(lo).copied().unwrap_or(0)))
245}
246
247impl<'a, Message, Theme, Renderer> From<ClampedText<'a, Theme, Renderer>> for Element<'a, Message, Theme, Renderer>
248where
249 Theme: 'a,
250 Renderer: text::Renderer + 'a,
251{
252 fn from(text: ClampedText<'a, Theme, Renderer>) -> Self {
253 Element::new(text)
254 }
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260 use iced::advanced::graphics::text::Paragraph as Shaped;
261 use iced::Font;
262
263 fn text(content: &str, width: f32, wrapping: Wrapping) -> Text<&str, Font> {
264 Text {
265 content,
266 bounds: Size::new(width, f32::INFINITY),
267 size: Pixels(14.0),
268 line_height: LineHeight::default(),
269 font: Font::default(),
270 align_x: text::Alignment::Center,
271 align_y: alignment::Vertical::Top,
272 shaping: Shaping::Advanced,
273 wrapping,
274 }
275 }
276
277 fn lines_of(content: &str, width: f32) -> f32 {
278 let t = text(content, width, Wrapping::WordOrGlyph);
279 Shaped::with_text(t).min_bounds().height / t.line_height.to_absolute(t.size).0
280 }
281
282 #[test]
284 fn text_that_fits_is_left_whole() {
285 let t = text("notes.txt", 200.0, Wrapping::WordOrGlyph);
286 assert!(matches!(clamp::<Shaped>(t, 2), Cow::Borrowed("notes.txt")));
287 }
288
289 #[test]
293 fn a_long_text_is_cut_at_the_line_limit_with_an_ellipsis() {
294 let long = "Quarterly report for the regional office, final revision three (approved by everyone).pdf";
295 for lines in 1..=3 {
296 let shown = clamp::<Shaped>(text(long, 120.0, Wrapping::WordOrGlyph), lines).into_owned();
297 assert!(shown.ends_with(ELLIPSIS), "{shown}");
298 assert!(lines_of(&shown, 120.0) <= lines as f32 + 0.01, "{shown} is more than {lines} lines");
299 let kept = shown.trim_end_matches(ELLIPSIS);
300 let next = long[kept.len()..].char_indices().find(|(_, c)| !c.is_whitespace());
303 let one_more = &long[..next.map_or(long.len(), |(at, c)| kept.len() + at + c.len_utf8())];
304 let longer = format!("{}{ELLIPSIS}", one_more.trim_end());
305 assert!(lines_of(&longer, 120.0) > lines as f32 + 0.01, "{longer} would have fitted in {lines}");
306 }
307 }
308
309 #[test]
312 fn a_cut_never_splits_a_grapheme() {
313 let decomposed = "e\u{301}".repeat(80);
314 let shown = clamp::<Shaped>(text(&decomposed, 60.0, Wrapping::WordOrGlyph), 1).into_owned();
315 let kept = shown.trim_end_matches(ELLIPSIS);
316 assert!(!kept.is_empty() && kept.len().is_multiple_of(3), "{kept:?} ends inside a grapheme");
317 }
318
319 #[test]
322 fn an_unwrapped_text_is_cut_at_the_width() {
323 let t = text("a-very-long-file-name-without-any-spaces-at-all.tar.gz", 100.0, Wrapping::None);
324 let shown = clamp::<Shaped>(t, 1).into_owned();
325 assert!(shown.ends_with(ELLIPSIS));
326 let width = Shaped::with_text(text(&shown, 100.0, Wrapping::None)).min_bounds().width;
327 assert!(width <= 100.5, "{shown} is {width} wide");
328 }
329
330 #[test]
332 fn an_unlimited_clamp_is_the_whole_text() {
333 let long = "word ".repeat(100);
334 assert_eq!(clamp::<Shaped>(text(&long, 50.0, Wrapping::WordOrGlyph), usize::MAX), long);
335 }
336
337 #[test]
339 fn a_box_too_small_for_one_letter_shows_the_ellipsis() {
340 let shown = clamp::<Shaped>(text("WWWWWWWW", 2.0, Wrapping::None), 1);
341 assert_eq!(shown, ELLIPSIS);
342 }
343}