-
Notifications
You must be signed in to change notification settings - Fork 14
/
transform_flexbox.rs
1449 lines (1332 loc) · 63.9 KB
/
transform_flexbox.rs
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
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::f32::consts::PI;
use crate::toolkit_font_style::{FontStyle, FontWeight};
use crate::toolkit_layout_style::{FlexWrap, Overflow};
use crate::toolkit_schema::ViewShape;
use crate::toolkit_style::{
Background, FilterOp, FontFeature, GridLayoutType, GridSpan, LayoutTransform, LineHeight,
MeterData, ShadowBox, StyledTextRun, TextAlign, TextOverflow, TextStyle, ViewStyle,
};
use crate::vector_schema;
use crate::{
component_context::ComponentContext,
extended_layout_schema::{ExtendedAutoLayout, LayoutType, SizePolicy}, //ExtendedTextLayout
figma_schema::{
BlendMode, Component, ComponentSet, EffectType, HorizontalLayoutConstraintValue,
LayoutAlign, LayoutAlignItems, LayoutMode, LayoutSizing, LayoutSizingMode, LineHeightUnit,
Node, NodeData, PaintData, StrokeAlign, TextAlignHorizontal, TextAlignVertical,
TextAutoResize, TextTruncation, VerticalLayoutConstraintValue,
},
image_context::ImageContext,
reaction_schema::{FrameExtras, Reaction, ReactionJson},
toolkit_schema::{ComponentInfo, OverflowDirection, RenderMethod, ScrollInfo, View},
};
use layout::styles::{
AlignContent, AlignItems, AlignSelf, FlexDirection, ItemSpacing, JustifyContent, PositionType,
};
use layout::types::Dimension;
use unicode_segmentation::UnicodeSegmentation;
//::{Taffy, Dimension, JustifyContent, Size, AvailableSpace, FlexDirection};
// If an Auto content preview widget specifies a "Hug contents" sizing policy, this
// overrides a fixed size sizing policy on its parent to allow it to grow to fit
// all of its child nodes.
fn check_child_size_override(node: &Node) -> Option<LayoutType> {
for child in node.children.iter() {
if child.is_widget() {
let plugin_data = child.shared_plugin_data.get("designcompose");
if let Some(vsw_data) = plugin_data {
if let Some(text_layout) = vsw_data.get("vsw-extended-auto-layout") {
let extended_auto_layout: Option<ExtendedAutoLayout> =
serde_json::from_str(text_layout.as_str()).ok();
if let Some(extended_auto_layout) = extended_auto_layout {
if extended_auto_layout.auto_layout_data.size_policy == SizePolicy::Hug {
return Some(extended_auto_layout.layout);
}
}
}
}
}
}
None
}
// Map Figma's new flexbox-based Auto Layout properties to our own flexbox-based layout
// properties.
fn compute_layout(node: &Node, parent: Option<&Node>) -> ViewStyle {
let mut style = ViewStyle::default();
// Determine if the parent is using Auto Layout (and thus is a Flexbox parent) or if it isn't.
let parent_frame = parent.and_then(|p| p.frame());
let parent_bounding_box = parent.and_then(|p| p.absolute_bounding_box);
//let parent_is_root = parent.is_none();
let parent_is_flexbox = if let Some(frame) = parent_frame {
!frame.layout_mode.is_none()
} else {
// The root container is from our toolkit, and uses flexbox.
//parent_is_root
false
};
let mut hug_width = false;
let mut hug_height = false;
if let Some(bounds) = node.absolute_bounding_box {
style.layout_style.bounding_box.width = bounds.width();
style.layout_style.bounding_box.height = bounds.height();
}
// Frames can implement Auto Layout on their children.
if let Some(frame) = node.frame() {
style.layout_style.position_type = PositionType::Relative;
style.layout_style.width = Dimension::Auto;
style.layout_style.height = Dimension::Auto;
style.layout_style.flex_grow = frame.layout_grow;
if frame.layout_grow == 1.0 {
// When the value of layout_grow is 1, it is because the node has
// its width or height set to FILL. Figma's node properties don't
// specify this, but flex_basis needs to be set to 0 so that it
// starts out small and grows to fill the container
style.layout_style.flex_basis = Dimension::Points(0.0);
}
style.layout_style.flex_shrink = 0.0;
style.node_style.horizontal_sizing = frame.layout_sizing_horizontal.into();
style.node_style.vertical_sizing = frame.layout_sizing_vertical.into();
// Check for a flex direction override, which can happen if this node has a child widget
let flex_direction_override = check_child_size_override(node);
if let Some(dir) = flex_direction_override {
style.layout_style.flex_direction = match dir {
LayoutType::Horizontal => FlexDirection::Row,
LayoutType::Vertical => FlexDirection::Column,
_ => FlexDirection::None,
};
} else {
style.layout_style.flex_direction = match frame.layout_mode {
LayoutMode::Horizontal => FlexDirection::Row,
LayoutMode::Vertical => FlexDirection::Column,
LayoutMode::None => FlexDirection::None,
};
}
style.layout_style.padding.start = Dimension::Points(frame.padding_left);
style.layout_style.padding.end = Dimension::Points(frame.padding_right);
style.layout_style.padding.top = Dimension::Points(frame.padding_top);
style.layout_style.padding.bottom = Dimension::Points(frame.padding_bottom);
style.layout_style.item_spacing = ItemSpacing::Fixed(frame.item_spacing as i32);
match frame.layout_align {
// Counter axis stretch
Some(LayoutAlign::Stretch) => {
style.layout_style.align_self = AlignSelf::Stretch;
}
_ => (),
};
style.layout_style.align_items = match frame.counter_axis_align_items {
LayoutAlignItems::Center => AlignItems::Center,
LayoutAlignItems::Max => AlignItems::FlexEnd,
LayoutAlignItems::Min => AlignItems::FlexStart,
LayoutAlignItems::SpaceBetween => AlignItems::FlexStart, // XXX
LayoutAlignItems::Baseline => AlignItems::FlexStart,
};
style.layout_style.justify_content = match frame.primary_axis_align_items {
LayoutAlignItems::Center => JustifyContent::Center,
LayoutAlignItems::Max => JustifyContent::FlexEnd,
LayoutAlignItems::Min => JustifyContent::FlexStart,
LayoutAlignItems::SpaceBetween => JustifyContent::SpaceBetween,
LayoutAlignItems::Baseline => JustifyContent::FlexStart,
};
// The toolkit picks "Stretch" as a sensible default, but we don't
// want that for Figma elements.
style.layout_style.align_content = AlignContent::FlexStart;
let align_self_stretch = style.layout_style.align_self == AlignSelf::Stretch;
if let Some(bounds) = node.absolute_bounding_box {
// If align_self is set to stretch, we want width/height to be Auto, even if the
// frame's primary or counter axis sizing mode is set to Fixed.
let dim_points_or_auto = |points| {
if align_self_stretch {
//|| parent_is_root {
Dimension::Auto
} else {
Dimension::Points(points)
}
};
match frame.layout_mode {
LayoutMode::Horizontal => {
hug_width = frame.primary_axis_sizing_mode == LayoutSizingMode::Auto;
hug_height = frame.counter_axis_sizing_mode == LayoutSizingMode::Auto;
style.layout_style.width = match frame.primary_axis_sizing_mode {
LayoutSizingMode::Fixed => dim_points_or_auto(bounds.width().ceil()),
LayoutSizingMode::Auto => Dimension::Auto,
};
style.layout_style.height = match frame.counter_axis_sizing_mode {
LayoutSizingMode::Fixed => dim_points_or_auto(bounds.height().ceil()),
LayoutSizingMode::Auto => Dimension::Auto,
};
if hug_width {
style.layout_style.min_width = Dimension::Auto;
}
}
LayoutMode::Vertical => {
hug_width = frame.counter_axis_sizing_mode == LayoutSizingMode::Auto;
hug_height = frame.primary_axis_sizing_mode == LayoutSizingMode::Auto;
style.layout_style.width = match frame.counter_axis_sizing_mode {
LayoutSizingMode::Fixed => dim_points_or_auto(bounds.width().ceil()),
LayoutSizingMode::Auto => Dimension::Auto,
};
style.layout_style.height = match frame.primary_axis_sizing_mode {
LayoutSizingMode::Fixed => dim_points_or_auto(bounds.height().ceil()),
LayoutSizingMode::Auto => Dimension::Auto,
};
if hug_height {
style.layout_style.min_height = Dimension::Auto;
}
}
_ => {
// Frame is not autolayout, so use the layout sizing mode
// to determine size. If we have a node size specified, use
// that instead of the bounds since the node size is the
// size without rotation and scale.
let (width, height) = if let Some(size) = &node.size {
(size.x(), size.y())
} else {
(bounds.width().ceil(), bounds.height().ceil())
};
if frame.layout_sizing_horizontal == LayoutSizing::Fill {
style.layout_style.width = Dimension::Auto;
} else {
style.layout_style.width = Dimension::Points(width);
}
if frame.layout_sizing_vertical == LayoutSizing::Fill {
style.layout_style.height = Dimension::Auto;
} else {
style.layout_style.height = Dimension::Points(height);
}
}
}
if frame.layout_mode != LayoutMode::None {
let width_points = bounds.width().ceil();
let height_points = bounds.height().ceil();
style.layout_style.width = match frame.layout_sizing_horizontal {
LayoutSizing::Fixed => Dimension::Points(width_points),
LayoutSizing::Fill => Dimension::Auto,
LayoutSizing::Hug => Dimension::Auto,
};
style.layout_style.height = match frame.layout_sizing_vertical {
LayoutSizing::Fixed => Dimension::Points(height_points),
LayoutSizing::Fill => Dimension::Auto,
LayoutSizing::Hug => Dimension::Auto,
};
}
}
}
// Setup widget size to expand to its parent
let mut is_widget_or_parent_widget = node.is_widget();
if let Some(parent) = parent {
if !is_widget_or_parent_widget {
is_widget_or_parent_widget = parent.is_widget();
}
}
if is_widget_or_parent_widget {
style.layout_style.position_type = PositionType::Absolute;
style.layout_style.width = Dimension::Auto;
style.layout_style.height = Dimension::Auto;
style.layout_style.left = Dimension::Points(0.0);
style.layout_style.right = Dimension::Points(0.0);
style.layout_style.top = Dimension::Points(0.0);
style.layout_style.bottom = Dimension::Points(0.0);
}
// Vector layers have some layout properties for themselves, but not for their children.
if let Some(vector) = node.vector() {
match vector.layout_align {
// Counter axis stretch
Some(LayoutAlign::Stretch) => {
style.layout_style.align_self = AlignSelf::Stretch;
}
_ => (),
};
style.layout_style.position_type = PositionType::Relative;
style.layout_style.width = Dimension::Auto;
style.layout_style.height = Dimension::Auto;
}
if let Some(bounds) = node.absolute_bounding_box {
if !hug_width {
style.layout_style.min_width = Dimension::Points(bounds.width().ceil());
}
if !hug_height {
style.layout_style.min_height = Dimension::Points(bounds.height().ceil());
}
}
if let Some(size) = &node.size {
if size.is_valid() {
if !hug_width {
style.layout_style.min_width = Dimension::Points(size.x());
}
if !hug_height {
style.layout_style.min_height = Dimension::Points(size.y());
}
// Set fixed vector size
// TODO need to change to support scale?
if node.vector().is_some() {
style.layout_style.width = Dimension::Points(size.x());
style.layout_style.height = Dimension::Points(size.y());
}
style.node_style.node_size.width = size.x();
style.node_style.node_size.height = size.y();
}
}
// For text we want to force the width.
if let NodeData::Text { vector, style: text_style, .. } = &node.data {
style.layout_style.flex_grow = vector.layout_grow;
if vector.layout_grow == 1.0 {
// When the value of layout_grow is 1, it is because the node has
// its width or height set to FILL. Figma's node properties don't
// specify this, but flex_basis needs to be set to 0 so that it
// starts out small and grows to fill the container
style.layout_style.flex_basis = Dimension::Points(0.0);
}
style.node_style.horizontal_sizing = vector.layout_sizing_horizontal.into();
style.node_style.vertical_sizing = vector.layout_sizing_vertical.into();
// The text style also contains some layout information. We previously exposed
// auto-width text in our plugin.
match text_style.text_auto_resize {
TextAutoResize::Height => {
if vector.layout_sizing_horizontal == LayoutSizing::Fill {
style.layout_style.width = Dimension::Auto;
} else {
style.layout_style.width = style.layout_style.min_width;
}
style.layout_style.height = Dimension::Auto;
}
TextAutoResize::WidthAndHeight => {
style.layout_style.min_width = Dimension::Auto;
style.layout_style.width = Dimension::Auto;
style.layout_style.height = Dimension::Auto;
}
// TextAutoResize::Truncate is deprecated
// Use fixed width and height
_ => {
style.layout_style.width = style.layout_style.min_width;
style.layout_style.height = style.layout_style.min_height;
}
}
}
if !parent_is_flexbox {
match (node.absolute_bounding_box, parent_bounding_box) {
(Some(bounds), Some(parent_bounds)) => {
style.layout_style.position_type = PositionType::Absolute;
// Figure out all the values we might need when calculating the layout constraints.
let (width, height) = if let Some(size) = &node.size {
(size.x(), size.y())
} else {
(bounds.width().ceil(), bounds.height().ceil())
};
let left = (bounds.x() - parent_bounds.x()).round();
let right = parent_bounds.width().ceil() - (left + bounds.width().ceil()); // px from our right edge to parent's right edge
let top = (bounds.y() - parent_bounds.y()).round();
let bottom = parent_bounds.height().ceil() - (top + bounds.height().ceil());
match node.constraints().map(|c| c.horizontal) {
Some(HorizontalLayoutConstraintValue::Left) | None => {
style.layout_style.left = Dimension::Percent(0.0);
style.layout_style.right = Dimension::Auto;
style.layout_style.margin.start = Dimension::Points(left);
if !hug_width && !node.is_text() {
style.layout_style.width = Dimension::Points(width);
}
}
Some(HorizontalLayoutConstraintValue::Right) => {
style.layout_style.left = Dimension::Auto;
style.layout_style.right = Dimension::Percent(0.0);
style.layout_style.margin.end = Dimension::Points(right);
if !hug_width && !node.is_text() {
style.layout_style.width = Dimension::Points(width);
}
}
Some(HorizontalLayoutConstraintValue::LeftRight) => {
style.layout_style.left = Dimension::Percent(0.0);
style.layout_style.right = Dimension::Percent(0.0);
style.layout_style.margin.start = Dimension::Points(left);
style.layout_style.margin.end = Dimension::Points(right);
style.layout_style.width = Dimension::Auto;
}
Some(HorizontalLayoutConstraintValue::Center) => {
// Centering with absolute positioning isn't directly possible; instead we
// give our style a left/top margin of 50%, which centers the left/top edge
// within the parent, then we apply the delta to move it to the correct
// location using the left/top property. All of this adds up to position the
// component where it was in Figma, but anchored to the horizontal/vertical
// centerpoint.
style.layout_style.left = Dimension::Percent(0.5);
style.layout_style.right = Dimension::Auto;
style.layout_style.margin.start =
Dimension::Points(left - parent_bounds.width().ceil() / 2.0);
if !hug_width && !node.is_text() {
style.layout_style.width = Dimension::Points(width);
}
}
Some(HorizontalLayoutConstraintValue::Scale) => {
style.layout_style.left =
Dimension::Percent(left / parent_bounds.width().ceil());
style.layout_style.right =
Dimension::Percent(right / parent_bounds.width().ceil());
style.layout_style.width = Dimension::Auto;
style.layout_style.min_width = Dimension::Auto;
}
}
match node.constraints().map(|c| c.vertical) {
Some(VerticalLayoutConstraintValue::Top) | None => {
style.layout_style.top = Dimension::Percent(0.0);
style.layout_style.bottom = Dimension::Auto;
style.layout_style.margin.top = Dimension::Points(top);
if !hug_height && !node.is_text() {
style.layout_style.height = Dimension::Points(height);
}
}
Some(VerticalLayoutConstraintValue::Bottom) => {
style.layout_style.top = Dimension::Auto;
style.layout_style.bottom = Dimension::Percent(0.0);
style.layout_style.margin.bottom = Dimension::Points(bottom);
if !hug_height && !node.is_text() {
style.layout_style.height = Dimension::Points(height);
}
}
Some(VerticalLayoutConstraintValue::TopBottom) => {
style.layout_style.top = Dimension::Percent(0.0);
style.layout_style.bottom = Dimension::Percent(0.0);
style.layout_style.margin.top = Dimension::Points(top);
style.layout_style.margin.bottom = Dimension::Points(bottom);
style.layout_style.height = Dimension::Auto;
}
Some(VerticalLayoutConstraintValue::Center) => {
style.layout_style.top = Dimension::Percent(0.5);
style.layout_style.bottom = Dimension::Auto;
style.layout_style.margin.top =
Dimension::Points(top - parent_bounds.height().ceil() / 2.0);
if !hug_height && !node.is_text() {
style.layout_style.height = Dimension::Points(height);
}
}
Some(VerticalLayoutConstraintValue::Scale) => {
style.layout_style.top =
Dimension::Percent(top / parent_bounds.height().ceil());
style.layout_style.bottom =
Dimension::Percent(bottom / parent_bounds.height().ceil());
style.layout_style.height = Dimension::Auto;
style.layout_style.min_height = Dimension::Auto;
}
}
}
_ => {}
}
}
style
}
fn convert_transform(transform: &crate::figma_schema::Transform) -> LayoutTransform {
LayoutTransform::row_major_2d(
transform[0][0].unwrap_or(1.0),
transform[1][0].unwrap_or(0.0),
transform[0][1].unwrap_or(0.0),
transform[1][1].unwrap_or(1.0),
transform[0][2].unwrap_or(0.0),
transform[1][2].unwrap_or(0.0),
)
}
fn convert_blend_mode(
blend_mode: Option<crate::figma_schema::BlendMode>,
) -> crate::toolkit_style::BlendMode {
match blend_mode {
Some(BlendMode::PassThrough) | None => crate::toolkit_style::BlendMode::PassThrough,
Some(BlendMode::Normal) => crate::toolkit_style::BlendMode::Normal,
Some(BlendMode::Darken) => crate::toolkit_style::BlendMode::Darken,
Some(BlendMode::Multiply) => crate::toolkit_style::BlendMode::Multiply,
Some(BlendMode::LinearBurn) => crate::toolkit_style::BlendMode::LinearBurn,
Some(BlendMode::ColorBurn) => crate::toolkit_style::BlendMode::ColorBurn,
Some(BlendMode::Lighten) => crate::toolkit_style::BlendMode::Lighten,
Some(BlendMode::Screen) => crate::toolkit_style::BlendMode::Screen,
Some(BlendMode::LinearDodge) => crate::toolkit_style::BlendMode::LinearDodge,
Some(BlendMode::ColorDodge) => crate::toolkit_style::BlendMode::ColorDodge,
Some(BlendMode::Overlay) => crate::toolkit_style::BlendMode::Overlay,
Some(BlendMode::SoftLight) => crate::toolkit_style::BlendMode::SoftLight,
Some(BlendMode::HardLight) => crate::toolkit_style::BlendMode::HardLight,
Some(BlendMode::Difference) => crate::toolkit_style::BlendMode::Difference,
Some(BlendMode::Exclusion) => crate::toolkit_style::BlendMode::Exclusion,
Some(BlendMode::Hue) => crate::toolkit_style::BlendMode::Hue,
Some(BlendMode::Saturation) => crate::toolkit_style::BlendMode::Saturation,
Some(BlendMode::Color) => crate::toolkit_style::BlendMode::Color,
Some(BlendMode::Luminosity) => crate::toolkit_style::BlendMode::Luminosity,
}
}
fn compute_background(
last_paint: &crate::figma_schema::Paint,
images: &mut ImageContext,
node_name: &String,
) -> crate::toolkit_style::Background {
if let PaintData::Solid { color } = &last_paint.data {
Background::Solid(crate::Color::from_f32s(
color.r,
color.g,
color.b,
color.a * last_paint.opacity,
))
} else if let PaintData::Image {
image_ref: Some(image_ref),
filters,
scale_mode,
image_transform,
scaling_factor,
rotation,
..
} = &last_paint.data
{
let mut image_filter_list = Vec::new();
if let Some(image_filters) = filters {
if let Some(sat) = image_filters.saturation {
image_filter_list.push(FilterOp::Grayscale(sat * -1.0));
}
if let Some(contrast) = image_filters.contrast {
image_filter_list.push(FilterOp::Contrast(contrast + 1.0));
}
if let Some(exposure) = image_filters.exposure {
let exp_adj: f32;
//Below 0, it's linear to -1. But don't let it get set to -1 or it goes black.
if exposure > 0.0 {
exp_adj = 1.0 + exposure * 6.0; //webrender's scaling for brightness isn't linear
} else {
exp_adj = 0.1 + (1.0 + exposure);
}
image_filter_list.push(FilterOp::Brightness(exp_adj));
}
}
// Figma's image transform is inverted from what most graphics APIs expect, so invert
// it here to avoid doing matrix inversions at render time.
let mut transform = image_transform
.map(|tx| convert_transform(&tx).inverse().unwrap_or(LayoutTransform::identity()))
.unwrap_or(LayoutTransform::identity());
// Figma has already applied the rotation in "stretch" mode.
if *rotation != 0.0 && *scale_mode != crate::figma_schema::ScaleMode::Stretch {
transform = transform.pre_rotate(0.0, 0.0, 1.0, euclid::Angle::degrees(*rotation));
}
if let Some(scale_factor) = *scaling_factor {
transform = transform.post_scale(scale_factor, scale_factor, scale_factor);
}
let bg_scale_mode = match scale_mode {
crate::figma_schema::ScaleMode::Tile => crate::toolkit_style::ScaleMode::Tile,
crate::figma_schema::ScaleMode::Fill => crate::toolkit_style::ScaleMode::Fill,
crate::figma_schema::ScaleMode::Fit => crate::toolkit_style::ScaleMode::Fit,
crate::figma_schema::ScaleMode::Stretch => crate::toolkit_style::ScaleMode::Stretch,
};
if let Some(fill) = images.image_fill(image_ref, node_name) {
Background::Image {
key: Some(fill),
filters: image_filter_list,
transform: Some(transform.to_2d()),
opacity: last_paint.opacity,
scale_mode: bg_scale_mode,
}
} else if !image_filter_list.is_empty() {
// There's no image but we have filters, so store those with no image in case there's
// a runtime customization that specifies an image source.
Background::Image {
key: None,
filters: image_filter_list,
transform: Some(transform.to_2d()),
opacity: last_paint.opacity,
scale_mode: bg_scale_mode,
}
} else {
Background::None
}
} else if let PaintData::GradientLinear { gradient } = &last_paint.data {
let start_x = gradient.gradient_handle_positions[0].x();
let start_y = gradient.gradient_handle_positions[0].y();
let end_x = gradient.gradient_handle_positions[1].x();
let end_y = gradient.gradient_handle_positions[1].y();
let mut g_stops: Vec<(f32, crate::Color)> = Vec::new();
let stops = &gradient.gradient_stops;
for s in stops {
let c = crate::Color::from_f32s(
s.color.r,
s.color.g,
s.color.b,
s.color.a * last_paint.opacity,
);
let g = (s.position, c);
g_stops.push(g);
}
Background::LinearGradient { start_x, start_y, end_x, end_y, color_stops: g_stops }
} else if let PaintData::GradientAngular { gradient } = &last_paint.data {
let center_x = gradient.gradient_handle_positions[0].x();
let center_y = gradient.gradient_handle_positions[0].y();
let end_x = gradient.gradient_handle_positions[1].x();
let end_y = gradient.gradient_handle_positions[1].y();
let cross_x = gradient.gradient_handle_positions[2].x();
let cross_y = gradient.gradient_handle_positions[2].y();
let angle = (f32::atan2(center_x - end_x, end_y - center_y) + PI) % (2.0 * PI);
let scale = f32::sqrt(f32::powf(end_x - center_x, 2.0) + f32::powf(end_y - center_y, 2.0))
/ f32::sqrt(f32::powf(cross_x - center_x, 2.0) + f32::powf(cross_y - center_y, 2.0));
let mut g_stops: Vec<(f32, crate::Color)> = Vec::new();
let stops = &gradient.gradient_stops;
for s in stops {
let c = crate::Color::from_f32s(
s.color.r,
s.color.g,
s.color.b,
s.color.a * last_paint.opacity,
);
let g = (s.position, c);
g_stops.push(g);
}
Background::AngularGradient { center_x, center_y, angle, scale, color_stops: g_stops }
} else if let PaintData::GradientRadial { gradient } = &last_paint.data {
let center_x = gradient.gradient_handle_positions[0].x();
let center_y = gradient.gradient_handle_positions[0].y();
let end_x = gradient.gradient_handle_positions[1].x();
let end_y = gradient.gradient_handle_positions[1].y();
let width_x = gradient.gradient_handle_positions[2].x();
let width_y = gradient.gradient_handle_positions[2].y();
let angle = (f32::atan2(center_x - end_x, end_y - center_y) + PI) % (2.0 * PI);
let radius = (
f32::sqrt(f32::powf(end_x - center_x, 2.0) + f32::powf(end_y - center_y, 2.0)),
f32::sqrt(f32::powf(width_x - center_x, 2.0) + f32::powf(width_y - center_y, 2.0)),
);
let mut g_stops: Vec<(f32, crate::Color)> = Vec::new();
let stops = &gradient.gradient_stops;
for s in stops {
let c = crate::Color::from_f32s(
s.color.r,
s.color.g,
s.color.b,
s.color.a * last_paint.opacity,
);
let g = (s.position, c);
g_stops.push(g);
}
Background::RadialGradient { center_x, center_y, radius, angle, color_stops: g_stops }
} else if let PaintData::GradientDiamond { gradient } = &last_paint.data {
let center_x = gradient.gradient_handle_positions[0].x();
let center_y = gradient.gradient_handle_positions[0].y();
let end_x = gradient.gradient_handle_positions[1].x();
let end_y = gradient.gradient_handle_positions[1].y();
let width_x = gradient.gradient_handle_positions[2].x();
let width_y = gradient.gradient_handle_positions[2].y();
let angle = (f32::atan2(center_x - end_x, end_y - center_y) + PI) % (2.0 * PI);
let radius = (
f32::sqrt(f32::powf(end_x - center_x, 2.0) + f32::powf(end_y - center_y, 2.0)),
f32::sqrt(f32::powf(width_x - center_x, 2.0) + f32::powf(width_y - center_y, 2.0)),
);
let mut g_stops: Vec<(f32, crate::Color)> = Vec::new();
let stops = &gradient.gradient_stops;
for s in stops {
let c = crate::Color::from_f32s(
s.color.r,
s.color.g,
s.color.b,
s.color.a * last_paint.opacity,
);
let g = (s.position, c);
g_stops.push(g);
}
Background::RadialGradient { center_x, center_y, radius, angle, color_stops: g_stops }
} else {
Background::None
}
}
// We have a 1:1 correspondence between Nodes and Views which is super nice.
fn visit_node(
node: &Node,
parent: Option<&Node>,
component_map: &HashMap<String, Component>,
component_set_map: &HashMap<String, ComponentSet>,
component_context: &mut ComponentContext,
images: &mut ImageContext,
parent_plugin_data: Option<&HashMap<String, String>>,
) -> View {
// See if we have any plugin data. If we have plugin data passed in, it came from a parent
// widget, so use it. Otherwise look for it in the shared plugin data.
let mut plugin_data = None;
let mut child_plugin_data = None;
if parent_plugin_data.is_some() {
plugin_data = parent_plugin_data;
} else if node.shared_plugin_data.contains_key("designcompose") {
plugin_data = node.shared_plugin_data.get("designcompose");
if node.is_widget() {
child_plugin_data = plugin_data;
plugin_data = None;
}
}
// First determine our layout style, then accumulate our visual style.
let mut style = compute_layout(node, parent);
let mut component_info = None;
// If this is an instance of a component, then link to the original component so that we can substitute
// Figma components for alternative implementations when the toolkit_schema tree gets mapped to actual
// views.
if let NodeData::Instance { component_id, .. } = &node.data {
if let Some(component_metadata) = component_map.get(component_id) {
component_info = Some(ComponentInfo {
name: component_metadata.name.clone(),
id: component_id.clone(),
component_set_name: component_set_map
.get(&component_metadata.component_set_id)
.unwrap_or(&ComponentSet::default())
.name
.clone(),
overrides: None,
});
// Make sure we convert this component node so that we can compute any variant style delta
// later on.
component_context.add_component_info(component_id);
}
}
// If this is a component, also set the component info so that if the variant changes at runtime, the
// variant node has this component info and can use it to change to the other variant.
if let NodeData::Component { frame: _ } = &node.data {
if let Some(component_metadata) = component_map.get(&node.id) {
component_info = Some(ComponentInfo {
name: component_metadata.name.clone(),
id: node.id.clone(),
component_set_name: component_set_map
.get(&component_metadata.component_set_id)
.unwrap_or(&ComponentSet::default())
.name
.clone(),
overrides: None,
});
}
}
// Check relative transform to see if there is a rotation.
if let Some(transform) = node.relative_transform {
let parent_bounding_box = parent.and_then(|p| p.absolute_bounding_box);
let bounds = node.absolute_bounding_box;
fn get(transform: [[Option<f32>; 3]; 2], a: usize, b: usize) -> f32 {
assert!(a <= 1);
assert!(b <= 2);
transform[a][b].unwrap_or(0.0)
}
if let (Some(parent_bounds), Some(bounds)) = (parent_bounding_box, bounds) {
let r = LayoutTransform::row_major_2d(
get(transform, 0, 0),
get(transform, 1, 0),
get(transform, 0, 1),
get(transform, 1, 1),
get(transform, 0, 2),
get(transform, 1, 2),
);
// Provide an unaltered transform from the last relevant parent.
style.node_style.relative_transform = Some(r.clone());
// And an additional transform with translation removed.
let r = r.post_translate(euclid::vec3(
-(bounds.x() - parent_bounds.x()),
-(bounds.y() - parent_bounds.y()),
0.0,
));
style.node_style.transform = Some(r);
}
}
// If there's interaction info from our plugin that syncs interactive data then
// parse it out.
let reactions: Option<Vec<Reaction>> = {
if let Some(vsw_data) = plugin_data {
if let Some(reactions) = vsw_data.get("vsw-reactions") {
serde_json::from_str(reactions.as_str())
.map(|mut x: Vec<ReactionJson>| {
// Convert from ReactionJson to Reaction
let reaction: Vec<Reaction> = x.drain(..).map(|r| r.into()).collect();
// Tell the component context about these reactions, too.
component_context.add_destination_nodes(&reaction);
Some(reaction)
})
.unwrap_or_else(|e| {
println!("Error parsing reaction: {}. Json: {}", e, reactions);
None
})
} else {
None
}
} else {
None
}
};
// We have some extra info for frames from the plugin which isn't present
// in the REST response.
let frame_extras: Option<FrameExtras> = {
if let Some(vsw_data) = plugin_data {
if let Some(extras) = vsw_data.get("vsw-frame-extras") {
serde_json::from_str(extras.as_str()).ok()
} else {
None
}
} else {
None
}
};
let mut scroll_info = ScrollInfo::default();
let extended_auto_layout: Option<ExtendedAutoLayout> = {
if let Some(vsw_data) = plugin_data {
if let Some(text_layout) = vsw_data.get("vsw-extended-auto-layout") {
serde_json::from_str(text_layout.as_str()).ok()
} else {
None
}
} else {
None
}
};
let mut has_extended_auto_layout = false;
let mut is_widget_list = false;
let mut size_policy = SizePolicy::default();
// Apply the extra auto layout properties.
if let Some(extended_auto_layout) = extended_auto_layout {
let layout = extended_auto_layout.layout;
// Only consider extended auto layout if the layout is not None. This filters out old
// extended layout data that may have been written to Figma nodes using an old widget
// or our old extended layout plugin.
has_extended_auto_layout = layout != LayoutType::None;
style.node_style.flex_wrap =
if extended_auto_layout.wrap { FlexWrap::Wrap } else { FlexWrap::NoWrap };
style.node_style.grid_layout = match layout {
LayoutType::AutoColumns => Some(GridLayoutType::AutoColumns),
LayoutType::FixedColumns => Some(GridLayoutType::FixedColumns),
LayoutType::FixedRows => Some(GridLayoutType::FixedRows),
LayoutType::AutoRows => Some(GridLayoutType::AutoRows),
LayoutType::Horizontal => Some(GridLayoutType::Horizontal),
LayoutType::Vertical => Some(GridLayoutType::Vertical),
_ => None,
};
if layout.is_grid() {
let cld = &extended_auto_layout.common_data;
let gld = &extended_auto_layout.grid_layout_data;
let horizontal =
layout == LayoutType::FixedColumns || layout == LayoutType::AutoColumns;
style.node_style.grid_adaptive_min_size = gld.adaptive_min_size;
style.node_style.grid_columns_rows = extended_auto_layout.grid_layout_data.columns_rows;
style.layout_style.padding.start = Dimension::Points(cld.margin_left);
style.layout_style.padding.end = Dimension::Points(cld.margin_right);
style.layout_style.padding.top = Dimension::Points(cld.margin_top);
style.layout_style.padding.bottom = Dimension::Points(cld.margin_bottom);
style.layout_style.item_spacing = if gld.auto_spacing {
if horizontal {
ItemSpacing::Auto(gld.horizontal_spacing, gld.auto_spacing_item_size)
} else {
ItemSpacing::Auto(gld.vertical_spacing, gld.auto_spacing_item_size)
}
} else if horizontal {
ItemSpacing::Fixed(gld.horizontal_spacing)
} else {
ItemSpacing::Fixed(gld.vertical_spacing)
};
style.node_style.cross_axis_item_spacing = if horizontal {
gld.vertical_spacing as f32
} else {
gld.horizontal_spacing as f32
};
if cld.scrolling {
scroll_info.overflow = if horizontal {
OverflowDirection::VerticalScrolling
} else {
OverflowDirection::HorizontalScrolling
};
}
for grid_span in extended_auto_layout.grid_layout_data.span_content {
// Parse variant name with format "property1=value1, property2=value2" into variant_hash
let mut variant_hash: HashMap<String, String> = HashMap::new();
let props_and_names = grid_span.node_name.split(',');
for prop_var in props_and_names {
let prop_variant = prop_var.to_string();
let variant_parts: Vec<&str> = prop_variant.split('=').collect();
if variant_parts.len() == 2 {
variant_hash
.insert(variant_parts[0].to_string(), variant_parts[1].to_string());
} else {
println!("Invalid grid span variant: {:?}", variant_parts);
}
}
style.node_style.grid_span_content.push(GridSpan {
node_name: grid_span.node_name.clone(),
node_variant: variant_hash,
span: grid_span.span,
max_span: grid_span.max_span,
})
}
} else if layout.is_row_or_column() {
// For a horizontal or vertical autolayout, the widget uses the
// standard Figma autolayout properties which is already handled by the frame layout
// code above, so all we need to do is set the scrolling info if it is checked and the
// space between boolean.
if extended_auto_layout.common_data.scrolling {
scroll_info.overflow = if layout == LayoutType::Vertical {
OverflowDirection::VerticalScrolling
} else {
OverflowDirection::HorizontalScrolling
};
}
if extended_auto_layout.auto_layout_data.space_between {
style.layout_style.justify_content = JustifyContent::SpaceBetween;
}
is_widget_list = true;
size_policy = extended_auto_layout.auto_layout_data.size_policy;
}
// Store the extra scrolling properties in scroll_info
scroll_info.paged_scrolling = extended_auto_layout.paged_scrolling;
// Set parameters that limit the number of children for this frame
if extended_auto_layout.limit_content {
let lcd = extended_auto_layout.limit_content_data;
style.node_style.max_children = Some(lcd.max_num_items);
style.node_style.overflow_node_id = Some(lcd.overflow_node_id);
style.node_style.overflow_node_name = Some(lcd.overflow_node_name);
}
}
if !has_extended_auto_layout && !is_widget_list {
let plugin_data = node.shared_plugin_data.get("designcompose");
if let Some(plugin_data) = plugin_data {
if let Some(auto_layout_str) = plugin_data.get("vsw-extended-auto-layout") {
let extended_auto_layout: Option<ExtendedAutoLayout> =
serde_json::from_str(auto_layout_str.as_str()).ok();
if let Some(extended_auto_layout) = extended_auto_layout {
is_widget_list = extended_auto_layout.layout.is_row_or_column();
size_policy = extended_auto_layout.auto_layout_data.size_policy;
}
}
}
}
// If this node is a widget or a child of a widget with a horizontal or vertical layout,
// we need to set our size depending on whether the size policy is hug or fixed.
if is_widget_list {
if size_policy == SizePolicy::Hug {
style.layout_style.position_type = PositionType::Relative;
style.layout_style.width = Dimension::Auto;
style.layout_style.height = Dimension::Auto;
} else {
style.layout_style.position_type = PositionType::Absolute;
}
}
// Blend mode is common to all elements.
style.node_style.blend_mode = convert_blend_mode(node.blend_mode);