1use super::measure::{Cost, inline_chars};
4use super::{Block, Document, Inline, ListItem, Media, Table};
5use crate::limits::Limits;
6
7#[derive(Debug, Clone, PartialEq)]
9pub struct FitOptions {
10 pub limits: Limits,
12 pub tail: Vec<Block>,
15 pub truncation_notice: Vec<Block>,
18 pub ellipsis: String,
20}
21
22impl Default for FitOptions {
23 fn default() -> Self {
24 Self {
25 limits: Limits::TELEGRAM,
26 tail: Vec::new(),
27 truncation_notice: Vec::new(),
28 ellipsis: "…".to_owned(),
29 }
30 }
31}
32
33impl Document {
34 pub fn fit(&mut self, opts: &FitOptions) -> bool {
49 let limits = &opts.limits;
50 let tail_cost = Cost::of_blocks(&opts.tail);
51 let notice_cost = Cost::of_blocks(&opts.truncation_notice);
52
53 limit_table_columns(&mut self.blocks, limits.max_table_columns);
54 let mut media_left = limits
55 .max_media
56 .saturating_sub(tail_cost.media + notice_cost.media);
57 limit_media(&mut self.blocks, &mut media_left);
58 let blocks = std::mem::take(&mut self.blocks);
59 self.blocks = limit_depth(blocks, 1, limits.max_depth);
60
61 let full = Cost {
62 chars: limits.max_chars,
63 blocks: limits.max_blocks,
64 media: limits.max_media,
65 };
66 let content_cost = Cost::of_blocks(&self.blocks);
67 let truncated = if (content_cost + tail_cost).fits_in(&full) {
68 false
69 } else {
70 let mut budget = full.saturating_sub(&(tail_cost + notice_cost));
71 let blocks = std::mem::take(&mut self.blocks);
72 let (kept, _) = take_blocks(blocks, &mut budget, &opts.ellipsis);
73 self.blocks = kept;
74 self.blocks.extend(opts.truncation_notice.iter().cloned());
75 true
76 };
77 self.blocks.extend(opts.tail.iter().cloned());
78 truncated
79 }
80}
81
82fn limit_table_columns(blocks: &mut [Block], max_cols: usize) {
86 for b in blocks {
87 match b {
88 Block::Table(t) => {
89 for row in &mut t.rows {
90 let mut used = 0usize;
91 let mut keep = 0usize;
92 for cell in row.iter_mut() {
93 if used >= max_cols {
94 break;
95 }
96 let span = cell.colspan.unwrap_or(1).max(1) as usize;
97 if used + span > max_cols {
98 cell.colspan = Some((max_cols - used) as u32);
99 }
100 used += span.min(max_cols - used);
101 keep += 1;
102 }
103 row.truncate(keep);
104 }
105 }
106 Block::List { items, .. } => {
107 for it in items {
108 limit_table_columns(&mut it.blocks, max_cols);
109 }
110 }
111 Block::Quote { blocks, .. } | Block::Details { blocks, .. } => {
112 limit_table_columns(blocks, max_cols)
113 }
114 _ => {}
115 }
116 }
117}
118
119fn media_as_link(m: &Media) -> Block {
123 let content = match &m.caption {
124 Some(c) if !c.is_empty() => c.clone(),
125 _ => vec![Inline::Text(m.src.clone())],
126 };
127 Block::Paragraph(vec![Inline::Link {
128 href: m.src.clone(),
129 content,
130 }])
131}
132
133fn limit_media(blocks: &mut [Block], left: &mut usize) {
134 for b in blocks {
135 match b {
136 Block::Media(m) => {
137 if *left == 0 {
138 *b = media_as_link(m);
139 } else {
140 *left -= 1;
141 }
142 }
143 Block::List { items, .. } => {
144 for it in items {
145 limit_media(&mut it.blocks, left);
146 }
147 }
148 Block::Quote { blocks, .. } | Block::Details { blocks, .. } => {
149 limit_media(blocks, left)
150 }
151 _ => {}
152 }
153 }
154}
155
156fn limit_inline_depth(inl: Vec<Inline>, depth: usize, max: usize) -> Vec<Inline> {
160 let mut out = Vec::with_capacity(inl.len());
161 for i in inl {
162 let rebuild = |c: Vec<Inline>, f: fn(Vec<Inline>) -> Inline, out: &mut Vec<Inline>| {
163 if depth + 1 > max {
164 out.extend(limit_inline_depth(c, depth, max));
165 } else {
166 out.push(f(limit_inline_depth(c, depth + 1, max)));
167 }
168 };
169 match i {
170 Inline::Bold(c) => rebuild(c, Inline::Bold, &mut out),
171 Inline::Italic(c) => rebuild(c, Inline::Italic, &mut out),
172 Inline::Underline(c) => rebuild(c, Inline::Underline, &mut out),
173 Inline::Strikethrough(c) => rebuild(c, Inline::Strikethrough, &mut out),
174 Inline::Spoiler(c) => rebuild(c, Inline::Spoiler, &mut out),
175 Inline::Marked(c) => rebuild(c, Inline::Marked, &mut out),
176 Inline::Subscript(c) => rebuild(c, Inline::Subscript, &mut out),
177 Inline::Superscript(c) => rebuild(c, Inline::Superscript, &mut out),
178 Inline::Link { href, content } => {
179 if depth + 1 > max {
180 out.extend(limit_inline_depth(content, depth, max));
181 } else {
182 out.push(Inline::Link {
183 href,
184 content: limit_inline_depth(content, depth + 1, max),
185 });
186 }
187 }
188 other => out.push(other),
189 }
190 }
191 out
192}
193
194fn limit_opt_inline(inl: Option<Vec<Inline>>, depth: usize, max: usize) -> Option<Vec<Inline>> {
195 inl.map(|i| limit_inline_depth(i, depth, max))
196}
197
198fn limit_depth(blocks: Vec<Block>, depth: usize, max: usize) -> Vec<Block> {
200 let mut out = Vec::with_capacity(blocks.len());
201 for b in blocks {
202 match b {
203 Block::Paragraph(i) => out.push(Block::Paragraph(limit_inline_depth(i, depth, max))),
204 Block::Footer(i) => out.push(Block::Footer(limit_inline_depth(i, depth, max))),
205 Block::Heading { level, content } => out.push(Block::Heading {
206 level,
207 content: limit_inline_depth(content, depth, max),
208 }),
209 Block::ExpandableQuote { content, credit } => out.push(Block::ExpandableQuote {
210 content: limit_inline_depth(content, depth, max),
211 credit: limit_opt_inline(credit, depth, max),
212 }),
213 Block::PullQuote { content, credit } => out.push(Block::PullQuote {
214 content: limit_inline_depth(content, depth, max),
215 credit: limit_opt_inline(credit, depth, max),
216 }),
217 Block::List {
218 ordered,
219 start,
220 items,
221 } => {
222 if depth + 2 > max {
224 for it in items {
225 out.extend(limit_depth(it.blocks, depth, max));
226 }
227 } else {
228 let items = items
229 .into_iter()
230 .map(|it| ListItem {
231 blocks: limit_depth(it.blocks, depth + 2, max),
232 checkbox: it.checkbox,
233 })
234 .collect();
235 out.push(Block::List {
236 ordered,
237 start,
238 items,
239 });
240 }
241 }
242 Block::Quote { blocks, credit } => {
243 if depth + 1 > max {
244 out.extend(limit_depth(blocks, depth, max));
245 } else {
246 out.push(Block::Quote {
247 blocks: limit_depth(blocks, depth + 1, max),
248 credit: limit_opt_inline(credit, depth, max),
249 });
250 }
251 }
252 Block::Details {
253 summary,
254 blocks,
255 open,
256 } => {
257 if depth + 1 > max {
258 out.push(Block::Paragraph(limit_inline_depth(summary, depth, max)));
259 out.extend(limit_depth(blocks, depth, max));
260 } else {
261 out.push(Block::Details {
262 summary: limit_inline_depth(summary, depth, max),
263 blocks: limit_depth(blocks, depth + 1, max),
264 open,
265 });
266 }
267 }
268 Block::Table(mut t) => {
269 for row in &mut t.rows {
270 for cell in row {
271 cell.content =
272 limit_inline_depth(std::mem::take(&mut cell.content), depth + 1, max);
273 }
274 }
275 t.caption = limit_opt_inline(t.caption, depth, max);
276 out.push(Block::Table(t));
277 }
278 Block::Media(mut m) => {
279 m.caption = limit_opt_inline(m.caption, depth, max);
280 m.credit = limit_opt_inline(m.credit, depth, max);
281 out.push(Block::Media(m));
282 }
283 other => out.push(other),
284 }
285 }
286 out
287}
288
289fn take_blocks(blocks: Vec<Block>, budget: &mut Cost, ellipsis: &str) -> (Vec<Block>, bool) {
296 let mut kept = Vec::new();
297 for b in blocks {
298 let c = Cost::of_block(&b);
299 if c.fits_in(budget) {
300 *budget = budget.saturating_sub(&c);
301 kept.push(b);
302 } else {
303 if let Some(p) = truncate_block(b, budget, ellipsis) {
304 let pc = Cost::of_block(&p);
305 *budget = budget.saturating_sub(&pc);
306 kept.push(p);
307 }
308 return (kept, true);
309 }
310 }
311 (kept, false)
312}
313
314fn truncate_inlines(inl: Vec<Inline>, max_chars: usize, ellipsis: &str) -> Option<Vec<Inline>> {
316 let ell = ellipsis.chars().count();
317 if max_chars <= ell {
318 return None;
319 }
320 let mut left = max_chars - ell;
321 let mut out = cut_inlines(inl, &mut left);
322 if out.is_empty() {
323 return None;
324 }
325 out.push(Inline::Text(ellipsis.to_owned()));
326 Some(out)
327}
328
329fn cut_inlines(inl: Vec<Inline>, left: &mut usize) -> Vec<Inline> {
330 let mut out = Vec::new();
331 for i in inl {
332 if *left == 0 {
333 break;
334 }
335 let n = inline_chars(std::slice::from_ref(&i));
336 if n <= *left {
337 *left -= n;
338 out.push(i);
339 continue;
340 }
341 let wrap = |c: Vec<Inline>, f: fn(Vec<Inline>) -> Inline, left: &mut usize| {
342 let c = cut_inlines(c, left);
343 (!c.is_empty()).then(|| f(c))
344 };
345 let part = match i {
346 Inline::Text(t) => Some(Inline::Text(take_chars(&t, left))),
347 Inline::Code(t) => Some(Inline::Code(take_chars(&t, left))),
348 Inline::Math(_) | Inline::LineBreak => None,
349 Inline::Bold(c) => wrap(c, Inline::Bold, left),
350 Inline::Italic(c) => wrap(c, Inline::Italic, left),
351 Inline::Underline(c) => wrap(c, Inline::Underline, left),
352 Inline::Strikethrough(c) => wrap(c, Inline::Strikethrough, left),
353 Inline::Spoiler(c) => wrap(c, Inline::Spoiler, left),
354 Inline::Marked(c) => wrap(c, Inline::Marked, left),
355 Inline::Subscript(c) => wrap(c, Inline::Subscript, left),
356 Inline::Superscript(c) => wrap(c, Inline::Superscript, left),
357 Inline::Link { href, content } => {
358 let c = cut_inlines(content, left);
359 (!c.is_empty()).then_some(Inline::Link { href, content: c })
360 }
361 };
362 out.extend(part);
363 *left = 0;
364 }
365 out
366}
367
368fn take_chars(s: &str, left: &mut usize) -> String {
369 let out: String = s.chars().take(*left).collect();
370 *left -= out.chars().count();
371 out
372}
373
374fn truncate_block(b: Block, budget: &Cost, ellipsis: &str) -> Option<Block> {
375 if budget.blocks == 0 {
376 return None;
377 }
378 let inner = Cost {
380 blocks: budget.blocks - 1,
381 ..*budget
382 };
383 match b {
384 Block::Paragraph(i) => truncate_inlines(i, budget.chars, ellipsis).map(Block::Paragraph),
385 Block::Footer(i) => truncate_inlines(i, budget.chars, ellipsis).map(Block::Footer),
386 Block::Heading { level, content } => truncate_inlines(content, budget.chars, ellipsis)
387 .map(|content| Block::Heading { level, content }),
388 Block::PullQuote { content, .. } => {
389 truncate_inlines(content, budget.chars, ellipsis).map(|content| Block::PullQuote {
390 content,
391 credit: None,
392 })
393 }
394 Block::ExpandableQuote { content, .. } => truncate_inlines(content, budget.chars, ellipsis)
395 .map(|content| Block::ExpandableQuote {
396 content,
397 credit: None,
398 }),
399 Block::Preformatted { language, text } => {
400 let ell = ellipsis.chars().count();
401 if budget.chars <= ell {
402 return None;
403 }
404 let mut left = budget.chars - ell;
405 let mut text = take_chars(&text, &mut left);
406 text.push_str(ellipsis);
407 Some(Block::Preformatted { language, text })
408 }
409 Block::List {
410 ordered,
411 start,
412 items,
413 } => {
414 let mut budget = inner;
415 let mut kept = Vec::new();
416 for it in items {
417 let item_cost = Cost::of_blocks(&it.blocks)
418 + Cost {
419 blocks: 1,
420 ..Cost::default()
421 };
422 if item_cost.fits_in(&budget) {
423 budget = budget.saturating_sub(&item_cost);
424 kept.push(it);
425 } else {
426 if budget.blocks > 1 {
427 let mut ib = Cost {
428 blocks: budget.blocks - 1,
429 ..budget
430 };
431 let (blocks, _) = take_blocks(it.blocks, &mut ib, ellipsis);
432 if !blocks.is_empty() {
433 kept.push(ListItem {
434 blocks,
435 checkbox: it.checkbox,
436 });
437 }
438 }
439 break;
440 }
441 }
442 (!kept.is_empty()).then_some(Block::List {
443 ordered,
444 start,
445 items: kept,
446 })
447 }
448 Block::Quote { blocks, .. } => {
449 let mut budget = inner;
450 let (blocks, _) = take_blocks(blocks, &mut budget, ellipsis);
451 (!blocks.is_empty()).then_some(Block::Quote {
452 blocks,
453 credit: None,
454 })
455 }
456 Block::Details {
457 summary,
458 blocks,
459 open,
460 } => {
461 let sc = inline_chars(&summary);
462 if sc >= inner.chars {
463 return None;
464 }
465 let mut budget = Cost {
466 chars: inner.chars - sc,
467 ..inner
468 };
469 let (blocks, _) = take_blocks(blocks, &mut budget, ellipsis);
470 (!blocks.is_empty()).then_some(Block::Details {
471 summary,
472 blocks,
473 open,
474 })
475 }
476 Block::Table(t) => truncate_table(t, &inner),
477 Block::Media(_)
479 | Block::Divider
480 | Block::Anchor(_)
481 | Block::MathBlock(_)
482 | Block::Buttons { .. } => None,
483 }
484}
485
486fn truncate_table(t: Table, budget: &Cost) -> Option<Block> {
487 let cap = t.caption.as_deref().map(inline_chars).unwrap_or(0);
488 let mut chars = budget.chars.checked_sub(cap)?;
489 let mut blocks = budget.blocks;
490 let mut rows = Vec::new();
491 for row in t.rows {
492 let rc: usize = row.iter().map(|c| inline_chars(&c.content)).sum();
493 if blocks == 0 || rc > chars {
494 break;
495 }
496 blocks -= 1;
497 chars -= rc;
498 rows.push(row);
499 }
500 (!rows.is_empty()).then_some(Block::Table(Table { rows, ..t }))
501}