disposition_input_ir_rt 0.1.0

Logic to map `disposition` input model to intermediate representation.
Documentation
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use std::fmt::Write;

use base64::{prelude::BASE64_STANDARD, Engine};
use disposition_ir_model::entity::EntityTailwindClasses;
use disposition_svg_model::{SvgEdgeInfo, SvgElements, SvgNodeInfo};
use disposition_taffy_model::{TEXT_FONT_SIZE, TEXT_LINE_HEIGHT};

use crate::NOTO_SANS_MONO_TTF;

/// CSS variables to ensure CSS works correctly with `encre-css`.
///
/// These are copied from `DEFAULT_PREFLIGHT` in [`encre-css/src/preflight.rs`].
///
/// We use inline `<styles>` in an SVG, but when the SVG is embedded directly
/// into an HTML DOM, those styles leak to the global scope. `encre-css`'s
/// default `Preflight::Full` variant includes styling that resets all elements'
/// styles, which can break web pages.
///
/// However, for `encre-css`'s generated styles to work, the variables it
/// defines must still be present in the document, otherwise the styles (e.g.
/// transform) won't be applied.
///
/// [`encre-css/src/preflight.rs`]: https://gitlab.com/encre-org/encre-css/-/blob/v0.21.2/crates/encre-css/src/preflight.rs?ref_type=tags#L369-416
const ENCRE_CSS_VARIABLES: &str = "svg {
    --en-border-spacing-x: 0;
    --en-border-spacing-y: 0;
    --en-translate-x: 0;
    --en-translate-y: 0;
    --en-translate-z: 0;
    --en-rotate-x: 0;
    --en-rotate-y: 0;
    --en-rotate-z: 0;
    --en-skew-x: 0;
    --en-skew-y: 0;
    --en-scale-x: 1;
    --en-scale-y: 1;
    --en-scale-z: 1;
    --en-pan-x: ;
    --en-pan-y: ;
    --en-pinch-zoom: ;
    --en-scroll-snap-strictness: proximity;
    --en-ordinal: ;
    --en-slashed-zero: ;
    --en-numeric-figure: ;
    --en-numeric-spacing: ;
    --en-numeric-fraction: ;
    --en-ring-inset: ;
    --en-ring-offset-width: 0px;
    --en-ring-offset-color: #fff;
    --en-ring-color: currentColor;
    --en-ring-offset-shadow: 0 0 #0000;
    --en-ring-shadow: 0 0 #0000;
    --en-shadow: 0 0 #0000;
    --en-shadow-colored: 0 0 #0000;
    --en-blur: ;
    --en-brightness: ;
    --en-contrast: ;
    --en-grayscale: ;
    --en-hue-rotate: ;
    --en-invert: ;
    --en-saturate: ;
    --en-sepia: ;
    --en-drop-shadow: ;
    --en-backdrop-blur: ;
    --en-backdrop-brightness: ;
    --en-backdrop-contrast: ;
    --en-backdrop-grayscale: ;
    --en-backdrop-hue-rotate: ;
    --en-backdrop-invert: ;
    --en-backdrop-opacity: ;
    --en-backdrop-saturate: ;
    --en-backdrop-sepia: ;
}";

#[derive(Clone, Copy, Debug)]
pub struct SvgElementsToSvgMapper;

impl SvgElementsToSvgMapper {
    /// Renders the SVG elements to a string.
    pub fn map(svg_elements: &SvgElements) -> String {
        let SvgElements {
            svg_width,
            svg_height,
            svg_node_infos,
            svg_edge_infos,
            svg_process_infos: _,
            tailwind_classes,
            css,
        } = svg_elements;

        let mut content_buffer = String::with_capacity(4096);
        let mut styles_buffer = String::with_capacity(2048);

        // Add default text styles
        writeln!(
            &mut styles_buffer,
            "text {{ \
                font-family: 'Noto Sans Mono', \
                    ui-monospace, \
                    SFMono-Regular, \
                    Menlo, \
                    Monaco, \
                    Consolas, \
                    'Liberation Mono', \
                    monospace; \
                font-size: {TEXT_FONT_SIZE}px; \
                line-height: {TEXT_LINE_HEIGHT}px; \
            }}"
        )
        .unwrap();

        // Add default font
        writeln!(
            &mut styles_buffer,
            "@font-face {{ \
                font-family: 'Noto Sans Mono'; \
                src: url(data:application/x-font-ttf;base64,{}) format('truetype'); \
            }}",
            BASE64_STANDARD.encode(NOTO_SANS_MONO_TTF)
        )
        .unwrap();

        // Render nodes
        Self::render_nodes(&mut content_buffer, svg_node_infos, tailwind_classes);

        // Render edges
        Self::render_edges(&mut content_buffer, svg_edge_infos, tailwind_classes);

        // Generate CSS from tailwind classes
        //
        // We also need to escape underscores in brackets for correct tailwind class
        // generation.
        let escaped_classes: Vec<String> = tailwind_classes
            .values()
            .map(|classes| Self::escape_ids_in_brackets(classes))
            .collect();
        let tailwind_classes_iter = escaped_classes.iter().map(String::as_str).chain(
            svg_node_infos
                .iter()
                .flat_map(|svg_node_info| svg_node_info.wrapper_tailwind_classes.iter())
                .map(|wrapper_tailwind_classes| wrapper_tailwind_classes.as_ref()),
        );
        // TODO: generate an ID for the SVG so that the `<styles>` don't leak to outer
        // document.
        let encre_css_config = {
            let mut encre_css_config = encre_css::Config::default();
            encre_css_config.preflight = encre_css::Preflight::new_custom(ENCRE_CSS_VARIABLES);
            encre_css_config
        };
        let generated_css =
            encre_css::generate(tailwind_classes_iter, &encre_css_config).replace("&", "&amp;");

        // Build the style content
        let mut style_content =
            String::with_capacity(generated_css.len() + styles_buffer.len() + css.len());
        style_content.push_str(&generated_css);
        if !styles_buffer.is_empty() {
            if !style_content.is_empty() {
                style_content.push('\n');
            }
            style_content.push_str(&styles_buffer);
        }
        if !css.is_empty() {
            if !style_content.is_empty() {
                style_content.push('\n');
            }
            style_content.push_str(css.as_str());
        }

        // Build final SVG
        let mut buffer = String::with_capacity(128 + style_content.len() + content_buffer.len());

        // Start SVG element
        write!(
            buffer,
            "<svg \
                xmlns=\"http://www.w3.org/2000/svg\" \
                width=\"{svg_width}\" \
                height=\"{svg_height}\" \
                class=\"group\"\
            >"
        )
        .unwrap();

        // Add style element first (before content)
        if !style_content.is_empty() {
            write!(buffer, "<style>{style_content}</style>").unwrap();
        }

        // Add content
        buffer.push_str(&content_buffer);

        // Close SVG element
        buffer.push_str("</svg>");

        buffer
    }

    /// Writes nodes to the SVG content buffer.
    ///
    /// These will be rendered as the following elements (some attributes
    /// omitted):
    ///
    /// ```svg
    /// <g id="{node_id}" ..>
    ///   <!-- background rectangle -->
    ///   <path d="{path_d}" .. />
    ///
    ///   <!-- node text -->
    ///   <text .. >{line_1}</text>
    ///   <text .. >{line_2}</text>
    /// </g>
    /// ```
    fn render_nodes(
        content_buffer: &mut String,
        svg_node_infos: &[SvgNodeInfo<'_>],
        tailwind_classes: &EntityTailwindClasses<'_>,
    ) {
        svg_node_infos.iter().for_each(|svg_node_info| {
            let node_id = &svg_node_info.node_id;
            let tab_index = svg_node_info.tab_index;
            let path_d = &svg_node_info.path_d_collapsed;

            let class_attr = {
                let tailwind_classes = tailwind_classes
                    .get(node_id.as_ref())
                    .cloned()
                    .unwrap_or_default();

                Self::class_attr_escaped(tailwind_classes)
            };

            // Start group element with id, tabindex, and optional class
            write!(
                content_buffer,
                r#"<g id="{node_id}"{class_attr} tabindex="{tab_index}">"#
            )
            .unwrap();

            // Add path element with corner radii.
            // If a circle is present, apply wrapper_tailwind_classes to make the
            // rect path invisible, and render the circle path separately.
            write!(content_buffer, r#"<path d="{path_d}" class="wrapper"#).unwrap();
            if let Some(wrapper_tw) = svg_node_info.wrapper_tailwind_classes.as_ref() {
                write!(content_buffer, " {wrapper_tw}").unwrap();
            }
            write!(content_buffer, r#"" />"#).unwrap();

            // Add circle path element if present
            if let Some(ref circle) = svg_node_info.circle {
                let circle_path_d = &circle.path_d;
                write!(content_buffer, r#"<path d="{circle_path_d}" />"#).unwrap();
            }

            // Add text elements for highlighted spans
            svg_node_info.text_spans.iter().for_each(|span| {
                let text_x = span.x;
                let text_y = span.y;
                let text_content = &span.text;

                // zero stroke-width because we want the tailwind classes from `<g>` to
                // apply to the `<path>`, but not to the `<text>`
                write!(
                    content_buffer,
                    "<text \
                        x=\"{text_x}\" \
                        y=\"{text_y}\" \
                        stroke-width=\"0\" \
                    >{text_content}</text>"
                )
                .unwrap();
            });

            // Close group element
            content_buffer.push_str("</g>");
        });
    }

    /// Writes edges to the SVG content buffer.
    ///
    /// These will be rendered as the following elements (some attributes
    /// omitted):
    ///
    /// ```svg
    /// <g id="{edge_id}" .. >
    ///   <path d="{path_d}" .. />
    ///   <g class="arrow_head" .. >
    ///     <path d="{arrow_head_path_d}" .. />
    ///   </g>
    /// </g>
    /// ```
    ///
    /// For interaction edges the arrowhead `<path>` also carries
    /// `offset-path`, `offset-rotate`, and animation tailwind classes
    /// looked up via the `{edge_id}__arrow_head` entity key.
    fn render_edges(
        content_buffer: &mut String,
        svg_edge_infos: &[SvgEdgeInfo<'_>],
        tailwind_classes: &EntityTailwindClasses<'_>,
    ) {
        svg_edge_infos.iter().for_each(|svg_edge_info| {
            let edge_id = &svg_edge_info.edge_id;
            let edge_group_id = &svg_edge_info.edge_group_id;
            let path_d = &svg_edge_info.path_d;
            let arrow_head_path_d = &svg_edge_info.arrow_head_path_d;

            // Build class attribute from tailwind_classes for the edge
            // First check for edge-specific classes, then fall back to edge group classes
            let class_attr = {
                let edge_classes = tailwind_classes
                    .get(edge_id.as_ref())
                    .map(|s| s.as_str())
                    .unwrap_or("");

                let edge_group_classes = tailwind_classes
                    .get(edge_group_id.as_ref())
                    .map(|s| s.as_str())
                    .unwrap_or("");

                let combined = if edge_classes.is_empty() {
                    edge_group_classes.to_string()
                } else if edge_group_classes.is_empty() {
                    edge_classes.to_string()
                } else {
                    format!("{edge_group_classes}\n{edge_classes}")
                };

                Self::class_attr_escaped(combined)
            };

            // Build class attribute for the arrowhead element.
            //
            // For interaction edges the builder stores offset-path and
            // animation tailwind classes under the key
            // `{edge_id}__arrow_head`.  For dependency edges no such entry
            // exists, so we fall back to a plain `arrow_head` class.
            let arrow_head_entity_key = format!("{edge_id}_arrow_head");
            let arrow_head_class_attr = if let Ok(arrow_head_id) =
                disposition_model_common::Id::try_from(arrow_head_entity_key)
            {
                let extra = tailwind_classes
                    .get(&arrow_head_id)
                    .map(|s| s.as_str())
                    .unwrap_or("");
                if extra.is_empty() {
                    Self::class_attr_escaped("arrow_head".to_string())
                } else {
                    Self::class_attr_escaped(format!("arrow_head\n{extra}"))
                }
            } else {
                Self::class_attr_escaped("arrow_head".to_string())
            };

            // Render edge as a group with a path and an arrowhead path
            //
            // The edge path has fill="none" since edges are stroked lines,
            // not filled shapes.  The arrowhead is a closed V-shape that
            // inherits stroke/fill from the <g>.
            write!(
                content_buffer,
                "<g \
                    id=\"{edge_id}\"\
                    {class_attr}\
                >\
                    <path \
                        d=\"{path_d}\" \
                        fill=\"none\" \
                    />\
                    <g \
                        {arrow_head_class_attr} \
                    >\
                        <path \
                            d=\"{arrow_head_path_d}\" \
                        />\
                    </g>
                </g>"
            )
            .unwrap();
        });
    }

    /// Returns the `class=".."` attribute with `&` escaped as `&amp;`.
    fn class_attr_escaped(tailwind_classes: String) -> String {
        if tailwind_classes.is_empty() {
            String::new()
        } else {
            let ampersand_count = tailwind_classes.matches('&').count();
            let mut classes_str =
                String::with_capacity(tailwind_classes.len() + ampersand_count * 5 + 10);
            classes_str.push_str(r#" class=""#);
            tailwind_classes.chars().for_each(|c| {
                if c == '&' {
                    classes_str.push_str("&amp;");
                } else {
                    classes_str.push(c);
                }
            });
            classes_str.push('"');
            classes_str
        }
    }

    /// Escapes underscores within ID selectors inside arbitrary variant
    /// brackets (`[...]`) in a tailwind class string.
    ///
    /// This is needed because encre-css interprets underscores as spaces within
    /// arbitrary variants. By replacing `_` with `&#95;` inside ID selectors
    /// (e.g. `#some_id`), we preserve the literal underscore in the generated
    /// CSS.
    ///
    /// Only underscores that are part of an ID selector (starting with `#`) are
    /// escaped. For example:
    /// - `group-has-[#some_id:focus]` -> `group-has-[#some&#95;id:focus]`
    /// - `peer/some-peer:animate-[animation-name_2s_linear_infinite]` ->
    ///   unchanged
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use disposition_input_ir_rt::SvgElementsToSvgMapper;
    /// // ID selectors have underscores escaped
    /// assert_eq!(
    ///     SvgElementsToSvgMapper::escape_ids_in_brackets(
    ///         "group-has-[#some_id:focus]:stroke-blue-500"
    ///     ),
    ///     "group-has-[#some&#95;id:focus]:stroke-blue-500"
    /// );
    ///
    /// // Multiple underscores in ID
    /// assert_eq!(
    ///     SvgElementsToSvgMapper::escape_ids_in_brackets(
    ///         "group-has-[#my_element_id:hover]:fill-red-500"
    ///     ),
    ///     "group-has-[#my&#95;element&#95;id:hover]:fill-red-500"
    /// );
    ///
    /// // Animation values are NOT escaped (no ID selector)
    /// assert_eq!(
    ///     SvgElementsToSvgMapper::escape_ids_in_brackets(
    ///         "peer/some-peer:animate-[animation-name_2s_linear_infinite]"
    ///     ),
    ///     "peer/some-peer:animate-[animation-name_2s_linear_infinite]"
    /// );
    ///
    /// // Mixed: ID escaped, non-ID not escaped
    /// assert_eq!(
    ///     SvgElementsToSvgMapper::escape_ids_in_brackets(
    ///         "group-has-[#some_id:focus]:animate-[fade_in_1s]"
    ///     ),
    ///     "group-has-[#some&#95;id:focus]:animate-[fade_in_1s]"
    /// );
    ///
    /// // No brackets - unchanged
    /// assert_eq!(
    ///     SvgElementsToSvgMapper::escape_ids_in_brackets("text_red-500"),
    ///     "text_red-500"
    /// );
    /// ```
    pub fn escape_ids_in_brackets(classes: &str) -> String {
        let mut bracket_depth: u32 = 0;
        let mut is_parsing_id = false;

        classes
            .chars()
            .fold(String::with_capacity(classes.len()), |mut result, c| {
                // https://docs.rs/encre-css/latest/encre_css/plugins/typography/content/index.html
                match c {
                    '[' => {
                        bracket_depth += 1;
                        is_parsing_id = false;
                        result.push(c);
                    }
                    ']' => {
                        bracket_depth = bracket_depth.saturating_sub(1);
                        is_parsing_id = false;
                        result.push(c);
                    }
                    '#' if bracket_depth > 0 => {
                        is_parsing_id = true;
                        result.push(c);
                    }
                    '"' if bracket_depth > 0 => {
                        result.push_str("&#34;");
                    }
                    '\'' if bracket_depth > 0 => {
                        result.push_str("&#39;");
                    }
                    '(' if bracket_depth > 0 => {
                        result.push_str("&#40;");
                    }
                    ')' if bracket_depth > 0 => {
                        result.push_str("&#41;");
                    }
                    '_' if bracket_depth > 0 && is_parsing_id => {
                        result.push_str("&#95;");
                    }
                    // Characters that end an ID context (not valid in CSS IDs)
                    ':' | ' ' | ',' | '.' | '>' | '+' | '~' | '(' | ')' if is_parsing_id => {
                        is_parsing_id = false;
                        result.push(c);
                    }
                    _ => {
                        result.push(c);
                    }
                }
                result
            })
    }
}