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
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
#![allow(clippy::collapsible_if)]

use crate::_private::NonExhaustive;
use crate::event::{DoubleClick, DoubleClickOutcome, EditKeys, EditOutcome};
use crate::selection::{CellSelection, RowSelection, RowSetSelection};
use crate::table::data::{DataRepr, DataReprIter};
use crate::textdata::{Row, TextTableData};
use crate::util::{revert_style, transfer_buffer};
use crate::{FTableContext, TableData, TableDataIter, TableSelection};
#[allow(unused_imports)]
use log::debug;
#[cfg(debug_assertions)]
use log::warn;
use rat_event::util::MouseFlags;
use rat_event::{ct_event, FocusKeys, HandleEvent, MouseOnly, Outcome};
use rat_focus::{FocusFlag, HasFocusFlag};
use rat_scrolled::{layout_scroll, Scroll, ScrollState};
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Flex, Layout, Rect};
use ratatui::style::Style;
#[cfg(debug_assertions)]
use ratatui::style::Stylize;
#[cfg(debug_assertions)]
use ratatui::text::Text;
use ratatui::widgets::{Block, StatefulWidget, StatefulWidgetRef, Widget, WidgetRef};
use std::cmp::{max, min};
use std::collections::HashSet;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem;
use std::rc::Rc;

/// FTable widget.
///
/// Can be used like a ratatui::Table, but the benefits only
/// show if you use [FTable::data] or [FTable::iter] to set the table data.
///
/// See [FTable::data] and [FTable::iter] for an example.
#[derive(Debug, Default)]
pub struct FTable<'a, Selection> {
    data: DataRepr<'a>,
    no_row_count: bool,

    header: Option<Row<'a>>,
    footer: Option<Row<'a>>,

    widths: Vec<Constraint>,
    flex: Flex,
    column_spacing: u16,
    layout_width: Option<u16>,

    block: Option<Block<'a>>,
    hscroll: Option<Scroll<'a>>,
    vscroll: Option<Scroll<'a>>,

    header_style: Option<Style>,
    footer_style: Option<Style>,
    style: Style,

    select_row_style: Option<Style>,
    show_row_focus: bool,
    select_column_style: Option<Style>,
    show_column_focus: bool,
    select_cell_style: Option<Style>,
    show_cell_focus: bool,
    select_header_style: Option<Style>,
    show_header_focus: bool,
    select_footer_style: Option<Style>,
    show_footer_focus: bool,

    focus_style: Option<Style>,

    debug: bool,

    _phantom: PhantomData<Selection>,
}

mod data {
    use crate::textdata::TextTableData;
    use crate::{FTableContext, TableData, TableDataIter};
    #[allow(unused_imports)]
    use log::debug;
    #[allow(unused_imports)]
    use log::warn;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    use ratatui::style::{Style, Stylize};
    use std::fmt::{Debug, Formatter};

    #[derive(Default)]
    pub(super) enum DataRepr<'a> {
        #[default]
        None,
        Text(TextTableData<'a>),
        Data(Box<dyn TableData<'a> + 'a>),
        Iter(Box<dyn TableDataIter<'a> + 'a>),
    }

    impl<'a> DataRepr<'a> {
        pub(super) fn into_iter(self) -> DataReprIter<'a, 'a> {
            match self {
                DataRepr::None => DataReprIter::None,
                DataRepr::Text(v) => DataReprIter::IterText(v, None),
                DataRepr::Data(v) => DataReprIter::IterData(v, None),
                DataRepr::Iter(v) => DataReprIter::IterIter(v),
            }
        }

        pub(super) fn iter<'b>(&'b self) -> DataReprIter<'a, 'b> {
            match self {
                DataRepr::None => DataReprIter::None,
                DataRepr::Text(v) => DataReprIter::IterDataRef(v, None),
                DataRepr::Data(v) => DataReprIter::IterDataRef(v.as_ref(), None),
                DataRepr::Iter(v) => {
                    // TableDataIter might not implement a valid cloned().
                    if let Some(v) = v.cloned() {
                        DataReprIter::IterIter(v)
                    } else {
                        DataReprIter::Invalid(None)
                    }
                }
            }
        }
    }

    impl<'a> Debug for DataRepr<'a> {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("Data").finish()
        }
    }

    #[derive(Default)]
    pub(super) enum DataReprIter<'a, 'b> {
        #[default]
        None,
        Invalid(Option<usize>),
        IterText(TextTableData<'a>, Option<usize>),
        IterData(Box<dyn TableData<'a> + 'a>, Option<usize>),
        IterDataRef(&'b dyn TableData<'a>, Option<usize>),
        IterIter(Box<dyn TableDataIter<'a> + 'a>),
    }

    impl<'a, 'b> TableDataIter<'a> for DataReprIter<'a, 'b> {
        fn rows(&self) -> Option<usize> {
            match self {
                DataReprIter::None => Some(0),
                DataReprIter::Invalid(_) => Some(1),
                DataReprIter::IterText(v, _) => Some(v.rows.len()),
                DataReprIter::IterData(v, _) => Some(v.rows()),
                DataReprIter::IterDataRef(v, _) => Some(v.rows()),
                DataReprIter::IterIter(v) => v.rows(),
            }
        }

        fn nth(&mut self, n: usize) -> bool {
            let incr = |row: &mut Option<usize>, rows: usize| match *row {
                None => {
                    *row = Some(n);
                    n < rows
                }
                Some(w) => {
                    *row = Some(w + n + 1);
                    w + n + 1 < rows
                }
            };

            match self {
                DataReprIter::None => false,
                DataReprIter::Invalid(row) => incr(row, 1),
                DataReprIter::IterText(v, row) => incr(row, v.rows.len()),
                DataReprIter::IterData(v, row) => incr(row, v.rows()),
                DataReprIter::IterDataRef(v, row) => incr(row, v.rows()),
                DataReprIter::IterIter(v) => v.nth(n),
            }
        }

        /// Row height.
        fn row_height(&self) -> u16 {
            match self {
                DataReprIter::None => 1,
                DataReprIter::Invalid(_) => 1,
                DataReprIter::IterText(v, n) => v.row_height(n.expect("row")),
                DataReprIter::IterData(v, n) => v.row_height(n.expect("row")),
                DataReprIter::IterDataRef(v, n) => v.row_height(n.expect("row")),
                DataReprIter::IterIter(v) => v.row_height(),
            }
        }

        fn row_style(&self) -> Option<Style> {
            match self {
                DataReprIter::None => None,
                DataReprIter::Invalid(_) => Some(Style::new().white().on_red()),
                DataReprIter::IterText(v, n) => v.row_style(n.expect("row")),
                DataReprIter::IterData(v, n) => v.row_style(n.expect("row")),
                DataReprIter::IterDataRef(v, n) => v.row_style(n.expect("row")),
                DataReprIter::IterIter(v) => v.row_style(),
            }
        }

        /// Render the cell given by column/row.
        fn render_cell(&self, ctx: &FTableContext, column: usize, area: Rect, buf: &mut Buffer) {
            match self {
                DataReprIter::None => {}
                DataReprIter::Invalid(_) => {
                    if column == 0 {
                        #[cfg(debug_assertions)]
                        warn!("FTable::render_ref - TableDataIter must implement a valid cloned() for this to work.");

                        buf.set_string(
                            area.x,
                            area.y,
                            "TableDataIter must implement a valid cloned() for this",
                            Style::default(),
                        );
                    }
                }
                DataReprIter::IterText(v, n) => {
                    v.render_cell(ctx, column, n.expect("row"), area, buf)
                }
                DataReprIter::IterData(v, n) => {
                    v.render_cell(ctx, column, n.expect("row"), area, buf)
                }
                DataReprIter::IterDataRef(v, n) => {
                    v.render_cell(ctx, column, n.expect("row"), area, buf)
                }
                DataReprIter::IterIter(v) => v.render_cell(ctx, column, area, buf),
            }
        }
    }
}

/// Combined style.
#[derive(Debug)]
pub struct FTableStyle {
    pub style: Style,
    pub header_style: Option<Style>,
    pub footer_style: Option<Style>,

    pub select_row_style: Option<Style>,
    pub select_column_style: Option<Style>,
    pub select_cell_style: Option<Style>,
    pub select_header_style: Option<Style>,
    pub select_footer_style: Option<Style>,

    pub show_row_focus: bool,
    pub show_column_focus: bool,
    pub show_cell_focus: bool,
    pub show_header_focus: bool,
    pub show_footer_focus: bool,

    pub focus_style: Option<Style>,

    pub non_exhaustive: NonExhaustive,
}

/// FTable state.
#[derive(Debug, Clone)]
pub struct FTableState<Selection> {
    /// Current focus state.
    pub focus: FocusFlag,

    /// Total area.
    pub area: Rect,
    /// Area inside the border and scrollbars
    pub inner: Rect,

    /// Total header area.
    pub header_area: Rect,
    /// Total table area.
    pub table_area: Rect,
    /// Area per visible row. The first element is at row_offset.
    pub row_areas: Vec<Rect>,
    /// Area per visible column, also contains the following spacer if any.
    /// The first element is at col_offset. Height is the height of the table_area.
    pub column_areas: Vec<Rect>,
    /// Area for each *defined* column without the spacer.
    /// Invisible columns have width 0. Height is the height of the table_area.
    pub base_column_areas: Vec<Rect>,
    /// Total footer area.
    pub footer_area: Rect,

    /// Row count.
    pub rows: usize,
    // debug info
    pub _counted_rows: usize,
    /// Column count.
    pub columns: usize,

    /// Row scrolling data.
    pub vscroll: ScrollState,
    /// Column scrolling data.
    pub hscroll: ScrollState,

    /// Selection data.
    pub selection: Selection,

    /// Helper for mouse interactions.
    pub mouse: MouseFlags,

    pub non_exhaustive: NonExhaustive,
}

impl<'a, Selection> FTable<'a, Selection> {
    /// New, empty Table.
    pub fn new() -> Self
    where
        Selection: Default,
    {
        Self::default()
    }

    /// Create a new FTable with preformatted data. For compatibility
    /// with ratatui.
    ///
    /// Use of [FTable::data] is preferred.
    pub fn new_ratatui<R, C>(rows: R, widths: C) -> Self
    where
        R: IntoIterator,
        R::Item: Into<Row<'a>>,
        C: IntoIterator,
        C::Item: Into<Constraint>,
        Selection: Default,
    {
        let widths = widths.into_iter().map(|v| v.into()).collect::<Vec<_>>();
        let data = TextTableData {
            rows: rows.into_iter().map(|v| v.into()).collect(),
        };
        Self {
            data: DataRepr::Text(data),
            widths,
            ..Default::default()
        }
    }

    /// Set preformatted row-data. For compatibility with ratatui.
    ///
    /// Use of [FTable::data] is preferred.
    pub fn rows<T>(mut self, rows: T) -> Self
    where
        T: IntoIterator<Item = Row<'a>>,
    {
        let rows = rows.into_iter().collect();
        self.data = DataRepr::Text(TextTableData { rows });
        self
    }

    /// Set a reference to the TableData facade to your data.
    ///
    /// The way to go is to define a small struct that contains just a
    /// reference to your data. Then implement TableData for this struct.
    ///
    /// ```rust
    /// use ratatui::buffer::Buffer;
    /// use ratatui::layout::Rect;
    /// use ratatui::prelude::Style;
    /// use ratatui::text::Span;
    /// use ratatui::widgets::{StatefulWidget, Widget};
    /// use rat_ftable::{FTable, FTableContext, FTableState, TableData};
    ///
    /// # struct SampleRow;
    /// # let area = Rect::default();
    /// # let mut buf = Buffer::empty(area);
    /// # let buf = &mut buf;
    ///
    /// struct Data1<'a>(&'a [SampleRow]);
    ///
    /// impl<'a> TableData<'a> for Data1<'a> {
    ///     fn rows(&self) -> usize {
    ///         self.0.len()
    ///     }
    ///
    ///     fn row_height(&self, row: usize) -> u16 {
    ///         // to some calculations ...
    ///         1
    ///     }
    ///
    ///     fn row_style(&self, row: usize) -> Style {
    ///         // to some calculations ...
    ///         Style::default()
    ///     }
    ///
    ///     fn render_cell(&self, ctx: &FTableContext, column: usize, row: usize, area: Rect, buf: &mut Buffer) {
    ///         if let Some(data) = self.0.get(row) {
    ///             let rend = match column {
    ///                 0 => Span::from("column1"),
    ///                 1 => Span::from("column2"),
    ///                 2 => Span::from("column3"),
    ///                 _ => return
    ///             };
    ///             rend.render(area, buf);
    ///         }
    ///     }
    /// }
    ///
    /// // When you are creating the table widget you hand over a reference
    /// // to the facade struct.
    ///
    /// let my_data_somewhere_else = vec![SampleRow;999999];
    /// let mut table_state_somewhere_else = FTableState::default();
    ///
    /// // ...
    ///
    /// let table1 = FTable::default().data(Data1(&my_data_somewhere_else));
    /// table1.render(area, buf, &mut table_state_somewhere_else);
    /// ```
    #[inline]
    pub fn data(mut self, data: impl TableData<'a> + 'a) -> Self {
        self.widths = data.widths();
        self.header = data.header();
        self.footer = data.footer();
        self.data = DataRepr::Data(Box::new(data));
        self
    }

    ///
    /// Alternative representation for the data as a kind of Iterator.
    /// It uses interior iteration, which fits quite nice for this and
    /// avoids handing out lifetime bound results of the actual iterator.
    /// Which is a bit nightmarish to get right.
    ///
    ///
    /// Caution: If you can't give the number of rows, the table will iterate over all
    /// the data. See [FTable::no_row_count].
    ///
    /// ```rust
    /// use std::iter::{Enumerate};
    /// use std::slice::Iter;
    /// use format_num_pattern::NumberFormat;
    /// use ratatui::buffer::Buffer;
    /// use ratatui::layout::{Constraint, Rect};
    /// use ratatui::prelude::Color;
    /// use ratatui::style::{Style, Stylize};
    /// use ratatui::text::Span;
    /// use ratatui::widgets::{Widget, StatefulWidget};
    /// use rat_ftable::{FTable, FTableContext, FTableState, TableDataIter};
    ///
    /// # struct Data {
    /// #     table_data: Vec<Sample>
    /// # }
    /// #
    /// # struct Sample {
    /// #     pub text: String
    /// # }
    /// #
    /// # let data = Data {
    /// #     table_data: vec![],
    /// # };
    /// # let area = Rect::default();
    /// # let mut buf = Buffer::empty(area);
    /// # let buf = &mut buf;
    ///
    /// struct RowIter1<'a> {
    ///     iter: Enumerate<Iter<'a, Sample>>,
    ///     item: Option<(usize, &'a Sample)>,
    /// }
    ///
    /// impl<'a> TableDataIter<'a> for RowIter1<'a> {
    ///     fn rows(&self) -> Option<usize> {
    ///         // If you can, give the length. Otherwise,
    ///         // the table will iterate all to find out a length.
    ///         None
    ///         // Some(100_000)
    ///     }
    ///
    ///     /// Select the nth element from the current position.
    ///     fn nth(&mut self, n: usize) -> bool {
    ///         self.item = self.iter.nth(n);
    ///         self.item.is_some()
    ///     }
    ///
    ///     /// Row height.
    ///     fn row_height(&self) -> u16 {
    ///         1
    ///     }
    ///
    ///     /// Row style.
    ///     fn row_style(&self) -> Style {
    ///         Style::default()
    ///     }
    ///
    ///     /// Render one cell.
    ///     fn render_cell(&self,
    ///                     ctx: &FTableContext,
    ///                     column: usize,
    ///                     area: Rect,
    ///                     buf: &mut Buffer)
    ///     {
    ///         let row = self.item.expect("data");
    ///         match column {
    ///             0 => {
    ///                 let row_fmt = NumberFormat::new("000000").expect("fmt");
    ///                 let span = Span::from(row_fmt.fmt_u(row.0));
    ///                 buf.set_style(area, Style::new().black().bg(Color::from_u32(0xe7c787)));
    ///                 span.render(area, buf);
    ///             }
    ///             1 => {
    ///                 let span = Span::from(&row.1.text);
    ///                 span.render(area, buf);
    ///             }
    ///             _ => {}
    ///         }
    ///     }
    /// }
    ///
    /// let mut rit = RowIter1 {
    ///     iter: data.table_data.iter().enumerate(),
    ///     item: None,
    /// };
    ///
    /// let table1 = FTable::default()
    ///     .iter(&mut rit)
    ///     .widths([
    ///         Constraint::Length(6),
    ///         Constraint::Length(20)
    ///     ]);
    ///
    /// let mut table_state_somewhere_else = FTableState::default();
    ///
    /// table1.render(area, buf, &mut table_state_somewhere_else);
    /// ```
    ///
    #[inline]
    pub fn iter(mut self, data: impl TableDataIter<'a> + 'a) -> Self {
        #[cfg(debug_assertions)]
        if data.rows().is_none() {
            warn!("FTable::iter - rows is None, this will be slower");
        }
        self.header = data.header();
        self.footer = data.footer();
        self.widths = data.widths();
        self.data = DataRepr::Iter(Box::new(data));
        self
    }

    /// If you work with an TableDataIter to fill the table, and
    /// if you don't return a count with rows(), FTable will run
    /// through all your iterator to find the actual number of rows.
    ///
    /// This may take its time.
    ///
    /// If you set no_row_count(true), this part will be skipped, and
    /// the row count will be set to an estimate of usize::MAX.
    /// This will destroy your ability to jump to the end of the data,
    /// but otherwise it's fine.
    /// You can still page-down through the data, and if you ever
    /// reach the end, the correct row-count can be established.
    ///
    /// _Extra info_: This might be only useful if you have a LOT of data.
    /// In my test it changed from 1.5ms to 150µs for about 100.000 rows.
    /// And 1.5ms is still not that much ... so you probably want to
    /// test without this first and then decide.
    pub fn no_row_count(mut self, no_row_count: bool) -> Self {
        self.no_row_count = no_row_count;
        self
    }

    /// Set the table-header.
    #[inline]
    pub fn header(mut self, header: Row<'a>) -> Self {
        self.header = Some(header);
        self
    }

    /// Set the table-footer.
    #[inline]
    pub fn footer(mut self, footer: Row<'a>) -> Self {
        self.footer = Some(footer);
        self
    }

    /// Column widths as Constraints.
    pub fn widths<I>(mut self, widths: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<Constraint>,
    {
        self.widths = widths.into_iter().map(|v| v.into()).collect();
        self
    }

    /// Flex for layout.
    #[inline]
    pub fn flex(mut self, flex: Flex) -> Self {
        self.flex = flex;
        self
    }

    /// Spacing between columns.
    #[inline]
    pub fn column_spacing(mut self, spacing: u16) -> Self {
        self.column_spacing = spacing;
        self
    }

    /// Overrides the width of the rendering area for layout purposes.
    /// Layout uses this width, even if it means that some columns are
    /// not visible.
    #[inline]
    pub fn layout_width(mut self, width: u16) -> Self {
        self.layout_width = Some(width);
        self
    }

    /// Draws a block around the table widget.
    #[inline]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Scrollbars
    pub fn scroll(mut self, scroll: Scroll<'a>) -> Self {
        self.hscroll = Some(scroll.clone().override_horizontal());
        self.vscroll = Some(scroll.override_vertical());
        self
    }

    /// Scrollbars
    pub fn hscroll(mut self, scroll: Scroll<'a>) -> Self {
        self.hscroll = Some(scroll.override_horizontal());
        self
    }

    /// Scrollbars
    pub fn vscroll(mut self, scroll: Scroll<'a>) -> Self {
        self.vscroll = Some(scroll.override_vertical());
        self
    }

    /// Set all styles as a bundle.
    #[inline]
    pub fn styles(mut self, styles: FTableStyle) -> Self {
        self.style = styles.style;
        self.header_style = styles.header_style;
        self.footer_style = styles.footer_style;

        self.select_row_style = styles.select_row_style;
        self.show_row_focus = styles.show_row_focus;
        self.select_column_style = styles.select_column_style;
        self.show_column_focus = styles.show_column_focus;
        self.select_cell_style = styles.select_cell_style;
        self.show_cell_focus = styles.show_cell_focus;
        self.select_header_style = styles.select_header_style;
        self.show_header_focus = styles.show_header_focus;
        self.select_footer_style = styles.select_footer_style;
        self.show_footer_focus = styles.show_footer_focus;

        self.focus_style = styles.focus_style;
        self
    }

    /// Base style for the table.
    #[inline]
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Base style for the table.
    #[inline]
    pub fn header_style(mut self, style: Option<Style>) -> Self {
        self.header_style = style;
        self
    }

    /// Base style for the table.
    #[inline]
    pub fn footer_style(mut self, style: Option<Style>) -> Self {
        self.footer_style = style;
        self
    }

    /// Style for a selected row. The chosen selection must support
    /// row-selection for this to take effect.
    #[inline]
    pub fn select_row_style(mut self, select_style: Option<Style>) -> Self {
        self.select_row_style = select_style;
        self
    }

    /// Add the focus-style to the row-style if the table is focused.
    #[inline]
    pub fn show_row_focus(mut self, show: bool) -> Self {
        self.show_row_focus = show;
        self
    }

    /// Style for a selected column. The chosen selection must support
    /// column-selection for this to take effect.
    #[inline]
    pub fn select_column_style(mut self, select_style: Option<Style>) -> Self {
        self.select_column_style = select_style;
        self
    }

    /// Add the focus-style to the column-style if the table is focused.
    #[inline]
    pub fn show_column_focus(mut self, show: bool) -> Self {
        self.show_column_focus = show;
        self
    }

    /// Style for a selected cell. The chosen selection must support
    /// cell-selection for this to take effect.
    #[inline]
    pub fn select_cell_style(mut self, select_style: Option<Style>) -> Self {
        self.select_cell_style = select_style;
        self
    }

    /// Add the focus-style to the cell-style if the table is focused.
    #[inline]
    pub fn show_cell_focus(mut self, show: bool) -> Self {
        self.show_cell_focus = show;
        self
    }

    /// Style for a selected header cell. The chosen selection must
    /// support column-selection for this to take effect.
    #[inline]
    pub fn select_header_style(mut self, select_style: Option<Style>) -> Self {
        self.select_header_style = select_style;
        self
    }

    /// Add the focus-style to the header-style if the table is focused.
    #[inline]
    pub fn show_header_focus(mut self, show: bool) -> Self {
        self.show_header_focus = show;
        self
    }

    /// Style for a selected footer cell. The chosen selection must
    /// support column-selection for this to take effect.
    #[inline]
    pub fn select_footer_style(mut self, select_style: Option<Style>) -> Self {
        self.select_footer_style = select_style;
        self
    }

    /// Add the footer-style to the table-style if the table is focused.
    #[inline]
    pub fn show_footer_focus(mut self, show: bool) -> Self {
        self.show_footer_focus = show;
        self
    }

    /// This style will be patched onto the selection to indicate that
    /// the widget has the input focus.
    ///
    /// The selection must support some kind of selection for this to
    /// be effective.
    #[inline]
    pub fn focus_style(mut self, focus_style: Option<Style>) -> Self {
        self.focus_style = focus_style;
        self
    }

    /// Just some utility to help with debugging. Usually does nothing.
    pub fn debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }
}

impl<'a, Selection> FTable<'a, Selection> {
    // area_width or layout_width
    #[inline]
    fn total_width(&self, area_width: u16) -> u16 {
        if let Some(layout_width) = self.layout_width {
            layout_width
        } else {
            area_width
        }
    }

    // Do the column-layout. Fill in missing columns, if necessary.
    #[inline]
    fn layout_columns(&self, width: u16) -> (u16, Rc<[Rect]>, Rc<[Rect]>) {
        let width = self.total_width(width);
        let area = Rect::new(0, 0, width, 0);

        let (layout, spacers) = Layout::horizontal(&self.widths)
            .flex(self.flex)
            .spacing(self.column_spacing)
            .split_with_spacers(area);

        (width, layout, spacers)
    }

    // Layout header/table/footer
    #[inline]
    fn layout_areas(&self, area: Rect) -> Rc<[Rect]> {
        let heights = vec![
            Constraint::Length(self.header.as_ref().map(|v| v.height).unwrap_or(0)),
            Constraint::Fill(1),
            Constraint::Length(self.footer.as_ref().map(|v| v.height).unwrap_or(0)),
        ];

        Layout::vertical(heights).split(area)
    }
}

impl<'a, Selection> StatefulWidgetRef for FTable<'a, Selection>
where
    Selection: TableSelection,
{
    type State = FTableState<Selection>;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let iter = self.data.iter();
        self.render_iter(iter, area, buf, state);
    }
}

impl<'a, Selection> StatefulWidget for FTable<'a, Selection>
where
    Selection: TableSelection,
{
    type State = FTableState<Selection>;

    fn render(mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let iter = mem::take(&mut self.data).into_iter();
        self.render_iter(iter, area, buf, state);
    }
}

impl<'a, Selection> FTable<'a, Selection>
where
    Selection: TableSelection,
{
    /// Render an Iterator over TableRowData.
    ///
    /// rows: If the row number is known, this can help.
    ///
    fn render_iter<'b>(
        &self,
        mut data: DataReprIter<'a, 'b>,
        area: Rect,
        buf: &mut Buffer,
        state: &mut FTableState<Selection>,
    ) {
        if let Some(rows) = data.rows() {
            state.rows = rows;
        }
        state.columns = self.widths.len();
        state.area = area;

        // vertical layout
        let (hscroll_area, vscroll_area, inner_area) = layout_scroll(
            area,
            self.block.as_ref(),
            self.hscroll.as_ref(),
            self.vscroll.as_ref(),
        );
        state.inner = inner_area;

        let l_rows = self.layout_areas(inner_area);
        state.header_area = l_rows[0];
        state.table_area = l_rows[1];
        state.footer_area = l_rows[2];

        // horizontal layout
        let (width, l_columns, l_spacers) = self.layout_columns(state.table_area.width);
        self.calculate_column_areas(state.columns, l_columns.as_ref(), l_spacers.as_ref(), state);

        // render header & footer
        self.render_header(
            state.columns,
            l_columns.as_ref(),
            l_spacers.as_ref(),
            buf,
            state,
        );
        self.render_footer(
            state.columns,
            l_columns.as_ref(),
            l_spacers.as_ref(),
            buf,
            state,
        );

        // render table
        buf.set_style(state.table_area, self.style);

        state.row_areas.clear();
        state.vscroll.set_page_len(0);

        let mut row_buf = Buffer::empty(Rect::new(0, 0, width, 1));
        let mut row = None;
        let mut row_y = state.table_area.y;
        let mut row_heights = Vec::new();
        #[cfg(debug_assertions)]
        let mut insane_offset = false;

        let mut ctx = FTableContext {
            focus: state.focus.get(),
            selected_cell: false,
            selected_row: false,
            selected_column: false,
            style: self.style,
            row_style: None,
            select_style: None,
            space_area: Default::default(),
            non_exhaustive: NonExhaustive,
        };

        if data.nth(state.vscroll.offset()) {
            row = Some(state.vscroll.offset());
            loop {
                ctx.row_style = data.row_style();
                // We render each row to a temporary buffer.
                // For ease of use we start each row at 0,0.
                // We still only render at least partially visible cells.
                let row_area = Rect::new(0, 0, width, max(data.row_height(), 1));
                // resize should work fine unless the row-heights vary wildly.
                row_buf.resize(row_area);

                if let Some(row_style) = ctx.row_style {
                    row_buf.set_style(row_area, row_style);
                } else {
                    row_buf.set_style(row_area, self.style);
                }

                row_heights.push(row_area.height);

                // Target area for the finished row.
                let visible_row = Rect::new(
                    state.table_area.x,
                    row_y,
                    state.table_area.width,
                    max(data.row_height(), 1),
                )
                .intersection(state.table_area);

                state.row_areas.push(visible_row);
                state.vscroll.set_page_len(state.vscroll.page_len() + 1);

                // todo: render_row

                let mut col = state.hscroll.offset();
                loop {
                    if col >= state.columns {
                        break;
                    }

                    let cell_area =
                        Rect::new(l_columns[col].x, 0, l_columns[col].width, row_area.height);
                    ctx.space_area = Rect::new(
                        l_spacers[col + 1].x,
                        0,
                        l_spacers[col + 1].width,
                        row_area.height,
                    );

                    ctx.select_style = if state.selection.is_selected_cell(col, row.expect("row")) {
                        ctx.selected_cell = true;
                        ctx.selected_row = false;
                        ctx.selected_column = false;
                        self.patch_select(
                            self.select_cell_style,
                            state.focus.get(),
                            self.show_cell_focus,
                        )
                    } else if state.selection.is_selected_row(row.expect("row")) {
                        ctx.selected_cell = false;
                        ctx.selected_row = true;
                        ctx.selected_column = false;
                        // use a fallback if no row-selected style is set.
                        if self.select_row_style.is_some() {
                            self.patch_select(
                                self.select_row_style,
                                state.focus.get(),
                                self.show_row_focus,
                            )
                        } else {
                            self.patch_select(
                                Some(revert_style(self.style)),
                                state.focus.get(),
                                self.show_row_focus,
                            )
                        }
                    } else if state.selection.is_selected_column(col) {
                        ctx.selected_cell = false;
                        ctx.selected_row = false;
                        ctx.selected_column = true;
                        self.patch_select(
                            self.select_column_style,
                            state.focus.get(),
                            self.show_column_focus,
                        )
                    } else {
                        ctx.selected_cell = false;
                        ctx.selected_row = false;
                        ctx.selected_column = false;
                        None
                    };
                    if let Some(select_style) = ctx.select_style {
                        row_buf.set_style(cell_area, select_style);
                        row_buf.set_style(ctx.space_area, select_style);
                    }

                    data.render_cell(&ctx, col, cell_area, &mut row_buf);

                    if cell_area.right() >= state.table_area.right() {
                        break;
                    }
                    col += 1;
                }

                // render shifted and clipped row.
                transfer_buffer(
                    &mut row_buf,
                    l_columns[state.hscroll.offset()].x,
                    visible_row,
                    buf,
                );

                if visible_row.bottom() >= state.table_area.bottom() {
                    break;
                }
                if !data.nth(0) {
                    break;
                }
                row = Some(row.expect("row") + 1);
                row_y += row_area.height;
            }
        } else {
            // can only guess whether the skip failed completely or partially.
            // so don't alter row here.

            // if this first skip fails all bets are off.
            if data.rows().is_none() || data.rows() == Some(0) {
                // this is ok
            } else {
                #[cfg(debug_assertions)]
                {
                    insane_offset = true;
                }
            }
        }

        // maximum offsets
        #[allow(unused_variables)]
        let algorithm;
        #[allow(unused_assignments)]
        {
            if let Some(rows) = data.rows() {
                algorithm = 0;
                // skip to a guess for the last page.
                // the guess uses row-height is 1, which may read a few more lines than
                // absolutely necessary.
                let skip_rows = rows
                    .saturating_sub(row.map_or(0, |v| v + 1))
                    .saturating_sub(state.table_area.height as usize);
                // if we can still skip some rows, then the data so far is useless.
                if skip_rows > 0 {
                    row_heights.clear();
                }
                let nth_row = skip_rows;
                // collect the remaining row-heights.
                if data.nth(nth_row) {
                    row = Some(row.map_or(nth_row, |row| row + nth_row + 1));
                    loop {
                        row_heights.push(data.row_height());
                        // don't need more.
                        if row_heights.len() > state.table_area.height as usize {
                            row_heights.remove(0);
                        }
                        if !data.nth(0) {
                            break;
                        }
                        row = Some(row.expect("row") + 1);
                        // if the given number of rows is too small, we would overshoot here.
                        if row.expect("row") > rows {
                            break;
                        }
                    }
                    // we break before to have an accurate last page.
                    // but we still want to report an error, if the count is off.
                    while data.nth(0) {
                        row = Some(row.expect("row") + 1);
                    }
                } else {
                    // skip failed, maybe again?
                    // leave everything as is and report later.
                }

                state.rows = rows;
                state._counted_rows = row.map_or(0, |v| v + 1);

                // have we got a page worth of data?
                if let Some(last_page) = state.calc_last_page(row_heights) {
                    state.vscroll.set_max_offset(state.rows - last_page);
                } else {
                    // we don't have enough data to establish the last page.
                    // either there are not enough rows or the given row-count
                    // was off. make a guess.
                    state.vscroll.set_max_offset(
                        state.rows.saturating_sub(state.table_area.height as usize),
                    );
                }
            } else if self.no_row_count {
                algorithm = 1;

                // We need to feel out a bit beyond the page, otherwise
                // we can't really stabilize the row count and the
                // display starts flickering.
                if row.is_some() {
                    if data.nth(0) {
                        // try one past page
                        row = Some(row.expect("row") + 1);
                        if data.nth(0) {
                            // have an unknown number of rows left.
                            row = Some(usize::MAX - 1);
                        }
                    }
                }

                state.rows = row.map_or(0, |v| v + 1);
                state._counted_rows = row.map_or(0, |v| v + 1);
                // rough estimate
                state.vscroll.set_max_offset(usize::MAX - 1);
                if state.vscroll.page_len() == 0 {
                    state.vscroll.set_page_len(state.table_area.height as usize);
                }
            } else {
                algorithm = 2;

                // Read all the rest to establish the exact row-count.
                while data.nth(0) {
                    row_heights.push(data.row_height());
                    // don't need more info. drop the oldest.
                    if row_heights.len() > state.table_area.height as usize {
                        row_heights.remove(0);
                    }
                    row = Some(row.map_or(0, |v| v + 1));
                }

                state.rows = row.map_or(0, |v| v + 1);
                state._counted_rows = row.map_or(0, |v| v + 1);

                // have we got a page worth of data?
                if let Some(last_page) = state.calc_last_page(row_heights) {
                    state.vscroll.set_max_offset(state.rows - last_page);
                } else {
                    state.vscroll.set_max_offset(0);
                }
            }
        }
        {
            state.hscroll.set_max_offset(0);
            let max_right = l_columns.last().map(|v| v.right()).unwrap_or(0);
            for c in (0..state.columns).rev() {
                if max_right - l_columns[c].left() >= state.table_area.width {
                    state.hscroll.set_max_offset(c);
                    break;
                }
            }
        }

        // render block+scroll
        self.block.render_ref(area, buf);
        if let Some(hscroll) = self.hscroll.as_ref() {
            hscroll.render_ref(hscroll_area, buf, &mut state.hscroll);
        }
        if let Some(vscroll) = self.vscroll.as_ref() {
            vscroll.render_ref(vscroll_area, buf, &mut state.vscroll);
        }

        #[cfg(debug_assertions)]
        {
            use std::fmt::Write;
            let mut msg = String::new();
            if insane_offset {
                _= write!(msg,
                          "FTable::render:\n        offset {}\n        rows {}\n        iter-rows {}max\n    don't match up\nCode X{}X\n",
                          state.vscroll.offset(), state.rows, state._counted_rows, algorithm
                );
            }
            if state.rows != state._counted_rows {
                _ = write!(
                    msg,
                    "FTable::render:\n    rows {} don't match\n    iterated rows {}\nCode X{}X\n",
                    state.rows, state._counted_rows, algorithm
                );
            }
            if !msg.is_empty() {
                warn!("{}", &msg);
                Text::from(msg)
                    .white()
                    .on_red()
                    .render(state.table_area, buf);
            }
        }
    }

    fn render_footer(
        &self,
        columns: usize,
        l_columns: &[Rect],
        l_spacers: &[Rect],
        buf: &mut Buffer,
        state: &mut FTableState<Selection>,
    ) {
        if let Some(footer) = &self.footer {
            if let Some(footer_style) = footer.style {
                buf.set_style(state.footer_area, footer_style);
            } else if let Some(footer_style) = self.footer_style {
                buf.set_style(state.footer_area, footer_style);
            } else {
                buf.set_style(state.footer_area, self.style);
            }

            let mut col = state.hscroll.offset();
            loop {
                if col >= columns {
                    break;
                }

                let cell_area = Rect::new(
                    state.footer_area.x + l_columns[col].x - l_columns[state.hscroll.offset()].x,
                    state.footer_area.y,
                    l_columns[col].width,
                    state.footer_area.height,
                )
                .intersection(state.footer_area);

                let space_area = Rect::new(
                    state.footer_area.x + l_spacers[col + 1].x
                        - l_columns[state.hscroll.offset()].x,
                    state.footer_area.y,
                    l_spacers[col + 1].width,
                    state.footer_area.height,
                )
                .intersection(state.footer_area);

                if state.selection.is_selected_column(col) {
                    if let Some(selected_style) = self.patch_select(
                        self.select_footer_style,
                        state.focus.get(),
                        self.show_footer_focus,
                    ) {
                        buf.set_style(cell_area, selected_style);
                        buf.set_style(space_area, selected_style);
                    }
                };

                if let Some(cell) = footer.cells.get(col) {
                    if let Some(cell_style) = cell.style {
                        buf.set_style(cell_area, cell_style);
                    }
                    cell.content.clone().render(cell_area, buf);
                }

                if cell_area.right() >= state.footer_area.right() {
                    break;
                }

                col += 1;
            }
        }
    }

    fn render_header(
        &self,
        columns: usize,
        l_columns: &[Rect],
        l_spacers: &[Rect],
        buf: &mut Buffer,
        state: &mut FTableState<Selection>,
    ) {
        if let Some(header) = &self.header {
            if let Some(header_style) = header.style {
                buf.set_style(state.header_area, header_style);
            } else if let Some(header_style) = self.header_style {
                buf.set_style(state.header_area, header_style);
            } else {
                buf.set_style(state.header_area, self.style);
            }

            let mut col = state.hscroll.offset();
            loop {
                if col >= columns {
                    break;
                }

                let cell_area = Rect::new(
                    state.header_area.x + l_columns[col].x - l_columns[state.hscroll.offset()].x,
                    state.header_area.y,
                    l_columns[col].width,
                    state.header_area.height,
                )
                .intersection(state.header_area);

                let space_area = Rect::new(
                    state.header_area.x + l_spacers[col + 1].x
                        - l_columns[state.hscroll.offset()].x,
                    state.header_area.y,
                    l_spacers[col + 1].width,
                    state.header_area.height,
                )
                .intersection(state.header_area);

                if state.selection.is_selected_column(col) {
                    if let Some(selected_style) = self.patch_select(
                        self.select_header_style,
                        state.focus.get(),
                        self.show_header_focus,
                    ) {
                        buf.set_style(cell_area, selected_style);
                        buf.set_style(space_area, selected_style);
                    }
                };

                if let Some(cell) = header.cells.get(col) {
                    if let Some(cell_style) = cell.style {
                        buf.set_style(cell_area, cell_style);
                    }
                    cell.content.clone().render(cell_area, buf);
                }

                if cell_area.right() >= state.header_area.right() {
                    break;
                }

                col += 1;
            }
        }
    }

    fn calculate_column_areas(
        &self,
        columns: usize,
        l_columns: &[Rect],
        l_spacers: &[Rect],
        state: &mut FTableState<Selection>,
    ) {
        state.column_areas.clear();
        state.hscroll.set_page_len(0);

        let mut col = state.hscroll.offset();
        loop {
            if col >= columns {
                break;
            }

            // merge the column + the folling spacer as the
            // column area.
            let mut column_area = Rect::new(
                state.table_area.x + l_columns[col].x - l_columns[state.hscroll.offset()].x,
                state.table_area.y,
                l_columns[col].width,
                state.table_area.height,
            );
            state
                .base_column_areas
                .push(column_area.intersection(state.table_area));

            column_area.width += l_spacers[col + 1].width;
            state
                .column_areas
                .push(column_area.intersection(state.table_area));

            state.hscroll.set_page_len(state.hscroll.page_len() + 1);

            if column_area.right() >= state.table_area.right() {
                break;
            }

            col += 1;
        }

        // Base areas for every column.
        state.base_column_areas.clear();
        for col in 0..columns {
            let column_area = if col < state.hscroll.offset() {
                Rect::new(0, state.table_area.y, 0, state.table_area.height)
            } else {
                Rect::new(
                    state.table_area.x + l_columns[col].x - l_columns[state.hscroll.offset()].x,
                    state.table_area.y,
                    l_columns[col].width,
                    state.table_area.height,
                )
            };
            let column_area = column_area.intersection(state.table_area);
            state.base_column_areas.push(column_area);
        }
    }

    fn patch_select(&self, style: Option<Style>, focus: bool, show: bool) -> Option<Style> {
        if let Some(style) = style {
            if let Some(focus_style) = self.focus_style {
                if focus && show {
                    Some(style.patch(focus_style))
                } else {
                    Some(style)
                }
            } else {
                Some(style)
            }
        } else {
            None
        }
    }
}

impl Default for FTableStyle {
    fn default() -> Self {
        Self {
            style: Default::default(),
            header_style: None,
            footer_style: None,
            select_row_style: None,
            select_column_style: None,
            select_cell_style: None,
            select_header_style: None,
            select_footer_style: None,
            show_row_focus: false,
            show_column_focus: false,
            show_cell_focus: false,
            show_header_focus: false,
            show_footer_focus: false,
            focus_style: None,
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<Selection: Default> Default for FTableState<Selection> {
    fn default() -> Self {
        Self {
            focus: Default::default(),
            area: Default::default(),
            inner: Default::default(),
            header_area: Default::default(),
            table_area: Default::default(),
            footer_area: Default::default(),
            row_areas: Default::default(),
            column_areas: Default::default(),
            base_column_areas: Default::default(),
            rows: 0,
            _counted_rows: 0,
            columns: 0,
            vscroll: Default::default(),
            hscroll: Default::default(),
            selection: Default::default(),
            mouse: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<Selection> HasFocusFlag for FTableState<Selection> {
    #[inline]
    fn focus(&self) -> &FocusFlag {
        &self.focus
    }

    #[inline]
    fn area(&self) -> Rect {
        self.area
    }
}

impl<Selection> FTableState<Selection> {
    fn calc_last_page(&self, mut row_heights: Vec<u16>) -> Option<usize> {
        let mut sum_heights = 0;
        let mut n_rows = 0;
        while let Some(h) = row_heights.pop() {
            sum_heights += h;
            n_rows += 1;
            if sum_heights >= self.table_area.height {
                break;
            }
        }

        if sum_heights < self.table_area.height {
            None
        } else {
            Some(n_rows)
        }
    }
}

// Baseline
impl<Selection> FTableState<Selection> {
    /// Number of rows.
    #[inline]
    pub fn rows(&self) -> usize {
        self.rows
    }

    /// Number of columns.
    #[inline]
    pub fn columns(&self) -> usize {
        self.columns
    }
}

// Table areas
impl<Selection> FTableState<Selection> {
    /// Returns the whole row-area and the cell-areas for the
    /// given row, if it is visible.
    ///
    /// Attention: These areas might be 0-length if the column is scrolled
    /// beyond the table-area.
    ///
    /// See: [FTableState::scroll_to]
    pub fn row_cells(&self, row: usize) -> Option<(Rect, Vec<Rect>)> {
        if row < self.vscroll.offset() || row >= self.vscroll.offset() + self.vscroll.page_len() {
            return None;
        }

        let mut areas = Vec::new();

        let r = self.row_areas[row];
        for c in &self.base_column_areas {
            areas.push(Rect::new(c.x, r.y, c.width, r.height));
        }

        Some((r, areas))
    }

    /// Cell at given position.
    pub fn cell_at_clicked(&self, pos: (u16, u16)) -> Option<(usize, usize)> {
        let col = self.column_at_clicked(pos);
        let row = self.row_at_clicked(pos);

        match (col, row) {
            (Some(col), Some(row)) => Some((col, row)),
            _ => None,
        }
    }

    /// Column at given position.
    pub fn column_at_clicked(&self, pos: (u16, u16)) -> Option<usize> {
        rat_event::util::column_at_clicked(&self.column_areas, pos.0)
            .map(|v| self.hscroll.offset() + v)
    }

    /// Row at given position.
    pub fn row_at_clicked(&self, pos: (u16, u16)) -> Option<usize> {
        rat_event::util::row_at_clicked(&self.row_areas, pos.1).map(|v| self.vscroll.offset() + v)
    }

    /// Cell when dragging. Position can be outside the table area.
    /// See [row_at_drag](FTableState::row_at_drag), [col_at_drag](FTableState::column_at_drag)
    pub fn cell_at_drag(&self, pos: (u16, u16)) -> (usize, usize) {
        let col = self.column_at_drag(pos);
        let row = self.row_at_drag(pos);

        (col, row)
    }

    /// Row when dragging. Position can be outside the table area.
    /// If the position is above the table-area this returns offset - #rows.
    /// If the position is below the table-area this returns offset + page_len + #rows.
    ///
    /// This doesn't account for the row-height of the actual rows outside
    /// the table area, just assumes '1'.
    pub fn row_at_drag(&self, pos: (u16, u16)) -> usize {
        match rat_event::util::row_at_drag(self.table_area, &self.row_areas, pos.1) {
            Ok(v) => self.vscroll.offset() + v,
            Err(v) if v <= 0 => self.vscroll.offset().saturating_sub((-v) as usize),
            Err(v) => self.vscroll.offset() + self.row_areas.len() + v as usize,
        }
    }

    /// Column when dragging. Position can be outside the table area.
    /// If the position is left of the table area this returns offset - 1.
    /// If the position is right of the table area this returns offset + page_width + 1.
    pub fn column_at_drag(&self, pos: (u16, u16)) -> usize {
        match rat_event::util::column_at_drag(self.table_area, &self.column_areas, pos.0) {
            Ok(v) => self.hscroll.offset() + v,
            Err(v) if v <= 0 => self.hscroll.offset().saturating_sub(1),
            Err(_v) => self.hscroll.offset() + self.column_areas.len() + 1,
        }
    }
}

// Offset related.
impl<Selection: TableSelection> FTableState<Selection> {
    /// Sets both offsets to 0.
    pub fn clear_offset(&mut self) {
        self.vscroll.set_offset(0);
        self.hscroll.set_offset(0);
    }

    /// Maximum offset that is accessible with scrolling.
    ///
    /// This is shorter than the length by whatever fills the last page.
    /// This is the base for the scrollbar content_length.
    pub fn row_max_offset(&self) -> usize {
        self.vscroll.max_offset()
    }

    /// Current vertical offset.
    pub fn row_offset(&self) -> usize {
        self.vscroll.offset()
    }

    /// Change the vertical offset.
    ///
    /// Due to overscroll it's possible that this is an invalid offset for the widget.
    /// The widget must deal with this situation.
    ///
    /// The widget returns true if the offset changed at all.
    pub fn set_row_offset(&mut self, offset: usize) -> bool {
        self.vscroll.set_offset(offset)
    }

    /// Vertical page-size at the current offset.
    pub fn page_len(&self) -> usize {
        self.vscroll.page_len()
    }

    /// Suggested scroll per scroll-event.
    pub fn row_scroll_by(&self) -> usize {
        self.vscroll.scroll_by()
    }

    /// Maximum offset that is accessible with scrolling.
    ///
    /// This is shorter than the length of the content by whatever fills the last page.
    /// This is the base for the scrollbar content_length.
    pub fn col_max_offset(&self) -> usize {
        self.hscroll.max_offset()
    }

    /// Current horizontal offset.
    pub fn col_offset(&self) -> usize {
        self.hscroll.offset()
    }

    /// Change the horizontal offset.
    ///
    /// Due to overscroll it's possible that this is an invalid offset for the widget.
    /// The widget must deal with this situation.
    ///
    /// The widget returns true if the offset changed at all.
    pub fn set_col_offset(&mut self, offset: usize) -> bool {
        self.hscroll.set_offset(offset)
    }

    /// Horizontal page-size at the current offset.
    pub fn page_width(&self) -> usize {
        self.hscroll.page_len()
    }

    /// Suggested scroll per scroll-event.
    pub fn col_scroll_by(&self) -> usize {
        self.hscroll.scroll_by()
    }

    /// Ensures that the selected item is visible.
    pub fn scroll_to_selected(&mut self) -> bool {
        if let Some(selected) = self.selection.lead_selection() {
            let c = self.scroll_to_col(selected.0);
            let r = self.scroll_to_row(selected.1);
            r || c
        } else {
            false
        }
    }

    /// Ensures that the given row is visible.
    pub fn scroll_to_row(&mut self, pos: usize) -> bool {
        if pos >= self.row_offset() + self.page_len() {
            self.set_row_offset(pos - self.page_len() + 1)
        } else if pos < self.row_offset() {
            self.set_row_offset(pos)
        } else {
            false
        }
    }

    /// Ensures that the given column is visible.
    pub fn scroll_to_col(&mut self, pos: usize) -> bool {
        if pos >= self.col_offset() + self.page_width() {
            self.set_col_offset(pos - self.page_width() + 1)
        } else if pos < self.col_offset() {
            self.set_col_offset(pos)
        } else {
            false
        }
    }

    /// Reduce the row-offset by n.
    pub fn scroll_up(&mut self, n: usize) -> bool {
        self.vscroll.scroll_up(n)
    }

    /// Increase the row-offset by n.
    pub fn scroll_down(&mut self, n: usize) -> bool {
        self.vscroll.scroll_down(n)
    }

    /// Reduce the col-offset by n.
    pub fn scroll_left(&mut self, n: usize) -> bool {
        self.hscroll.scroll_left(n)
    }

    /// Increase the col-offset by n.
    pub fn scroll_right(&mut self, n: usize) -> bool {
        self.hscroll.scroll_right(n)
    }
}

impl FTableState<RowSelection> {
    /// When scrolling the table, change the selection instead of the offset.
    #[inline]
    pub fn set_scroll_selection(&mut self, scroll: bool) {
        self.selection.set_scroll_selected(scroll);
    }

    /// Clear the selection.
    #[inline]
    pub fn clear_selection(&mut self) {
        self.selection.clear();
    }

    /// Anything selected?
    #[inline]
    pub fn has_selection(&mut self) -> bool {
        self.selection.has_selection()
    }

    /// Selected row.
    #[inline]
    pub fn selected(&self) -> Option<usize> {
        self.selection.selected()
    }

    /// Select the row. Limits the value to the number of rows.
    #[inline]
    pub fn select(&mut self, row: Option<usize>) -> bool {
        if let Some(row) = row {
            self.selection
                .select(Some(min(row, self.rows.saturating_sub(1))))
        } else {
            self.selection.select(None)
        }
    }

    /// Scroll delivers a value between 0 and max_offset as offset.
    /// This remaps the ratio to the selection with a range 0..row_len.
    ///
    pub(crate) fn remap_offset_selection(&self, offset: usize) -> usize {
        if self.vscroll.max_offset() > 0 {
            (self.rows * offset) / self.vscroll.max_offset()
        } else {
            0 // ???
        }
    }

    /// Move the selection to the given row.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_to(&mut self, row: usize) -> bool {
        let r = self.selection.move_to(row, self.rows.saturating_sub(1));
        let s = self.scroll_to_row(self.selection.selected().expect("row"));
        r || s
    }

    /// Move the selection up n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_up(&mut self, n: usize) -> bool {
        let r = self.selection.move_up(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_row(self.selection.selected().expect("row"));
        r || s
    }

    /// Move the selection down n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_down(&mut self, n: usize) -> bool {
        let r = self.selection.move_down(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_row(self.selection.selected().expect("row"));
        r || s
    }
}

impl FTableState<RowSetSelection> {
    /// Clear the selection.
    #[inline]
    pub fn clear_selection(&mut self) {
        self.selection.clear();
    }

    /// Anything selected?
    #[inline]
    pub fn has_selection(&mut self) -> bool {
        self.selection.has_selection()
    }

    /// Selected rows.
    #[inline]
    pub fn selected(&self) -> HashSet<usize> {
        self.selection.selected()
    }

    /// Change the lead-selection. Limits the value to the number of rows.
    /// If extend is false the current selection is cleared and both lead and
    /// anchor are set to the given value.
    /// If extend is true, the anchor is kept where it is and lead is changed.
    /// Everything in the range `anchor..lead` is selected. It doesn't matter
    /// if anchor < lead.
    #[inline]
    pub fn set_lead(&mut self, row: Option<usize>, extend: bool) -> bool {
        if let Some(row) = row {
            self.selection
                .set_lead(Some(min(row, self.rows.saturating_sub(1))), extend)
        } else {
            self.selection.set_lead(None, extend)
        }
    }

    /// Current lead.
    #[inline]
    pub fn lead(&self) -> Option<usize> {
        self.selection.lead()
    }

    /// Current anchor.
    #[inline]
    pub fn anchor(&self) -> Option<usize> {
        self.selection.anchor()
    }

    /// Retire the current anchor/lead selection to the set of selected rows.
    /// Resets lead and anchor and starts a new selection round.
    #[inline]
    pub fn retire_selection(&mut self) {
        self.selection.retire_selection();
    }

    /// Add to selection. Only works for retired selections, not for the
    /// active anchor-lead range.
    #[inline]
    pub fn add_selected(&mut self, idx: usize) {
        self.selection.add(idx);
    }

    /// Remove from selection. Only works for retired selections, not for the
    /// active anchor-lead range.
    #[inline]
    pub fn remove_selected(&mut self, idx: usize) {
        self.selection.remove(idx);
    }

    /// Move the selection to the given row.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_to(&mut self, row: usize, extend: bool) -> bool {
        let r = self
            .selection
            .move_to(row, self.rows.saturating_sub(1), extend);
        let s = self.scroll_to_row(self.selection.lead().expect("row"));
        r || s
    }

    /// Move the selection up n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_up(&mut self, n: usize, extend: bool) -> bool {
        let r = self
            .selection
            .move_up(n, self.rows.saturating_sub(1), extend);
        let s = self.scroll_to_row(self.selection.lead().expect("row"));
        r || s
    }

    /// Move the selection down n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_down(&mut self, n: usize, extend: bool) -> bool {
        let r = self
            .selection
            .move_down(n, self.rows.saturating_sub(1), extend);
        let s = self.scroll_to_row(self.selection.lead().expect("row"));
        r || s
    }
}

impl FTableState<CellSelection> {
    #[inline]
    pub fn clear_selection(&mut self) {
        self.selection.clear();
    }

    #[inline]
    pub fn has_selection(&mut self) -> bool {
        self.selection.has_selection()
    }

    /// Selected cell.
    #[inline]
    pub fn selected(&self) -> Option<(usize, usize)> {
        self.selection.selected()
    }

    /// Select a cell.
    #[inline]
    pub fn select_cell(&mut self, select: Option<(usize, usize)>) -> bool {
        if let Some((col, row)) = select {
            self.selection.select_cell(Some((
                min(col, self.columns.saturating_sub(1)),
                min(row, self.rows.saturating_sub(1)),
            )))
        } else {
            self.selection.select_cell(None)
        }
    }

    /// Select a row. Column stays the same.
    #[inline]
    pub fn select_row(&mut self, row: Option<usize>) -> bool {
        if let Some(row) = row {
            self.selection
                .select_row(Some(min(row, self.rows.saturating_sub(1))))
        } else {
            self.selection.select_row(None)
        }
    }

    /// Select a column, row stays the same.
    #[inline]
    pub fn select_column(&mut self, column: Option<usize>) -> bool {
        if let Some(column) = column {
            self.selection
                .select_column(Some(min(column, self.columns.saturating_sub(1))))
        } else {
            self.selection.select_column(None)
        }
    }

    /// Select a cell, limit to maximum.
    #[inline]
    pub fn move_to(&mut self, select: (usize, usize)) -> bool {
        let r = self.selection.move_to(
            select,
            (self.columns.saturating_sub(1), self.rows.saturating_sub(1)),
        );
        let s = self.scroll_to_selected();
        r || s
    }

    /// Select a row, limit to maximum.
    #[inline]
    pub fn move_to_row(&mut self, row: usize) -> bool {
        let r = self.selection.move_to_row(row, self.rows.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Select a cell, clamp between 0 and maximum.
    #[inline]
    pub fn move_to_col(&mut self, col: usize) -> bool {
        let r = self
            .selection
            .move_to_col(col, self.columns.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection up n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_up(&mut self, n: usize) -> bool {
        let r = self.selection.move_up(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection down n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_down(&mut self, n: usize) -> bool {
        let r = self.selection.move_down(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection left n columns.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_left(&mut self, n: usize) -> bool {
        let r = self.selection.move_left(n, self.columns.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection right n columns.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_right(&mut self, n: usize) -> bool {
        let r = self.selection.move_right(n, self.columns.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }
}

impl<Selection> HandleEvent<crossterm::event::Event, DoubleClick, DoubleClickOutcome>
    for FTableState<Selection>
{
    /// Handles double-click events on the table.
    fn handle(
        &mut self,
        event: &crossterm::event::Event,
        _keymap: DoubleClick,
    ) -> DoubleClickOutcome {
        match event {
            ct_event!(mouse any for m) if self.mouse.doubleclick(self.table_area, m) => {
                if let Some((col, row)) = self.cell_at_clicked((m.column, m.row)) {
                    DoubleClickOutcome::ClickClick(col, row)
                } else {
                    DoubleClickOutcome::NotUsed
                }
            }
            _ => DoubleClickOutcome::NotUsed,
        }
    }
}

/// Handle all events for recognizing double-clicks.
pub fn handle_doubleclick_events<Selection: TableSelection>(
    state: &mut FTableState<Selection>,
    event: &crossterm::event::Event,
) -> DoubleClickOutcome {
    state.handle(event, DoubleClick)
}

impl<Selection: TableSelection> HandleEvent<crossterm::event::Event, EditKeys, EditOutcome>
    for FTableState<Selection>
where
    Self: HandleEvent<crossterm::event::Event, FocusKeys, Outcome>,
{
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: EditKeys) -> EditOutcome {
        match event {
            ct_event!(keycode press Insert) => EditOutcome::Insert,
            ct_event!(keycode press Delete) => EditOutcome::Remove,
            ct_event!(keycode press Enter) => EditOutcome::Edit,
            ct_event!(keycode press Down) => {
                if let Some((_column, row)) = self.selection.lead_selection() {
                    if row == self.rows().saturating_sub(1) {
                        return EditOutcome::Append;
                    }
                }
                <Self as HandleEvent<_, FocusKeys, Outcome>>::handle(self, event, FocusKeys).into()
            }

            ct_event!(keycode release  Insert)
            | ct_event!(keycode release Delete)
            | ct_event!(keycode release Enter)
            | ct_event!(keycode release Down) => EditOutcome::Unchanged,

            _ => {
                <Self as HandleEvent<_, FocusKeys, Outcome>>::handle(self, event, FocusKeys).into()
            }
        }
    }
}

/// Handle all events.
/// Text events are only processed if focus is true.
/// Mouse events are processed if they are in range.
pub fn handle_edit_events<Selection: TableSelection>(
    state: &mut FTableState<Selection>,
    focus: bool,
    event: &crossterm::event::Event,
) -> EditOutcome
where
    FTableState<Selection>: HandleEvent<crossterm::event::Event, FocusKeys, Outcome>,
    FTableState<Selection>: HandleEvent<crossterm::event::Event, MouseOnly, Outcome>,
{
    state.focus.set(focus);
    state.handle(event, EditKeys)
}