declarative 0.7.3

Generic DSL macros for easy view code manipulation
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
<!--
	SPDX-FileCopyrightText: 2025 Eduardo Javier Alvarado Aarón <eduardo.javier.alvarado.aaron@gmail.com>
	
	SPDX-License-Identifier: CC-BY-SA-4.0
-->

# <img src="logo.svg" width="96" align="left"/> `declarative`

[![REUSE status]][reuse] [![On crates.io]][crate.io]

[REUSE status]: https://api.reuse.software/badge/github.com/ejaa3/declarative
[reuse]: https://api.reuse.software/info/github.com/ejaa3/declarative
[On crates.io]: https://img.shields.io/crates/v/declarative.svg?color=6081D4
[crate.io]: https://crates.io/crates/declarative

A proc-macro library that implements a generic [DSL] to create complex reactive view code easier to edit and maintain.

[DSL]: https://en.wikipedia.org/wiki/Domain-specific_language

To use it, add to your Cargo.toml:

~~~ toml
[dependencies.declarative]
version = '0.7.3'
~~~

To learn how to use macros, the quick way is to see the [usage](#usage), or clone the repository to read the source code of the examples in alphabetical order and run them like this:

~~~ bash
cargo run --example EXAMPLE_NAME
~~~

The examples depend on [gtk-rs], so you should familiarize yourself with [gtk-rs] a bit before ([gtk-rs book]). Using Rust Analyzer's [macro expansion tool] would help to better understand by seeing the code generated by the macros.

[gtk-rs]: https://gtk-rs.org
[gtk-rs book]: https://gtk-rs.org/gtk4-rs/stable/latest/book
[macro expansion tool]: https://rust-analyzer.github.io/book/features.html?highlight=macro#expand-macro-recursively

In addition to macro features, the examples also show some usage patterns (templates, components, Elm, etc.). GTK has a pattern of its own due to its object orientation and `declarative` integrates well, but there is no example about it (it would be verbose and exclusive to GTK, while `declarative` is not GTK based).

<details><summary><h3>Counter application example</h3></summary>

The following is an implementation of the Elm architecture with [gtk-rs]:

![Light theme app screenshot](light.png)
![Dark theme app screenshot](dark.png)

~~~ rust
use declarative::{block as view, clone, construct};
use gtk::{glib, prelude::*};

enum Msg { Increase, Decrease }

// syntactic sugar for sending messages:
macro_rules! send { [$msg:expr => $tx:expr] => [$tx.send_blocking($msg).unwrap()] }

fn start(app: &gtk::Application) {
    let (tx, rx) = async_channel::bounded(1);
    let mut count = 0; // the state

    view![ gtk::ApplicationWindow window {
        application: app
        title: "My Application"
        titlebar: &gtk::HeaderBar::new()

        child: &_ @ gtk::Box {
            orientation: gtk::Orientation::Vertical
            spacing: 6
            margin_top: 6
            margin_bottom: 6
            margin_start: 6
            margin_end: 6
            ~
            append: &_ @ gtk::Label {
                label: "Count unchanged"
                'bind set_label: &format!("The count is: {count}")
            }
            append: &_ @ gtk::Button {
                label: "Increase" ~
                connect_clicked: clone![tx; move |_| send!(Msg::Increase => tx)]
            }
            append: &_ @ gtk::Button::with_label("Decrease") {
                connect_clicked: move |_| send!(Msg::Decrease => tx)
            }
            'consume refresh = move |count| bindings!()
        }
    } ];

    let update = |count: &mut u8, msg| match msg {
        Msg::Increase => *count = count.wrapping_add(1),
        Msg::Decrease => *count = count.wrapping_sub(1),
    };

    glib::spawn_future_local(async move {
        while let Ok(msg) = rx.recv().await {
            update(&mut count, msg); // the state is updated
            refresh(count); // now the view is refreshed
        }
    });

    window.present()
}

fn main() -> glib::ExitCode {
    let app = gtk::Application::default();
    app.connect_activate(start);
    app.run()
}
~~~

To execute, run:

~~~ bash
cargo run --example y_readme
~~~

</details>

## Usage

This is a non-exhaustive summary of how `declarative` expands in the most common use cases. The code snippets on the left expand into the code blocks on the right, and assume the following at the beginning of the file:

~~~ rust
#![allow(unused)]
use declarative::{block, construct, view};
use gtk::{prelude::*, Orientation::*, glib::object::IsA};
~~~

<details><summary>Root items and property assignments</summary><br/><table><tr><td>

~~~ rust
block! {
	gtk::Frame { } // just a type
	gtk::Button { label: "Click" }
	gtk::Label { label: "Text"; lines: 2 }
	
	gtk::Window::new() { // a function call
		#[cfg(debug_assertions)]
		add_css_class: "devel"
	}
}
~~~

</td><td>

Items defined with the builder pattern are expanded in reverse order:

~~~ rust
let gtk_window_new_3 = gtk::Window::new();
let gtk_label_2 = <gtk::Label>::builder().label("Text").lines(2).build();
let gtk_button_1 = <gtk::Button>::builder().label("Click").build();
let gtk_frame_0 = <gtk::Frame>::builder().build();
#[cfg(debug_assertions)]
gtk_window_new_3.add_css_class("devel");
~~~

</td></tr></table><br/></details>

<details><summary>Child items</summary><br/>

The underscore (_) in an argument is a placeholder for the variable name of the item followed by the at sign (@).

<table><tr><td>

~~~ rust
block!(gtk::Frame {
	child: &_ @ gtk::ScrolledWindow {
		child: &_ @ gtk::Button { label: "Click" }
	}
	label_widget: &_ @ gtk::Label { }
});
~~~

Reverse order allows child items in the builder pattern.

</td><td>

~~~ rust
let gtk_label_3 = <gtk::Label>::builder().build();
let gtk_button_2 = <gtk::Button>::builder().label("Click").build();
let gtk_scrolledwindow_1 = <gtk::ScrolledWindow>::builder()
    .child(&gtk_button_2)
    .build();
let gtk_frame_0 = <gtk::Frame>::builder()
    .child(&gtk_scrolledwindow_1)
    .label_widget(&gtk_label_3)
    .build();
~~~

</td></tr></table><br/></details>

<details><summary>Do not use the builder pattern</summary><br/>

<table><tr><td>

~~~ rust
block! {
	gtk::Box {
		set_orientation: Vertical
		set_spacing: 6
		set_margin_start: 6
	}! // just add `!` after `}`
	
	// or call a function:
	gtk::Box::new(Horizontal, 6) {
		set_margin_start: 6
	}
}
~~~

</td><td>

In this case the items are expanded in the same order:

~~~ rust
let gtk_box_0 = <gtk::Box>::default();
let gtk_box_new_1 = gtk::Box::new(Horizontal, 6);
gtk_box_0.set_orientation(Vertical);
gtk_box_0.set_spacing(6);
gtk_box_0.set_margin_start(6);
gtk_box_new_1.set_margin_start(6);
~~~

</td></tr></table><br/></details>

<details><summary>Multiple arguments</summary><br/>

<table><tr><td>

As always, the comma (,) separates arguments:

~~~ rust
block!(gtk::Grid::new() {
	attach: &_, 0, 0, 1, 1 @ gtk::Label { }
	attach: &_, 1, 0, 1, 1 @ gtk::Label { }
});
~~~

</td><td>

~~~ rust
let gtk_grid_new_0 = gtk::Grid::new();
let gtk_label_2 = <gtk::Label>::builder().build();
let gtk_label_1 = <gtk::Label>::builder().build();
gtk_grid_new_0.attach(&gtk_label_1, 0, 0, 1, 1);
gtk_grid_new_0.attach(&gtk_label_2, 1, 0, 1, 1);
~~~

</td></tr></table><br/></details>

<details><summary>Multiple child items in the same property assignment</summary><br/>

Basically one at sign for each underscore. The first underscore is for the first @ item, and the last underscore is for the last @ item.

<table><tr><td>

~~~ rust
block!(gtk::Notebook::new() {
	append_page: &_, Some(&_)
		@ gtk::Button { label: "Click 1" }
		@ gtk::Label { label: "Tab 1" }
	
	append_page_menu: &_, Some(&_), Some(&_)
		@ gtk::Button { label: "Click 2" }
		@ gtk::Label { label: "Tab 2" }
		@ gtk::Label { label: "Menu 2" }
});
~~~

</td><td>

~~~ rust
let gtk_notebook_new_0 = gtk::Notebook::new();
let gtk_label_5 = <gtk::Label>::builder().label("Menu 2").build();
let gtk_label_4 = <gtk::Label>::builder().label("Tab 2").build();
let gtk_button_3 = <gtk::Button>::builder().label("Click 2").build();
let gtk_label_2 = <gtk::Label>::builder().label("Tab 1").build();
let gtk_button_1 = <gtk::Button>::builder().label("Click 1").build();
gtk_notebook_new_0.append_page(&gtk_button_1, Some(&gtk_label_2));
gtk_notebook_new_0.append_page_menu(&gtk_button_3, Some(&gtk_label_4), Some(&gtk_label_5));
~~~

</td></tr></table><br/></details>

<details><summary>Share property assignments</summary><br/>

The last underscore (_) without a corresponding at sign (@) indicates the variable name of the current item as an argument to a function (not a method).

<table><tr><td>

~~~ rust
fn main() {
	block! {
		gtk::Button { label: "Click"; set_all_margins: 6, &_ }
		gtk::Label { label: "Text"; set_all_margins: 12, &_ }
	}
}

fn set_all_margins(px: i32, widget: &impl IsA<gtk::Widget>) {
	block!(ref widget { // `ref` to refer to an existing variable
		set_margin_bottom: px
		set_margin_end: px
		set_margin_start: px
		set_margin_top: px
	}); // `ref widget { }` is an item
}
~~~

</td><td>

~~~ rust
fn main() {
	let gtk_label_1 = <gtk::Label>::builder().label("Text").build();
	let gtk_button_0 = <gtk::Button>::builder().label("Click").build();
	set_all_margins(6, &gtk_button_0);
	set_all_margins(12, &gtk_label_1);
}

fn set_all_margins(px: i32, widget: &impl IsA<gtk::Widget>) {
	let _ = widget;
	widget.set_margin_bottom(px);
	widget.set_margin_end(px);
	widget.set_margin_start(px);
	widget.set_margin_top(px);
}
~~~

</td></tr></table><br/></details>

<details><summary>Items with custom variable name</summary><br/>

<table><tr><td>

~~~ rust
block!(gtk::Box::new(Vertical, 6) vert_box {
	append: &_ @ gtk::Button my_button { }
});
~~~

</td><td>

~~~ rust
let vert_box = gtk::Box::new(Vertical, 6);
let my_button = <gtk::Button>::builder().build();
vert_box.append(&my_button);
~~~

</td></tr></table><br/></details>

<details><summary>Break the builder pattern</summary><br/>

<table><tr><td>

~~~ rust
block! {
	gtk::Box {
		orientation: Vertical
		~ // adds `build()` automatically
		set_spacing: 6
	}
	gtk::Box {
		orientation: Horizontal
		build; // semicolon for not receiving arguments
		~~ // we had added `build()`
		set_spacing: 12
	}
}
~~~

</td><td>

Methods outside the builder pattern are called in the same order.

~~~ rust
let gtk_box_1 = <gtk::Box>::builder()
    .orientation(Horizontal)
    .build();
let gtk_box_0 = <gtk::Box>::builder()
    .orientation(Vertical)
    .build();
gtk_box_0.set_spacing(6);
gtk_box_1.set_spacing(12);
~~~

</td></tr></table><br/></details>

<details><summary>Expand builder patterns in order</summary><br/>

<table><tr><td>

~~~ rust
block! {
	gtk::Box {
		orientation: Vertical
		~> // just add `>`
		set_spacing: 6
	}
	gtk::Box {
		orientation: Horizontal
		build;
		~~>
		set_spacing: 12
	}
}
~~~

</td><td>

~~~ rust
let gtk_box_0 = <gtk::Box>::builder()
    .orientation(Vertical)
    .build();
let gtk_box_1 = <gtk::Box>::builder()
    .orientation(Horizontal)
    .build();
gtk_box_0.set_spacing(6);
gtk_box_1.set_spacing(12);
~~~

</td></tr></table><br/></details>

<details><summary>Expand properties as chain methods when defining an item with a function call</summary><br/>

<table><tr><td>

~~~ rust
block! { // call a function:
	gtk::Box::builder() {
		orientation: Vertical
		spacing: 6
	}! // and add `!` after `}`
	
	gtk::Box::builder() {
		orientation: Horizontal
		~ // this way can also be broken
		set_spacing: 12
	}!
}
~~~

</td><td>

This way also defines variables in reverse order, unless `>` is added after `~` or `~~`:

~~~ rust
let gtk_box_builder_1 = gtk::Box::builder()
	.orientation(Horizontal)
	.build();
let gtk_box_builder_0 = gtk::Box::builder()
	.orientation(Vertical)
	.spacing(6)
	.build();
gtk_box_builder_1.set_spacing(12);
~~~

</td></tr></table><br/></details>

<details><summary>Edit returns with <code>'back</code></summary><br/>

<table><tr><td>

~~~ rust
block!(gtk::Stack stack {
	bind_property: "hexpand", &stack, "vexpand"
		'back { bidirectional; sync_create; } // chained
		// `build!()` is added (`~` can be used)
	
	add_child: &_ @ gtk::Label { label: "Label" }
		'back { set_title: "Page 1"; set_name: "page_1" }!
		// `!` is added after `}` to prevent methods from chaining
	
	add_child: &_ @ gtk::Button { } // custom name:
		'back my_page { set_title: "Page 2" }!
}!);
~~~

</td><td>

~~~ rust
let stack = <gtk::Stack>::default();
let gtk_button_3 = <gtk::Button>::builder().build();
let gtk_label_1 = <gtk::Label>::builder().label("Label").build();
stack.bind_property("hexpand", &stack, "vexpand")
    .bidirectional()
    .sync_create()
    .build();
let back_2 = stack.add_child(&gtk_label_1);
back_2.set_title("Page 1");
back_2.set_name("page_1");
let my_page = stack.add_child(&gtk_button_3);
my_page.set_title("Page 2");
~~~

</td></tr></table><br/></details>

<details><summary>Conditional property assignments</summary><br/>

<table><tr><td>

~~~ rust
let device = "phone";

block!(gtk::Box {
	spacing: if device == "phone" { 6 } else { 12 }
	
	if device == "laptop" {
		set_margin_end: 12
		set_orientation: Horizontal
	} else {
		set_margin_bottom: 12
		set_orientation: Vertical
	} // builder pattern is ignored inside conditionals
	
	match device { // chain methods too
		"phone" => set_tooltip_text: Some("phone")
		"laptop" => {
			set_tooltip_text: Some("laptop")
			set_css_classes: &["laptop"]
		}
		_ => { set_hexpand: false; set_vexpand: false }
	}
	
	margin_end: 6; margin_bottom: 6
});
~~~

</td><td>

~~~ rust
let gtk_box_0 = <gtk::Box>::builder()
    .spacing(if device == "phone" { 6 } else { 12 })
    .margin_end(6)
    .margin_bottom(6)
    .build();
if device == "laptop" {
    gtk_box_0.set_margin_end(12);
    gtk_box_0.set_orientation(Horizontal);
} else {
    gtk_box_0.set_margin_bottom(12);
    gtk_box_0.set_orientation(Vertical);
}
match device {
    "phone" => {
        gtk_box_0.set_tooltip_text(Some("phone"));
    }
    "laptop" => {
        gtk_box_0.set_tooltip_text(Some("laptop"));
        gtk_box_0.set_css_classes(&["laptop"]);
    }
    _ => {
        gtk_box_0.set_hexpand(false);
        gtk_box_0.set_vexpand(false);
    }
}
~~~

</td></tr></table><br/></details>

<details><summary>Property bindings</summary><br/>

<table><tr><td>

~~~ rust
block!(gtk::Box root {
	// let's make the margins always...
	spacing: 6 // equal to the spacing
	
	// prefix 'bind to the properties to be bound
	'bind set_margin_top: root.spacing()
	'bind set_margin_bottom: root.spacing()
	'bind { // or use braces for many properties
		set_margin_start: root.spacing()
		set_margin_end: root.spacing()
	} // bindings do not expand in chain
	~
	append: &_ @ gtk::Label label { }
	
	// this method calls a closure when `spacing` changes
	connect_spacing_notify: move |root| {
		let text = format!("spacing is {}", root.spacing());
		bindings! { } // here the bindings are expanded
		label.set_label(&text);
	}
});
~~~

</td><td>

~~~ rust
let label = <gtk::Label>::builder().build();
let root = <gtk::Box>::builder().spacing(6).build();
root.append(&label);
root.connect_spacing_notify(move |root| {
    let text = alloc::__export::must_use({
        alloc::fmt::format(alloc::__export::format_args!(
            "spacing is {}",
            root.spacing()
        ))
    });
    root.set_margin_top(root.spacing());
    root.set_margin_bottom(root.spacing());
    {
        root.set_margin_start(root.spacing());
        root.set_margin_end(root.spacing());
    }
    label.set_label(&text);
});
~~~

</td></tr></table><br/></details>

<details><summary>Expand bindings twice</summary><br/>

<table><tr><td>

~~~ rust
block!(gtk::Box root {
	spacing: 6
	~ // just add `#` after 'bind
	'bind #set_margin_top: root.spacing()
	'bind #set_margin_bottom: root.spacing()
	'bind #{
		set_margin_start: root.spacing()
		set_margin_end: root.spacing()
	}
	connect_spacing_notify: |root| bindings!()
});
~~~

Bindings will be expanded as usual (like a normal property assignment) and in the `bindings!()` placeholder macro.

</td><td>

~~~ rust
let root = <gtk::Box>::builder().spacing(6).build();
root.set_margin_top(root.spacing());
root.set_margin_bottom(root.spacing());
{
    root.set_margin_start(root.spacing());
    root.set_margin_end(root.spacing());
}
root.connect_spacing_notify(|root| {
    root.set_margin_top(root.spacing());
    root.set_margin_bottom(root.spacing());
    {
        root.set_margin_start(root.spacing());
        root.set_margin_end(root.spacing());
    }
});
~~~

</td></tr></table><br/></details>

<details><summary>Expand bindings in a variable</summary><br/>

<table><tr><td>

~~~ rust
let mut resets = 0;

block!(gtk::Box root {
	margin_top: 6; margin_start: 6
	~
	'bind #set_margin_bottom: root.margin_top()
	'consume top_to_bottom = |root: &gtk::Box| bindings!()
	// all bindings declared up to here were...
	// consumed in the `top_to_bottom` variable
	
	'bind #set_margin_end: root.margin_start()
	'consume start_to_end = |root: &gtk::Box| bindings!()
	// to consume multiple times, ...
	// there must be new bindings beforehand
	
	connect_margin_top_notify: top_to_bottom
	connect_margin_start_notify: start_to_end
	
	'bind { set_margin_top: 6; set_margin_start: 6 }
	'consume mut reset = || { resets += 1; bindings!() }
}); // the consumer variable can be mutable

reset()
~~~

</td><td>

~~~ rust
let mut resets = 0;
let root = <gtk::Box>::builder().margin_top(6).margin_start(6).build();
root.set_margin_bottom(root.margin_top());
let top_to_bottom = |root: &gtk::Box| {
    root.set_margin_bottom(root.margin_top());
};
root.set_margin_end(root.margin_start());
let start_to_end = |root: &gtk::Box| {
    root.set_margin_end(root.margin_start());
};
root.connect_margin_top_notify(top_to_bottom);
root.connect_margin_start_notify(start_to_end);
let mut reset = || {
    resets += 1;
    {
        {
            root.set_margin_top(6);
            root.set_margin_start(6);
        }
    }
};
reset()
~~~

</td></tr></table><br/></details>

<details><summary>Expand bindings out of view</summary><br/>

<table><tr><td>

~~~ rust
#[view(gtk::ToggleButton root {
	label: "any label"
	'bind set_label: argument
	'bind set_active: !root.is_active()
})] // the view code is written in this attribute
fn main() {
	expand_view_here! { } // placeholder macro
	let toggle = move |argument| bindings!();
	toggle("new label");
}
~~~

</td><td>

~~~ rust
fn main() {
    let root = <gtk::ToggleButton>::builder().label("any label").build();
    let toggle = move |argument| {
        root.set_label(argument);
        root.set_active(!root.is_active());
    };
    toggle("new label");
}
~~~

</td></tr><tr><td>

~~~ rust
#[view] // this way the view code can be...
mod module { // written after the function
	use super::*;
	fn function() {
		expand_view_here! { } // placeholder macro
		let toggle = move |argument| bindings!();
		toggle("new label");
	}
	view!(gtk::ToggleButton root {
		label: "any label"
		'bind set_label: argument
		'bind set_active: !root.is_active()
	});
}
~~~

</td><td>

~~~ rust
mod module {
    use super::*;
    fn function() {
        let root = <gtk::ToggleButton>::builder().label("any label").build();
        let toggle = move |argument| {
            root.set_label(argument);
            root.set_active(!root.is_active());
        };
        toggle("new label");
    }
}
~~~

</td></tr></table><br/></details>

<details><summary>Templates</summary><br/>

A template is simply a struct that references some widgets in the view. Several structs can be defined, but each one is followed by one or more items.

<table><tr><td>

~~~ rust
#[view]
mod module {
	pub fn template(text: &str) -> Template {
		use super::*;
		expand_view_here! { }
		Template { int: 7, float: 7.0, root, button, label }
	}
	view! { // a struct is declared inside the view
		pub struct Template { int: i32, pub float: f32 }
		
		// due to `pub` this item is included in the...
		gtk::Box pub root { // template as a public field
			append: &_ @ gtk::Button { label: text }
			append: &_ @ gtk::Button pub button { }
			// the first button is not included
			
			append: &_ @ gtk::Label ref label { } // ...
		}! // due to `ref` the label is included as private
	}
}

fn main() {
	block!(gtk::Frame { // the child is the...
		// root item, not the template itself
		child: &_.root @ module::template("text") {
			// to edit template fields, use a dot
			root.set_spacing: 6
			button.set_label: "Button"
			
			// `ref` to edit a template field...
			ref root { // within a scope
				set_margin_top: 6
				set_margin_bottom: 6
			}
		}
	});
}
~~~

</td><td>

~~~ rust
mod module {
    pub fn template(text: &str) -> Template {
        use super::*;
        let root = <gtk::Box>::default();
        let label = <gtk::Label>::builder().build();
        let button = <gtk::Button>::builder().build();
        let gtk_button_0 = <gtk::Button>::builder().label(text).build();
        root.append(&gtk_button_0);
        root.append(&button);
        root.append(&label);
        Template { int: 7, float: 7.0, root, button, label }
    }
    pub struct Template {
        int: i32,
        pub float: f32,
        pub root: gtk::Box,
        pub button: gtk::Button,
        label: gtk::Label,
    }
}

fn main() {
    let module_template_1 = module::template("text");
    let gtk_frame_0 = <gtk::Frame>::builder()
        .child(&module_template_1.root)
        .build();
    module_template_1.root.set_spacing(6);
    module_template_1.button.set_label("Button");
    let _ = module_template_1.root;
    module_template_1.root.set_margin_top(6);
    module_template_1.root.set_margin_bottom(6);
}
~~~

</td></tr><tr><td>

~~~ rust
#[view { // a struct is declared inside the view
	pub struct Template { int: i32, pub float: f32 }
	
	// due to `pub` this item is included in the...
	gtk::Box pub root { // template as a public field
		append: &_ @ gtk::Button { label: text }
		append: &_ @ gtk::Button pub button { }
		// the first button is not included
		
		append: &_ @ gtk::Label ref label { } // ...
	}! // due to `ref` the label is included as private
}]
pub fn template(text: &str) -> Template {
	expand_view_here! { }
	Template { int: 7, float: 7.0, root, button, label }
}

fn main() {
	block!(gtk::Frame { // the child is the...
		// root item, not the template itself
		child: &_.root @ template("text") {
			// to edit template fields, use a dot
			root.set_spacing: 6
			button.set_label: "Button"
			
			// `ref` to edit a template...
			ref root { // field within a scope
				set_margin_top: 6
				set_margin_bottom: 6
			}
		}
	});
}
~~~

</td><td>

Almost the same code as the previous row is generated, but the view code is written in an attribute to avoid using a module.

~~~ rust
pub struct Template {
    int: i32,
    pub float: f32,
    pub root: gtk::Box,
    pub button: gtk::Button,
    label: gtk::Label,
}
pub fn template(text: &str) -> Template {
    let root = <gtk::Box>::default();
    let label = <gtk::Label>::builder().build();
    let button = <gtk::Button>::builder().build();
    let gtk_button_0 = <gtk::Button>::builder().label(text).build();
    root.append(&gtk_button_0);
    root.append(&button);
    root.append(&label);
    Template { int: 7, float: 7.0, root, button, label }
}
fn main() {
    let template_1 = template("text");
    let gtk_frame_0 = <gtk::Frame>::builder().child(&template_1.root).build();
    template_1.root.set_spacing(6);
    template_1.button.set_label("Button");
    let _ = template_1.root;
    template_1.root.set_margin_top(6);
    template_1.root.set_margin_bottom(6);
}
~~~

</td></tr></table><br/></details>

<details><summary>Template without declaring struct in the view</summary><br/>

<table><tr><td>

~~~ rust
#[view(pub, int: i32, pub float: f32)]
impl Template {
	fn new(text: &str) -> Self {
		expand_view_here! { }
		Self { int: 7, float: 7.0, root, label }
	}
	view!(gtk::Box ref root {
		append: &_ @ gtk::Button { label: text }
		append: &_ @ gtk::Label pub label { }
	}!);
}
~~~

</td><td rowspan="2">

The attribute is used for `impl`, where the first argument is the visibility of the struct to be generated (optional) and the rest of the arguments are additional fields, although it is also possible to leave the attribute empty for `impl` and define the struct in the view. Both ways expand equally:

~~~ rust
pub struct Template {
    int: i32,
    pub float: f32,
    root: gtk::Box,
    pub label: gtk::Label,
}
impl Template {
    fn new(text: &str) -> Self {
        let root = <gtk::Box>::default();
        let label = <gtk::Label>::builder()
            .build();
        let gtk_button_0 = <gtk::Button>::builder()
            .label(text).build();
        root.append(&gtk_button_0);
        root.append(&label);
        Self { int: 7, float: 7.0, root, label }
    }
}
~~~

</td></tr><tr><td>

~~~ rust
#[view] // although the struct can still be...
impl Template { // defined in the view for `impl`
	view! {
		pub struct Template { int: i32, pub float: f32 }
		gtk::Box ref root {
			append: &_ @ gtk::Button { label: text }
			append: &_ @ gtk::Label pub label { }
		}!
	}
	fn new(text: &str) -> Self {
		expand_view_here! { }
		Self { int: 7, float: 7.0, root, label }
	}
}
~~~

</td></tr></table><br/></details>

<details><summary>The above but with <code>mod</code>, and returning to a template</summary><br/>

In addition to visibility, the first attribute argument can be the name of a template struct, or its generics, or two of them at once, or all three at once.

<table><tr><td>

~~~ rust
#[view(pub Template<'a, T>, text: &'a T)]
mod module {
	type Any = Box<dyn std::any::Any>;
	
	fn template<'a, T>(text: &'a T) -> Template<'a, T> {
		use super::*;
		expand_view_here! { }
		
		let frame = Box::new(frame);
		Template { root, text, my_page, frame }
	}
	
	view!(gtk::Stack pub root {
		// a template field type other than
		// the one assumed by the macro can
		// be specified for an item with `as`
		add_child: &_ @ gtk::Frame ref frame as Any { }
			// returns can also be referenced in the
			// template by specifying the type with `as`
			'back pub my_page as gtk::StackPage { }!
	}!);
}
~~~

</td><td>

~~~ rust
mod module {
    type Any = Box<dyn std::any::Any>;
    fn template<'a, T>(text: &'a T) -> Template<'a, T> {
        use super::*;
        let root = <gtk::Stack>::default();
        let frame = <gtk::Frame>::builder().build();
        let my_page = root.add_child(&frame);
        let frame = Box::new(frame);
        Template { root, text, my_page }
    }
    pub struct Template<'a, T> {
        text: &'a T,
        pub root: gtk::Stack,
        frame: Any,
        pub my_page: gtk::StackPage,
    }
}
~~~

</td></tr></table><br/></details>

<details><summary>Avoid templates with too many arguments</summary><br/>

<table><tr><td>

~~~ rust
struct CustomBox { // simply use struct fields...
	expanded: bool, // instead of arguments
	margin: i32,
	name: &'static str,
} // these fields will behave as "custom properties"

#[view(Template)]
impl CustomBox {
	fn start(self) -> Template {
		expand_view_here! { }    // `fn start(self)`...
		Template { root, frame } // "must" be defined
	}
	view!(gtk::Box ref root {
		margin_start: self.margin
		margin_end: self.margin
		hexpand: self.expanded
		vexpand: self.expanded
		~
		append: &_ @ gtk::Label {
			label: format!("Name: {}", self.name)
		}
		append: &_ @gtk::Frame ref frame { }
	});
}
fn main() {
	block!(gtk::Frame {
		child: &_.root @ CustomBox {
			// "custom properties" go here
			expanded: true; margin: 12; name: "First"
			~ // `.start()` is chained
			
			// template fields can now be edited
			root.set_spacing: 6
			frame.set_child: Some(&_) @ gtk::Label { }
		}? // requires adding `?` after `}`
	});
}
~~~

</td><td>

~~~ rust
struct CustomBox {
    expanded: bool,
    margin: i32,
    name: &'static str,
}
struct Template {
    root: gtk::Box,
    frame: gtk::Frame,
}
impl CustomBox {
    fn start(self) -> Template {
        let frame = <gtk::Frame>::builder().build();
        let gtk_label_0 = <gtk::Label>::builder()
            .label(alloc::__export::must_use({
                alloc::fmt::format(alloc::__export::format_args!("Name: {}", self.name))
            }))
            .build();
        let root = <gtk::Box>::builder()
            .margin_start(self.margin)
            .margin_end(self.margin)
            .hexpand(self.expanded)
            .vexpand(self.expanded)
            .build();
        root.append(&gtk_label_0);
        root.append(&frame);
        Template { root, frame }
    }
}
fn main() {
    let gtk_label_2 = <gtk::Label>::builder().build();
    let custombox_1 = (CustomBox {
        expanded: true,
        margin: 12,
        name: "First",
    }).start();
    let gtk_frame_0 = <gtk::Frame>::builder().child(&custombox_1.root).build();
    custombox_1.root.set_spacing(6);
    custombox_1.frame.set_child(Some(&gtk_label_2));
}
~~~

</td></tr></table><br/></details>

## Basic maintenance

The following commands must be executed and must not give any problems:

~~~ bash
cargo check  -p declarative-macros
cargo clippy -p declarative-macros
cargo test   -p declarative-macros
cargo check
cargo clippy
cargo test
# and now run and check each example
~~~

If you need a changelog, maybe the commit log will help (the last ones try to have the most important details).

<br/>

#### License

<sub>Licensed under either of Apache License, Version 2.0 (<a href="LICENSES/Apache-2.0.txt">Apache-2.0.txt</a> or http://www.apache.org/licenses/LICENSE-2.0) or MIT license (<a href="LICENSES/MIT.txt">MIT.txt</a> or http://opensource.org/licenses/MIT) at your option.</sub>

<sub>Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.</sub>