mzrs-sdk 0.1.21

High-level Rust SDK for Mezon platform
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
//! Rich text builder with inline formatting spans.
//!
//! Produces the Mezon JSON content format with `t` (text), `mk`
//! (formatting), `hg` (hashtags), `ej` (emoji), and `lk`/`vk` (links).
//!
//! All positions are tracked as **UTF-16 code units** to match the
//! JavaScript client's string indexing.

use mzrs_proto::api::MessageMention;
use serde::{Deserialize, Serialize};

// ── Span types ──────────────────────────────────────────────────────

/// Strongly-typed span kind matching the Mezon wire format.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum SpanKind {
    /// Bold text.
    #[default]
    Bold,
    /// Italic text (SINGLE).
    Italic,
    /// Bold-italic (TRIPLE).
    Triple,
    /// Inline code.
    Code,
    /// Code block (pre-formatted).
    Pre,
    /// Hyperlink.
    Link,
    /// Voice-room link.
    Voice,
    /// YouTube link.
    YouTube,
    /// Strikethrough text.
    Strikethrough,
    /// Forward-compat fallback.
    Custom(String),
}

impl SpanKind {
    fn as_str(&self) -> &str {
        match self {
            SpanKind::Bold => "b",
            SpanKind::Italic => "s",
            SpanKind::Triple => "t",
            SpanKind::Code => "c",
            SpanKind::Pre => "pre",
            SpanKind::Link => "lk",
            SpanKind::Voice => "vk",
            SpanKind::YouTube => "lk_yt",
            SpanKind::Strikethrough => "st",
            SpanKind::Custom(s) => s.as_str(),
        }
    }
}

impl Serialize for SpanKind {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for SpanKind {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let raw = String::deserialize(d)?;
        Ok(match raw.as_str() {
            "b" => SpanKind::Bold,
            "s" => SpanKind::Italic,
            "t" => SpanKind::Triple,
            "c" => SpanKind::Code,
            "pre" => SpanKind::Pre,
            "lk" => SpanKind::Link,
            "vk" => SpanKind::Voice,
            "lk_yt" => SpanKind::YouTube,
            "st" => SpanKind::Strikethrough,
            _ => SpanKind::Custom(raw),
        })
    }
}

/// A single formatting region in the `mk` array.
///
/// Positions `s`/`e` are **UTF-16 code units**.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FormattingSpan {
    /// The type of formatting.
    #[serde(rename = "type")]
    pub kind: SpanKind,
    /// Start position (UTF-16 code units).
    pub s: usize,
    /// End position (UTF-16 code units).
    pub e: usize,
    /// URL for links, or language hint for code blocks.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub l: Option<String>,
}

/// A channel-hashtag annotation in the `hg` array.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HashtagSpan {
    /// The channel being referenced.
    #[serde(rename = "channelId")]
    pub channel_id: String,
    /// Start position (UTF-16).
    pub s: usize,
    /// End position (UTF-16).
    pub e: usize,
}

/// A custom-emoji annotation in the `ej` array.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EmojiSpan {
    /// The emoji ID.
    pub emojiid: String,
    /// Start position (UTF-16).
    pub s: usize,
    /// End position (UTF-16).
    pub e: usize,
}

/// A URL link span in the `lk` or `vk` array.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LinkSpan {
    /// Start position (UTF-16).
    pub s: usize,
    /// End position (UTF-16).
    pub e: usize,
}

/// Raw parts produced by [`RichText::into_parts`].
pub struct RichTextParts {
    /// The plain text content.
    pub text: String,
    /// Formatting spans.
    pub mk: Vec<FormattingSpan>,
    /// Hashtag spans.
    pub hg: Vec<HashtagSpan>,
    /// Emoji spans.
    pub ej: Vec<EmojiSpan>,
    /// Link spans.
    pub lk: Vec<LinkSpan>,
    /// Voice link spans.
    pub vk: Vec<LinkSpan>,
    /// Proto mention entries.
    pub mentions: Vec<MessageMention>,
}

/// Internal JSON structure for serialization.
#[derive(Serialize)]
struct RichTextJson {
    #[serde(rename = "t", skip_serializing_if = "str::is_empty")]
    t: String,
    #[serde(rename = "mk", skip_serializing_if = "Vec::is_empty")]
    mk: Vec<FormattingSpan>,
    #[serde(rename = "hg", skip_serializing_if = "Vec::is_empty")]
    hg: Vec<HashtagSpan>,
    #[serde(rename = "ej", skip_serializing_if = "Vec::is_empty")]
    ej: Vec<EmojiSpan>,
    #[serde(rename = "lk", skip_serializing_if = "Vec::is_empty")]
    lk: Vec<LinkSpan>,
    #[serde(rename = "vk", skip_serializing_if = "Vec::is_empty")]
    vk: Vec<LinkSpan>,
}

// ── RichText builder ────────────────────────────────────────────────

/// Fluent builder for Mezon rich-text message content.
///
/// Tracks positions in UTF-16 code units to match JavaScript client
/// expectations.
///
/// # Example
///
/// ```rust
/// use mzrs_sdk::RichText;
///
/// let (json, mentions) = RichText::new()
///     .text("Status: ")
///     .bold("ONLINE")
///     .text(" | code: ")
///     .code("42")
///     .finish();
///
/// assert!(json.contains("\"mk\""));
/// assert!(mentions.is_empty());
/// ```
#[derive(Debug, Default)]
pub struct RichText {
    buf: String,
    /// Running position in UTF-16 code units.
    pos: usize,
    mk: Vec<FormattingSpan>,
    mentions: Vec<MessageMention>,
    hg: Vec<HashtagSpan>,
    ej: Vec<EmojiSpan>,
    lk: Vec<LinkSpan>,
    vk: Vec<LinkSpan>,
}

impl RichText {
    /// Create a new empty rich text builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Count UTF-16 code units in a string.
    fn u16len(s: &str) -> usize {
        s.encode_utf16().count()
    }

    /// Push text and advance the UTF-16 position.
    fn push(&mut self, s: &str) {
        self.buf.push_str(s);
        self.pos += Self::u16len(s);
    }

    // ── Plain text ──────────────────────────────────────────────────

    /// Append plain (unstyled) text.
    pub fn text(mut self, t: &str) -> Self {
        self.push(t);
        self
    }

    /// Append a newline character.
    pub fn newline(mut self) -> Self {
        self.push("\n");
        self
    }

    // ── Inline formatting ───────────────────────────────────────────

    /// Append **bold** text.
    pub fn bold(mut self, t: &str) -> Self {
        let s = self.pos;
        self.push(t);
        self.mk.push(FormattingSpan {
            kind: SpanKind::Bold,
            s,
            e: self.pos,
            l: None,
        });
        self
    }

    /// Append *italic* text.
    pub fn italic(mut self, t: &str) -> Self {
        let s = self.pos;
        self.push(t);
        self.mk.push(FormattingSpan {
            kind: SpanKind::Italic,
            s,
            e: self.pos,
            l: None,
        });
        self
    }

    /// Append ~~strikethrough~~ text.
    pub fn strikethrough(mut self, t: &str) -> Self {
        let s = self.pos;
        self.push(t);
        self.mk.push(FormattingSpan {
            kind: SpanKind::Strikethrough,
            s,
            e: self.pos,
            l: None,
        });
        self
    }

    /// Append inline `code`.
    pub fn code(mut self, t: &str) -> Self {
        let s = self.pos;
        self.push(t);
        self.mk.push(FormattingSpan {
            kind: SpanKind::Code,
            s,
            e: self.pos,
            l: None,
        });
        self
    }

    /// Append a code block.
    pub fn code_block(mut self, code: &str) -> Self {
        let s = self.pos;
        self.push(code);
        self.mk.push(FormattingSpan {
            kind: SpanKind::Pre,
            s,
            e: self.pos,
            l: None,
        });
        self
    }

    /// Append a code block with a language hint.
    pub fn code_block_lang(mut self, code: &str, lang: &str) -> Self {
        let s = self.pos;
        self.push(code);
        self.mk.push(FormattingSpan {
            kind: SpanKind::Pre,
            s,
            e: self.pos,
            l: Some(lang.to_owned()),
        });
        self
    }

    // ── Links ───────────────────────────────────────────────────────

    /// Append a clickable URL.
    ///
    /// The URL is placed directly in the text buffer — the Mezon protocol
    /// identifies links by their position in `t`, so the URL **must** be
    /// the visible text at `s..e`. Custom display text is not supported by
    /// the wire format.
    pub fn link(mut self, url: &str) -> Self {
        let s = self.pos;
        self.push(url);
        let e = self.pos;
        self.lk.push(LinkSpan { s, e });
        self.mk.push(FormattingSpan {
            kind: SpanKind::Link,
            s,
            e,
            l: None,
        });
        self
    }

    /// Append a voice-room link.
    pub fn voice_link(mut self, url: &str) -> Self {
        let s = self.pos;
        self.push(url);
        let e = self.pos;
        self.vk.push(LinkSpan { s, e });
        self.mk.push(FormattingSpan {
            kind: SpanKind::Voice,
            s,
            e,
            l: None,
        });
        self
    }

    // ── Hashtag / Emoji ─────────────────────────────────────────────

    /// Append a `#channel-name` hashtag.
    pub fn hashtag(mut self, channel_id: impl Into<String>, name: &str) -> Self {
        let s = self.pos;
        self.push(&format!("#{name}"));
        self.hg.push(HashtagSpan {
            channel_id: channel_id.into(),
            s,
            e: self.pos,
        });
        self
    }

    /// Append a custom emoji.
    pub fn emoji(mut self, emoji_id: impl Into<String>, shortcode: &str) -> Self {
        let s = self.pos;
        self.push(shortcode);
        self.ej.push(EmojiSpan {
            emojiid: emoji_id.into(),
            s,
            e: self.pos,
        });
        self
    }

    // ── Mentions ────────────────────────────────────────────────────

    /// Append `@username` and register the proto mention.
    pub fn mention_user(mut self, user_id: i64, username: &str) -> Self {
        let s = self.pos as i32;
        self.push(&format!("@{username}"));
        let e = self.pos as i32;
        self.mentions.push(MessageMention {
            user_id,
            username: username.to_owned(),
            s,
            e,
            ..Default::default()
        });
        self
    }

    /// Append `@rolename` and register the proto mention for a role.
    pub fn mention_role(mut self, role_id: i64, rolename: &str) -> Self {
        let s = self.pos as i32;
        self.push(&format!("@{rolename}"));
        let e = self.pos as i32;
        self.mentions.push(MessageMention {
            role_id,
            rolename: rolename.to_owned(),
            s,
            e,
            ..Default::default()
        });
        self
    }

    // ── Build ───────────────────────────────────────────────────────

    /// Consume and return the raw parts without JSON serialisation.
    pub fn into_parts(self) -> RichTextParts {
        RichTextParts {
            text: self.buf,
            mk: self.mk,
            hg: self.hg,
            ej: self.ej,
            lk: self.lk,
            vk: self.vk,
            mentions: self.mentions,
        }
    }

    /// Finalise and return `(content_json_string, proto_mentions)`.
    pub fn finish(self) -> (String, Vec<MessageMention>) {
        let mentions = self.mentions.clone();
        let json = serde_json::to_string(&RichTextJson {
            t: self.buf,
            mk: self.mk,
            hg: self.hg,
            ej: self.ej,
            lk: self.lk,
            vk: self.vk,
        })
        .unwrap_or_else(|_| "{}".into());
        (json, mentions)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plain_text_no_mk() {
        let (json, mentions) = RichText::new().text("hello").finish();
        assert!(json.contains(r#""t":"hello"#));
        assert!(!json.contains("mk"));
        assert!(mentions.is_empty());
    }

    #[test]
    fn bold_generates_mk_span() {
        let (json, _) = RichText::new().bold("hi").finish();
        assert!(json.contains(r#""type":"b"#));
        assert!(json.contains(r#""s":0"#));
        assert!(json.contains(r#""e":2"#));
    }

    #[test]
    fn utf16_positions_for_emoji() {
        // Crab emoji is 2 UTF-16 code units
        let (json, _) = RichText::new().text("\u{1F980}").bold("ok").finish();
        // "🦀" = 2 UTF-16 units, "ok" starts at 2
        assert!(json.contains(r#""s":2"#));
        assert!(json.contains(r#""e":4"#));
    }

    #[test]
    fn mention_user_generates_proto() {
        let (_, mentions) = RichText::new()
            .text("Hello ")
            .mention_user(42, "alice")
            .finish();
        assert_eq!(mentions.len(), 1);
        assert_eq!(mentions[0].user_id, 42);
        assert_eq!(mentions[0].username, "alice");
    }
}