nsh-core 0.1.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
//! The host elements beyond views, texts and images: inputs, scroll views,
//! navigation stacks and their screens, modals, canvases, web views, videos
//! and the embedder's native components, with their props and typed events. Their props are the
//! core's [`Prop`]s, kept per element and diffed by kind: a prop a render
//! no longer sets goes back to its default, as when JS clears it.

use std::sync::Arc;

use super::{
    Accessible, AnyElement, Interactive,
    element::{ElNode, Element, IntoElement, Listener, ParentElement},
    events::{self, NativeEvent, Selection, VideoInfo, VideoProgress, WebNavigation},
};
use crate::{
    AutoCapitalize, AutoFill, Color, EventKind, HeaderSlot, JsonValue, KeyboardAppearance,
    KeyboardType, ModalAnimation, ModalPresentation, ModalProp, NativeProp, Prop, ResizeMode,
    ReturnKeyType, ScreenAnimation, ScreenProp, ScrollProp, Size, SubmitBehavior, Tag, WebSource,
    canvas::{
        CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
        Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp,
    },
    js::host::HostProps,
};

/// Whether `a` and `b` set the same property (their values aside).
pub(crate) fn same_kind(a: &Prop, b: &Prop) -> bool {
    match (a, b) {
        (Prop::ComponentProp(a, _), Prop::ComponentProp(b, _)) => a == b,
        _ => HostProps::same_kind(a, b),
    }
}

/// `prop`'s property at its default (what clearing it from JS sets), for
/// the props elements set; `None` for those set once.
pub(crate) fn reset(prop: &Prop) -> Option<Prop> {
    match prop {
        Prop::ComponentProp(name, _) => Some(Prop::ComponentProp(name.clone(), None)),
        _ => HostProps::reset(prop),
    }
}

/// Sets `prop` on `node`, replacing the value of the same property.
pub(crate) fn set(node: &mut ElNode, prop: Prop) {
    let props = &mut node.attrs.props;
    match props.iter_mut().find(|p| same_kind(p, &prop)) {
        Some(p) => *p = prop,
        None => props.push(prop),
    }
}

/// Adds a typed listener of `kind`.
fn listen<T: ?Sized + ToOwned + 'static>(
    node: &mut ElNode,
    kind: EventKind,
    listener: Listener<T>,
    decode: events::Decode<T>,
) {
    node.handlers.push((kind, events::typed(listener, decode)));
}

macro_rules! host_element {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        #[derive(Clone)]
        pub struct $name(ElNode);

        impl Element for $name {
            fn node(&mut self) -> &mut ElNode {
                &mut self.0
            }
        }

        impl IntoElement for $name {
            fn into_element(self) -> AnyElement {
                AnyElement(self.0)
            }
        }

        impl Accessible for $name {}
        impl Interactive for $name {}

        // Not every element has props of its own and events.
        #[allow(dead_code)]
        impl $name {
            fn set(mut self, prop: Prop) -> Self {
                set(&mut self.0, prop);
                self
            }

            fn listen<T: ?Sized + ToOwned + 'static>(
                mut self,
                kind: EventKind,
                listener: Listener<T>,
                decode: events::Decode<T>,
            ) -> Self {
                listen(&mut self.0, kind, listener, decode);
                self
            }
        }
    };
}

host_element! {
    /// A text field (`<input>`), made by [`input`]: one line, or several
    /// with [`Input::multiline`]. Its text style comes from its styles.
    Input
}

host_element! {
    /// A scroll view (`<scroll>`), made by [`scroll`]: its children are its
    /// content.
    Scroll
}

host_element! {
    /// A native navigation stack (`<stack>`), made by [`stack`]:
    /// UINavigationController on iOS (swipe back, native header), a stack
    /// with a toolbar and predictive back on Android. Its children are its
    /// [`Screen`]s, bottom to top.
    Stack
}

host_element! {
    /// One screen of a [`Stack`] (`<screen>`), made by [`screen`]: its
    /// header options and its content (its children).
    Screen
}

host_element! {
    /// A modal (`<modal>`), made by [`modal`]: presented while it is in the
    /// render, over everything else; its children are its content.
    Modal
}

host_element! {
    /// A bar over the keyboard (`<inputaccessory>`, TS: `InputAccessoryView`
    /// of `nsh/ios`), made by [`input_accessory_view`]: its children are its
    /// content.
    InputAccessoryView
}

host_element! {
    /// A view drawn with a [`Drawing`] (`<canvas>`), made by [`canvas`].
    CanvasView
}

host_element! {
    /// A web page (`<webview>`), made by [`web_view`].
    WebView
}

host_element! {
    /// A video player (`<video>`), made by [`video`].
    Video
}

host_element! {
    /// A native component the embedding app registered (`<native>`), made
    /// by [`native`].
    NativeView
}

impl ParentElement for Scroll {}
impl ParentElement for Stack {}
impl ParentElement for Screen {}
impl ParentElement for Modal {}

/// Android has no input accessories: there the bar keeps no content.
impl ParentElement for InputAccessoryView {
    fn child(mut self, child: impl IntoElement) -> Self {
        if !cfg!(target_os = "android") {
            self.0.children.push(child.into_element().0);
        }
        self
    }

    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
        if !cfg!(target_os = "android") {
            self.0
                .children
                .extend(children.into_iter().map(|c| c.into_element().0));
        }
        self
    }
}

/// A text field.
pub fn input() -> Input {
    Input(ElNode::new(Tag::Input))
}

/// A vertical scroll view ([`Scroll::horizontal`] for a horizontal one).
pub fn scroll() -> Scroll {
    Scroll(ElNode::new(Tag::Scroll))
}

/// A native navigation stack of [`screen`]s: put a screen in to push it,
/// leave it out to pop it. Give each screen a [`Element::key`] (its route)
/// so the screens below keep their state.
pub fn stack() -> Stack {
    Stack(ElNode::new(Tag::Stack))
}

/// A screen of a [`stack`]. What it renders reads its insets below the
/// header ([`super::RenderCx::insets`]).
pub fn screen() -> Screen {
    let mut node = ElNode::new(Tag::Screen);
    // Its insets come with this event.
    node.handlers.push((EventKind::Insets, Listener::noop()));
    Screen(node)
}

/// A modal presenting its children. Put it in the render to present it,
/// leave it out to dismiss it.
pub fn modal() -> Modal {
    let mut node = ElNode::new(Tag::Modal);
    // Its insets (`RenderCx::insets` inside it) come with this event.
    node.handlers.push((EventKind::Insets, Listener::noop()));
    Modal(node)
}

/// A bar shown over the keyboard of the inputs whose
/// [`Input::input_accessory`] is `native_id` (iOS's `inputAccessoryView`):
/// as wide as the window and as tall as its content, moving with the
/// keyboard natively. It takes no room where the render places it; on
/// Android, which has no input accessories, it is an empty hidden view.
pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
    let tag = if cfg!(target_os = "android") {
        Tag::View
    } else {
        Tag::InputAccessory
    };
    let mut node = ElNode::new(tag);
    if cfg!(target_os = "android") {
        node.style.keyword(crate::StyleKey::Display, "none");
    } else {
        set(&mut node, Prop::NativeId(Some(native_id.into())));
    }
    InputAccessoryView(node)
}

/// A canvas showing what `painter` recorded (draw again, e.g. from
/// `on_layout`'s size, to change it; native values in it move natively).
pub fn canvas(painter: impl Into<Painter>) -> CanvasView {
    let painter = painter.into();
    let mut node = ElNode::new(Tag::Canvas);
    node.attrs.drawing = Some(Arc::new(painter.drawing));
    node.attrs.bound = painter.nodes;
    CanvasView(node)
}

/// A web view loading `url`.
pub fn web_view(url: &str) -> WebView {
    WebView(ElNode::new(Tag::WebView))
        .set(Prop::Native(NativeProp::Source(WebSource::Uri(url.into()))))
}

/// A web view showing the page `html`, its relative links resolved against
/// `base_url` (TS: `source={{ html, baseUrl }}`).
pub fn web_view_html(html: &str, base_url: Option<&str>) -> WebView {
    WebView(ElNode::new(Tag::WebView)).html(html, base_url)
}

/// A video playing the file or stream at `url`.
pub fn video(url: &str) -> Video {
    Video(ElNode::new(Tag::Video)).set(Prop::Native(NativeProp::Source(WebSource::Uri(url.into()))))
}

/// The embedder's native component registered as `name`.
pub fn native(name: &str) -> NativeView {
    NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
}

impl Input {
    /// The text, when the component controls it (update it from
    /// [`Self::on_change_text`]).
    pub fn value(self, text: impl Into<String>) -> Self {
        self.set(Prop::Value(text.into()))
    }

    /// The first text, when the input keeps its own.
    pub fn default_value(self, text: impl Into<String>) -> Self {
        self.set(Prop::DefaultValue(text.into()))
    }

    /// Shown while it is empty.
    pub fn placeholder(self, text: impl Into<String>) -> Self {
        self.set(Prop::Placeholder(text.into()))
    }

    /// The placeholder's color (`cx.color(theme.muted_foreground)`).
    pub fn placeholder_color(self, color: Color) -> Self {
        self.set(Prop::PlaceholderColor(Some(color)))
    }

    /// The caret's and the selection's color.
    pub fn selection_color(self, color: Color) -> Self {
        self.set(Prop::SelectionColor(Some(color)))
    }

    /// Hides what is typed (passwords).
    pub fn secure(self, secure: bool) -> Self {
        self.set(Prop::Secure(secure))
    }

    /// The software keyboard's layout.
    pub fn keyboard_type(self, kind: KeyboardType) -> Self {
        self.set(Prop::KeyboardType(kind))
    }

    /// The software keyboard's light or dark look (iOS; TS:
    /// `ios={{ keyboardAppearance }}`).
    pub fn keyboard_appearance(self, appearance: KeyboardAppearance) -> Self {
        self.set(Prop::KeyboardAppearance(appearance))
    }

    /// The return key's label.
    pub fn return_key_type(self, kind: ReturnKeyType) -> Self {
        self.set(Prop::ReturnKeyType(kind))
    }

    /// Automatic capitals.
    pub fn auto_capitalize(self, mode: AutoCapitalize) -> Self {
        self.set(Prop::AutoCapitalize(mode))
    }

    /// Spelling correction (default on).
    pub fn auto_correct(self, on: bool) -> Self {
        self.set(Prop::AutoCorrect(on))
    }

    /// What it holds, for autofill and suggestions.
    pub fn auto_fill(self, kind: AutoFill) -> Self {
        self.set(Prop::AutoFill(kind))
    }

    /// Several lines, growing with the text (return adds a line).
    pub fn multiline(self, multiline: bool) -> Self {
        self.set(Prop::Multiline(multiline))
    }

    /// At most `length` characters.
    pub fn max_length(self, length: u32) -> Self {
        self.set(Prop::MaxLength(Some(length)))
    }

    /// Editable (default yes).
    pub fn editable(self, editable: bool) -> Self {
        self.set(Prop::Editable(editable))
    }

    /// The return key unfocuses it (default yes, for one line).
    pub fn blur_on_submit(self, blur: bool) -> Self {
        self.set(Prop::BlurOnSubmit(blur))
    }

    /// What return does (`submitBehavior`; default: submit and unfocus for
    /// one line, a line break for several).
    pub fn submit_behavior(self, behavior: SubmitBehavior) -> Self {
        self.set(Prop::SubmitBehavior(Some(behavior)))
    }

    /// Focused when it appears.
    pub fn auto_focus(self, focus: bool) -> Self {
        self.set(Prop::AutoFocus(focus))
    }

    /// No caret.
    pub fn caret_hidden(self, hidden: bool) -> Self {
        self.set(Prop::CaretHidden(hidden))
    }

    /// Shows the input accessory with this `nativeID` over the keyboard
    /// ([`input_accessory_view`]; iOS).
    pub fn input_accessory(self, native_id: &str) -> Self {
        self.set(Prop::InputAccessoryViewId(Some(native_id.into())))
    }

    /// Selects `start..end` (UTF-16 units; a caret when equal) when the
    /// value differs from the last render's (TS: the controlled
    /// `selection`); the user moves it on from there
    /// ([`Self::on_selection_change`]).
    pub fn selection(self, start: u32, end: u32) -> Self {
        self.set(Prop::Selection(start, end))
    }

    /// The text changed (the new text).
    pub fn on_change_text(self, listener: Listener<str>) -> Self {
        self.listen(EventKind::ChangeText, listener, events::text)
    }

    /// The return key was pressed (the text).
    pub fn on_submit_editing(self, listener: Listener<str>) -> Self {
        self.listen(EventKind::SubmitEditing, listener, events::text)
    }

    /// It became focused.
    pub fn on_focus(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::Focus, listener, events::unit)
    }

    /// It lost focus.
    pub fn on_blur(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::Blur, listener, events::unit)
    }

    /// The selection or caret moved.
    pub fn on_selection_change(self, listener: Listener<Selection>) -> Self {
        self.listen(EventKind::SelectionChange, listener, events::selection)
    }

    /// A key was pressed: the character, `Backspace` or `Enter`.
    pub fn on_key_press(self, listener: Listener<str>) -> Self {
        self.listen(EventKind::KeyPress, listener, events::key)
    }

    /// The text's size changed (multiline inputs growing).
    pub fn on_content_size_change(self, listener: Listener<Size>) -> Self {
        self.listen(EventKind::ContentSizeChange, listener, events::size)
    }
}

impl Scroll {
    /// Scrolls horizontally.
    pub fn horizontal(self) -> Self {
        self.set(Prop::Horizontal(true))
    }

    /// Whether the scroll indicator shows (default yes).
    pub fn shows_indicator(self, shows: bool) -> Self {
        self.set(Prop::ShowsIndicator(shows))
    }

    /// Pinch zoom between `min` and `max`.
    pub fn zoom_range(self, min: f32, max: f32) -> Self {
        self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
            .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
    }

    /// The zoom.
    pub fn zoom(self, scale: f32) -> Self {
        self.set(Prop::Scroll(ScrollProp::Zoom(scale)))
    }

    /// Pinches may go past the zoom limits and spring back (default yes;
    /// TS: `bouncesZoom`).
    pub fn bounces_zoom(self, bounces: bool) -> Self {
        self.set(Prop::Scroll(ScrollProp::BouncesZoom(bounces)))
    }

    /// The user can pinch to zoom (default yes; TS: `pinchGestureEnabled`).
    pub fn pinch_gesture_enabled(self, enabled: bool) -> Self {
        self.set(Prop::Scroll(ScrollProp::Pinch(enabled)))
    }

    /// Content smaller than the view sits in its center (zoomed images).
    pub fn center_content(self, center: bool) -> Self {
        self.set(Prop::Scroll(ScrollProp::CenterContent(center)))
    }
}

impl super::Scrollable for Scroll {}

impl Screen {
    fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
        let mut node = ElNode::new(Tag::HeaderItem);
        node.key = Some(key.into());
        set(&mut node, Prop::HeaderSlot(slot));
        node.children.push(item.into_element().0);
        self.0.children.push(node);
        self
    }

    fn screen(self, prop: ScreenProp) -> Self {
        self.set(Prop::Screen(prop))
    }

    /// The header's title.
    pub fn title(self, title: impl Into<Arc<str>>) -> Self {
        self.screen(ScreenProp::Title(Some(title.into())))
    }

    /// Whether the header shows (default true).
    pub fn header_shown(self, shown: bool) -> Self {
        self.screen(ScreenProp::HeaderShown(shown))
    }

    /// A large title (iOS); the content scrolls under the header.
    pub fn header_large_title(self, large: bool) -> Self {
        self.screen(ScreenProp::HeaderLargeTitle(large))
    }

    /// The content extends under the header.
    pub fn header_transparent(self, transparent: bool) -> Self {
        self.screen(ScreenProp::HeaderTransparent(transparent))
    }

    /// The back button's and bar buttons' color.
    pub fn header_tint_color(self, color: impl Into<Color>) -> Self {
        self.screen(ScreenProp::HeaderTintColor(Some(color.into())))
    }

    /// The header's background.
    pub fn header_background_color(self, color: impl Into<Color>) -> Self {
        self.screen(ScreenProp::HeaderBackgroundColor(Some(color.into())))
    }

    /// The title's color.
    pub fn header_title_color(self, color: impl Into<Color>) -> Self {
        self.screen(ScreenProp::HeaderTitleColor(Some(color.into())))
    }

    /// The label of the back button leading back to this screen (iOS).
    pub fn header_back_title(self, title: impl Into<Arc<str>>) -> Self {
        self.screen(ScreenProp::HeaderBackTitle(Some(title.into())))
    }

    /// Whether the back button shows (default true).
    pub fn header_back_visible(self, visible: bool) -> Self {
        self.screen(ScreenProp::HeaderBackVisible(visible))
    }

    /// The interactive back gesture (iOS swipe back, Android predictive
    /// back); the back buttons pop either way (default true).
    pub fn gesture_enabled(self, enabled: bool) -> Self {
        self.screen(ScreenProp::GestureEnabled(enabled))
    }

    /// The user cannot leave the screen: no swipe back, and the back
    /// buttons report [`Self::on_back_request`] instead of popping. Decided
    /// natively when the system asks, so set it before the user acts.
    pub fn prevent_back(self, prevent: bool) -> Self {
        self.screen(ScreenProp::PreventBack(prevent))
    }

    /// How the screen enters and leaves.
    pub fn animation(self, animation: ScreenAnimation) -> Self {
        self.screen(ScreenProp::Animation(animation))
    }

    /// An element at the header's start (instead of the back button).
    pub fn header_left(self, item: impl IntoElement) -> Self {
        self.header_item(HeaderSlot::Left, "header-left", item)
    }

    /// An element at the header's end.
    pub fn header_right(self, item: impl IntoElement) -> Self {
        self.header_item(HeaderSlot::Right, "header-right", item)
    }

    /// An element replacing the title.
    pub fn header_title(self, item: impl IntoElement) -> Self {
        self.header_item(HeaderSlot::Title, "header-title", item)
    }

    /// The user popped the screen natively (back button, swipe): leave it
    /// out of the next render.
    pub fn on_dismiss(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::Dismiss, listener, events::unit)
    }

    /// The user tried to leave a screen that [`Self::prevent_back`]s.
    pub fn on_back_request(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::BackRequest, listener, events::unit)
    }
}

impl Modal {
    /// How it comes in (default: slides up).
    pub fn animation(self, animation: ModalAnimation) -> Self {
        self.set(Prop::Modal(ModalProp::Animation(animation)))
    }

    /// Full screen, or a sheet (iOS).
    pub fn presentation(self, presentation: ModalPresentation) -> Self {
        self.set(Prop::Modal(ModalProp::Presentation(presentation)))
    }

    /// What is behind shows through (its content draws the dimming).
    pub fn transparent(self, transparent: bool) -> Self {
        self.set(Prop::Modal(ModalProp::Transparent(transparent)))
    }

    /// Under the status bar (Android).
    pub fn status_bar_translucent(self, translucent: bool) -> Self {
        self.set(Prop::Modal(ModalProp::StatusBarTranslucent(translucent)))
    }

    /// The orientations it allows while it is presented (iOS; default:
    /// those of what presents it).
    pub fn supported_orientations(
        self,
        orientations: impl IntoIterator<Item = Orientation>,
    ) -> Self {
        let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
        self.set(Prop::Modal(ModalProp::Orientations(bits)))
    }

    /// Swipes down and the back button dismiss it, reporting
    /// [`Self::on_dismiss`] (default: they ask with
    /// [`Self::on_request_close`]).
    pub fn dismissible(self, dismissible: bool) -> Self {
        self.set(Prop::Modal(ModalProp::Dismissible(dismissible)))
    }

    /// The user asked to close it (back button, swipe down): leave it out
    /// of the next render to close it.
    pub fn on_request_close(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::RequestClose, listener, events::unit)
    }

    /// It finished appearing.
    pub fn on_show(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::Show, listener, events::unit)
    }

    /// The user or the system dismissed it.
    pub fn on_dismiss(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::Dismiss, listener, events::unit)
    }
}

/// An orientation of the screen ([`Modal::supported_orientations`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
    /// Upright.
    Portrait,
    /// Upside down.
    PortraitUpsideDown,
    /// Either landscape.
    Landscape,
    /// Landscape, the top on the left.
    LandscapeLeft,
    /// Landscape, the top on the right.
    LandscapeRight,
}

impl Orientation {
    fn bits(self) -> u8 {
        use crate::ModalConfig as M;
        match self {
            Orientation::Portrait => M::PORTRAIT,
            Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
            Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
            Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
            Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
        }
    }
}

impl WebView {
    /// Loads `html` (relative links against `base_url`) instead of a URL.
    pub fn html(self, html: &str, base_url: Option<&str>) -> Self {
        self.set(Prop::Native(NativeProp::Source(WebSource::Html {
            html: html.into(),
            base_url: base_url.map(Into::into),
        })))
    }

    /// Runs after each page loads.
    pub fn injected_java_script(self, script: &str) -> Self {
        self.set(Prop::Native(NativeProp::InjectedJavaScript(Some(
            script.into(),
        ))))
    }

    /// Runs before each page's own scripts.
    pub fn injected_java_script_before_content(self, script: &str) -> Self {
        self.set(Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(
            script.into(),
        ))))
    }

    /// The user agent it sends.
    pub fn user_agent(self, agent: &str) -> Self {
        self.set(Prop::Native(NativeProp::UserAgent(Some(agent.into()))))
    }

    /// Scrolls (default yes).
    pub fn scroll_enabled(self, enabled: bool) -> Self {
        self.set(Prop::Native(NativeProp::ScrollEnabled(enabled)))
    }

    /// Runs the pages' JavaScript (default yes).
    pub fn java_script_enabled(self, enabled: bool) -> Self {
        self.set(Prop::Native(NativeProp::JavaScriptEnabled(enabled)))
    }

    /// Swipes go back and forward (iOS).
    pub fn back_forward_gestures(self, enabled: bool) -> Self {
        self.set(Prop::Native(NativeProp::BackForwardGestures(enabled)))
    }

    /// A page started loading.
    pub fn on_load_start(self, listener: Listener<WebNavigation>) -> Self {
        self.listen(EventKind::LoadStart, listener, events::navigation)
    }

    /// A page loaded.
    pub fn on_load(self, listener: Listener<WebNavigation>) -> Self {
        self.listen(EventKind::Load, listener, events::navigation)
    }

    /// A page failed to load (the message).
    pub fn on_error(self, listener: Listener<str>) -> Self {
        self.listen(EventKind::Error, listener, events::message)
    }

    /// The page called `window.ReactNativeWebView.postMessage(data)`.
    pub fn on_message(self, listener: Listener<str>) -> Self {
        self.listen(EventKind::Message, listener, events::data)
    }

    /// It navigated.
    pub fn on_navigation_state_change(self, listener: Listener<WebNavigation>) -> Self {
        self.listen(
            EventKind::NavigationStateChange,
            listener,
            events::navigation,
        )
    }
}

impl Video {
    /// Paused.
    pub fn paused(self, paused: bool) -> Self {
        self.set(Prop::Native(NativeProp::Paused(paused)))
    }

    /// Without sound.
    pub fn muted(self, muted: bool) -> Self {
        self.set(Prop::Native(NativeProp::Muted(muted)))
    }

    /// 0..1.
    pub fn volume(self, volume: f32) -> Self {
        self.set(Prop::Native(NativeProp::Volume(volume)))
    }

    /// Playback speed.
    pub fn rate(self, rate: f32) -> Self {
        self.set(Prop::Native(NativeProp::Rate(rate)))
    }

    /// Starts over at the end.
    pub fn repeat(self, repeat: bool) -> Self {
        self.set(Prop::Native(NativeProp::Repeat(repeat)))
    }

    /// How the picture fits (default: contain).
    pub fn resize_mode(self, mode: ResizeMode) -> Self {
        self.set(Prop::Native(NativeProp::VideoResizeMode(mode)))
    }

    /// The platform's playback controls.
    pub fn controls(self, controls: bool) -> Self {
        self.set(Prop::Native(NativeProp::Controls(controls)))
    }

    /// Milliseconds between [`Self::on_progress`] events (default 250).
    pub fn progress_interval(self, ms: f32) -> Self {
        self.set(Prop::Native(NativeProp::ProgressInterval(ms)))
    }

    /// It started loading.
    pub fn on_load_start(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::LoadStart, listener, events::unit)
    }

    /// It loaded: length and size.
    pub fn on_load(self, listener: Listener<VideoInfo>) -> Self {
        self.listen(EventKind::Load, listener, events::video)
    }

    /// It played on.
    pub fn on_progress(self, listener: Listener<VideoProgress>) -> Self {
        self.listen(EventKind::Progress, listener, events::progress)
    }

    /// It played to its end.
    pub fn on_end(self, listener: Listener<()>) -> Self {
        self.listen(EventKind::End, listener, events::unit)
    }

    /// It started (`true`) or stopped buffering.
    pub fn on_buffer(self, listener: Listener<bool>) -> Self {
        self.listen(EventKind::Buffer, listener, events::buffering)
    }

    /// It failed (the message).
    pub fn on_error(self, listener: Listener<str>) -> Self {
        self.listen(EventKind::Error, listener, events::message)
    }
}

impl NativeView {
    /// Its prop `name` (any JSON value), as JS's `nativeComponent` passes it.
    pub fn prop(self, name: &str, value: JsonValue) -> Self {
        self.set(Prop::ComponentProp(name.into(), Some(value)))
    }

    /// It emitted an event.
    pub fn on_native_event(self, listener: Listener<NativeEvent>) -> Self {
        self.listen(EventKind::NativeEvent, listener, events::native)
    }
}

/// A number in a drawing: a constant, or a native value the canvas reads
/// while it draws (it draws again natively as the value moves).
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasArg(pub(crate) CanvasArgKind);

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum CanvasArgKind {
    Const(f32),
    Node(super::NativeNode),
}

impl From<f32> for CanvasArg {
    fn from(n: f32) -> Self {
        Self(CanvasArgKind::Const(n))
    }
}

impl<A: super::Animated> From<&A> for CanvasArg {
    fn from(a: &A) -> Self {
        Self(CanvasArgKind::Node(a.native_node()))
    }
}

/// What a drawing fills or strokes with (`fillStyle` / `strokeStyle`): a
/// color, a gradient ([`CanvasGradient::linear`], `radial`, `conic`), or a
/// native value interpolating colors
/// ([`super::NativeNode::interpolate_colors`]), read as it moves.
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasPaint(CanvasPaintKind);

#[derive(Debug, Clone, PartialEq)]
enum CanvasPaintKind {
    Color(Color),
    Gradient(Arc<CanvasGradient>),
    Node(super::NativeNode),
}

impl From<Color> for CanvasPaint {
    fn from(color: Color) -> Self {
        Self(CanvasPaintKind::Color(color))
    }
}

impl From<CanvasGradient> for CanvasPaint {
    fn from(gradient: CanvasGradient) -> Self {
        Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
    }
}

impl From<Arc<CanvasGradient>> for CanvasPaint {
    fn from(gradient: Arc<CanvasGradient>) -> Self {
        Self(CanvasPaintKind::Gradient(gradient))
    }
}

impl<A: super::Animated> From<&A> for CanvasPaint {
    fn from(a: &A) -> Self {
        Self(CanvasPaintKind::Node(a.native_node()))
    }
}

/// Records a [`Drawing`] with the HTML Canvas 2D operations (Rust names):
/// `Painter::new().fill_color(red).fill_rect(0.0, 0.0, w, h).finish()`.
/// Coordinates are points from the canvas's top left. Numbers and paints
/// may be native values (the canvas draws again natively as they move);
/// operations without a method here are built by hand with
/// [`Painter::num`], [`Painter::paint`] and [`Painter::op`]. Text is
/// measured with [`super::RenderCx::measure_text`].
#[derive(Debug, Clone, Default)]
pub struct Painter {
    drawing: Drawing,
    /// The native values the drawing reads, kept alive with it.
    nodes: Vec<super::NativeNode>,
}

impl Painter {
    /// An empty drawing.
    pub fn new() -> Self {
        Self::default()
    }

    /// The drawing.
    pub fn finish(self) -> Drawing {
        self.drawing
    }

    /// `value` as a number of this drawing, for an operation built by hand
    /// ([`Self::op`]): a native value becomes a slot the canvas reads while
    /// it draws, kept alive with the drawing.
    pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
        match value.into().0 {
            CanvasArgKind::Const(n) => Num::Const(n),
            CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
        }
    }

    /// `paint` as a paint of this drawing, for an operation built by hand
    /// ([`Self::op`]).
    pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
        match paint.into().0 {
            CanvasPaintKind::Color(color) => Paint::Color(color),
            CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
            CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
        }
    }

    fn slot(&mut self, node: super::NativeNode) -> u16 {
        let slot = self.drawing.slot(node.id());
        self.nodes.push(node);
        slot
    }

    /// Records `op` (one built by hand: its numbers and paints from
    /// [`Self::num`] and [`Self::paint`]).
    pub fn op(mut self, op: CanvasOp) -> Self {
        self.drawing.ops.push(op);
        self
    }

    fn path(self, op: PathOp) -> Self {
        self.op(CanvasOp::Path(op))
    }

    /// Whether point (`x`, `y`) (canvas points, as a touch's `location_x` /
    /// `location_y`) is inside the current path by `rule`, with the
    /// transform, as recorded so far (TS: `ctx.isPointInPath(x, y, rule)`).
    /// Answered from the geometry here, with no platform round trip; a
    /// number given as a native value counts as 0, as in TS. To find what
    /// is under a tap, build the render's painter in a method the press
    /// handler calls too.
    pub fn is_point_in_path(&self, x: f32, y: f32, rule: FillRule) -> bool {
        crate::canvas::point_in_path(&self.drawing.ops, None, rule, x, y, |_| 0.0)
    }

    /// Whether point (`x`, `y`) is on the stroke of the current path with
    /// the line width and cap recorded so far (TS: `ctx.isPointInStroke(x,
    /// y)`; round joins, no dashes). See [`Self::is_point_in_path`].
    pub fn is_point_in_stroke(&self, x: f32, y: f32) -> bool {
        crate::canvas::point_in_stroke(&self.drawing.ops, None, x, y, |_| 0.0)
    }

    /// Whether point (`x`, `y`) is inside `path` by `rule`, with the
    /// transform recorded so far (TS: `ctx.isPointInPath(path2d, x, y,
    /// rule)`): the shape [`Self::fill_path`] drew under a tap. See
    /// [`Self::is_point_in_path`].
    pub fn path_contains(&self, path: &Path, x: f32, y: f32, rule: FillRule) -> bool {
        crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, x, y, |_| 0.0)
    }

    /// Whether point (`x`, `y`) is on the stroke of `path` with the
    /// transform, line width and cap recorded so far (TS:
    /// `ctx.isPointInStroke(path2d, x, y)`). See [`Self::is_point_in_path`].
    pub fn stroke_contains(&self, path: &Path, x: f32, y: f32) -> bool {
        crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), x, y, |_| 0.0)
    }

    /// Saves the state (styles, transform, clip).
    pub fn save(self) -> Self {
        self.op(CanvasOp::Save)
    }

    /// Restores the state saved last.
    pub fn restore(self) -> Self {
        self.op(CanvasOp::Restore)
    }

    /// Moves the origin.
    pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.op(CanvasOp::Translate(x, y))
    }

    /// Scales the axes.
    pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.op(CanvasOp::Scale(x, y))
    }

    /// Rotates the axes (radians, clockwise).
    pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
        let a = self.num(angle);
        self.op(CanvasOp::Rotate(a))
    }

    /// Multiplies the transform by the matrix `[a c e; b d f]`
    /// (`transform`).
    pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
        let m = m.map(|n| self.num(n));
        self.op(CanvasOp::Transform(m))
    }

    /// Replaces the transform with the matrix `[a c e; b d f]`
    /// (`setTransform`).
    pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
        let m = m.map(|n| self.num(n));
        self.op(CanvasOp::SetTransform(m))
    }

    /// Back to no transform (`resetTransform`).
    pub fn reset_transform(self) -> Self {
        self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
    }

    /// Starts a new path.
    pub fn begin_path(self) -> Self {
        self.op(CanvasOp::BeginPath)
    }

    /// Starts a subpath at (`x`, `y`).
    pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.path(PathOp::MoveTo(x, y))
    }

    /// A straight line to (`x`, `y`).
    pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.path(PathOp::LineTo(x, y))
    }

    /// A quadratic Bézier curve to `to` (`quadraticCurveTo`).
    pub fn quadratic_curve_to(self, control: (f32, f32), to: (f32, f32)) -> Self {
        let c = Num::Const;
        self.path(PathOp::QuadTo([
            c(control.0),
            c(control.1),
            c(to.0),
            c(to.1),
        ]))
    }

    /// A cubic Bézier curve to (`x`, `y`).
    pub fn bezier_curve_to(self, c1: (f32, f32), c2: (f32, f32), to: (f32, f32)) -> Self {
        let c = Num::Const;
        self.path(PathOp::CubicTo([
            c(c1.0),
            c(c1.1),
            c(c2.0),
            c(c2.1),
            c(to.0),
            c(to.1),
        ]))
    }

    /// A circular arc around (`x`, `y`); angles in radians, clockwise from
    /// the x axis.
    pub fn arc(
        self,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        radius: impl Into<CanvasArg>,
        start: impl Into<CanvasArg>,
        end: impl Into<CanvasArg>,
    ) -> Self {
        self.arc_in(x, y, radius, start, end, false)
    }

    /// [`Self::arc`] drawn counterclockwise.
    pub fn arc_counterclockwise(
        self,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        radius: impl Into<CanvasArg>,
        start: impl Into<CanvasArg>,
        end: impl Into<CanvasArg>,
    ) -> Self {
        self.arc_in(x, y, radius, start, end, true)
    }

    fn arc_in(
        mut self,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        radius: impl Into<CanvasArg>,
        start: impl Into<CanvasArg>,
        end: impl Into<CanvasArg>,
        ccw: bool,
    ) -> Self {
        let (x, y, radius, start, end) = (
            self.num(x),
            self.num(y),
            self.num(radius),
            self.num(start),
            self.num(end),
        );
        self.path(PathOp::Arc {
            x,
            y,
            radius,
            start,
            end,
            ccw,
        })
    }

    /// An arc of `radius` tangent to the lines to (`x1`, `y1`) and on to
    /// (`x2`, `y2`) (`arcTo`): a rounded corner.
    pub fn arc_to(self, x1: f32, y1: f32, x2: f32, y2: f32, radius: f32) -> Self {
        let c = Num::Const;
        self.path(PathOp::ArcTo([c(x1), c(y1), c(x2), c(y2), c(radius)]))
    }

    /// An elliptical arc around (`x`, `y`) with radii `radius` turned by
    /// `rotation`; angles in radians, clockwise (`counterclockwise` draws
    /// the other way).
    #[allow(clippy::too_many_arguments)]
    pub fn ellipse(
        self,
        x: f32,
        y: f32,
        radius: (f32, f32),
        rotation: f32,
        start: f32,
        end: f32,
        counterclockwise: bool,
    ) -> Self {
        let c = Num::Const;
        self.path(PathOp::Ellipse {
            geometry: [c(x), c(y), c(radius.0), c(radius.1), c(rotation)],
            start: c(start),
            end: c(end),
            ccw: counterclockwise,
        })
    }

    /// A rectangle subpath.
    pub fn rect(self, x: f32, y: f32, w: f32, h: f32) -> Self {
        let c = Num::Const;
        self.path(PathOp::Rect([c(x), c(y), c(w), c(h)]))
    }

    /// A rectangle subpath with round corners (one radius for all).
    pub fn round_rect(self, x: f32, y: f32, w: f32, h: f32, radius: f32) -> Self {
        self.round_rect_corners(x, y, w, h, [radius; 4])
    }

    /// A rectangle subpath with round corners: top left, top right, bottom
    /// right, bottom left.
    pub fn round_rect_corners(self, x: f32, y: f32, w: f32, h: f32, radii: [f32; 4]) -> Self {
        let c = Num::Const;
        self.path(PathOp::RoundRect([c(x), c(y), c(w), c(h)], radii.map(c)))
    }

    /// A straight line back to the subpath's start.
    pub fn close_path(self) -> Self {
        self.path(PathOp::Close)
    }

    /// Fills the current path.
    pub fn fill(self) -> Self {
        self.fill_with(FillRule::NonZero)
    }

    /// Fills the current path by `rule`.
    pub fn fill_with(self, rule: FillRule) -> Self {
        self.op(CanvasOp::Fill(None, rule))
    }

    /// Fills `path` (TS: `fill(path2d)`; parse SVG data once with
    /// [`crate::canvas::svg_path`]).
    pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
        self.op(CanvasOp::Fill(Some(path.clone()), rule))
    }

    /// Fills SVG path data (parsed now: [`Self::fill_path`] reuses a
    /// parsed path).
    pub fn fill_svg(self, data: &str) -> Self {
        self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
    }

    /// Strokes the current path.
    pub fn stroke(self) -> Self {
        self.op(CanvasOp::Stroke(None))
    }

    /// Strokes `path` (TS: `stroke(path2d)`).
    pub fn stroke_path(self, path: &Path) -> Self {
        self.op(CanvasOp::Stroke(Some(path.clone())))
    }

    /// Strokes SVG path data (parsed now).
    pub fn stroke_svg(self, data: &str) -> Self {
        self.stroke_path(&crate::canvas::svg_path(data))
    }

    /// Clips to the current path.
    pub fn clip(self) -> Self {
        self.clip_with(FillRule::NonZero)
    }

    /// Clips to the current path by `rule`.
    pub fn clip_with(self, rule: FillRule) -> Self {
        self.op(CanvasOp::Clip(None, rule))
    }

    /// Clips to `path` (TS: `clip(path2d)`).
    pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
        self.op(CanvasOp::Clip(Some(path.clone()), rule))
    }

    /// Fills a rectangle.
    pub fn fill_rect(
        mut self,
        x: f32,
        y: f32,
        w: impl Into<CanvasArg>,
        h: impl Into<CanvasArg>,
    ) -> Self {
        let (w, h) = (self.num(w), self.num(h));
        self.op(CanvasOp::FillRect([Num::Const(x), Num::Const(y), w, h]))
    }

    /// Strokes a rectangle.
    pub fn stroke_rect(self, x: f32, y: f32, w: f32, h: f32) -> Self {
        let c = Num::Const;
        self.op(CanvasOp::StrokeRect([c(x), c(y), c(w), c(h)]))
    }

    /// Makes a rectangle transparent.
    pub fn clear_rect(self, x: f32, y: f32, w: f32, h: f32) -> Self {
        let c = Num::Const;
        self.op(CanvasOp::ClearRect([c(x), c(y), c(w), c(h)]))
    }

    /// Fills with `color`.
    pub fn fill_color(self, color: Color) -> Self {
        self.fill_style(color)
    }

    /// Strokes with `color`.
    pub fn stroke_color(self, color: Color) -> Self {
        self.stroke_style(color)
    }

    /// Fills with `paint`: a color, a gradient or a native value of colors
    /// (`fillStyle`).
    pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
        let paint = self.paint(paint);
        self.op(CanvasOp::FillStyle(paint))
    }

    /// Strokes with `paint` (`strokeStyle`).
    pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
        let paint = self.paint(paint);
        self.op(CanvasOp::StrokeStyle(paint))
    }

    /// The stroke width.
    pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
        let w = self.num(width);
        self.op(CanvasOp::LineWidth(w))
    }

    /// How strokes end.
    pub fn line_cap(self, cap: LineCap) -> Self {
        self.op(CanvasOp::LineCap(cap))
    }

    /// How stroke segments join.
    pub fn line_join(self, join: LineJoin) -> Self {
        self.op(CanvasOp::LineJoin(join))
    }

    /// How far mitered joins reach, in line widths (`miterLimit`; at least
    /// 1).
    pub fn miter_limit(self, limit: f32) -> Self {
        self.op(CanvasOp::MiterLimit(limit.max(1.0)))
    }

    /// Dashes: lengths of dashes and gaps.
    pub fn line_dash(self, segments: &[f32]) -> Self {
        self.op(CanvasOp::LineDash(segments.into()))
    }

    /// Where the dashes start along the line (`lineDashOffset`; a native
    /// value marches them).
    pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
        let o = self.num(offset);
        self.op(CanvasOp::LineDashOffset(o))
    }

    /// The opacity of what is drawn next.
    pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
        let a = self.num(alpha);
        self.op(CanvasOp::GlobalAlpha(a))
    }

    /// How what is drawn next combines with the canvas.
    pub fn composite(self, composite: Composite) -> Self {
        self.op(CanvasOp::Composite(composite))
    }

    /// Shadows of what is drawn next.
    pub fn shadow(self, color: Color, blur: f32, offset: (f32, f32)) -> Self {
        self.op(CanvasOp::ShadowColor(color))
            .op(CanvasOp::ShadowBlur(blur.max(0.0)))
            .op(CanvasOp::ShadowOffset(offset.0, offset.1))
    }

    /// The font (CSS `font` shorthand: `"600 14px Inter"`); an invalid one
    /// keeps the previous font, as in HTML.
    pub fn font(self, font: &str) -> Self {
        match CanvasFont::parse(font) {
            Some(font) => self.op(CanvasOp::Font(font)),
            None => self,
        }
    }

    /// The number forms of text (TS: `fontVariantNumeric`): with
    /// [`crate::style::FontVariant::TABULAR_NUMS`] figures have equal widths, so changing
    /// values do not jitter; `FontVariant::default()` keeps the font's.
    pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
        self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
            numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
        )))
    }

    /// Where text sits relative to its x.
    pub fn text_align(self, align: CanvasTextAlign) -> Self {
        self.op(CanvasOp::TextAlign(align))
    }

    /// Where text sits relative to its y.
    pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
        self.op(CanvasOp::TextBaseline(baseline))
    }

    /// Fills `text` at (`x`, `y`).
    pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        self.text(text, x, y, None, false)
    }

    /// Fills `text` at (`x`, `y`), narrowed to fit `max_width`.
    pub fn fill_text_max_width(
        self,
        text: &str,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        max_width: f32,
    ) -> Self {
        self.text(text, x, y, Some(max_width), false)
    }

    /// Strokes the outline of `text` at (`x`, `y`).
    pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        self.text(text, x, y, None, true)
    }

    /// Strokes the outline of `text` at (`x`, `y`), narrowed to fit
    /// `max_width`.
    pub fn stroke_text_max_width(
        self,
        text: &str,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        max_width: f32,
    ) -> Self {
        self.text(text, x, y, Some(max_width), true)
    }

    fn text(
        mut self,
        text: &str,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        max_width: Option<f32>,
        stroke: bool,
    ) -> Self {
        let (text, x, y) = (text.into(), self.num(x), self.num(y));
        self.op(if stroke {
            CanvasOp::StrokeText {
                text,
                x,
                y,
                max_width,
            }
        } else {
            CanvasOp::FillText {
                text,
                x,
                y,
                max_width,
            }
        })
    }

    /// Draws the image at `uri` (a URL or `asset:/path`) into the rectangle.
    pub fn draw_image(self, uri: &str, x: f32, y: f32, w: f32, h: f32) -> Self {
        self.draw_image_part(uri, None, [x, y, w, h])
    }

    /// Draws the part `source` of the image at `uri` (`[x, y, w, h]` in
    /// image pixels; `None`: all of it) into `dest` (`[x, y, w, h]`).
    pub fn draw_image_part(self, uri: &str, source: Option<[f32; 4]>, dest: [f32; 4]) -> Self {
        self.op(CanvasOp::DrawImage {
            image: CanvasImage { uri: uri.into() },
            source,
            dest: dest.map(Num::Const),
        })
    }
}

impl From<Drawing> for Painter {
    fn from(drawing: Drawing) -> Self {
        Self {
            drawing,
            nodes: Vec::new(),
        }
    }
}