Skip to main content

logicaffeine_web/ui/components/
ast_tree.rs

1//! The Syntax Tree: how a sentence parses, drawn with the Studio's tree.
2//!
3//! The top row is the whole sentence as parsed, and each row below splits its phrase into its
4//! parts. A row is a node's label — the formula piece it stands for, in the notation the Logic
5//! Output prints — then a pill naming its kind, in the reader's word and the colour of the one
6//! syntax palette (`--syntax-*`). A short note above the tree says how to read it, with a legend
7//! of the pill colours. Every level opens as the tree opens; a node's row folds its parts away.
8
9use crate::ui::components::tree::{Tree, TreeNode};
10use crate::AstNode;
11use dioxus::prelude::*;
12
13const SYNTAX_TREE_STYLE: &str = r#"
14/* How to read the tree, quietly above it: a line of prose, then the pill colours. */
15.syntax-tree-guide {
16    display: flex;
17    flex-direction: column;
18    gap: 8px;
19    font-size: 13px;
20    line-height: 1.5;
21    color: var(--studio-text-secondary);
22}
23
24.syntax-tree-note {
25    margin: 0;
26}
27
28.syntax-tree-legend {
29    display: flex;
30    flex-wrap: wrap;
31    gap: 6px;
32}
33
34/* The tree runs the column's whole width, so its first line stands one step from the column's
35   edge, and a tree wider than the column scrolls sideways across it. */
36.syntax-tree {
37    --tree-pad-top: 12px;
38    --tree-pad-bottom: 0px;
39    margin: 0 calc(-1 * var(--studio-inset, 20px));
40    overflow-x: auto;
41}
42
43.syntax-label {
44    flex: none;
45    margin-right: 8px;
46    font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
47    font-size: 13px;
48    color: var(--studio-text);
49    white-space: nowrap;
50}
51
52/* A kind's pill: its word in its swatch, on a tint of the same. */
53.syntax-kind {
54    flex: none;
55    padding: 2px 6px;
56    border-radius: 4px;
57    font-size: 13px;
58    line-height: 16px;
59    white-space: nowrap;
60    color: var(--kind, var(--studio-text-secondary));
61    background: color-mix(in srgb, var(--kind, var(--studio-text-secondary)) 18%, transparent);
62}
63
64.syntax-kind.quantifier { --kind: var(--syntax-quantifier); }
65.syntax-kind.connective { --kind: var(--syntax-connective); }
66.syntax-kind.predicate { --kind: var(--syntax-predicate); }
67.syntax-kind.individual { --kind: var(--syntax-individual); }
68.syntax-kind.role { --kind: var(--syntax-role); }
69.syntax-kind.variable { --kind: var(--syntax-variable); }
70.syntax-kind.modal { --kind: var(--syntax-modal); }
71.syntax-kind.tense { --kind: var(--syntax-tense); }
72"#;
73
74/// A swatch of the one syntax palette (`--syntax-*` in the Studio's tokens).
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum Swatch {
77    Quantifier,
78    Connective,
79    Predicate,
80    Individual,
81    Role,
82    Variable,
83    Modal,
84    Tense,
85}
86
87impl Swatch {
88    /// Its name in the palette: the pill's class and its token, `--syntax-{name}`.
89    pub fn name(self) -> &'static str {
90        match self {
91            Swatch::Quantifier => "quantifier",
92            Swatch::Connective => "connective",
93            Swatch::Predicate => "predicate",
94            Swatch::Individual => "individual",
95            Swatch::Role => "role",
96            Swatch::Variable => "variable",
97            Swatch::Modal => "modal",
98            Swatch::Tense => "tense",
99        }
100    }
101}
102
103/// A node kind as a reader sees it: the word its pill says and the swatch it wears.
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct KindLook {
106    pub word: &'static str,
107    pub swatch: Swatch,
108}
109
110/// The look of each kind the compiler names a node (`ui_bridge::expr_to_ast_node`), in the words
111/// the Symbol Dictionary uses where it has one.
112pub fn kind_look(node_type: &str) -> Option<KindLook> {
113    use Swatch::*;
114    let (word, swatch) = match node_type {
115        "quantifier" => ("quantifier", Quantifier),
116        "question" => ("question", Quantifier),
117        "binary_op" | "unary_op" => ("connective", Connective),
118        "identity" => ("identity", Connective),
119        "conditional" => ("conditional", Connective),
120        "causal" => ("causal", Connective),
121        "concessive" => ("concessive", Connective),
122        "lambda" => ("lambda", Connective),
123        "application" => ("application", Connective),
124        "speech_act" => ("speech act", Connective),
125        "implicature" => ("implicature", Connective),
126        "presupposition" => ("presupposition", Connective),
127        "focus" => ("focus", Connective),
128        "scopal" => ("scopal", Connective),
129        "distributive" => ("distributive", Connective),
130        "predicate" => ("predicate", Predicate),
131        "event" => ("event", Predicate),
132        "relation" => ("relation", Predicate),
133        "atom" => ("atom", Predicate),
134        "categorical" => ("categorical", Predicate),
135        "comparative" => ("comparative", Predicate),
136        "superlative" => ("superlative", Predicate),
137        "metaphor" => ("metaphor", Predicate),
138        "modifier" => ("modifier", Predicate),
139        "control" => ("control", Predicate),
140        "constant" => ("individual", Individual),
141        "term" => ("term", Individual),
142        "function" => ("function", Individual),
143        "group" => ("group", Individual),
144        "proposition" => ("proposition", Individual),
145        "role" => ("role", Role),
146        "variable" => ("variable", Variable),
147        "modal" => ("modal", Modal),
148        "intensional" => ("intensional", Modal),
149        "temporal" => ("tense", Tense),
150        "aspect" => ("aspect", Tense),
151        "voice" => ("voice", Tense),
152        _ => return None,
153    };
154    Some(KindLook { word, swatch })
155}
156
157/// The legend's groups: the kinds each pill colour marks, and the swatches that wear it. The
158/// swatches of one group share a colour in the palette.
159pub const LEGEND: &[(&str, &[Swatch])] = &[
160    (
161        "quantifier · connective",
162        &[Swatch::Quantifier, Swatch::Connective],
163    ),
164    ("predicate · event", &[Swatch::Predicate]),
165    ("individual · role", &[Swatch::Individual, Swatch::Role]),
166    ("variable", &[Swatch::Variable]),
167    ("modal · tense", &[Swatch::Modal, Swatch::Tense]),
168];
169
170#[component]
171pub fn AstTree(ast: AstNode) -> Element {
172    rsx! {
173        style { "{SYNTAX_TREE_STYLE}" }
174        div { class: "syntax-tree-guide",
175            p { class: "syntax-tree-note",
176                "Read it from the top: the first row is the whole sentence as parsed, and each row below splits its phrase into its parts. Press a row with a chevron to fold its parts away."
177            }
178            div { class: "syntax-tree-legend",
179                for (label, swatches) in LEGEND.iter() {
180                    span { key: "{label}", class: "syntax-kind {swatches[0].name()}", "{label}" }
181                }
182            }
183        }
184        Tree { kind: "syntax-tree", label: "Syntax Tree",
185            SyntaxNode { node: ast, depth: 0, last: true }
186        }
187    }
188}
189
190/// One node of the sentence and its parts. Every level opens as the tree opens.
191#[component]
192fn SyntaxNode(node: AstNode, depth: usize, last: bool) -> Element {
193    let mut open = use_signal(|| true);
194    let expandable = !node.children.is_empty();
195    let (word, swatch) = match kind_look(&node.node_type) {
196        Some(look) => (look.word.to_string(), look.swatch.name()),
197        None => (node.node_type.replace('_', " "), ""),
198    };
199    let count = node.children.len();
200
201    rsx! {
202        TreeNode {
203            depth,
204            last,
205            expandable,
206            open: open(),
207            stop: depth == 0,
208            on_press: if expandable {
209                Some(EventHandler::new(move |_| {
210                    let now = open();
211                    open.set(!now);
212                }))
213            } else {
214                None
215            },
216            row: rsx! {
217                span { class: "syntax-label", "{node.label}" }
218                span { class: "syntax-kind {swatch}", "{word}" }
219            },
220            for (i, child) in node.children.iter().enumerate() {
221                SyntaxNode { key: "{i}", node: child.clone(), depth: depth + 1, last: i + 1 == count }
222            }
223        }
224    }
225}
226
227#[cfg(test)]
228#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/components/ast_tree/tests.rs"]
229mod tests;