Skip to main content

renderdag/pipeline/
types.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#[cfg(feature = "serialize")]
9use serde::Serialize;
10
11use super::coloring;
12pub use crate::render::Ancestor;
13pub use crate::render::LinkLine;
14pub use crate::render::NodeLine;
15pub use crate::render::PadLine;
16
17/// Style choices that affect graph row shapes and text placement.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19#[cfg_attr(feature = "serialize", derive(Serialize))]
20pub struct GraphRowShapeStyle {
21    /// How long indirect-ancestor dash lines remain in ancestor style.
22    pub dash_style: DashStyle,
23
24    /// Where link-related padding lines are placed around the node line.
25    pub link_line_placement: LinkLinePlacement,
26
27    /// Requested number of character columns between adjacent vertical lines.
28    /// Box drawing uses this value directly, including zero for no gap.
29    /// ASCII uses at least one; ASCII large uses at least two.
30    pub column_spacing: usize,
31
32    /// Additional spaces between the graph prefix and message text.
33    /// The prefix may already contain trailing column padding.
34    pub text_gap: usize,
35}
36
37impl Default for GraphRowShapeStyle {
38    fn default() -> Self {
39        Self {
40            dash_style: DashStyle::Persistent,
41            link_line_placement: LinkLinePlacement::Top,
42            column_spacing: 1,
43            text_gap: 1,
44        }
45    }
46}
47
48/// How indirect-ancestor dash lines continue across rows.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50#[cfg_attr(feature = "serialize", derive(Serialize))]
51pub enum DashStyle {
52    /// Keep ancestor lines in ancestor style until the branch disappears.
53    ///
54    /// ```plain
55    ///   o
56    ///   ╷
57    ///   ╷
58    ///   ╷
59    ///   o
60    /// ```
61    Persistent,
62
63    /// Render ancestor style at most once per branch, then continue as parent.
64    ///
65    /// ```plain
66    ///   o
67    ///   ┆
68    ///   │
69    ///   │
70    ///   o
71    /// ```
72    Once,
73}
74
75/// Where link-line padding is placed relative to the node line.
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77#[cfg_attr(feature = "serialize", derive(Serialize))]
78pub enum LinkLinePlacement {
79    /// Link lines are at the top.
80    ///
81    /// ```plain
82    ///   o
83    ///   ├─╮
84    ///   │ │
85    ///   │ │
86    /// ```
87    #[default]
88    Top,
89
90    /// Link lines are at the bottom.
91    ///
92    /// ```plain
93    ///   o
94    ///   │
95    ///   │
96    ///   ├─╮
97    /// ```
98    Bottom,
99}
100
101/// Options that affect the graph row shape produced from the input node stream.
102///
103/// These options belong to the first pipeline stage. They may affect column
104/// allocation, separator rows, and the abstract edge shape. They do not choose
105/// glyph characters or place message text.
106pub type GraphRowShapeOptions = crate::OutputRendererOptions;
107
108/// An abstract graph row shape for one rendered node.
109///
110/// This is the output of the graph-to-rows stage. It captures the node's
111/// current column, the edge shape around it, and any row-level facts needed by
112/// later stages. It intentionally does not contain glyphs or message text.
113///
114/// Example of different type of lines, depending on the rendering style,
115/// certain lines can be skipped or repeated:
116///
117/// ```plain
118///   │                            // pre_node_line() (optional, repeatable)
119///   │                            // pre_node_line()
120///   o      F                     // node_line (mandory, once)
121///   │      very long message 0   // post_node_line() (optional, repeatable)
122///   │      very long message 0   // post_node_line()
123///   ├─┬─╮  very long message 1   // link_line (mandory, once)
124///   │ │ ~  very long message 2   // term_line (mandory, once)
125///   : │    very long message 3   // ancestry_line (mandory, once or repeatable)
126///   │ │    very long message 4   // post_ancestry_line() (optional, repeatable)
127///   │ │    very long message 5   // post_ancestry_line()
128/// ```
129#[derive(Clone, Debug, PartialEq, Eq)]
130// This is `Serialize` so non-text environment (e.g. via wasm) can get
131// the rich data (than just ambiguous text characters) to render more
132// precisely. Example: `RenderDag.js` in D41252231.
133#[cfg_attr(feature = "serialize", derive(Serialize))]
134pub struct GraphRowShape<N> {
135    /// The node represented by this row.
136    pub node: N,
137
138    /// True if this row connects to multiple parents.
139    ///
140    /// Some prefix renderers use this to choose clearer junction glyphs.
141    pub merge: bool,
142
143    /// True if this row needs a blank separator before its graph lines.
144    pub separator_line: bool,
145
146    /// Style used to produce this row shape.
147    pub style: GraphRowShapeStyle,
148
149    /// True if this node is a head (no children, uses a new column).
150    pub is_head: bool,
151
152    /// True if this node has no parents.
153    pub is_root: bool,
154
155    /// The column containing the node glyph.
156    pub node_column: usize,
157
158    /// The columns occupied by this node's parents.
159    pub parent_columns: Vec<usize>,
160
161    /// Abstract columns for the line containing the node.
162    pub node_line: Vec<NodeLine>,
163
164    /// Abstract columns for the line connecting the node to its parents.
165    ///
166    /// This is absent when the node and its parents can be represented without
167    /// an explicit link line.
168    pub link_line: Option<Vec<LinkLine>>,
169
170    /// Terminator columns for anonymous parents.
171    ///
172    /// A `true` entry marks a column where the edge should terminate. Other
173    /// columns should be rendered using the row's padding columns.
174    pub term_line: Option<Vec<bool>>,
175
176    /// Abstract columns for ancestry continuation below this row.
177    pub ancestry_line: Vec<PadLine>,
178
179    /// Optional line identities for graph coloring.
180    #[cfg(feature = "coloring")]
181    pub line_ids: Option<Box<coloring::GraphRowLineIds>>,
182}
183
184// See `GraphRowShape` docstring for what the lines mean.
185impl<N> GraphRowShape<N> {
186    /// True if the ancestry line contains an indirect ancestor edge.
187    pub fn has_indirect_ancestor(&self) -> bool {
188        self.ancestry_line.contains(&PadLine::Ancestor)
189    }
190
191    /// Derive the repeatable padding line before the node line.
192    pub fn pre_node_line(&self) -> Vec<PadLine> {
193        self.node_line
194            .iter()
195            .map(|line| node_to_pad_line(*line, self.is_head))
196            .collect()
197    }
198
199    /// Derive the repeatable padding line after the node line.
200    pub fn post_node_line(&self) -> Vec<PadLine> {
201        self.node_line
202            .iter()
203            .map(|line| node_to_pad_line(*line, self.is_root))
204            .collect()
205    }
206
207    /// Derive the repeatable padding line after the ancestry line.
208    pub fn post_ancestry_line(&self) -> Vec<PadLine> {
209        self.ancestry_line
210            .iter()
211            .map(|line| match line {
212                PadLine::Ancestor => PadLine::Parent,
213                other => *other,
214            })
215            .collect()
216    }
217}
218
219fn node_to_pad_line(line: NodeLine, use_blank_for_node: bool) -> PadLine {
220    match line {
221        NodeLine::Blank => PadLine::Blank,
222        NodeLine::Ancestor => PadLine::Ancestor,
223        NodeLine::Parent => PadLine::Parent,
224        NodeLine::Node => {
225            if use_blank_for_node {
226                PadLine::Blank
227            } else {
228                PadLine::Parent
229            }
230        }
231    }
232}
233
234/// A left-side graph prefix line before message text is attached.
235///
236/// This is the output of the row-shapes-to-prefix-lines stage. A prefix line
237/// may contain a node glyph slot, but it does not know what glyph will fill
238/// that slot and it does not contain any right-side message text.
239#[derive(Clone, Debug, PartialEq, Eq)]
240pub struct PrefixLine {
241    /// The ordered pieces that make up the graph prefix.
242    /// Text pieces can have an optional line ID. Built-in renderers leave node
243    /// glyph slots untracked so callers can style them independently.
244    /// With coloring enabled, `None` is used for untracked text and padding.
245    /// Without coloring, the metadata type is `()` and takes no space.
246    pub parts: Vec<(PrefixLinePart, coloring::PrefixLineColor)>,
247
248    /// The semantic role of this line within the rendered row.
249    pub kind: PrefixLineKind,
250}
251
252impl PrefixLine {
253    /// Create an empty prefix line of the given kind.
254    pub fn new(kind: PrefixLineKind) -> Self {
255        Self {
256            parts: Vec::with_capacity(if kind == PrefixLineKind::Node { 4 } else { 1 }),
257            kind,
258        }
259    }
260}
261
262/// A complete text line with an optional line ID for each fragment.
263/// Glyph slots have been filled; message and gap fragments have no line IDs.
264/// Newlines are represented by line boundaries, not embedded in the fragments.
265pub type TextLine = Vec<(String, coloring::PrefixLineColor)>;
266
267/// A piece of a graph prefix line.
268#[derive(Clone, Debug, PartialEq, Eq)]
269pub enum PrefixLinePart {
270    /// Literal graph text.
271    Text(String),
272
273    /// Placeholder for the rendered node glyph.
274    ///
275    /// Keeping the glyph as a slot lets callers cache prefix lines and fill in
276    /// status-dependent glyphs later.
277    NodeGlyph,
278}
279
280/// The semantic role of a prefix line.
281///
282/// The text-output stage can use this to decide where messages should attach,
283/// which lines may repeat, and which lines are meaningful for consumers that do
284/// not render plain text.
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
286#[cfg_attr(feature = "serialize", derive(Serialize))]
287pub enum PrefixLineKind {
288    /// A blank line separating disconnected one-line rows.
289    Separator,
290
291    /// A repeatable line before the node line.
292    PreNode,
293
294    /// The line containing the rendered node glyph.
295    Node,
296
297    /// A repeatable line after the node line and before edge links.
298    PostNode,
299
300    /// A line connecting the node to parent or ancestor columns.
301    Link,
302
303    /// A line terminating an anonymous parent edge.
304    Term,
305
306    /// A line continuing ancestry or parent edges.
307    Ancestry,
308
309    /// A repeatable line after ancestry continuation.
310    PostAncestry,
311}
312
313impl PrefixLineKind {
314    /// True if this line kind can be repeated to carry additional message lines.
315    pub fn is_repeatable(self) -> bool {
316        matches!(
317            self,
318            PrefixLineKind::PreNode | PrefixLineKind::PostNode | PrefixLineKind::PostAncestry
319        )
320    }
321}
322
323/// Converts graph row shapes into prefix lines.
324pub trait PrefixLineRenderer<N> {
325    /// Convert the next graph row shape into prefix lines.
326    fn next_prefix_lines(&mut self, row_shape: &GraphRowShape<N>) -> Vec<PrefixLine>;
327}