Skip to main content

glory_render/
rich_document.rs

1//! Finite rich document model, independent of HTML and host editing APIs.
2//! Shared value/selection model used by the independently driven host editor.
3use crate::Error;
4
5pub const MAX_RICH_BLOCKS: usize = 128;
6pub const MAX_RICH_RUNS: usize = 2048;
7pub const MAX_RICH_TEXT_BYTES: usize = 65_536;
8pub const MAX_RICH_LINK_BYTES: usize = 2048;
9pub const MAX_RICH_METADATA_BYTES: usize = 131_072;
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum RichBlockKind {
12    #[default]
13    Paragraph,
14    Heading(u8),
15    Quote,
16}
17#[derive(Clone, Debug, Default, PartialEq, Eq)]
18pub struct RichMarks {
19    pub bold: bool,
20    pub italic: bool,
21    pub code: bool,
22    pub link: Option<String>,
23}
24#[derive(Clone, Debug, Default, PartialEq, Eq)]
25pub struct RichRun {
26    pub text: String,
27    pub marks: RichMarks,
28}
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
30pub struct RichBlock {
31    pub kind: RichBlockKind,
32    pub runs: Vec<RichRun>,
33}
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct RichDocument {
36    pub blocks: Vec<RichBlock>,
37}
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
39pub struct RichPoint {
40    pub block: usize,
41    pub offset: usize,
42}
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub struct RichSelection {
45    pub anchor: RichPoint,
46    pub focus: RichPoint,
47}
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum RichFormat {
50    Bold(bool),
51    Italic(bool),
52    Code(bool),
53    Link(Option<String>),
54    Block(RichBlockKind),
55}
56impl RichFormat {
57    pub fn validate(&self) -> Result<(), Error> {
58        match self {
59            Self::Link(Some(link)) => validate_link(link),
60            Self::Block(value) => kind(*value),
61            _ => Ok(()),
62        }
63    }
64}
65impl Default for RichDocument {
66    fn default() -> Self {
67        Self {
68            blocks: vec![RichBlock {
69                kind: RichBlockKind::Paragraph,
70                runs: vec![RichRun::default()],
71            }],
72        }
73    }
74}
75fn invalid(message: &'static str) -> Error {
76    Error::InvalidProps(message)
77}
78fn validate_link(link: &str) -> Result<(), Error> {
79    if link.is_empty()
80        || link.len() > MAX_RICH_LINK_BYTES
81        || link.chars().any(|ch| ch.is_control() || ch.is_whitespace())
82    {
83        return Err(invalid(
84            "rich link requires a finite http/https/mailto target",
85        ));
86    }
87    let valid = link.split_once(':').is_some_and(|(scheme, rest)| {
88        !rest.is_empty()
89            && ["http", "https", "mailto"]
90                .iter()
91                .any(|allowed| scheme.eq_ignore_ascii_case(allowed))
92    });
93    if !valid {
94        return Err(invalid(
95            "rich link requires a finite http/https/mailto target",
96        ));
97    }
98    Ok(())
99}
100impl RichMarks {
101    pub fn validate(&self) -> Result<(), Error> {
102        if let Some(link) = &self.link {
103            validate_link(link)?;
104        }
105        Ok(())
106    }
107    fn apply(&mut self, format: &RichFormat) {
108        match format {
109            RichFormat::Bold(value) => self.bold = *value,
110            RichFormat::Italic(value) => self.italic = *value,
111            RichFormat::Code(value) => self.code = *value,
112            RichFormat::Link(value) => self.link = value.clone(),
113            RichFormat::Block(_) => {}
114        }
115    }
116}
117fn kind(kind: RichBlockKind) -> Result<(), Error> {
118    if matches!(kind,RichBlockKind::Heading(level) if !(1..=6).contains(&level)) {
119        return Err(invalid("rich heading level must be 1..=6"));
120    }
121    Ok(())
122}
123fn byte_offset(text: &str, utf16: usize) -> Result<usize, Error> {
124    let mut offset = 0;
125    for (byte, ch) in text.char_indices() {
126        if offset == utf16 {
127            return Ok(byte);
128        }
129        offset += ch.len_utf16();
130        if offset > utf16 {
131            return Err(invalid("rich selection splits a UTF-16 surrogate pair"));
132        }
133    }
134    if offset == utf16 {
135        Ok(text.len())
136    } else {
137        Err(invalid("rich selection exceeds its block"))
138    }
139}
140impl RichBlock {
141    pub fn utf16_len(&self) -> usize {
142        self.runs
143            .iter()
144            .map(|run| run.text.encode_utf16().count())
145            .sum()
146    }
147    fn point(&self, offset: usize) -> Result<(), Error> {
148        let mut remaining = offset;
149        for run in &self.runs {
150            let length = run.text.encode_utf16().count();
151            if remaining <= length {
152                byte_offset(&run.text, remaining)?;
153                return Ok(());
154            }
155            remaining -= length;
156        }
157        Err(invalid("rich selection exceeds its block"))
158    }
159    fn slice(&self, start: usize, end: usize) -> Result<Vec<RichRun>, Error> {
160        let mut output = Vec::new();
161        let mut cursor = 0;
162        for run in &self.runs {
163            let length = run.text.encode_utf16().count();
164            let left = start.saturating_sub(cursor).min(length);
165            let right = end.saturating_sub(cursor).min(length);
166            if left < right {
167                output.push(RichRun {
168                    text: run.text[byte_offset(&run.text, left)?..byte_offset(&run.text, right)?]
169                        .into(),
170                    marks: run.marks.clone(),
171                });
172            }
173            cursor += length;
174        }
175        Ok(output)
176    }
177}
178impl RichSelection {
179    pub fn ordered(self) -> (RichPoint, RichPoint) {
180        if self.anchor <= self.focus {
181            (self.anchor, self.focus)
182        } else {
183            (self.focus, self.anchor)
184        }
185    }
186    pub fn collapsed(point: RichPoint) -> Self {
187        Self {
188            anchor: point,
189            focus: point,
190        }
191    }
192    pub fn is_collapsed(self) -> bool {
193        self.anchor == self.focus
194    }
195}
196impl RichDocument {
197    /// Canonicalize only an already bounded owned declaration. No business
198    /// iterator/source is collected or scanned by this constructor.
199    pub fn new(blocks: Vec<RichBlock>) -> Result<Self, Error> {
200        let mut doc = Self { blocks };
201        doc.validate_limits()?;
202        for block in &mut doc.blocks {
203            let mut runs: Vec<RichRun> = Vec::with_capacity(block.runs.len());
204            for run in std::mem::take(&mut block.runs) {
205                if run.text.is_empty() {
206                    continue;
207                }
208                if let Some(previous) = runs
209                    .last_mut()
210                    .filter(|previous| previous.marks == run.marks)
211                {
212                    previous.text.push_str(&run.text);
213                } else {
214                    runs.push(run);
215                }
216            }
217            if runs.is_empty() {
218                runs.push(RichRun::default());
219            }
220            block.runs = runs;
221        }
222        doc.validate()?;
223        Ok(doc)
224    }
225    fn validate_limits(&self) -> Result<(), Error> {
226        if self.blocks.is_empty() || self.blocks.len() > MAX_RICH_BLOCKS {
227            return Err(invalid("rich document requires 1..=128 blocks"));
228        }
229        let mut runs = 0usize;
230        let mut text = 0usize;
231        let mut metadata = 0usize;
232        for block in &self.blocks {
233            kind(block.kind)?;
234            runs = runs
235                .checked_add(block.runs.len())
236                .ok_or_else(|| invalid("rich run count overflow"))?;
237            if block.runs.is_empty() || runs > MAX_RICH_RUNS {
238                return Err(invalid("rich document requires bounded nonempty runs"));
239            }
240            for run in &block.runs {
241                if run.text.contains(['\0', '\r', '\n']) {
242                    return Err(invalid("rich runs use canonical single-paragraph text"));
243                }
244                run.marks.validate()?;
245                text = text
246                    .checked_add(run.text.len())
247                    .ok_or_else(|| invalid("rich text budget overflow"))?;
248                metadata = metadata
249                    .checked_add(run.marks.link.as_ref().map_or(0, String::len))
250                    .ok_or_else(|| invalid("rich metadata overflow"))?;
251                if text > MAX_RICH_TEXT_BYTES || metadata > MAX_RICH_METADATA_BYTES {
252                    return Err(invalid("rich document text/metadata budget"));
253                }
254            }
255        }
256        Ok(())
257    }
258    pub fn validate(&self) -> Result<(), Error> {
259        self.validate_limits()?;
260        for block in &self.blocks {
261            if block.runs.iter().any(|run| {
262                run.text.is_empty() && (block.runs.len() != 1 || run.marks != RichMarks::default())
263            }) || block
264                .runs
265                .windows(2)
266                .any(|pair| pair[0].marks == pair[1].marks)
267            {
268                return Err(invalid("rich runs must be canonically merged"));
269            }
270        }
271        Ok(())
272    }
273    pub fn validate_selection(&self, selection: RichSelection) -> Result<(), Error> {
274        for point in [selection.anchor, selection.focus] {
275            self.blocks
276                .get(point.block)
277                .ok_or_else(|| invalid("rich selection block is missing"))?
278                .point(point.offset)?;
279        }
280        Ok(())
281    }
282    pub fn plain_text(&self) -> String {
283        let mut text = String::new();
284        for (index, block) in self.blocks.iter().enumerate() {
285            if index != 0 {
286                text.push('\n');
287            }
288            for run in &block.runs {
289                text.push_str(&run.text);
290            }
291        }
292        text
293    }
294    /// Charged document payload and finite run/block bookkeeping. This is not
295    /// an RSS/allocator-capacity claim, nor a budget for business-owned sources.
296    pub fn charged_bytes(&self) -> usize {
297        self.blocks.len() * std::mem::size_of::<RichBlock>()
298            + self
299                .blocks
300                .iter()
301                .map(|block| {
302                    block.runs.len() * std::mem::size_of::<RichRun>()
303                        + block
304                            .runs
305                            .iter()
306                            .map(|run| {
307                                run.text.len() + run.marks.link.as_ref().map_or(0, String::len)
308                            })
309                            .sum::<usize>()
310                })
311                .sum::<usize>()
312    }
313    pub fn replace(
314        &self,
315        selection: RichSelection,
316        text: &str,
317        marks: RichMarks,
318    ) -> Result<(Self, RichSelection), Error> {
319        self.validate()?;
320        self.validate_selection(selection)?;
321        marks.validate()?;
322        if text.len() > MAX_RICH_TEXT_BYTES {
323            return Err(invalid("rich insertion exceeds text budget"));
324        }
325        let text = crate::normalize_text(text, true);
326        let lines = text.bytes().filter(|byte| *byte == b'\n').count() + 1;
327        let (start, end) = selection.ordered();
328        let blocks = self.blocks.len() - (end.block - start.block) + lines - 1;
329        if blocks > MAX_RICH_BLOCKS {
330            return Err(invalid("rich insertion exceeds block budget"));
331        }
332        let mut output = Vec::with_capacity(blocks);
333        output.extend(self.blocks[..start.block].iter().cloned());
334        let prefix = self.blocks[start.block].slice(0, start.offset)?;
335        let suffix =
336            self.blocks[end.block].slice(end.offset, self.blocks[end.block].utf16_len())?;
337        let mut inserted = text.split('\n').peekable();
338        let mut index = 0;
339        let mut caret = RichPoint {
340            block: start.block,
341            offset: start.offset,
342        };
343        while let Some(line) = inserted.next() {
344            let mut runs = if index == 0 {
345                prefix.clone()
346            } else {
347                Vec::new()
348            };
349            runs.push(RichRun {
350                text: line.into(),
351                marks: marks.clone(),
352            });
353            caret = RichPoint {
354                block: start.block + index,
355                offset: if index == 0 { start.offset } else { 0 } + line.encode_utf16().count(),
356            };
357            if inserted.peek().is_none() {
358                runs.extend(suffix.iter().cloned());
359            }
360            output.push(RichBlock {
361                kind: self.blocks[start.block].kind,
362                runs,
363            });
364            index += 1;
365        }
366        output.extend(self.blocks[end.block + 1..].iter().cloned());
367        Ok((Self::new(output)?, RichSelection::collapsed(caret)))
368    }
369    pub fn format(&self, selection: RichSelection, format: RichFormat) -> Result<Self, Error> {
370        self.validate()?;
371        self.validate_selection(selection)?;
372        format.validate()?;
373        if selection.is_collapsed() && !matches!(format, RichFormat::Block(_)) {
374            return Ok(self.clone());
375        }
376        let (start, end) = selection.ordered();
377        let mut blocks = self.blocks.clone();
378        for (index, block) in blocks
379            .iter_mut()
380            .enumerate()
381            .take(end.block + 1)
382            .skip(start.block)
383        {
384            if let RichFormat::Block(kind) = format {
385                block.kind = kind;
386                continue;
387            }
388            let first = if index == start.block {
389                start.offset
390            } else {
391                0
392            };
393            let last = if index == end.block {
394                end.offset
395            } else {
396                block.utf16_len()
397            };
398            let mut runs = block.slice(0, first)?;
399            let mut selected = block.slice(first, last)?;
400            for run in &mut selected {
401                run.marks.apply(&format);
402            }
403            runs.extend(selected);
404            runs.extend(block.slice(last, block.utf16_len())?);
405            block.runs = runs;
406        }
407        Self::new(blocks)
408    }
409}