konoma 0.28.1

Terminal file browser built for AI pair-programming — full-screen previews (Markdown, images, PDF, CSV), a git suite (jj/Jujutsu in preview), and an agent-watch mode that follows your AI's edits (macOS and Linux)
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
//! The intermediate representation the sequence parser produces.
//!
//! Structure, no geometry — the same contract the other four parsers have. The shape is mermaid's
//! own (`sequenceDb.ts`): a list of participants in the order they first appeared, the boxes that
//! group them, and **one flat stream of events in source order**. Nesting is not a tree here
//! because it is not a tree upstream either: a `loop` is a `BlockStart` event and an `end` is a
//! `BlockEnd` event, and everything between them is simply what came in between. That is what
//! makes "a message's y is greater than the previous message's" a statement about a list rather
//! than a walk, and it is why the renderer can lay the diagram out with one pass and a stack.

use std::collections::HashMap;
use std::fmt;

/// How a participant is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ParticipantKind {
    /// `participant A` — a labelled box.
    #[default]
    Participant,
    /// `actor A` — a stick figure over the name. See [`render::sequence`] for why konoma draws
    /// the figure where the crate it replaces draws another box.
    ///
    /// [`render::sequence`]: crate::preview::mermaid::render::sequence
    Actor,
}

/// One participant, in the order it first appeared.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Participant {
    /// The name messages refer to it by.
    pub id: String,
    /// The text drawn: the alias when `participant A as Alice` gave one, else the id.
    pub label: String,
    /// Box or stick figure.
    pub kind: ParticipantKind,
    /// Index into [`SequenceDiagram::events`] of the `create` that declared it, if any. A created
    /// participant is not drawn until the message that creates it.
    pub created_at: Option<usize>,
    /// Index into [`SequenceDiagram::events`] of the `destroy` that ended it, if any.
    pub destroyed_at: Option<usize>,
    /// The `box` that holds it, if any.
    pub box_id: Option<String>,
}

/// One `box` — a group of participants drawn as a vertical band.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ParticipantBox {
    /// Generated: `box<n>`.
    pub id: String,
    /// The text on the band. Empty for `box` with no title.
    pub title: String,
    /// The colour the author asked for, kept and **not drawn** — see [`SequenceDiagram`].
    pub color: Option<String>,
    /// The participants inside, in declaration order.
    pub members: Vec<String>,
}

/// Whether a message's shaft is drawn solid or dashed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Line {
    /// One dash: `->`, `->>`, `-x`, `-)`.
    #[default]
    Solid,
    /// Two dashes: `-->`, `-->>`, `--x`, `--)`. A reply, by convention.
    Dotted,
}

/// What is drawn at one end of a message.
///
/// Four kinds, which is what mermaid's marker set comes to once the sixteen half-arrow spellings
/// are folded together (see [`super::parser`]): nothing, a filled triangle, a cross, and the
/// concave chevron mermaid calls `filled-head` and its documentation calls "an open arrow
/// (async)".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Head {
    /// `->` and `-->`: mermaid's documentation calls these "solid/dotted line **without** arrow",
    /// and its renderer really does attach no marker to them.
    #[default]
    None,
    /// `->>`, `-->>`, and both ends of `<<->>` / `<<-->>`.
    Arrow,
    /// `-x` and `--x`.
    Cross,
    /// `-)` and `--)` — an asynchronous message.
    Async,
}

/// A message's line style and the mark at each of its ends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Signal {
    /// Solid or dashed.
    pub line: Line,
    /// The mark at the sending end. Only `<<->>` / `<<-->>` and the reverse half-arrows put one
    /// here.
    pub start: Head,
    /// The mark at the receiving end.
    pub end: Head,
}

/// One message.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Message {
    /// Sender.
    pub from: String,
    /// Receiver.
    pub to: String,
    /// The text after the `:`, with `<br>` already turned into newlines.
    pub text: String,
    /// What is drawn.
    pub signal: Signal,
    /// 1-based source line, for diagnostics.
    pub line: usize,
}

/// Which side of a participant a note is drawn on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Placement {
    /// `note left of A`.
    LeftOf,
    /// `note right of A`.
    RightOf,
    /// `note over A` and `note over A,B`.
    #[default]
    Over,
}

/// One note.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Note {
    /// One participant, or the two of a `note over A,B`.
    pub actors: Vec<String>,
    /// Which side.
    pub placement: Placement,
    /// The text after the `:`.
    pub text: String,
}

/// A block statement that opens a frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BlockKind {
    /// `loop`.
    Loop,
    /// `alt`, which `else` divides.
    Alt,
    /// `opt`.
    Opt,
    /// `par`, which `and` divides.
    Par,
    /// `par_over` — a `par` mermaid draws with its sections overlapping. konoma draws it as a
    /// `par`; see [`super::parser`].
    ParOver,
    /// `critical`, which `option` divides.
    Critical,
    /// `break`.
    Break,
    /// `rect` — a background highlight. The colour is parsed and not drawn.
    Rect,
    /// `try { … } catch { … }` — **ZenUML only**. `sequenceDiagram` has no such keyword, and
    /// mapping it onto `critical` would draw a frame labelled "critical" around a try block,
    /// which says something the author did not.
    Try,
}

impl BlockKind {
    /// The keyword, as it is written and as it is drawn on the frame.
    pub fn keyword(self) -> &'static str {
        match self {
            BlockKind::Loop => "loop",
            BlockKind::Alt => "alt",
            BlockKind::Opt => "opt",
            BlockKind::Par | BlockKind::ParOver => "par",
            BlockKind::Critical => "critical",
            BlockKind::Break => "break",
            BlockKind::Rect => "rect",
            BlockKind::Try => "try",
        }
    }
}

/// A statement that divides an open block into sections.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SectionKind {
    /// `else`, inside `alt`.
    Else,
    /// `and`, inside `par`.
    And,
    /// `option`, inside `critical`.
    Option,
    /// `catch`, inside a ZenUML `try`.
    Catch,
    /// `finally`, inside a ZenUML `try`.
    Finally,
}

impl SectionKind {
    /// The keyword, as written and as drawn.
    pub fn keyword(self) -> &'static str {
        match self {
            SectionKind::Else => "else",
            SectionKind::And => "and",
            SectionKind::Option => "option",
            SectionKind::Catch => "catch",
            SectionKind::Finally => "finally",
        }
    }
}

/// What `autonumber` asked for.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum AutoNumber {
    /// `autonumber`, `autonumber <start>`, `autonumber <start> <step>`.
    On {
        /// The number the next message gets.
        start: f64,
        /// How much each message after it adds.
        step: f64,
    },
    /// `autonumber off`.
    #[default]
    Off,
}

/// One thing that happened, in source order.
///
/// The stream is flat on purpose — see the module docs.
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
    /// A message from one participant to another.
    Message(Message),
    /// A note beside or over a participant.
    Note(Note),
    /// `activate A`, or the `+` on a message (which lands here immediately after it).
    Activate(String),
    /// `deactivate A`, or the `-` on a message.
    Deactivate(String),
    /// `loop` / `alt` / `opt` / `par` / `critical` / `break` / `rect`.
    BlockStart {
        /// Which keyword opened it.
        kind: BlockKind,
        /// The rest of the line.
        title: String,
    },
    /// `else` / `and` / `option`.
    Section {
        /// Which keyword.
        kind: SectionKind,
        /// The rest of the line.
        title: String,
    },
    /// `end`.
    BlockEnd,
    /// `autonumber` in any of its four forms.
    AutoNumber(AutoNumber),
    /// `create participant X` / `create actor X`. Carried as an event so the renderer knows *when*
    /// the participant appears.
    Create(String),
    /// `destroy X`.
    Destroy(String),
}

/// A parsed `sequenceDiagram`.
///
/// # What is parsed and deliberately not drawn
///
/// * `links` / `link` / `properties` / `details` declare an actor popup menu. There is nothing to
///   click in a terminal, so the payload is dropped — but the statement is still *parsed*, because
///   a statement a parser fails to understand becomes a phantom participant (§2-3).
/// * a `box`'s colour, and a `rect`'s. konoma composites onto the terminal (§1), so an opaque
///   highlight is a grey slab rather than a tint.
/// * `accTitle` / `accDescr`, which are for screen readers.
/// * the `wrap:` / `nowrap:` prefixes, because there is no automatic wrapping at all (§2-5).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SequenceDiagram {
    /// `title X`, `title: X`, or `title:` from a YAML front matter block. Drawn above everything.
    pub title: Option<String>,
    /// `accTitle:` — not drawn.
    pub acc_title: Option<String>,
    /// `accDescr:` in either form — not drawn.
    pub acc_descr: Option<String>,
    /// Every participant, in the order it first appeared.
    pub participants: Vec<Participant>,
    /// Every `box`, in source order.
    pub boxes: Vec<ParticipantBox>,
    /// Everything that happened, in source order.
    pub events: Vec<Event>,
    /// id -> index into [`SequenceDiagram::participants`]. Maintained by [`SequenceDiagram::ensure`]
    /// so that "has this participant been seen?" is one lookup rather than a scan.
    pub(super) index: HashMap<String, usize>,
}

impl SequenceDiagram {
    /// Looks a participant up by id.
    pub fn participant(&self, id: &str) -> Option<&Participant> {
        self.index.get(id).map(|i| &self.participants[*i])
    }

    /// Whether a participant with this id has been declared.
    pub fn has(&self, id: &str) -> bool {
        self.index.contains_key(id)
    }

    /// Puts a participant at the **front**, keeping the id index correct.
    ///
    /// Only [`zenuml`] needs this. Its implicit starter is discovered when the first top-level
    /// sync call is read, by which time other participants may already have been declared — and
    /// the starter has to be the leftmost lifeline, because "the call came from outside" is what
    /// its position says. Nothing happens if the id is already declared.
    ///
    /// [`zenuml`]: crate::preview::mermaid::zenuml
    pub fn push_front(&mut self, participant: Participant) {
        if self.index.contains_key(&participant.id) {
            return;
        }
        self.participants.insert(0, participant);
        self.index = self
            .participants
            .iter()
            .enumerate()
            .map(|(i, p)| (p.id.clone(), i))
            .collect();
    }

    /// Registers a participant if it is new, and returns its index either way.
    ///
    /// mermaid's `addActor`: **a message, a note, a `links` and a `link` all bring a participant
    /// into existence**, in the order they mention it, while `activate` and `destroy` do not (the
    /// grammar drops the `addParticipant` object those two produce). Getting that wrong reorders
    /// the columns.
    pub fn ensure(&mut self, id: &str, kind: ParticipantKind) -> usize {
        if let Some(i) = self.index.get(id) {
            return *i;
        }
        let i = self.participants.len();
        self.participants.push(Participant {
            id: id.to_string(),
            label: id.to_string(),
            kind,
            ..Participant::default()
        });
        self.index.insert(id.to_string(), i);
        i
    }

    /// Mutable access by id, for the statements that refine a participant already registered.
    pub fn participant_mut(&mut self, id: &str) -> Option<&mut Participant> {
        self.index
            .get(id)
            .copied()
            .map(|i| &mut self.participants[i])
    }

    /// Every message, in source order. The renderer walks the events; this is for the tests.
    pub fn messages(&self) -> impl Iterator<Item = &Message> {
        self.events.iter().filter_map(|e| match e {
            Event::Message(m) => Some(m),
            _ => None,
        })
    }

    /// Every note, in source order.
    pub fn notes(&self) -> impl Iterator<Item = &Note> {
        self.events.iter().filter_map(|e| match e {
            Event::Note(n) => Some(n),
            _ => None,
        })
    }
}

/// Why a source could not be read.
///
/// Every variant is a case where mermaid also refuses, except that konoma keeps the reason
/// (§8: the crate throws its messages away). Refusing means the fence degrades to the Unicode
/// text diagram — it is **never** handed to the crate for a second opinion (§1, stage 1's rule).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
    /// The source does not begin with `sequenceDiagram`.
    NotASequenceDiagram {
        /// The first word that was there instead, for the message.
        header: String,
    },
    /// Nothing but blank lines and comments.
    Empty,
    /// A `sequenceDiagram` header with no participant under it.
    ///
    /// Refused rather than drawn: an empty diagram rasterises to a transparent rectangle that the
    /// pane then stretches, which is exactly the failure §6 records the current crate having.
    NoParticipants,
    /// An `end` with no block open.
    UnmatchedEnd {
        /// 1-based source line.
        line: usize,
    },
    /// A block that never met its `end`.
    UnclosedBlock {
        /// The keyword that opened it.
        keyword: &'static str,
        /// 1-based source line of that keyword.
        line: usize,
    },
    /// An `else` / `and` / `option` outside any block.
    SectionOutsideBlock {
        /// The keyword.
        keyword: &'static str,
        /// 1-based source line.
        line: usize,
    },
    /// `deactivate X` (or a `-` suffix) where `X` has nothing to deactivate. mermaid throws
    /// "Trying to inactivate an inactive participant".
    NotActive {
        /// The participant named.
        name: String,
        /// 1-based source line.
        line: usize,
    },
    /// `create participant X` where `X` already exists. mermaid throws, because the two would be
    /// one column.
    DuplicateCreate {
        /// The participant named.
        name: String,
        /// 1-based source line.
        line: usize,
    },
    /// A statement that needs a participant and was given none, e.g. a bare `note over`.
    MissingActor {
        /// The keyword that needed one.
        keyword: &'static str,
        /// 1-based source line.
        line: usize,
    },
    /// More messages than the renderer will draw. mermaid has the same kind of ceiling
    /// (`maxEdges`); without one, a generated file can hang the worker thread.
    TooManyMessages {
        /// The ceiling.
        limit: usize,
    },
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::NotASequenceDiagram { header } => {
                write!(f, "not a sequence diagram: `{header}`")
            }
            ParseError::Empty => write!(f, "sequence diagram is empty"),
            ParseError::NoParticipants => write!(f, "sequence diagram declares no participants"),
            ParseError::UnmatchedEnd { line } => {
                write!(f, "`end` with no open block at line {line}")
            }
            ParseError::UnclosedBlock { keyword, line } => {
                write!(f, "`{keyword}` at line {line} was never closed with `end`")
            }
            ParseError::SectionOutsideBlock { keyword, line } => {
                write!(f, "`{keyword}` outside any block at line {line}")
            }
            ParseError::NotActive { name, line } => {
                write!(f, "`{name}` is not active at line {line}")
            }
            ParseError::DuplicateCreate { name, line } => {
                write!(
                    f,
                    "`{name}` already exists and cannot be created at line {line}"
                )
            }
            ParseError::MissingActor { keyword, line } => {
                write!(f, "`{keyword}` names no participant at line {line}")
            }
            ParseError::TooManyMessages { limit } => {
                write!(f, "sequence diagram has more than {limit} messages")
            }
        }
    }
}

impl std::error::Error for ParseError {}