hikari-extra-components 0.2.0

Advanced UI components (node graph, rich text, etc.) for the Hikari design system
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! RichTextEditor - Framework Agnostic State Model
//!
//! ## Migration Notice
//!
//! Previously a Dioxus component using `web-sys` (`contenteditable`, `execCommand`).
//! Now provides a pure state model with formatting commands and content tracking.
//!
//! ## Platform API
//!
//! Formatting commands delegate to `platform::exec_command` (tairitsu WIT binding).
//! Content retrieval uses `platform::get_inner_html` / `platform::set_content_editable`.

use serde::{Deserialize, Serialize};
use tairitsu_vdom::{VElement, VNode, VText};

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
pub enum EditorMode {
    #[default]
    Rich,
    Markdown,
    Html,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum TextFormat {
    Bold,
    Italic,
    Underline,
    Strikethrough,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum TextAlignment {
    Left,
    Center,
    Right,
    Justify,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum ListType {
    Ordered,
    Unordered,
}

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct RichTextEditorState {
    pub content: String,
    pub mode: EditorMode,
    pub placeholder: String,
    pub show_toolbar: bool,
    pub readonly: bool,
    pub min_height: Option<String>,
    pub class: String,
    pub is_focused: bool,
    pub selection_start: Option<u32>,
    pub selection_end: Option<u32>,
    pub active_formats: Vec<TextFormat>,
    pub alignment: TextAlignment,
}

impl RichTextEditorState {
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            mode: EditorMode::default(),
            placeholder: String::new(),
            show_toolbar: true,
            readonly: false,
            min_height: None,
            class: String::new(),
            is_focused: false,
            selection_start: None,
            selection_end: None,
            active_formats: Vec::new(),
            alignment: TextAlignment::Left,
        }
    }

    pub fn with_mode(mut self, mode: EditorMode) -> Self {
        self.mode = mode;
        self
    }

    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    pub fn with_show_toolbar(mut self, show: bool) -> Self {
        self.show_toolbar = show;
        self
    }

    pub fn with_readonly(mut self, readonly: bool) -> Self {
        self.readonly = readonly;
        self
    }

    pub fn with_min_height(mut self, height: impl Into<String>) -> Self {
        self.min_height = Some(height.into());
        self
    }

    pub fn with_class(mut self, class: impl Into<String>) -> Self {
        self.class = class.into();
        self
    }

    pub fn set_content(&mut self, content: impl Into<String>) {
        self.content = content.into();
    }

    pub fn set_focused(&mut self, focused: bool) {
        self.is_focused = focused;
    }

    pub fn set_selection(&mut self, start: Option<u32>, end: Option<u32>) {
        self.selection_start = start;
        self.selection_end = end;
    }

    pub fn has_selection(&self) -> bool {
        self.selection_start.is_some() && self.selection_end.is_some()
    }

    pub fn is_bold(&self) -> bool {
        self.active_formats.contains(&TextFormat::Bold)
    }

    pub fn is_italic(&self) -> bool {
        self.active_formats.contains(&TextFormat::Italic)
    }

    pub fn is_underline(&self) -> bool {
        self.active_formats.contains(&TextFormat::Underline)
    }

    pub fn toggle_format(&mut self, format: TextFormat) {
        if let Some(pos) = self.active_formats.iter().position(|f| *f == format) {
            self.active_formats.remove(pos);
        } else {
            self.active_formats.push(format);
        }
    }

    pub fn set_alignment(&mut self, alignment: TextAlignment) {
        self.alignment = alignment;
    }

    pub fn format_command(format: TextFormat) -> &'static str {
        match format {
            TextFormat::Bold => "bold",
            TextFormat::Italic => "italic",
            TextFormat::Underline => "underline",
            TextFormat::Strikethrough => "strikeThrough",
        }
    }

    pub fn alignment_command(alignment: TextAlignment) -> &'static str {
        match alignment {
            TextAlignment::Left => "justifyLeft",
            TextAlignment::Center => "justifyCenter",
            TextAlignment::Right => "justifyRight",
            TextAlignment::Justify => "justifyFull",
        }
    }

    pub fn list_command(list_type: ListType) -> &'static str {
        match list_type {
            ListType::Ordered => "insertOrderedList",
            ListType::Unordered => "insertUnorderedList",
        }
    }

    pub fn height_style(&self) -> String {
        match &self.min_height {
            Some(h) => format!("min-height: {};", h),
            None => String::new(),
        }
    }

    pub fn class_string(&self) -> String {
        if self.class.is_empty() {
            "hi-editor".to_string()
        } else {
            format!("hi-editor {}", self.class)
        }
    }

    pub fn editor_class_string(&self) -> String {
        let mut cls = String::from("hi-editor-content");
        if self.readonly {
            cls.push_str(" hi-editor-readonly");
        }
        cls
    }

    pub fn placeholder_attr(&self) -> &str {
        &self.placeholder
    }
}

impl Default for RichTextEditorState {
    fn default() -> Self {
        Self::new("")
    }
}

#[derive(Clone, PartialEq, Debug)]
pub struct ContentChangeEvent {
    pub content: String,
    pub html: String,
}

#[derive(Clone, PartialEq, Debug)]
pub struct FormatChangeEvent {
    pub format: TextFormat,
    pub active: bool,
}

pub const RICH_TEXT_EDITOR_STYLES: &str = r#"
.hi-editor {
  width: 100%;
  border: 1px solid var(--hi-border);
  border-radius: 8px;
  overflow: hidden;
  background: var(--hi-surface);
}

[data-theme="dark"] .hi-editor {
  background: var(--hi-background);
  border-color: var(--hi-border);
}

.hi-editor:focus-within {
  border-color: var(--hi-color-primary);
  box-shadow: 0 0 2px var(--hi-color-primary-glow);
}

.hi-editor-toolbar {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-bottom: 1px solid var(--hi-border);
  background: var(--hi-surface);
}

[data-theme="dark"] .hi-editor-toolbar {
  background: var(--hi-background);
  border-bottom-color: var(--hi-border);
}

.hi-editor-divider {
  width: 1px;
  height: 20px;
  background: var(--hi-border);
  margin: 0 4px;
}

[data-theme="dark"] .hi-editor-divider {
  background: var(--hi-border);
}

.hi-editor-content {
  padding: 16px;
  min-height: 200px;
  outline: none;
  line-height: 1.6;
  color: var(--hi-text-primary);
}

[data-theme="dark"] .hi-editor-content {
  color: var(--hi-text-primary);
}

.hi-editor-content:empty:before {
  content: attr(data-placeholder);
  color: var(--hi-text-secondary);
}

[data-theme="dark"] .hi-editor-content:empty:before {
  color: var(--hi-text-secondary);
}

.hi-editor-content:focus {
  outline: none;
}

.hi-editor-readonly {
  opacity: 0.7;
  cursor: not-allowed;
}
"#;

pub fn render_rich_text_editor(state: &RichTextEditorState) -> VNode {
    let mut container_children: Vec<VNode> = Vec::new();

    if state.show_toolbar {
        let mut toolbar = VElement::new("div").class("hi-editor-toolbar");

        let bold_active = if state.is_bold() {
            "hi-editor-tool-btn hi-editor-tool-btn--active"
        } else {
            "hi-editor-tool-btn"
        };
        let italic_active = if state.is_italic() {
            "hi-editor-tool-btn hi-editor-tool-btn--active"
        } else {
            "hi-editor-tool-btn"
        };
        let underline_active = if state.is_underline() {
            "hi-editor-tool-btn hi-editor-tool-btn--active"
        } else {
            "hi-editor-tool-btn"
        };
        let strike_active = if state.active_formats.contains(&TextFormat::Strikethrough) {
            "hi-editor-tool-btn hi-editor-tool-btn--active"
        } else {
            "hi-editor-tool-btn"
        };

        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class(bold_active)
                .attr(
                    "data-command",
                    RichTextEditorState::format_command(TextFormat::Bold),
                )
                .child(VNode::Text(VText::new("B"))),
        ));
        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class(italic_active)
                .attr(
                    "data-command",
                    RichTextEditorState::format_command(TextFormat::Italic),
                )
                .child(VNode::Text(VText::new("I"))),
        ));
        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class(underline_active)
                .attr(
                    "data-command",
                    RichTextEditorState::format_command(TextFormat::Underline),
                )
                .child(VNode::Text(VText::new("U"))),
        ));
        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class(strike_active)
                .attr(
                    "data-command",
                    RichTextEditorState::format_command(TextFormat::Strikethrough),
                )
                .child(VNode::Text(VText::new("S"))),
        ));

        toolbar = toolbar.child(VNode::Element(
            VElement::new("div").class("hi-editor-divider"),
        ));

        let align_left = if state.alignment == TextAlignment::Left {
            "hi-editor-tool-btn hi-editor-tool-btn--active"
        } else {
            "hi-editor-tool-btn"
        };
        let align_center = if state.alignment == TextAlignment::Center {
            "hi-editor-tool-btn hi-editor-tool-btn--active"
        } else {
            "hi-editor-tool-btn"
        };
        let align_right = if state.alignment == TextAlignment::Right {
            "hi-editor-tool-btn hi-editor-tool-btn--active"
        } else {
            "hi-editor-tool-btn"
        };

        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class(align_left)
                .attr(
                    "data-command",
                    RichTextEditorState::alignment_command(TextAlignment::Left),
                )
                .child(VNode::Text(VText::new("Left"))),
        ));
        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class(align_center)
                .attr(
                    "data-command",
                    RichTextEditorState::alignment_command(TextAlignment::Center),
                )
                .child(VNode::Text(VText::new("Center"))),
        ));
        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class(align_right)
                .attr(
                    "data-command",
                    RichTextEditorState::alignment_command(TextAlignment::Right),
                )
                .child(VNode::Text(VText::new("Right"))),
        ));

        toolbar = toolbar.child(VNode::Element(
            VElement::new("div").class("hi-editor-divider"),
        ));

        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class("hi-editor-tool-btn")
                .attr(
                    "data-command",
                    RichTextEditorState::list_command(ListType::Ordered),
                )
                .child(VNode::Text(VText::new("OL"))),
        ));
        toolbar = toolbar.child(VNode::Element(
            VElement::new("span")
                .class("hi-editor-tool-btn")
                .attr(
                    "data-command",
                    RichTextEditorState::list_command(ListType::Unordered),
                )
                .child(VNode::Text(VText::new("UL"))),
        ));

        container_children.push(VNode::Element(toolbar));
    }

    let content_class = format!("{} {}", state.editor_class_string(), state.class_string());
    let mut content = VElement::new("div")
        .class(content_class)
        .attr(
            "data-contenteditable",
            if state.readonly { "false" } else { "true" },
        )
        .attr("data-placeholder", state.placeholder_attr());

    if !state.content.is_empty() {
        content = content.attr("dangerous_inner_html", &state.content);
    }

    if !state.height_style().is_empty() {
        content = content.attr("style", state.height_style());
    }

    container_children.push(VNode::Element(content));

    VNode::Element(
        VElement::new("div")
            .class(state.class_string())
            .children(container_children),
    )
}

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

    #[test]
    fn test_new_state() {
        let state = RichTextEditorState::new("Hello");
        assert_eq!(state.content, "Hello");
        assert_eq!(state.mode, EditorMode::Rich);
        assert!(state.show_toolbar);
        assert!(!state.readonly);
        assert!(!state.is_focused);
        assert!(state.active_formats.is_empty());
        assert_eq!(state.alignment, TextAlignment::Left);
    }

    #[test]
    fn test_builder() {
        let state = RichTextEditorState::new("")
            .with_mode(EditorMode::Markdown)
            .with_placeholder("Type here...")
            .with_show_toolbar(false)
            .with_readonly(true)
            .with_min_height("300px")
            .with_class("custom");

        assert_eq!(state.mode, EditorMode::Markdown);
        assert_eq!(state.placeholder, "Type here...");
        assert!(!state.show_toolbar);
        assert!(state.readonly);
        assert_eq!(state.min_height.as_deref(), Some("300px"));
        assert_eq!(state.class, "custom");
    }

    #[test]
    fn test_toggle_format() {
        let mut state = RichTextEditorState::new("");

        state.toggle_format(TextFormat::Bold);
        assert!(state.is_bold());

        state.toggle_format(TextFormat::Italic);
        assert!(state.is_italic());
        assert_eq!(state.active_formats.len(), 2);

        state.toggle_format(TextFormat::Bold);
        assert!(!state.is_bold());
        assert_eq!(state.active_formats.len(), 1);
    }

    #[test]
    fn test_alignment() {
        let mut state = RichTextEditorState::new("");
        assert_eq!(state.alignment, TextAlignment::Left);

        state.set_alignment(TextAlignment::Center);
        assert_eq!(state.alignment, TextAlignment::Center);
    }

    #[test]
    fn test_selection() {
        let mut state = RichTextEditorState::new("");
        assert!(!state.has_selection());

        state.set_selection(Some(0), Some(5));
        assert!(state.has_selection());
        assert_eq!(state.selection_start, Some(0));
        assert_eq!(state.selection_end, Some(5));
    }

    #[test]
    fn test_format_command() {
        assert_eq!(
            RichTextEditorState::format_command(TextFormat::Bold),
            "bold"
        );
        assert_eq!(
            RichTextEditorState::format_command(TextFormat::Italic),
            "italic"
        );
        assert_eq!(
            RichTextEditorState::format_command(TextFormat::Underline),
            "underline"
        );
        assert_eq!(
            RichTextEditorState::format_command(TextFormat::Strikethrough),
            "strikeThrough"
        );
    }

    #[test]
    fn test_alignment_command() {
        assert_eq!(
            RichTextEditorState::alignment_command(TextAlignment::Left),
            "justifyLeft"
        );
        assert_eq!(
            RichTextEditorState::alignment_command(TextAlignment::Center),
            "justifyCenter"
        );
        assert_eq!(
            RichTextEditorState::alignment_command(TextAlignment::Right),
            "justifyRight"
        );
        assert_eq!(
            RichTextEditorState::alignment_command(TextAlignment::Justify),
            "justifyFull"
        );
    }

    #[test]
    fn test_list_command() {
        assert_eq!(
            RichTextEditorState::list_command(ListType::Ordered),
            "insertOrderedList"
        );
        assert_eq!(
            RichTextEditorState::list_command(ListType::Unordered),
            "insertUnorderedList"
        );
    }

    #[test]
    fn test_class_strings() {
        let state = RichTextEditorState::new("");
        assert_eq!(state.class_string(), "hi-editor");

        let state = RichTextEditorState::new("").with_class("my-class");
        assert_eq!(state.class_string(), "hi-editor my-class");

        assert!(state.editor_class_string().contains("hi-editor-content"));
    }

    #[test]
    fn test_height_style() {
        let state = RichTextEditorState::new("");
        assert!(state.height_style().is_empty());

        let state = RichTextEditorState::new("").with_min_height("300px");
        assert_eq!(state.height_style(), "min-height: 300px;");
    }

    #[test]
    fn test_set_content() {
        let mut state = RichTextEditorState::new("");
        state.set_content("<p>New content</p>");
        assert_eq!(state.content, "<p>New content</p>");
    }

    #[test]
    fn test_default() {
        let state = RichTextEditorState::default();
        assert_eq!(state.content, "");
    }
}