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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
use crate::{
makepad_derive_widget::*,
makepad_draw::*,
makepad_html::*,
text_flow::TextFlow,
widget::*,
};
const BULLET: &str = "•";
live_design!{
link widgets;
use link::theme::*;
use makepad_draw::shader::std::*;
pub HtmlLinkBase = {{HtmlLink}} {
/*link = {
draw_text:{
// other blue hyperlink colors: #1a0dab, // #0969da // #0c50d1
color: #1a0dab
}
}*/
}
pub HtmlBase = {{Html}} {
// ok so we can use one drawtext
// change to italic, change bold (SDF), strikethrough
ul_markers: ["•", "-"],
ol_markers: [Numbers, LowerAlpha, LowerRoman],
ol_separator: ".",
}
pub HtmlLink = <HtmlLinkBase> {
width: Fit, height: Fit,
align: {x: 0., y: 0.}
color: #x0000EE,
hover_color: #x00EE00,
pressed_color: #xEE0000,
// instance hovered: 0.0
// instance pressed: 0.0
animator: {
hover = {
default: off,
off = {
redraw: true,
from: {all: Forward {duration: 0.01}}
apply: {
hovered: 0.0,
pressed: 0.0,
}
}
on = {
redraw: true,
from: {
all: Forward {duration: 0.1}
pressed: Forward {duration: 0.01}
}
apply: {
hovered: [{time: 0.0, value: 1.0}],
pressed: [{time: 0.0, value: 1.0}],
}
}
pressed = {
redraw: true,
from: {all: Forward {duration: 0.01}}
apply: {
hovered: [{time: 0.0, value: 1.0}],
pressed: [{time: 0.0, value: 1.0}],
}
}
}
}
}
pub Html = <HtmlBase> {
width: Fill, height: Fit,
flow: RightWrap,
width:Fill,
height:Fit,
padding: <THEME_MSPACE_1> {}
heading_margin: {top:1.0, bottom:0.1}
paragraph_margin: {top: 0.33, bottom:0.33}
font_size: (THEME_FONT_SIZE_P),
font_color: (THEME_COLOR_LABEL_OUTER),
draw_normal: {
text_style: <THEME_FONT_REGULAR> {
font_size: (THEME_FONT_SIZE_P)
}
color: (THEME_COLOR_LABEL_OUTER)
}
draw_italic: {
text_style: <THEME_FONT_ITALIC> {
font_size: (THEME_FONT_SIZE_P)
}
color: (THEME_COLOR_LABEL_OUTER)
}
draw_bold: {
text_style: <THEME_FONT_BOLD> {
font_size: (THEME_FONT_SIZE_P)
}
color: (THEME_COLOR_LABEL_OUTER)
}
draw_bold_italic: {
text_style: <THEME_FONT_BOLD_ITALIC> {
font_size: (THEME_FONT_SIZE_P)
}
color: (THEME_COLOR_LABEL_OUTER)
}
draw_fixed: {
temp_y_shift: 0.24
text_style: <THEME_FONT_CODE> {
font_size: (THEME_FONT_SIZE_P)
}
color: (THEME_COLOR_LABEL_OUTER)
}
code_layout: {
flow: RightWrap,
padding: <THEME_MSPACE_2> {left: (THEME_SPACE_3), right: (THEME_SPACE_3) }
}
code_walk: { width: Fill, height: Fit }
quote_layout: {
flow: RightWrap,
padding: <THEME_MSPACE_2> { left: (THEME_SPACE_3), right: (THEME_SPACE_3) }
}
quote_walk: { width: Fill, height: Fit, }
list_item_layout: {
flow: RightWrap,
padding: <THEME_MSPACE_1> {}
}
list_item_walk: {
height: Fit, width: Fill,
}
inline_code_padding: <THEME_MSPACE_1> {},
inline_code_margin: <THEME_MSPACE_1> {},
sep_walk: {
width: Fill, height: 4.
margin: <THEME_MSPACE_V_1> {}
}
a = <HtmlLink> {}
draw_block:{
line_color: (THEME_COLOR_LABEL_OUTER)
sep_color: (THEME_COLOR_SHADOW)
quote_bg_color: (THEME_COLOR_BG_HIGHLIGHT)
quote_fg_color: (THEME_COLOR_LABEL_OUTER)
code_color: (THEME_COLOR_BG_HIGHLIGHT)
fn pixel(self) -> vec4 {
let sdf = Sdf2d::viewport(self.pos * self.rect_size);
match self.block_type {
FlowBlockType::Quote => {
sdf.box(
0.,
0.,
self.rect_size.x,
self.rect_size.y,
2.
);
sdf.fill(self.quote_bg_color)
sdf.box(
THEME_SPACE_1,
THEME_SPACE_1,
THEME_SPACE_1,
self.rect_size.y - THEME_SPACE_2,
1.5
);
sdf.fill(self.quote_fg_color);
return sdf.result;
}
FlowBlockType::Sep => {
sdf.box(
0.,
1.,
self.rect_size.x-1,
self.rect_size.y-2.,
2.
);
sdf.fill(self.sep_color);
return sdf.result;
}
FlowBlockType::Code => {
sdf.box(
0.,
0.,
self.rect_size.x,
self.rect_size.y,
2.
);
sdf.fill(self.code_color);
return sdf.result;
}
FlowBlockType::InlineCode => {
sdf.box(
1.,
1.,
self.rect_size.x-2.,
self.rect_size.y-2.,
2.
);
sdf.fill(self.code_color);
return sdf.result;
}
FlowBlockType::Underline => {
sdf.box(
0.,
self.rect_size.y-2,
self.rect_size.x,
2.0,
0.5
);
sdf.fill(self.line_color);
return sdf.result;
}
FlowBlockType::Strikethrough => {
sdf.box(
0.,
self.rect_size.y * 0.45,
self.rect_size.x,
2.0,
0.5
);
sdf.fill(self.line_color);
return sdf.result;
}
}
return #f00
}
}
}
}
/// Whether to trim leading and trailing whitespace in the text body of an HTML tag.
///
/// Currently, *all* Unicode whitespace characters are trimmed, not just ASCII whitespace.
///
/// The default is to keep all whitespace.
#[derive(Copy, Clone, PartialEq, Default)]
pub enum TrimWhitespaceInText {
/// Leading and trailing whitespace will be preserved in the text.
#[default]
Keep,
/// Leading and trailing whitespace will be trimmed from the text.
Trim,
}
#[derive(Live, Widget)]
pub struct Html {
#[deref] pub text_flow: TextFlow,
#[live] pub body: ArcStringMut,
#[rust] pub doc: HtmlDoc,
/// Markers used for unordered lists, indexed by the list's nesting level.
/// The marker can be an arbitrary string, such as a bullet point or a custom icon.
#[live] ul_markers: Vec<String>,
/// Markers used for ordered lists, indexed by the list's nesting level.
#[live] ol_markers: Vec<OrderedListType>,
/// The character used to separate an ordered list's item number from the content.
#[live] ol_separator: String,
/// The stack of list levels encountered so far, used to track nested lists.
#[rust] list_stack: Vec<ListLevel>,
}
// alright lets parse the HTML
impl LiveHook for Html {
fn after_apply_from(&mut self, _cx: &mut Cx, _apply:&mut Apply) {
let mut errors = Some(Vec::new());
let new_doc = parse_html(self.body.as_ref(), &mut errors, InternLiveId::No);
if new_doc != self.doc{
self.doc = new_doc;
self.text_flow.clear_items();
}
if errors.as_ref().unwrap().len()>0{
log!("HTML parser returned errors {:?}", errors)
}
}
}
impl Html {
fn handle_open_tag(
cx: &mut Cx2d,
tf: &mut TextFlow,
node: &mut HtmlWalker,
list_stack: &mut Vec<ListLevel>,
ul_markers: &Vec<String>,
ol_markers: &Vec<OrderedListType>,
ol_separator: &str,
) -> (Option<LiveId>, TrimWhitespaceInText) {
let mut trim_whitespace_in_text = TrimWhitespaceInText::default();
fn open_header_tag(cx: &mut Cx2d, tf: &mut TextFlow, scale: f64, trim: &mut TrimWhitespaceInText) {
*trim = TrimWhitespaceInText::Trim;
tf.bold.push();
tf.push_size_abs_scale(scale);
let fs = *tf.font_sizes.last().unwrap_or(&tf.font_size) as f64;
tf.new_line_collapsed_with_spacing(cx, fs * tf.heading_margin.top);
}
match node.open_tag_lc() {
some_id!(h1) => open_header_tag(cx, tf, 2.0, &mut trim_whitespace_in_text),
some_id!(h2) => open_header_tag(cx, tf, 1.5, &mut trim_whitespace_in_text),
some_id!(h3) => open_header_tag(cx, tf, 1.17, &mut trim_whitespace_in_text),
some_id!(h4) => open_header_tag(cx, tf, 1.0, &mut trim_whitespace_in_text),
some_id!(h5) => open_header_tag(cx, tf, 0.83, &mut trim_whitespace_in_text),
some_id!(h6) => open_header_tag(cx, tf, 0.67, &mut trim_whitespace_in_text),
some_id!(p) => {
// there's probably a better way to do this by setting margins...
let fs = *tf.font_sizes.last().unwrap_or(&tf.font_size) as f64;
tf.new_line_collapsed_with_spacing(cx, fs * tf.paragraph_margin.top);
//tf.new_line_collapsed(cx);
trim_whitespace_in_text = TrimWhitespaceInText::Trim;
}
some_id!(code) => {
const FIXED_FONT_SIZE_SCALE: f64 = 0.85;
tf.push_size_rel_scale(FIXED_FONT_SIZE_SCALE);
//tf.top_drop.push(1.2/FIXED_FONT_SIZE_SCALE); // to achieve a top_drop of 1.2
tf.combine_spaces.push(false);
tf.fixed.push();
tf.inline_code.push();
}
some_id!(pre) => {
tf.new_line_collapsed(cx);
tf.fixed.push();
tf.ignore_newlines.push(false);
tf.combine_spaces.push(false);
tf.begin_code(cx);
}
some_id!(blockquote) => {
tf.new_line_collapsed(cx);
tf.ignore_newlines.push(false);
tf.combine_spaces.push(false);
tf.begin_quote(cx);
trim_whitespace_in_text = TrimWhitespaceInText::Trim;
}
some_id!(br) => {
tf.new_line_collapsed(cx);
trim_whitespace_in_text = TrimWhitespaceInText::Trim;
}
some_id!(hr)
| some_id!(sep) => {
tf.new_line_collapsed(cx);
tf.sep(cx);
tf.new_line_collapsed(cx);
trim_whitespace_in_text = TrimWhitespaceInText::Trim;
}
some_id!(u) => tf.underline.push(),
some_id!(del)
| some_id!(s)
| some_id!(strike) => tf.strikethrough.push(),
some_id!(b)
| some_id!(strong) => tf.bold.push(),
some_id!(i)
| some_id!(em) => tf.italic.push(),
some_id!(sub) => {
// Adjust the top drop to move the text slightly downwards.
//let curr_top_drop = tf.top_drop.last()
// .unwrap_or(&1.2);
// A 55% increase in top_drop seems to look good for subscripts,
// which should be slightly below the halfway point in the line
//let new_top_drop = curr_top_drop * 1.55;
//tf.top_drop.push(new_top_drop);
tf.push_size_rel_scale(0.7);
}
some_id!(sup) => {
tf.push_size_rel_scale(0.7);
}
some_id!(ul) => {
trim_whitespace_in_text = TrimWhitespaceInText::Trim;
list_stack.push(ListLevel {
list_kind: ListKind::Unordered,
numbering_type: None,
li_count: 1,
padding: 2.5,
});
}
some_id!(ol) => {
trim_whitespace_in_text = TrimWhitespaceInText::Trim;
// Handle the "start" attribute
let start_attr = node.find_attr_lc(live_id!(start));
let start: i32 = start_attr
.and_then(|s| s.parse().ok())
.unwrap_or(1);
// Handle the "type" attribute
let type_attr = node.find_attr_lc(live_id!(type));
let numbering_type = type_attr.and_then(OrderedListType::from_type_attribute);
list_stack.push(ListLevel {
list_kind: ListKind::Ordered,
numbering_type,
li_count: start,
padding: 2.5,
});
}
some_id!(li) => {
trim_whitespace_in_text = TrimWhitespaceInText::Trim;
let indent_level = list_stack.len();
let index = indent_level.saturating_sub(1);
// log!("indent_level: {indent_level}, index: {index}, list_stack: {list_stack:?}");
let marker_and_pad = list_stack.last_mut().map(|ll| {
let marker = match ll.list_kind {
ListKind::Unordered => {
ul_markers.get(index).cloned()
.unwrap_or_else(|| BULLET.into()) // default to bullet point
}
ListKind::Ordered => {
// Handle the "value" attribute, only relevant to <ol>.
let value_attr = node.find_attr_lc(live_id!(value));
let value: i32 = value_attr
.and_then(|s| s.parse().ok())
.unwrap_or(ll.li_count);
// Handle the "type" attribute, only relevant to <ol>.
let type_attr = node.find_attr_lc(live_id!(type));
let numbering_type = type_attr.and_then(OrderedListType::from_type_attribute);
// Generate this <li> marker string using either:
// * the <li> element's numbering type, otherwise,
// * the outer <ol>'s numbering type, otherwise,
// * the DSL-specified numbering type for the current nesting level,
// * otherwise a literal "#" character, which indicates malformed HTML.
numbering_type.as_ref()
.or_else(|| ll.numbering_type.as_ref())
.or_else(|| ol_markers.get(index))
.map(|ol_type| ol_type.marker(value, ol_separator))
.unwrap_or_else(|| "#".into())
}
};
ll.li_count += 1;
(marker, ll.padding)
});
let (marker, pad) = marker_and_pad.as_ref()
.map(|(m, p)| (m.as_str(), *p))
.unwrap_or((BULLET, 2.5));
// Now, actually emit the list item.
// log!("marker: {marker}, pad: {pad}");
// ok so what if we only have drawn whitespace here
tf.new_line_collapsed(cx);
tf.begin_list_item(cx, marker, pad);
}
Some(x) => return (Some(x), trim_whitespace_in_text),
_ => ()
}
(None, trim_whitespace_in_text)
}
fn handle_close_tag(
cx: &mut Cx2d,
tf: &mut TextFlow,
node: &mut HtmlWalker,
list_stack: &mut Vec<ListLevel>,
) -> Option<LiveId> {
match node.close_tag_lc() {
some_id!(h1)
| some_id!(h2)
| some_id!(h3)
| some_id!(h4)
| some_id!(h5)
| some_id!(h6) => {
let size = tf.font_sizes.pop();
tf.bold.pop();
tf.new_line_collapsed_with_spacing(cx, size.unwrap_or(0.0) as f64 * tf.heading_margin.bottom);
// we wanna add extra spacing here
}
some_id!(b)
| some_id!(strong) => tf.bold.pop(),
some_id!(i)
| some_id!(em) => tf.italic.pop(),
some_id!(p) => {
let fs = *tf.font_sizes.last().unwrap_or(&tf.font_size) as f64;
tf.new_line_collapsed_with_spacing(cx, fs * tf.paragraph_margin.bottom);
//tf.new_line_collapsed(cx);
}
some_id!(blockquote) => {
tf.ignore_newlines.pop();
tf.combine_spaces.pop();
tf.end_quote(cx);
}
some_id!(code) => {
tf.inline_code.pop();
//tf.top_drop.pop();
tf.font_sizes.pop();
tf.combine_spaces.pop();
tf.fixed.pop();
}
some_id!(pre) => {
tf.fixed.pop();
tf.ignore_newlines.pop();
tf.combine_spaces.pop();
tf.end_code(cx);
}
some_id!(sub)=>{
//tf.top_drop.pop();
tf.font_sizes.pop();
}
some_id!(sup) => {
tf.font_sizes.pop();
}
some_id!(ul)
| some_id!(ol) => {
list_stack.pop();
}
some_id!(li) => tf.end_list_item(cx),
some_id!(u) => tf.underline.pop(),
some_id!(del)
| some_id!(s)
| some_id!(strike) => tf.strikethrough.pop(),
_ => ()
}
None
}
pub fn handle_text_node(
cx: &mut Cx2d,
tf: &mut TextFlow,
node: &mut HtmlWalker,
trim: TrimWhitespaceInText,
) -> bool {
if let Some(text) = node.text() {
let text = if trim == TrimWhitespaceInText::Trim {
text.trim_matches(char::is_whitespace)
} else {
text
};
tf.draw_text(cx, text);
true
}
else {
false
}
}
}
impl Widget for Html {
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
self.text_flow.handle_event(cx, event, scope);
}
fn draw_walk(&mut self, cx: &mut Cx2d, scope: &mut Scope, walk: Walk) -> DrawStep {
let tf = &mut self.text_flow;
tf.begin(cx, walk);
// alright lets iterate the html doc and draw it
let mut node = self.doc.new_walker();
let mut auto_id = 0;
while !node.done() {
let mut trim = TrimWhitespaceInText::default();
match Self::handle_open_tag(cx, tf, &mut node, &mut self.list_stack, &self.ul_markers, &self.ol_markers, &self.ol_separator) {
(Some(_), _tws) => {
handle_custom_widget(cx, scope, tf, &self.doc, &mut node, &mut auto_id);
}
(None, tws) => {
trim = tws;
}
}
match Self::handle_close_tag(cx, tf, &mut node, &mut self.list_stack) {
_ => ()
}
Self::handle_text_node(cx, tf, &mut node, trim);
node.walk();
}
tf.end(cx);
DrawStep::done()
}
fn text(&self) -> String {
self.body.as_ref().to_string()
}
fn set_text(&mut self, cx:&mut Cx, v:&str){
self.body.set(v);
let mut errors = Some(Vec::new());
self.doc = parse_html(self.body.as_ref(), &mut errors, InternLiveId::No);
if errors.as_ref().unwrap().len()>0{
log!("HTML parser returned errors {:?}", errors)
}
self.redraw(cx);
}
}
fn handle_custom_widget(
cx: &mut Cx2d,
_scope: &mut Scope,
tf: &mut TextFlow,
doc: &HtmlDoc,
node: &mut HtmlWalker,
auto_id: &mut u64,
) {
let id = if let Some(id) = node.find_attr_lc(live_id!(id)) {
LiveId::from_str(id)
} else {
*auto_id += 1;
LiveId(*auto_id)
};
let template = node.open_tag_nc().unwrap();
// lets grab the nodes+index from the walker
let mut scope_with_attrs = Scope::with_props_index(doc, node.index);
// log!("FOUND CUSTOM WIDGET! template: {template:?}, id: {id:?}, attrs: {attrs:?}");
if let Some(item) = tf.item_with_scope(cx, &mut scope_with_attrs, id, template) {
item.set_text(cx, node.find_text().unwrap_or(""));
let mut draw_scope = Scope::with_data(tf);
item.draw_all(cx, &mut draw_scope);
}
node.jump_to_close();
}
#[derive(Debug, Clone, DefaultNone)]
pub enum HtmlLinkAction {
Clicked {
url: String,
key_modifiers: KeyModifiers,
},
SecondaryClicked {
url: String,
key_modifiers: KeyModifiers,
},
None,
}
#[derive(Live, Widget)]
pub struct HtmlLink {
#[animator] animator: Animator,
// TODO: this is unusued; just here to invalidly satisfy the area provider.
// I'm not sure how to implement `fn area()` given that it has multiple area rects.
#[redraw] #[area] area: Area,
// TODO: remove these if they're unneeded
#[walk] walk: Walk,
#[layout] layout: Layout,
#[rust] drawn_areas: SmallVec<[Area; 2]>,
#[live(true)] grab_key_focus: bool,
#[live] hovered: f32,
#[live] pressed: f32,
/// The default font color for the link when not hovered on or pressed.
#[live] color: Option<Vec4>,
/// The font color used when the link is hovered on.
#[live] hover_color: Option<Vec4>,
/// The font color used when the link is pressed.
#[live] pressed_color: Option<Vec4>,
#[live] pub text: ArcStringMut,
#[live] pub url: String,
}
impl LiveHook for HtmlLink {
// After an HtmlLink instance has been instantiated ("applied"),
// populate its struct fields from the `<a>` tag's attributes.
fn after_apply(&mut self, _cx: &mut Cx, apply: &mut Apply, _index: usize, _nodes: &[LiveNode]) {
//log!("HtmlLink::after_apply(): apply.from: {:?}, apply.scope exists: {:?}", apply.from, apply.scope.is_some());
match apply.from {
ApplyFrom::NewFromDoc {..} => {
let scope = apply.scope.as_ref().unwrap();
let doc = scope.props.get::<HtmlDoc>().unwrap();
let mut walker = doc.new_walker_with_index(scope.index + 1);
if let Some((lc, attr)) = walker.while_attr_lc() {
match lc {
live_id!(href)=> {
self.url = attr.into()
}
_=>()
}
}
}
_ => ()
}
}
}
impl Widget for HtmlLink {
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
if self.animator_handle_event(cx, event).must_redraw() {
// Currently, this conditional will never be true because the `scope`
// isn't yet populated with the Html's TextFlow.
if let Some(tf) = scope.data.get_mut::<TextFlow>() {
tf.redraw(cx);
} else {
self.drawn_areas.iter().for_each(|area| area.redraw(cx));
}
// This won't work, as this widget owns no views, so redrawing it does nothing.
// self.redraw(cx);
}
for area in self.drawn_areas.clone().into_iter() {
match event.hits(cx, area) {
Hit::FingerDown(fe) => {
if fe.is_primary_hit() {
if self.grab_key_focus {
cx.set_key_focus(self.area());
}
self.animator_play(cx, id!(hover.pressed));
}
// Fire a secondary click action on a right-click *down* event.
else if fe.mouse_button().is_some_and(|mb| mb.is_secondary()) {
cx.widget_action(
self.widget_uid(),
&scope.path,
HtmlLinkAction::SecondaryClicked {
url: self.url.clone(),
key_modifiers: fe.modifiers,
},
);
}
}
Hit::FingerHoverIn(_) => {
cx.set_cursor(MouseCursor::Hand);
self.animator_play(cx, id!(hover.on));
}
Hit::FingerHoverOut(_) => {
self.animator_play(cx, id!(hover.off));
}
Hit::FingerLongPress(_) => {
cx.widget_action(
self.widget_uid(),
&scope.path,
HtmlLinkAction::SecondaryClicked {
url: self.url.clone(),
key_modifiers: Default::default(),
},
);
}
Hit::FingerUp(fu) => {
if fu.is_over {
cx.set_cursor(MouseCursor::Hand);
self.animator_play(cx, id!(hover.on));
} else {
self.animator_play(cx, id!(hover.off));
}
if fu.is_over
&& fu.is_primary_hit()
&& fu.was_tap()
{
cx.widget_action(
self.widget_uid(),
&scope.path,
HtmlLinkAction::Clicked {
url: self.url.clone(),
key_modifiers: fu.modifiers,
},
);
}
}
_ => (),
}
}
}
fn draw_walk(&mut self, cx: &mut Cx2d, scope: &mut Scope, _walk: Walk) -> DrawStep {
let Some(tf) = scope.data.get_mut::<TextFlow>() else {
return DrawStep::done();
};
// Here: the text flow has already began drawing, so we just need to draw the text.
tf.underline.push();
tf.areas_tracker.push_tracker();
let mut pushed_color = false;
if self.hovered > 0.0 {
if let Some(color) = self.hover_color {
tf.font_colors.push(color);
pushed_color = true;
}
} else if self.pressed > 0.0 {
if let Some(color) = self.pressed_color {
tf.font_colors.push(color);
pushed_color = true;
}
} else {
if let Some(color) = self.color {
tf.font_colors.push(color);
pushed_color = true;
}
}
tf.draw_text(cx, self.text.as_ref());
if pushed_color {
tf.font_colors.pop();
}
tf.underline.pop();
let (start, end) = tf.areas_tracker.pop_tracker();
if self.drawn_areas.len() == end-start{
for i in 0..end-start{
self.drawn_areas[i] = cx.update_area_refs( self.drawn_areas[i],
tf.areas_tracker.areas[i+start]);
}
}
else{
self.drawn_areas = SmallVec::from(
&tf.areas_tracker.areas[start..end]
);
}
DrawStep::done()
}
fn text(&self) -> String {
self.text.as_ref().to_string()
}
fn set_text(&mut self, cx:&mut Cx, v: &str) {
self.text.as_mut_empty().push_str(v);
self.redraw(cx);
}
}
impl HtmlLinkRef {
pub fn set_url(&mut self, url: &str) {
if let Some(mut inner) = self.borrow_mut() {
inner.url = url.to_string();
}
}
pub fn url(&self) -> Option<String> {
if let Some(inner) = self.borrow() {
Some(inner.url.clone())
} else {
None
}
}
}
/// The format and metadata of a list at a given nesting level.
#[derive(Debug)]
struct ListLevel {
/// The kind of list, either ordered or unordered.
list_kind: ListKind,
/// The type of marker formatting for ordered lists,
/// if overridden for this particular list level.
numbering_type: Option<OrderedListType>,
/// The number of list items encountered so far at this level of nesting.
/// This is a 1-indexed value, so the default initial value should be 1.
/// This is an integer because negative numbering values are supported.
li_count: i32,
/// The padding space inserted to the left of each list item,
/// where the list marker is drawn.
padding: f64,
}
/// List kinds: ordered (numbered) and unordered (bulleted).
#[derive(Debug)]
enum ListKind {
Unordered,
Ordered,
}
/// The type of marker used for ordered lists.
///
/// See the ["type" attribute docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol#attributes)
/// for more info.
#[derive(Copy, Clone, Debug, Live, LiveHook)]
#[live_ignore]
pub enum OrderedListType {
#[pick] // must be the top-most attribute
/// Decimal integers: 1, 2, 3, 4, ...
///
/// This *does* support negative integer values, e.g., -2, -1, 0, 1, 2 ...
Numbers,
/// Uppercase letters: A, B, C, D, ...
UpperAlpha,
/// Lowercase letters: a, b, c, d, ...
LowerAlpha,
/// Uppercase roman numerals: I, II, III, IV, ...
UpperRoman,
/// Lowercase roman numerals: i, ii, iii, iv, ...
LowerRoman,
}
impl Default for OrderedListType {
fn default() -> Self {
OrderedListType::Numbers
}
}
impl OrderedListType {
/// Returns the marker for the given count and separator character.
///
/// ## Notes on behavior
/// * A negative or zero `count` will always return an integer number marker.
/// * Currently, for `UpperApha` and `LowerAlpha`, a `count` higher than 25 will result in a wrong character.
/// * Roman numerals >= 4000 will return an integer number marker.
pub fn marker(&self, count: i32, separator: &str) -> String {
let to_number = || format!("{count}{separator}");
if count <= 0 { return to_number(); }
match self {
OrderedListType::Numbers => to_number(),
// TODO: fix alpha implementations
OrderedListType::UpperAlpha => format!("{}{separator}", ('A' as u8 + count as u8 - 1) as char),
OrderedListType::LowerAlpha => format!("{}{separator}", ('a' as u8 + count as u8 - 1) as char),
OrderedListType::UpperRoman => to_roman_numeral(count)
.map(|m| format!("{}{separator}", m))
.unwrap_or_else(to_number),
OrderedListType::LowerRoman => to_roman_numeral(count)
.map(|m| format!("{}{separator}", m.to_lowercase()))
.unwrap_or_else(to_number),
}
}
/// Returns an ordered list type based on the given HTML `type` attribute value string `s`.
///
/// Returns `None` if an invalid value is given.
pub fn from_type_attribute(s: &str) -> Option<Self> {
match s {
"a" => Some(OrderedListType::LowerAlpha),
"A" => Some(OrderedListType::UpperAlpha),
"i" => Some(OrderedListType::LowerRoman),
"I" => Some(OrderedListType::UpperRoman),
"1" => Some(OrderedListType::Numbers),
_ => None,
}
}
}
/// Converts an integer into an uppercase roman numeral string.
///
/// Returns `None` if the input is not between 1 and 3999 inclusive.
///
/// This code was adapted from the [`roman` crate](https://crates.io/crates/roman).
pub fn to_roman_numeral(mut count: i32) -> Option<String> {
const MAX: i32 = 3999;
static NUMERALS: &[(i32, &str)] = &[
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"),
(1, "I")
];
if count <= 0 || count > MAX { return None; }
let mut output = String::new();
for &(value, s) in NUMERALS.iter() {
while count >= value {
count -= value;
output.push_str(s);
}
}
if count == 0 {
Some(output)
} else {
None
}
}