# Events and Event Types

This document describes the event system used by Wasot. For the overall event-driven [architecture](./architecture.md), see the architecture document.

Wasot uses an event-driven streaming model where documents are parsed into a sequence of events. This enables memory-efficient processing of files larger than available RAM.

## Event Enum

The core event type is defined in [`src/events/events.rs:55-86`](../src/events/events.rs).

```rust
pub enum Event {
    BlockStarted { meta_line: MetaLine },
    BlockFinished,
    TextFinished { lines: Vec<String>, links: Vec<Vec<Link>>, footnotes: Vec<Footnote> },
    ContextLine { meta_line: MetaLine },
    VoidElement { meta_line: MetaLine },
}
```

### BlockStarted

Fired when a new block is started. Contains the `MetaLine` that defined this block.

**Wasot syntax:**
```wasot
.paragraph                   # level 1 block
..nested                     # level 2 block
.div :my-id                  # block with ID
.p Some inline text          # block with inline text
.div .. class=container      # block with arguments
```

### BlockFinished

Fired when a block is finished. No payload - the block context is maintained by the consumer.

**Wasot syntax:**
```wasot
./                           # explicit close
                             # or implicit close when dedenting
```

### TextFinished

Fired when a text element is finished. Contains:
- `lines: Vec<String>` - The actual text lines
- `links: Vec<Vec<Link>>` - Links found in each line (one `Vec<Link>` per line)
- `footnotes: Vec<Footnote>` - Footnotes found in the text

**Wasot syntax:**
```wasot
.p
This is the text content.
Multiple lines are collected.
Check ((this link :https://example.com)) here.
```

### ContextLine

Fired when a context line is encountered. Context lines provide metadata without being part of the content hierarchy.

**Wasot syntax:**
```wasot
.%context-type value
```

### VoidElement

Fired when a void element is encountered. Void elements are self-closing and cannot have children (like HTML `<br>`, `<img>`).

**Wasot syntax:**
```wasot
.hr:                         # void element (trailing colon)
.img: alt text .. src=photo.jpg
```

---

## Supporting Data Structures

### MetaLine

Defined in [`src/parsers/wasot/parser.rs:101-113`](../src/parsers/wasot/parser.rs).

```rust
pub struct MetaLine {
    pub type_name: String,           // Block type (e.g., "p", "div", "h1")
    pub inline_text: QuotedString,   // Inline text after block type
    pub level: usize,                // Nesting level (number of dots)
    pub id: Id,                      // Optional block ID
    pub line_index: Option<usize>,   // Source line number
    pub arguments: ParsedArguments,  // Positional and keyword arguments
    pub is_void: bool,               // If true, this is a void element
}
```

### QuotedString

Defined in [`src/parsers/wasot/parser.rs:1-6`](../src/parsers/wasot/parser.rs).

```rust
pub struct QuotedString {
    pub content: String,    // The actual string content
    pub quoted: bool,       // Whether the string was originally quoted
    pub links: Vec<Link>,   // Links detected within the content
}
```

### Id

Defined in [`src/parsers/wasot/parser.rs:37-41`](../src/parsers/wasot/parser.rs).

```rust
pub struct Id {
    pub value: String,      // The ID value (supports base36 encoding)
}
```

IDs can be:
- String-based: `:my-custom-id`
- Numeric (base36-encoded): for auto-generated IDs

### ParsedArguments

Defined in [`src/parsers/wasot/arguments.rs:4-8`](../src/parsers/wasot/arguments.rs).

```rust
pub struct ParsedArguments {
    pub args: Vec<QuotedString>,                    // Positional arguments
    pub kwargs: Vec<(QuotedString, QuotedString)>,  // Key-value pairs
}
```

**Wasot syntax:**
```wasot
.block arg1 "arg with spaces" key=value "key with spaces"="value with spaces"
```

### Link

Defined in [`src/parsers/wasot/parser.rs:176-184`](../src/parsers/wasot/parser.rs).

```rust
pub struct Link {
    pub name: Option<QuotedString>,    // Display name
    pub target: Option<String>,        // Target reference
    pub target_type: TargetType,       // Type of target
    pub arguments: ParsedArguments,    // Link arguments
    pub start_index: usize,            // Position in source text
    pub length: usize,                 // Length in source text
}
```

**Wasot syntax:**
```wasot
((Click here :https://example.com))           # URI link
((See section :intro))                        # ID reference
((Reference :*1))                             # Footnote reference
((External :otherdoc.section))                # Cross-document link
((Named link .. arg1 key=val :target))        # Link with arguments
```

### TargetType

Defined in [`src/parsers/wasot/parser.rs:167-174`](../src/parsers/wasot/parser.rs).

```rust
pub enum TargetType {
    Uri,                                    // External URL
    Id,                                     // Local ID reference
    FootNote,                               // Footnote reference (*1, *2, etc.)
    IdInDocument(ExternalIdReference),      // Cross-document reference
}
```

### ExternalIdReference

Defined in [`src/parsers/wasot/parser.rs:115-120`](../src/parsers/wasot/parser.rs).

```rust
pub struct ExternalIdReference {
    pub document_id: Id,                // Target document ID
    pub local_id: Id,                   // ID within that document
    pub document_path: Option<String>,  // Resolved file path (if known)
}
```

### Footnote

Defined in [`src/parsers/wasot/footnote_parser.rs:1-5`](../src/parsers/wasot/footnote_parser.rs).

```rust
pub struct Footnote {
    pub marker: u32,       // Footnote number (e.g., 1, 2, 3)
    pub link: String,      // The footnote content/URL
}
```

**Wasot syntax (in text blocks):**
```wasot
*1 https://example.com/reference
*2 See chapter 5 for details
```

---

## Protobuf Definition

For serialization, events are also defined in [`proto/wasot.proto`](../proto/wasot.proto):

```protobuf
message WasotEvent {
  oneof event {
    BlockStartedEvent block_started = 1;
    BlockFinishedEvent block_finished = 2;
    TextEvent text_finished = 3;
    ContextLineEvent context_line = 4;
  }
}
```

---

## Emitter and Consumer Traits

### Emitter Trait

Defined in [`src/events/events.rs:4-22`](../src/events/events.rs).

```rust
pub trait Emitter: Send + Sync {
    type Reader: Iterator<Item = Event> + Send;

    fn subscribe(&self) -> Self::Reader;
    fn run(self);
    fn run_with_context(self, context: &mut Context);
}
```

### Consumer Trait

Defined in [`src/events/events.rs:24-52`](../src/events/events.rs).

```rust
pub trait Consumer: Send + Sync {
    fn on_start(&mut self) {}
    fn on_finish(&mut self) {}
    fn handle(&mut self, event: Event) {}
    fn handle_with_context(&mut self, event: Event, context: &mut Context);
    fn run<I>(&mut self, events: I) where I: Iterator<Item = Event> + Send;
}
```

---

## Event Flow Example

```
┌──────────────────┐
│   Wasot File     │
│   .wasot         │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│    Emitter       │
│  (WasotParser)   │
└────────┬─────────┘
         │ Events
         ▼
┌──────────────────┐     ┌──────────────────┐
│   Transformer    │────▶│    Consumer      │
│  (SelectorFilter)│     │  (XmlListener)   │
└──────────────────┘     └──────────────────┘
```

For more on the event flow, see [architecture](./architecture.md) and [emitter composition](./emitter_composition.md).
