Repository navigation
Expand file tree
/
Copy pathnode.rs
More file actions
1527 lines (1351 loc) · 51.9 KB
/
Copy pathnode.rs
File metadata and controls
1527 lines (1351 loc) · 51.9 KB
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::Document;
use crate::layout::damage::HoistedPaintChildren;
use bitflags::bitflags;
use blitz_traits::events::{
BlitzPointerEvent, BlitzPointerId, DomEventData, HitResult, PointerCoords,
};
use blitz_traits::node_id::NodeId;
use blitz_traits::shell::ShellProvider;
use euclid::{Point2D, Rect, Size2D};
use html_escape::encode_quoted_attribute_to_string;
use keyboard_types::Modifiers;
use kurbo::{Affine, Rect as KurboRect};
use markup5ever::{LocalName, local_name};
use parley::{BreakReason, Cluster, ClusterSide};
use selectors::matching::ElementSelectorFlags;
use std::cell::{Cell, RefCell};
use std::fmt::Write;
use std::ops::Deref;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use style::Atom;
use style::invalidation::element::restyle_hints::RestyleHint;
use style::properties::ComputedValues;
use style::properties::generated::longhands::position::computed_value::T as Position;
use style::selector_parser::{PseudoElement, RestyleDamage};
use style::servo_arc::Arc as ServoArc;
use style::shared_lock::SharedRwLock;
use style::stylesheets::UrlExtraData;
use style::values::computed::CSSPixelLength;
use style::values::computed::Display as StyloDisplay;
use style::values::specified::box_::{DisplayInside, DisplayOutside};
use style_dom::ElementState;
use style_traits::values::ToCss;
use taffy::{
Cache,
prelude::{Layout, Style},
};
use thin_vec::ThinVec;
use super::stylo_data::StyloData;
use super::{Attribute, DocumentData, ElementData};
#[derive(Clone, Copy)]
enum OutputStyle {
Normal,
Pretty,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DisplayOuter {
Block,
Inline,
None,
}
bitflags! {
#[derive(Clone, Copy, PartialEq)]
pub struct NodeFlags: u32 {
/// Whether the node is the root node of an Inline Formatting Context
const IS_INLINE_ROOT = 0b00000001;
/// Whether the node is the root node of an Table formatting context
const IS_TABLE_ROOT = 0b00000010;
/// Whether the node is "in the document" (~= has a parent and isn't a template node)
const IS_IN_DOCUMENT = 0b00000100;
}
}
impl NodeFlags {
#[inline(always)]
pub fn is_inline_root(&self) -> bool {
self.contains(Self::IS_INLINE_ROOT)
}
#[inline(always)]
pub fn is_table_root(&self) -> bool {
self.contains(Self::IS_TABLE_ROOT)
}
#[inline(always)]
pub fn is_in_document(&self) -> bool {
self.contains(Self::IS_IN_DOCUMENT)
}
#[inline(always)]
pub fn reset_construction_flags(&mut self) {
self.remove(Self::IS_INLINE_ROOT);
self.remove(Self::IS_TABLE_ROOT);
}
}
pub struct Node {
// The actual tree we belong to. This is unsafe!!
tree: *mut crate::NodeTree,
/// Our Id
pub id: NodeId,
/// Our parent's ID
pub parent: Option<NodeId>,
// What are our children?
pub children: ThinVec<NodeId>,
/// Our parent in the layout hierachy: a separate list that includes anonymous collections of inline elements
pub layout_parent: Cell<Option<NodeId>>,
/// A separate child list that includes anonymous collections of inline elements
pub layout_children: RefCell<Option<ThinVec<NodeId>>>,
/// Anonymous block boxes created for this node during layout construction.
///
/// Anonymous blocks live only in the slab (they are not part of the DOM
/// `children` list), so we track the ones we own here to be able to
/// deallocate them when this node is reconstructed.
pub anonymous_blocks: ThinVec<NodeId>,
/// The same as layout_children, but sorted by z-index
pub paint_children: RefCell<Option<ThinVec<NodeId>>>,
pub stacking_context: Option<Box<HoistedPaintChildren>>,
// Flags
pub flags: NodeFlags,
/// Node type (Element, TextNode, etc) specific data.
///
/// For element nodes this holds the [`ElementData`], which stores most of
/// the per-node style/layout state. For the document node it holds the
/// [`DocumentData`]. Access the moved fields through the forwarding methods
/// on [`Node`] (e.g. [`Node::style`], [`Node::final_layout`]).
pub data: NodeData,
}
unsafe impl Send for Node {}
unsafe impl Sync for Node {}
/// Generates forwarding accessors for fields that live on both [`ElementData`]
/// (element / anonymous block nodes) and [`DocumentData`] (the document node).
macro_rules! universal_accessors {
($($(#[$meta:meta])* $field:ident / $field_mut:ident : $ty:ty),* $(,)?) => {
impl Node {
$(
$(#[$meta])*
#[inline]
pub fn $field(&self) -> &$ty {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &data.$field,
NodeData::Document(data) => &data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
$(#[$meta])*
#[inline]
pub fn $field_mut(&mut self) -> &mut $ty {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &mut data.$field,
NodeData::Document(data) => &mut data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
)*
}
};
}
/// Generates forwarding accessors for fields that only live on [`ElementData`]
/// (element / anonymous block nodes).
macro_rules! element_accessors {
($($(#[$meta:meta])* $field:ident / $field_mut:ident : $ty:ty),* $(,)?) => {
impl Node {
$(
$(#[$meta])*
#[inline]
pub fn $field(&self) -> &$ty {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
$(#[$meta])*
#[inline]
pub fn $field_mut(&mut self) -> &mut $ty {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &mut data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
)*
}
};
}
universal_accessors! {
stylo_element_data / stylo_element_data_mut: StyloData,
style / style_mut: Style<Atom>,
cache / cache_mut: Cache,
unrounded_layout / unrounded_layout_mut: Layout,
final_layout / final_layout_mut: Layout,
scroll_offset / scroll_offset_mut: crate::Point<f64>,
scrollable_overflow / scrollable_overflow_mut: KurboRect,
transform / transform_mut: Option<Affine>,
display_constructed_as / display_constructed_as_mut: StyloDisplay,
// The document node is styled/snapshotted like an element, so it also
// carries these:
element_state / element_state_mut: ElementState,
snapshot_handled / snapshot_handled_mut: AtomicBool,
}
element_accessors! {
selector_flags / selector_flags_mut: Cell<ElementSelectorFlags>,
}
impl Node {
/// Style data from stylo, if this node kind carries it (element or document
/// nodes). Returns `None` for text/comment nodes.
#[inline]
pub fn stylo_element_data_opt(&self) -> Option<&StyloData> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&data.stylo_element_data)
}
NodeData::Document(data) => Some(&data.stylo_element_data),
_ => None,
}
}
#[inline]
pub fn stylo_element_data_opt_mut(&mut self) -> Option<&mut StyloData> {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&mut data.stylo_element_data)
}
NodeData::Document(data) => Some(&mut data.stylo_element_data),
_ => None,
}
}
/// The `dirty_descendants` flag, if this node kind carries it (element or
/// document nodes). Returns `None` for text/comment nodes.
#[inline]
fn dirty_descendants_flag(&self) -> Option<&AtomicBool> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&data.dirty_descendants)
}
NodeData::Document(data) => Some(&data.dirty_descendants),
_ => None,
}
}
/// The document's shared style lock. Only available on element and
/// document nodes.
#[inline]
pub fn guard(&self) -> &SharedRwLock {
let guard = match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.guard.as_ref(),
NodeData::Document(data) => data.guard.as_ref(),
_ => None,
};
guard.expect("`guard` is not available on this node kind")
}
#[inline]
pub fn has_snapshot(&self) -> bool {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot,
NodeData::Document(data) => data.has_snapshot,
_ => false,
}
}
#[inline]
pub fn set_has_snapshot(&mut self, value: bool) {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot = value,
NodeData::Document(data) => data.has_snapshot = value,
_ => {}
}
}
#[inline]
pub fn before(&self) -> Option<NodeId> {
self.element_data().and_then(|data| data.before)
}
#[inline]
pub fn after(&self) -> Option<NodeId> {
self.element_data().and_then(|data| data.after)
}
}
impl Node {
pub(crate) fn new(
tree: *mut crate::NodeTree,
id: NodeId,
guard: SharedRwLock,
mut data: NodeData,
) -> Self {
// Store a handle to the document's shared style lock on the node data.
// Both element and document nodes are styled by stylo and so need it.
match &mut data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
data.guard = Some(guard);
}
NodeData::Document(data) => data.guard = Some(guard),
_ => {}
}
Self {
tree,
id,
parent: None,
children: ThinVec::new(),
layout_parent: Cell::new(None),
layout_children: RefCell::new(None),
anonymous_blocks: ThinVec::new(),
paint_children: RefCell::new(None),
stacking_context: None,
flags: NodeFlags::empty(),
data,
}
}
pub fn set_transform(&mut self, scale: f32) -> Option<Affine> {
let transform = self.primary_styles().and_then(|s| {
let size = self.final_layout().size;
let reference_box = Rect::new(
Point2D::new(CSSPixelLength::new(0.0), CSSPixelLength::new(0.0)),
Size2D::new(
CSSPixelLength::new(size.width),
CSSPixelLength::new(size.height),
),
);
// Resolve the transform in CSS pixels, then convert it to device-pixel space
// (S * T * S^-1): translation components are scaled, linear components are not.
crate::resolve_2d_transform(s.get_box(), reference_box).map(|t| {
let scale = scale as f64;
let [m11, m12, m21, m22, m41, m42] = t.as_coeffs();
Affine::new([m11, m12, m21, m22, m41 * scale, m42 * scale])
})
});
*self.transform_mut() = transform;
transform
}
pub fn pe_by_index(&self, index: usize) -> Option<NodeId> {
match index {
0 => self.after(),
1 => self.before(),
_ => panic!("Invalid pseudo element index"),
}
}
pub fn set_pe_by_index(&mut self, index: usize, value: Option<NodeId>) {
let Some(data) = self.element_data_mut() else {
return;
};
match index {
0 => data.after = value,
1 => data.before = value,
_ => panic!("Invalid pseudo element index"),
}
}
pub(crate) fn display_style(&self) -> Option<StyloDisplay> {
Some(self.primary_styles().as_ref()?.clone_display())
}
pub fn is_or_contains_block(&self) -> bool {
let style = self.primary_styles();
let style = style.as_ref();
// Ignore out-of-flow items
let position = style
.map(|s| s.clone_position())
.unwrap_or(Position::Relative);
let is_in_flow = matches!(
position,
Position::Static | Position::Relative | Position::Sticky
);
if !is_in_flow {
return false;
}
let display = style
.map(|s| s.clone_display())
.unwrap_or(StyloDisplay::inline());
match display.outside() {
DisplayOutside::None => false,
DisplayOutside::Block => true,
_ => {
if display.inside() == DisplayInside::Flow {
self.children
.iter()
.copied()
.any(|child_id| self.tree()[child_id].is_or_contains_block())
} else {
false
}
}
}
}
pub fn is_whitespace_node(&self) -> bool {
match &self.data {
NodeData::Text(data) => data.content.chars().all(|c| c.is_ascii_whitespace()),
_ => false,
}
}
pub fn is_focussable(&self) -> bool {
self.data
.downcast_element()
.map(|el| el.is_focussable)
.unwrap_or(false)
}
pub fn set_restyle_hint(&mut self, hint: RestyleHint) {
if let Some(stylo_element_data) = self.stylo_element_data_opt_mut() {
if let Some(mut element_data) = stylo_element_data.get_mut() {
element_data.hint.insert(hint);
}
}
// Mark all ancestors as having dirty descendants so the style traversal
// will visit this node's subtree
self.mark_ancestors_dirty();
}
/// Returns whether this node has any descendants that need restyling.
pub fn has_dirty_descendants(&self) -> bool {
self.dirty_descendants_flag()
.is_some_and(|flag| flag.load(Ordering::Relaxed))
}
/// Sets the dirty_descendants flag on this node.
pub fn set_dirty_descendants(&self) {
if let Some(flag) = self.dirty_descendants_flag() {
flag.store(true, Ordering::Relaxed);
}
}
/// Clears the dirty_descendants flag on this node.
pub fn unset_dirty_descendants(&self) {
if let Some(flag) = self.dirty_descendants_flag() {
flag.store(false, Ordering::Relaxed);
}
}
/// Set appropriate damage for Stylo when an element's style attribute is updated
pub(crate) fn mark_style_attr_updated(&mut self) {
if let Some(stylo_element_data) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo_element_data.get_mut() {
data.hint |= RestyleHint::RESTYLE_STYLE_ATTRIBUTE;
}
}
self.set_dirty_descendants();
self.mark_ancestors_dirty();
}
/// Marks all ancestors of this node as having dirty descendants.
/// This propagates the dirty flag up the tree so that the style traversal
/// knows to visit the subtree containing this node.
pub fn mark_ancestors_dirty(&self) {
let mut current_id = self.parent;
while let Some(parent_id) = current_id {
let parent = &self.tree()[parent_id];
// If this ancestor already has dirty_descendants set, we can stop
// because all further ancestors must also have it set
if let Some(flag) = parent.dirty_descendants_flag() {
if flag.swap(true, Ordering::Relaxed) {
break;
}
}
current_id = parent.parent;
}
}
// pub fn damage_mut(&mut self) -> Option<&mut RestyleDamage> {
// self.stylo_element_data
// .get_mut()
// .map(|mut data: ElementDataMut<'a>| &'a mut data.damage)
// }
pub fn damage(&self) -> Option<RestyleDamage> {
self.stylo_element_data_opt()
.and_then(|stylo| stylo.get().map(|data| data.damage))
}
pub fn set_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage = damage;
}
}
}
pub fn insert_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage |= damage;
}
}
}
pub fn remove_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage.remove(damage);
}
}
}
pub fn clear_damage_mut(&mut self) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage = RestyleDamage::empty();
}
}
}
pub fn hover(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.insert(ElementState::HOVER);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn unhover(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.remove(ElementState::HOVER);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn is_hovered(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::HOVER))
}
pub fn focus(&mut self, shell_provider: Arc<dyn ShellProvider>) {
if let Some(data) = self.element_data_mut() {
data.element_state
.insert(ElementState::FOCUS | ElementState::FOCUSRING);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
// If focussing a text input, enable IME and set IME area
if self
.element_data()
.and_then(|elem| elem.text_input_data())
.is_some()
{
shell_provider.set_ime_enabled(true);
let mut pos = self.absolute_position(0.0, 0.0);
pos.x += self.final_layout().content_box_x();
pos.y += self.final_layout().content_box_y();
let width = self.final_layout().content_box_width();
let height = self.final_layout().content_box_height();
shell_provider.set_ime_cursor_area(pos.x, pos.y, width, height);
}
}
pub fn blur(&mut self, shell_provider: Arc<dyn ShellProvider>) {
if let Some(data) = self.element_data_mut() {
data.element_state
.remove(ElementState::FOCUS | ElementState::FOCUSRING);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
// If blurring a text input, disable IME
if self
.element_data()
.and_then(|elem| elem.text_input_data())
.is_some()
{
shell_provider.set_ime_enabled(false);
}
}
pub fn is_focussed(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::FOCUS))
}
pub fn active(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.insert(ElementState::ACTIVE);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn unactive(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.remove(ElementState::ACTIVE);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn is_active(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::ACTIVE))
}
// Marks the node as disabled if it can be.
// It does not disable any children which should be disabled as well (relevant for the `select` element).
pub fn disable(&mut self) {
if let Some(data) = self.element_data_mut() {
if data.can_be_disabled() {
data.element_state.insert(ElementState::DISABLED);
data.element_state.remove(ElementState::ENABLED);
}
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
// Marks the node as enabled if it can be.
// It does not enable any children which should be enabled as well (relevant for the `select` element).
pub fn enable(&mut self) {
if let Some(data) = self.element_data_mut() {
if data.can_be_disabled() {
data.element_state.insert(ElementState::ENABLED);
data.element_state.remove(ElementState::DISABLED);
}
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn subdoc(&self) -> Option<&dyn Document> {
self.element_data().and_then(|el| el.sub_doc_data())
}
pub fn subdoc_mut(&mut self) -> Option<&mut dyn Document> {
self.element_data_mut().and_then(|el| el.sub_doc_data_mut())
}
pub fn text_input_v_centering_offset(&self, scale: f64) -> f64 {
// For single-line inputs, add an offset to vertically center the text input layout
// within the content box of it's node.
if let Some(input_data) = self
.data
.downcast_element()
.and_then(|el| el.text_input_data())
{
if !input_data.is_multiline {
let content_box_height = self.final_layout().content_box_height();
let input_height = input_data.editor.try_layout().unwrap().height() / scale as f32;
let y_offset = ((content_box_height - input_height) / 2.0).max(0.0);
return y_offset as f64;
}
}
0.0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum NodeKind {
Document,
Element,
AnonymousBlock,
Text,
Comment,
}
/// The different kinds of nodes in the DOM.
#[derive(Debug, Clone)]
pub enum NodeData {
/// The `Document` itself - the root node of a HTML document.
Document(Box<DocumentData>),
/// An element with attributes.
Element(Box<ElementData>),
/// An anonymous block box
AnonymousBlock(Box<ElementData>),
/// A text node.
Text(TextNodeData),
/// A comment.
Comment {
/// The textual content of the comment
contents: String,
},
// /// A `DOCTYPE` with name, public id, and system id. See
// /// [document type declaration on wikipedia][https://en.wikipedia.org/wiki/Document_type_declaration]
// Doctype { name: String, public_id: String, system_id: String },
// /// A Processing instruction.
// ProcessingInstruction { target: String, contents: String },
}
impl NodeData {
pub fn downcast_element(&self) -> Option<&ElementData> {
match self {
Self::Element(data) => Some(data),
Self::AnonymousBlock(data) => Some(data),
_ => None,
}
}
pub fn downcast_element_mut(&mut self) -> Option<&mut ElementData> {
match self {
Self::Element(data) => Some(data),
Self::AnonymousBlock(data) => Some(data),
_ => None,
}
}
pub fn is_element_with_tag_name(&self, name: &impl PartialEq<LocalName>) -> bool {
let Some(elem) = self.downcast_element() else {
return false;
};
*name == elem.name.local
}
pub fn attrs(&self) -> Option<&[Attribute]> {
Some(&self.downcast_element()?.attrs)
}
pub fn attr(&self, name: impl PartialEq<LocalName>) -> Option<&str> {
self.downcast_element()?.attr(name)
}
pub fn has_attr(&self, name: impl PartialEq<LocalName>) -> bool {
self.downcast_element()
.is_some_and(|elem| elem.has_attr(name))
}
pub fn kind(&self) -> NodeKind {
match self {
NodeData::Document(_) => NodeKind::Document,
NodeData::Element(_) => NodeKind::Element,
NodeData::AnonymousBlock(_) => NodeKind::AnonymousBlock,
NodeData::Text(_) => NodeKind::Text,
NodeData::Comment { .. } => NodeKind::Comment,
}
}
}
#[derive(Debug, Clone)]
pub struct TextNodeData {
/// The textual content of the text node
pub content: String,
}
impl TextNodeData {
pub fn new(content: String) -> Self {
Self { content }
}
}
/*
-> Computed styles
-> Layout
-----> Needs to happen only when styles are computed
*/
// type DomRefCell<T> = RefCell<T>;
// pub struct DomData {
// // ... we can probs just get away with using the html5ever types directly. basically just using the servo dom, but without the bindings
// local_name: html5ever::LocalName,
// tag_name: html5ever::QualName,
// namespace: html5ever::Namespace,
// prefix: DomRefCell<Option<html5ever::Prefix>>,
// attrs: DomRefCell<Vec<Attr>>,
// // attrs: DomRefCell<Vec<Dom<Attr>>>,
// id_attribute: DomRefCell<Option<Atom>>,
// is: DomRefCell<Option<LocalName>>,
// // style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
// // attr_list: MutNullableDom<NamedNodeMap>,
// // class_list: MutNullableDom<DOMTokenList>,
// state: Cell<ElementState>,
// }
impl Node {
pub fn tree(&self) -> &crate::NodeTree {
unsafe { &*self.tree }
}
#[track_caller]
pub fn with(&self, id: NodeId) -> &Node {
self.tree().get(id).unwrap()
}
pub fn print_tree(&self, level: usize) {
println!(
"{} {} {:?} {} {:?}",
" ".repeat(level),
self.id,
self.parent,
self.node_debug_str().replace('\n', ""),
self.children
);
// println!("{} {:?}", " ".repeat(level), self.children);
for child_id in self.children.iter() {
let child = self.with(*child_id);
child.print_tree(level + 1)
}
}
// Get the index of the current node in the parents child list
pub fn index_of_child(&self, child_id: NodeId) -> Option<usize> {
self.children.iter().position(|id| *id == child_id)
}
// Get the index of the current node in the parents child list
pub fn child_index(&self) -> Option<usize> {
self.tree()[self.parent?]
.children
.iter()
.position(|id| *id == self.id)
}
// Get the nth node in the parents child list
pub fn forward(&self, n: usize) -> Option<&Node> {
let child_idx = self.child_index().unwrap_or(0);
self.tree()[self.parent?]
.children
.get(child_idx + n)
.map(|id| self.with(*id))
}
pub fn backward(&self, n: usize) -> Option<&Node> {
let child_idx = self.child_index().unwrap_or(0);
if child_idx < n {
return None;
}
self.tree()[self.parent?]
.children
.get(child_idx - n)
.map(|id| self.with(*id))
}
pub fn is_element(&self) -> bool {
matches!(self.data, NodeData::Element { .. })
}
pub fn is_anonymous(&self) -> bool {
matches!(self.data, NodeData::AnonymousBlock { .. })
}
pub fn is_text_node(&self) -> bool {
matches!(self.data, NodeData::Text { .. })
}
pub fn element_data(&self) -> Option<&ElementData> {
match self.data {
NodeData::Element(ref data) => Some(data),
NodeData::AnonymousBlock(ref data) => Some(data),
_ => None,
}
}
pub fn element_data_mut(&mut self) -> Option<&mut ElementData> {
match self.data {
NodeData::Element(ref mut data) => Some(data),
NodeData::AnonymousBlock(ref mut data) => Some(data),
_ => None,
}
}
pub fn text_data(&self) -> Option<&TextNodeData> {
match self.data {
NodeData::Text(ref data) => Some(data),
_ => None,
}
}
pub fn text_data_mut(&mut self) -> Option<&mut TextNodeData> {
match self.data {
NodeData::Text(ref mut data) => Some(data),
_ => None,
}
}
pub fn node_debug_str(&self) -> String {
let mut s = String::new();
match &self.data {
NodeData::Document(_) => write!(s, "DOCUMENT"),
// NodeData::Doctype { name, .. } => write!(s, "DOCTYPE {name}"),
NodeData::Text(data) => {
let bytes = data.content.as_bytes();
write!(
s,
"TEXT {}",
std::str::from_utf8(bytes.split_at(10.min(bytes.len())).0)
.unwrap_or("INVALID UTF8")
)
}
NodeData::Comment { .. } => write!(s, "COMMENT"),
NodeData::AnonymousBlock(_) => write!(s, "AnonymousBlock"),
NodeData::Element(data) => {
let name = &data.name;
let class = self.attr(local_name!("class")).unwrap_or("");
let id = self.attr(local_name!("id")).unwrap_or("");
let display = self.display_constructed_as().to_css_string();
write!(s, "<{}", name.local).unwrap();
if !id.is_empty() {
write!(s, " #{id}").unwrap();
}
if !class.is_empty() {
if class.contains(' ') {
write!(s, " class=\"{class}\"").unwrap()
} else {
write!(s, " .{class}").unwrap()
}
}
write!(s, "> ({display})")
} // NodeData::ProcessingInstruction { .. } => write!(s, "ProcessingInstruction"),
}
.unwrap();
s
}
/// Renders the HTML of this node and all its children as a `String` without extra whitespace.
///
/// Example output:
///
/// ```text
/// <html><head /><body><main id="main"><div class="arbitrary-class" /></main></body></html>
/// ```
pub fn outer_html(&self) -> String {
let mut output = String::new();
self.write_outer_html(&mut output);
output
}
/// Renders the HTML of this node and all its children as a `String` with whitespace for human
/// readability.
///
/// Example output:
///
/// ```text
/// <html>
/// <head />
/// <body>
/// <main id="main">
/// <div class="arbitrary-class" />
/// </main>
/// </body>
/// </html>
/// ```
pub fn outer_html_pretty(&self) -> String {
let mut output = String::new();
self.write_outer_html_pretty(&mut output);
output
}
pub fn write_outer_html(&self, writer: &mut String) {
self.write_outer_html_in_style(writer, OutputStyle::Normal, 0);
}
pub fn write_outer_html_pretty(&self, writer: &mut String) {
self.write_outer_html_in_style(writer, OutputStyle::Pretty, 0);
}
fn write_outer_html_in_style(&self, writer: &mut String, style: OutputStyle, nesting: usize) {
const INDENT: &str = " ";
let has_children = !self.children.is_empty();
let current_color = self
.primary_styles()
.map(|style| style.clone_color())
.map(|color| color.to_css_string());
match &self.data {
NodeData::Document(_) => {}
NodeData::Comment { .. } => {}
NodeData::AnonymousBlock(_) => {}
// NodeData::Doctype { name, .. } => write!(s, "DOCTYPE {name}"),
NodeData::Text(data) => {
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
writer.push_str(data.content.as_str());
if matches!(style, OutputStyle::Pretty) {
writer.push('\n');
}
}
NodeData::Element(data) => {
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
writer.push('<');
writer.push_str(&data.name.local);
for attr in data.attrs() {
writer.push(' ');
writer.push_str(&attr.name.local);
writer.push_str("=\"");
#[allow(clippy::unnecessary_unwrap)] // Convert to if-let chain once stabilised
if current_color.is_some() && attr.value.contains("currentColor") {
let value = attr
.value
.replace("currentColor", current_color.as_ref().unwrap());